Gradio适合做演示,但要做一个有对话历史、用户认证、持久化存储的AI应用,Chainlit是更好的选择。
为什么选Chainlit
专为AI对话应用设计。内置对话历史管理、支持用户认证、支持文件上传、支持中间步骤展示。界面类似ChatGPT,用户体验好。
快速开始
pip install chainlit
import chainlit as cl
from openai import OpenAI
@cl.on_message
async def main(message: cl.Message):
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
response = client.chat.completions.create(
model="qwen2.5:7b",
messages=[{"role": "user", "content": message.content}],
stream=True
)
msg = cl.Message(content="")
for chunk in response:
if chunk.choices[0].delta.content:
await msg.stream_token(chunk.choices[0].delta.content)
await msg.update()
运行chainlit run app.py,打开http://localhost:8000。
对话历史
Chainlit自动管理每个用户的对话历史。通过cl.on_chat_start初始化会话,通过cl.user_session存取上下文。
文件上传
用户可以上传文件,代码中通过message.elements获取。配合RAG系统,实现"上传文档然后提问"的功能。
中间步骤
用cl.Step展示Agent的推理过程——用户能看到模型在调用什么工具、检索了什么文档、做了什么决策。这对调试和用户信任都很重要。