chatapp stream 模式还是很重要的,现在的llm api 基本都支持stream模式了chainlit 也提供了stream 模式的支持

参考处理

登录后复制
import chainlit as cl
from openai import AsyncOpenAI
 
client = AsyncOpenAI(
    api_key="sk-ZTp5zuetNQoJNgG4xHgGzw",
    base_url="http://localhost:4000"
)
 
settings = {
    "model": "dalongdemov3",
    "temperature": 0,
}
 
@cl.on_message
async def on_message(message: cl.Message):
    response = await client.chat.completions.create(
       # api 开启stream 
        stream= True,
        messages=[
            {
                "content": "You are a helpful bot, you always reply in chinese.",
                "role": "system"
            },
            {
                "content": message.content,
                "role": "user"
            }
        ],
        **settings
    ) 
    msg = cl.Message(content="")
    await msg.send()
    async for token in  response:
       # stream_token 是核心
        await msg.stream_token(token.choices[0].delta.content or "")
    await msg.update()
 
@cl.on_chat_start
async def main():
    await cl.Message(content="你好").send()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
登录后复制
from openai import AsyncOpenAI
  • 1.

说明

以上是一个简单说明,官方文档也有详细的示例可以参考学习

参考资料

 https://docs.chainlit.io/advanced-features/streaming