
agent pydanticai
ReAct Agent implementation with configuration management
Repository Info
About This Server
ReAct Agent implementation with configuration management
Model Context Protocol (MCP) - This server can be integrated with AI applications to provide additional context and capabilities, enabling enhanced AI interactions and functionality.
Documentation
ReAct Agent with Configuration Management
基于 ReAct(Reasoning + Acting)设计模式的智能体实现,支持配置文件管理和详细的调试日志系统。
🎯 项目特点
- 🧠 ReAct 设计模式: 结合推理和行动的智能体架构
- ⚙️ 配置管理: 支持配置文件和环境变量管理
- 🔍 详细日志: 完整的调试日志系统,可视化 ReAct 执行过程
- 🔧 多 API 支持: 支持 OpenAI 和 OpenRouter 等多种 API 提供商
- 🛠️ 工具集成: 内置计算器、搜索、天气等工具
- 📡 MCP 协议支持: 集成 Model Context Protocol,支持外部工具和数据源
- 🔒 安全保护: 敏感信息不会被提交到版本控制
📁 项目结构
├── src/
│ ├── react_agent_simple.py # 主要的 ReAct Agent 实现
│ ├── config.py # 配置管理模块
│ ├── mcp_client.py # MCP 客户端实现
│ └── mcp_demo.py # MCP 功能演示脚本
├── config.env # 配置文件(不会提交到 Git)
├── config.env.template # 配置文件模板
├── install_mcp.py # MCP 安装脚本
├── mcp_servers.toml # MCP 服务器配置(安装后生成)
├── .gitignore # Git 忽略文件
├── README.md # 项目说明文档
└── .venv/ # Python 虚拟环境
🚀 快速开始
1. 环境设置
# 克隆仓库
git clone https://github.com/alex-llm/agent-pydanticai.git
cd agent-pydanticai
# 创建并激活虚拟环境
python -m venv .venv
# Windows
.venv\Scripts\activate
# Linux/macOS
source .venv/bin/activate
# 安装依赖
pip install openai pydantic
2. 配置 API 密钥
方法一:使用配置文件(推荐)
# 复制配置模板
cp config.env.template config.env
# 编辑 config.env 文件,填入你的 API 密钥
# OPENAI_API_KEY=your_api_key_here
方法二:使用环境变量
# Windows (PowerShell)
$env:OPENAI_API_KEY="your_api_key_here"
# Windows (CMD)
set OPENAI_API_KEY=your_api_key_here
# Linux/macOS
export OPENAI_API_KEY="your_api_key_here"
3. 运行 Agent
python src/react_agent_simple.py
⚙️ 配置选项
API 配置
| 配置项 | 说明 | 默认值 | 示例 |
|---|---|---|---|
OPENAI_API_KEY | API 密钥(必填) | - | sk-... 或 sk-or-v1-... |
API_BASE_URL | API 基础 URL | 自动检测 | https://openrouter.ai/api/v1 |
API_MODEL | 使用的模型 | openai/gpt-4o-mini | gpt-4o, openai/gpt-4o-mini |
Agent 配置
| 配置项 | 说明 | 默认值 | 范围 |
|---|---|---|---|
MAX_ITERATIONS | 最大迭代次数 | 5 | 1-20 |
TEMPERATURE | 模型温度参数 | 0.2 | 0.0-2.0 |
DEBUG_MODE | 调试模式 | true | true/false |
日志配置
| 配置项 | 说明 | 默认值 | 选项 |
|---|---|---|---|
LOG_LEVEL | 日志级别 | INFO | DEBUG, INFO, WARNING, ERROR |
LOG_FILE | 日志文件路径 | react_agent.log | 任意文件路径 |
MCP 配置
| 配置项 | 说明 | 默认值 | 选项 |
|---|---|---|---|
MCP_ENABLED | 是否启用 MCP 支持 | false | true/false |
MCP_SERVERS | MCP 服务器列表(逗号分隔) | - | filesystem,git,sqlite |
MCP_FILESYSTEM_BASE_DIR | 文件系统服务器基础目录 | . | 任意目录路径 |
MCP_GIT_REPOSITORY | Git 服务器仓库路径 | . | 任意 Git 仓库路径 |
MCP_SQLITE_DB_PATH | SQLite 数据库路径 | database.db | 任意数据库文件路径 |
🔧 支持的 API 提供商
OpenAI
OPENAI_API_KEY=sk-...
API_MODEL=gpt-4o
OpenRouter
OPENAI_API_KEY=sk-or-v1-...
API_BASE_URL=https://openrouter.ai/api/v1
API_MODEL=openai/gpt-4o-mini
自定义 API 服务
OPENAI_API_KEY=your_custom_key
API_BASE_URL=https://your-api-server.com/v1
API_MODEL=your_model_name
🎯 ReAct 模式说明
ReAct (Reasoning + Acting) 是一种 AI Agent 设计模式,包含以下循环:
🧠 Reasoning (推理) → ⚡ Acting (行动) → 👁️ Observation (观察) → 🔄 循环
执行流程
- 🧠 Reasoning: Agent 分析问题,制定行动计划
- ⚡ Acting: Agent 选择并执行具体的工具
- 👁️ Observation: Agent 观察工具执行结果
- 🔄 循环: 基于观察结果继续推理,直到得出最终答案
调试日志示例
🎬 [开始] ReAct Agent 开始处理用户查询
❓ [用户查询] 计算 (23 * 4) / 2 的结果
🔄 [第 1 轮] ReAct 循环开始
🧠 [Reasoning] 开始推理阶段...
🧠 [思考] 用户需要进行数学计算,我应该使用计算器工具
⚡ [Acting] 开始行动阶段...
🧮 [工具调用] 计算器 - 表达式: (23 * 4) / 2
✅ [工具结果] 计算器 - 结果: 46.0
👁️ [Observation] 开始观察阶段...
🎯 [完成] 检测到最终答案,ReAct 循环结束
✅ [结果] 最终答案: 46.0
🛠️ 可用工具
内置工具
| 工具 | 功能 | 输入示例 | 输出示例 |
|---|---|---|---|
| calculator | 数学计算 | (23 * 4) / 2 | 46.0 |
| search | 信息搜索(模拟) | 人工智能 | 搜索结果: 人工智能 的相关信息 |
| weather | 天气查询(模拟) | 北京 | 北京的天气: 晴天,温度25°C |
MCP 工具(需要启用 MCP 支持)
| 工具 | 功能 | 输入示例 | 输出示例 |
|---|---|---|---|
| filesystem:read_file | 读取文件内容 | {"path": "README.md"} | 文件内容文本 |
| filesystem:write_file | 写入文件内容 | {"path": "test.txt", "content": "Hello"} | 写入成功确认 |
| filesystem:list_directory | 列出目录内容 | {"path": "."} | 文件和目录列表 |
| filesystem:search_files | 搜索文件 | {"pattern": "*.py"} | 匹配的文件列表 |
| git:git_status | Git 状态查看 | {} | Git 仓库状态信息 |
| git:git_log | Git 提交历史 | {"limit": 5} | 最近提交记录 |
| sqlite:execute_query | 执行 SQL 查询 | {"query": "SELECT * FROM users"} | 查询结果 |
| sqlite:list_tables | 列出数据库表 | {} | 表名列表 |
📝 使用示例
基本使用
from src.react_agent_simple import SimpleReActAgent
# 使用配置文件
agent = SimpleReActAgent()
# 运行查询
result = agent.run("计算 (23 * 4) / 2 的结果")
print(result) # 输出: 46.0
自定义配置
# 手动指定配置
agent = SimpleReActAgent(
api_key="your_api_key",
base_url="https://api.openai.com/v1",
debug=True
)
# 自定义迭代次数
result = agent.run("复杂问题", max_iterations=10)
批量处理
queries = [
"计算 100 * 50 / 25",
"北京的天气如何?",
"搜索机器学习相关信息"
]
for query in queries:
result = agent.run(query)
print(f"问题: {query}")
print(f"答案: {result}\n")
🐛 调试和故障排除
查看配置信息
运行程序时会自动显示当前配置(敏感信息会被隐藏):
📋 [配置信息]
🔑 API 密钥: ***0118
🌐 API 基础 URL: https://openrouter.ai/api/v1
🤖 API 模型: openai/gpt-4o-mini
查看详细日志
# 查看日志文件
cat react_agent.log
# 实时查看日志(Linux/macOS)
tail -f react_agent.log
# Windows PowerShell
Get-Content react_agent.log -Wait
调整日志级别
在 config.env 中设置:
LOG_LEVEL=DEBUG # 显示更详细的调试信息
常见问题
1. API 密钥错误
❌ [错误] 未找到 API 密钥!
💡 [解决方案] 请执行以下步骤之一:
1. 在 config.env 文件中设置 OPENAI_API_KEY
2. 设置环境变量: export OPENAI_API_KEY=your_api_key
2. API 调用失败
❌ [API错误] API 调用失败: Error code: 401
🔄 [切换] 切换到模拟模式...
3. 模型不支持
检查你的 API 提供商是否支持指定的模型,并在 config.env 中更新 API_MODEL。
🔒 安全注意事项
-
🔐 API 密钥保护
config.env文件已被添加到.gitignore- 永远不要将 API 密钥提交到版本控制系统
- 使用环境变量在生产环境中管理密钥
-
📄 日志安全
- 日志文件
*.log被排除在版本控制之外 - 敏感信息在日志中会被部分隐藏
- 日志文件
-
🔧 配置模板
- 使用
config.env.template分享配置结构 - 不要在模板中包含真实的 API 密钥
- 使用
🚀 扩展开发
添加新工具
def new_tool(input_param: str) -> str:
"""新工具的实现"""
# 工具逻辑
return result
# 在 SimpleReActAgent 中注册
self.tools["new_tool"] = new_tool
自定义系统提示
修改 SimpleReActAgent 类中的 system_prompt 来改变 Agent 的行为模式。
添加新的配置选项
在 src/config.py 中添加新的配置属性,并在 config.env.template 中添加说明。
📄 许可证
MIT License
🤝 贡献
欢迎提交 Issue 和 Pull Request!
- Fork 这个仓库
- 创建你的特性分支 (
git checkout -b feature/AmazingFeature) - 提交你的更改 (
git commit -m 'Add some AmazingFeature') - 推送到分支 (
git push origin feature/AmazingFeature) - 打开一个 Pull Request
📡 MCP (Model Context Protocol) 支持
什么是 MCP?
MCP (Model Context Protocol) 是一个开放协议,用于连接 AI 应用与外部数据源和工具。它提供了一种标准化的方式来扩展 AI Agent 的能力。
MCP 功能特点
- 🔧 动态工具发现: 自动发现和加载 MCP 服务器提供的工具
- 📁 文件系统操作: 读取、写入、搜索文件和目录
- 🔄 Git 仓库管理: 查看状态、提交历史、分支管理等
- 🗄️ 数据库访问: SQLite 数据库查询和操作
- 🔌 可扩展架构: 支持自定义 MCP 服务器
安装 MCP 支持
自动安装(推荐)
# 运行 MCP 安装脚本
python install_mcp.py
手动安装
# 安装 MCP 核心库
pip install mcp
# 安装 MCP 服务器
pip install mcp-server-filesystem
pip install mcp-server-git
pip install mcp-server-sqlite
# 在 config.env 中启用 MCP
echo "MCP_ENABLED=true" >> config.env
echo "MCP_SERVERS=filesystem,git" >> config.env
MCP 配置示例
# 启用 MCP 支持
MCP_ENABLED=true
# 配置要使用的 MCP 服务器
MCP_SERVERS=filesystem,git,sqlite
# 文件系统服务器配置
MCP_FILESYSTEM_BASE_DIR=./workspace
# Git 服务器配置
MCP_GIT_REPOSITORY=.
# SQLite 服务器配置
MCP_SQLITE_DB_PATH=./data/app.db
支持的 MCP 服务器
| 服务器 | 功能 | 提供的工具 |
|---|---|---|
| filesystem | 文件系统操作 | read_file, write_file, list_directory, search_files |
| git | Git 仓库管理 | git_status, git_log, git_diff, git_branch |
| sqlite | SQLite 数据库 | execute_query, list_tables, describe_table |
MCP 使用示例
文件系统操作
# Agent 可以自动使用 MCP 文件系统工具
result = agent.run("列出当前目录下的所有 Python 文件")
result = agent.run("读取 config.py 文件的内容")
result = agent.run("在项目中搜索包含 'MCP' 的文件")
Git 操作
# Agent 可以自动使用 MCP Git 工具
result = agent.run("查看当前 Git 仓库的状态")
result = agent.run("显示最近 5 次提交记录")
result = agent.run("查看当前分支和所有分支")
数据库操作
# Agent 可以自动使用 MCP SQLite 工具
result = agent.run("列出数据库中的所有表")
result = agent.run("查询用户表中的前 10 条记录")
result = agent.run("统计订单表中的记录数量")
MCP 演示
运行 MCP 功能演示:
python src/mcp_demo.py
这将展示:
- MCP 服务器连接过程
- 可用工具的自动发现
- 各种 MCP 工具的使用示例
- 详细的执行日志
📞 联系方式
如果你有任何问题或建议,请通过 GitHub Issues 联系我们。
Quick Start
Clone the repository
git clone https://github.com/alex-llm/agent-pydanticaiInstall dependencies
cd agent-pydanticai
npm installFollow the documentation
Check the repository's README.md file for specific installation and usage instructions.
Repository Details
Recommended MCP Servers
Discord MCP
Enable AI assistants to seamlessly interact with Discord servers, channels, and messages.
Knit MCP
Connect AI agents to 200+ SaaS applications and automate workflows.
Apify MCP Server
Deploy and interact with Apify actors for web scraping and data extraction.
BrowserStack MCP
BrowserStack MCP Server for automated testing across multiple browsers.
Zapier MCP
A Zapier server that provides automation capabilities for various apps.