AI智能体, Python、LangChain

fengyanglei c7ab038dbe start.sh преди 4 месеца
.gitignore c15cc493fc init преди 4 месеца
README.md cef7727e1c demo преди 4 месеца
main.py cef7727e1c demo преди 4 месеца
requirements.txt cef7727e1c demo преди 4 месеца
start.sh c7ab038dbe start.sh преди 4 месеца
test-chat.html cef7727e1c demo преди 4 месеца

README.md

AI Agent

一个基于LangChain v1.1.0、FastAPI、OpenAI模型及 create_agent 智能体的聊天系统,支持流式输出。

技术栈

  • 语言: Python 3.10+
  • 框架:
    • FastAPI - Web框架
    • LangChain v1.1.0 - AI应用框架(最新版本)
    • Uvicorn - ASGI服务器
  • 模型: OpenAI Chat Completions (如 gpt-4o, qwen-plus)
  • 特性: create_agent 智能体、工具调用、流式输出 (Server-Sent Events)

功能特性

  • ✅ 基于LangChain v1.1.0框架
  • ✅ FastAPI RESTful API
  • ✅ OpenAI模型集成
  • ✅ create_agent 智能体 + 工具调用
  • ✅ 流式输出支持
  • ✅ 异步处理
  • ✅ API文档自动生成 (Swagger UI)

安装步骤

1. 克隆或下载项目

cd baoshi-ai-agent

2. 创建虚拟环境(推荐)

# Windows
python -m venv venv
venv\Scripts\activate

# Linux/Mac
python -m venv venv
source venv/bin/activate

3. 安装依赖

pip install -r requirements.txt

4. 配置API密钥

创建 .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。

运行应用

方式1: 直接运行

python main.py

方式2: 使用Uvicorn(推荐)

uvicorn main:app --host 0.0.0.0 --port 8080 --reload

注意: 如果直接运行 python main.py 遇到启动错误,建议使用方式2(命令行启动),这种方式更稳定可靠。

应用启动后,访问:

API接口

1. 非流式聊天接口

POST /chat

请求体:

{
  "message": "你好,请介绍一下你自己",
  "conversation_id": "default"
}

响应:

{
  "content": "我是通义千问...",
  "conversation_id": "default"
}

2. 流式聊天接口

POST /chat/stream

请求体:

{
  "message": "写一首关于春天的诗",
  "conversation_id": "default"
}

响应:Server-Sent Events (SSE) 流式数据

3. 根路径

GET /

返回API基本信息

使用示例

Python示例

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示例

# 非流式聊天
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

JavaScript示例

// 流式聊天
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('你好');

配置说明

OpenAI模型 & create_agent 智能体

  • 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 中修改端口号

注意事项

  1. 确保已正确设置 OPENAI_API_KEY 环境变量
  2. OpenAI 模型调用需要稳定的网络连接
  3. 流式输出使用Server-Sent Events (SSE)协议
  4. 建议在生产环境中使用HTTPS和适当的认证机制

故障排除

问题: API密钥错误

解决方案: 检查 .env 文件或环境变量中的 OPENAI_API_KEY 是否正确设置。

问题: 模块导入错误

解决方案: 确保已安装所有依赖:

pip install -r requirements.txt

问题: 端口被占用

解决方案: 修改 main.py 中的端口号,或关闭占用端口的程序。

许可证

MIT License

贡献

欢迎提交Issue和Pull Request!