异步编程是一种强大的方式,可以在不阻塞程序执行的情况下并发处理多个任务。Chainlit 默认是异步的,以便代理可以并行执行任务并允许单个应用程序支持多个用户。Python 引入了 asyncio 库,使得使用 async/await 语法编写异步代码更加容易。本入门指南将帮助您理解 Python 异步编程的基础知识以及如何在 Chainlit 项目中使用它。

理解 async/await

asyncawait 关键字用于在 Python 中定义和处理异步代码。一个 async 函数是一个协程(coroutine),它是一种特殊的函数,可以暂停执行并在稍后恢复,同时允许其他任务在此期间运行。

要定义一个异步函数,请使用 async def 语法

async def my_async_function():
    # Your async code goes here

要调用一个异步函数,您需要使用 await 关键字

async def another_async_function():
    result = await my_async_function()

使用 Chainlit

Chainlit 使用异步编程来高效地处理事件和任务。创建 Chainlit 代理时,您通常需要定义异步函数来处理事件并执行操作。

例如,创建一个在 Chainlit 中响应消息的异步函数

import chainlit as cl

@cl.on_message
async def main(message: cl.Message):
    # Your custom logic goes here

    # Send a response back to the user
    await cl.Message(
        content=f"Received: {message.content}",
    ).send()

长时间运行的同步任务

在某些情况下,您需要在 Chainlit 项目中运行长时间运行的同步函数。为了防止阻塞事件循环,您可以使用 Chainlit 库提供的 make_async 函数将同步函数转换为异步函数

from chainlit import make_async

def my_sync_function():
    # Your synchronous code goes here
    import time
    time.sleep(10)
    return 0

async_function = make_async(my_sync_function)

async def main():
    result = await async_function()

通过使用这种方法,您可以保持项目的非阻塞特性,同时在必要时仍然可以集成同步函数。

从同步函数中调用异步函数

如果您需要在同步函数内部运行异步函数,可以使用 Chainlit 库提供的 run_sync 函数

from chainlit import run_sync

async def my_async_function():
    # Your asynchronous code goes here

def main():
    result = run_sync(my_async_function())

main()

通过遵循本指南,您现在应该对 Python 中的异步编程以及如何在 Chainlit 项目中使用它有了基本的了解。随着您继续使用 Chainlit,您会发现 async/await 和 asyncio 库提供了一种强大而高效的方式来并发处理多个代理/任务。