基于 LangGraph ReAct 的深度搜索 Agent,使用 Qwen 3.5 Plus 和 Tavily 搜索。
- 多轮对话支持 - 使用 LangGraph 内置 checkpointer 维护对话状态
- 智能上下文摘要 - 对话过长时自动触发 LLM 摘要,减少 token 消耗
- 流式输出 - 支持流式响应
- 多线程会话 - 支持多个独立对话线程
# 1. 安装依赖
pip install -r requirements.txt
# 2. 配置环境变量
cp .env.example .env
# 编辑 .env 填入你的 API keys
# 3. 运行示例
python examples/basic_usage.pyfrom deep_search_agent import DeepSearchAgent, AgentConfig
# 初始化
config = AgentConfig(model_name="qwen-plus")
agent = DeepSearchAgent(config)
# 单轮对话
response = agent.chat("查找 LangGraph 最新特性")
print(response)
# 多轮对话(自动维护上下文)
response = agent.chat("详细说明其中一点")
# 流式输出
for chunk in agent.stream_chat("搜索 Python 异步编程"):
print(chunk, end="")
# 多线程会话
response = agent.chat("问题1", thread_id="session_1")
response = agent.chat("问题2", thread_id="session_2")
# 重置对话
agent.reset()
# 查看上下文统计
print(agent.get_context_summary())- DashScope: https://dashscope.aliyun.com/
- Tavily: https://tavily.com/
使用 LangGraph InMemorySaver 作为 checkpointer,配合自定义 ConversationMemory 类实现智能摘要:
# 当消息数超过阈值时自动触发摘要
if len(messages) >= config.max_messages_before_summary:
summary, recent_messages = memory.summarize(messages, llm)
# 用摘要替代旧消息,保留最近 N 条{
"messages": List[BaseMessage], # 当前窗口的消息
"summary": Optional[str] # 历史摘要
}| 参数 | 说明 | 默认值 |
|---|---|---|
| model_name | Qwen 模型名称 | qwen-plus |
| max_search_rounds | 最大搜索轮数 | 5 |
| max_messages_before_summary | 触发摘要的消息数 | 10 |
| max_messages_keep_after_summary | 摘要后保留的消息数 | 5 |
| tavily_max_results | 搜索结果数量 | 5 |
deep_search_agent/
├── __init__.py # 包导出
├── agent.py # 核心 Agent 类
├── config.py # 配置管理
├── memory.py # 上下文摘要逻辑
└── tools.py # Tavily 搜索工具
tests/
├── test_agent.py # Agent 测试
├── test_memory.py # Memory 测试
└── test_tools.py # Tools 测试
examples/
└── basic_usage.py # 使用示例