这是一个完整的 AI Agent 学习项目,展示了如何使用 ReAct 范式构建智能代理,并集成了 RAG(检索增强生成)功能。
.
├── first-call.py # 手动实现的 ReAct Agent(学习原理)
├── langchain_agent.py # 使用 LangGraph 框架的 Agent(生产环境)
├── tools.py # Agent 工具函数定义
├── build_rag_hf.py # RAG 知识库构建脚本
├── build_rag_index.py # RAG 索引构建脚本(简化版)
├── knowledge.txt # 知识库文档
├── requirements.txt # 项目依赖
├── Dockerfile # Docker 镜像构建文件
├── docker-compose.yml # Docker Compose 配置
├── .dockerignore # Docker 忽略文件
└── README.md # 项目说明文档
pip install -r requirements.txt创建 .env 文件,添加以下配置:
# OpenRouter API(必需)
OPENROUTER_API_KEY=your_openrouter_api_key
# Google Search API(可选,用于 real_search 工具)
Custom_Google_Search_API=your_google_search_api_key
GOOGLE_CSE_ID=your_cse_idpython first-call.py这个版本展示了 ReAct 范式的完整实现过程,包括:
- 手动解析 LLM 输出
- 手动管理对话历史
- 手动实现工具调用循环
python langchain_agent.py这个版本使用 LangGraph 框架,代码更简洁,适合生产环境。
使用 Dockerfile 构建和运行:
# 构建镜像
docker build -t react-agent-tutorial .
# 运行容器(交互式)
docker run -it --rm \
-v $(pwd)/.env:/app/.env:ro \
-v $(pwd)/knowledge.txt:/app/knowledge.txt:rw \
-v $(pwd)/faiss_index:/app/faiss_index:rw \
react-agent-tutorial使用 Docker Compose(推荐):
# 启动服务(运行 first-call.py)
docker-compose up
# 运行 langchain_agent.py
docker-compose run react-agent python langchain_agent.py
# 后台运行
docker-compose up -d
# 查看日志
docker-compose logs -f
# 停止服务
docker-compose down执行简单的数学运算(二元运算)
示例:
10 + 520 * 3100 / 4
实时互联网搜索(需要配置 Google Search API)
示例:
- "北京天气"
- "最新新闻"
- "xAI 创始人"
查询本地知识库(RAG)
使用前需要先构建索引:
python build_rag_hf.py深度逻辑推理工具,用于解决复杂问题
- 编辑
knowledge.txt文件,添加你的知识内容 - 运行构建脚本:
python build_rag_hf.py
- 索引会保存在
faiss_index/目录
在 Agent 对话中,Agent 会自动使用 query_local_knowledge 工具来查询知识库。
示例对话:
用户: 什么是 ReAct 范式?
Agent: [自动调用 query_local_knowledge] → 返回相关知识
- Thought: Agent 思考当前情况
- Action: Agent 选择并执行工具
- Observation: Agent 观察工具执行结果
- Final Answer: Agent 基于观察给出最终答案
- 大脑 (LLM): 负责思考和决策
- 记忆 (Message History): 保存对话历史
- 工具 (Tools): Agent 可以调用的函数
- 解析器 (Parser): 解析 LLM 输出
- 文档加载和分割
- 向量嵌入和索引构建
- 相似度搜索
- 知识检索和生成
- 如何定义工具函数
- 如何使用 LangChain 的
@tool装饰器 - 如何将工具集成到 Agent 中
手动实现的 ReAct Agent,包含:
parse_output(): 使用正则表达式解析 LLM 输出get_llm_response(): 调用 LLM APIrun_agent_loop(): 主循环,实现 ReAct 范式
使用 LangGraph 框架的 Agent:
- 使用
create_react_agent()自动创建 Agent - 使用流式输出显示思考过程
- 更简洁的代码结构
工具函数定义:
simple_calculator: 安全计算器real_search: Google 搜索集成query_local_knowledge: RAG 知识库查询deep_think: 深度推理工具
RAG 知识库构建脚本:
- 使用 HuggingFace 本地嵌入模型(免费)
- 文档分割和向量化
- FAISS 索引构建和保存
- Python 3.8+
- OpenAI API (通过 OpenRouter)
- LangChain: Agent 框架
- LangGraph: Agent 工作流框架
- FAISS: 向量数据库
- HuggingFace Embeddings: 本地嵌入模型
- Google Search API: 实时搜索
- 基础理解: 阅读
first-call.py,理解 ReAct 范式的基本实现 - 框架学习: 对比
langchain_agent.py,学习如何使用框架简化开发 - 工具开发: 研究
tools.py,学习如何定义和集成工具 - RAG 实践: 运行
build_rag_hf.py,理解 RAG 的工作原理 - 项目扩展: 添加自己的工具和知识库
- API 密钥: 确保正确配置所有必需的 API 密钥
- RAG 索引: 使用 RAG 功能前需要先构建索引
- 编码问题: Windows 系统可能需要设置 UTF-8 编码
- 依赖版本: 注意 LangChain 版本兼容性
欢迎提交 Issue 和 Pull Request!
本项目仅用于学习目的。
Created with ❤️ by Lewis