|
|
4 ماه پیش | |
|---|---|---|
| .gitignore | 4 ماه پیش | |
| README.md | 4 ماه پیش | |
| main.py | 4 ماه پیش | |
| requirements.txt | 4 ماه پیش | |
| test-chat.html | 4 ماه پیش |
一个基于LangChain v1.1.0、FastAPI、OpenAI模型及 create_agent 智能体的聊天系统,支持流式输出。
cd baoshi-ai-agent
# Windows
python -m venv venv
venv\Scripts\activate
# Linux/Mac
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
创建 .env 文件(在项目根目录),添加您的 OpenAI API 密钥:
OPENAI_API_KEY=sk-xxxx
或者直接设置环境变量:
# Windows PowerShell
$env:OPENAI_API_KEY="sk-xxxx"
# Linux/Mac
export OPENAI_API_KEY="sk-xxxx"
获取API密钥: 前往 OpenAI 控制台 生成 API Key。
python main.py
uvicorn main:app --host 0.0.0.0 --port 8080 --reload
注意: 如果直接运行 python main.py 遇到启动错误,建议使用方式2(命令行启动),这种方式更稳定可靠。
应用启动后,访问:
POST /chat
请求体:
{
"message": "你好,请介绍一下你自己",
"conversation_id": "default"
}
响应:
{
"content": "我是通义千问...",
"conversation_id": "default"
}
POST /chat/stream
请求体:
{
"message": "写一首关于春天的诗",
"conversation_id": "default"
}
响应:Server-Sent Events (SSE) 流式数据
GET /
返回API基本信息
import requests
import json
# 非流式聊天
response = requests.post(
"http://localhost:8080/chat",
json={
"message": "你好",
"conversation_id": "test-001"
}
)
print(response.json())
# 流式聊天
response = requests.post(
"http://localhost:8080/chat/stream",
json={
"message": "写一首诗",
"conversation_id": "test-001"
},
stream=True
)
for line in response.iter_lines():
if line:
decoded_line = line.decode('utf-8')
if decoded_line.startswith('data: '):
data = decoded_line[6:] # 移除 'data: ' 前缀
if data == '[DONE]':
break
print(data, end='', flush=True)
# 非流式聊天
curl -X POST "http://localhost:8080/chat" \
-H "Content-Type: application/json" \
-d '{"message": "你好", "conversation_id": "test-001"}'
# 流式聊天
curl -X POST "http://localhost:8080/chat/stream" \
-H "Content-Type: application/json" \
-d '{"message": "写一首诗", "conversation_id": "test-001"}' \
--no-buffer
// 流式聊天
async function streamChat(message) {
const response = await fetch('http://localhost:8080/chat/stream', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: message,
conversation_id: 'test-001'
})
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') return;
console.log(data);
}
}
}
}
streamChat('你好');
create_agent 会将 LLM 与工具列表绑定成可调用的智能体。main.py 中通过 ChatOpenAI 配置模型(默认 gpt-4o-mini)。get_current_time: 返回服务器当前时间。summarize_project: 输出项目简介(可替换为数据库/知识库查询)。可根据需要扩展更多工具,或更换模型名称:
openai_model = ChatOpenAI(
model="gpt-4o", # 支持 gpt-4o / gpt-4o-mini / gpt-4.1 等
temperature=0.7,
streaming=True,
)
agent = create_agent(
model=openai_model,
tools=tools, # 自定义 Tool 列表
system_prompt="自定义系统提示",
)
默认端口为 8080,可以在 main.py 中修改,或通过命令行参数指定:
# 命令行方式(推荐)
uvicorn main:app --host 0.0.0.0 --port 8080
# 或在 main.py 中修改端口号
OPENAI_API_KEY 环境变量解决方案: 检查 .env 文件或环境变量中的 OPENAI_API_KEY 是否正确设置。
解决方案: 确保已安装所有依赖:
pip install -r requirements.txt
解决方案: 修改 main.py 中的端口号,或关闭占用端口的程序。
MIT License
欢迎提交Issue和Pull Request!