asyncio library to make it easier to write asynchronous code using the async/await syntax. This onboarding guide will help you understand the basics of asynchronous programming in Python and how to use it in your Chainlit project.
Understanding async/await
Theasync and await keywords are used to define and work with asynchronous code in Python. An async function is a coroutine, which is a special type of function that can pause its execution and resume later, allowing other tasks to run in the meantime.
To define an async function, use the async def syntax:
await keyword:
Working with Chainlit
Chainlit uses asynchronous programming to handle events and tasks efficiently. When creating a Chainlit agent, you’ll often need to define async functions to handle events and perform actions. For example, to create an async function that responds to messages in Chainlit:Long running synchronous tasks
In some cases, you need to run long running synchronous functions in your Chainlit project. To prevent blocking the event loop, you can utilize themake_async function provided by the Chainlit library to transform a synchronous function into an asynchronous one:
Call an async function from a sync function
If you need to run an asynchronous function inside a sync function, you can use therun_sync function provided by the Chainlit library: