|
|
vor 16 Stunden | |
|---|---|---|
| .. | ||
| skills | vor 16 Stunden | |
| .env.example | vor 16 Stunden | |
| README.md | vor 16 Stunden | |
| run.py | vor 16 Stunden | |
这是一个可直接用于生产环境的 Agent 模板项目。
# 从项目根目录安装
pip install -r requirements.txt
pip install dbutils pymysql # browser 模块依赖
创建 .env 文件:
# LLM 配置
OPENROUTER_API_KEY=your-api-key-here
MODEL=anthropic/claude-sonnet-4.5
TEMPERATURE=0.3
MAX_ITERATIONS=30
# 存储配置
TRACE_DIR=.cache/traces
OUTPUT_DIR=.cache/output
# Skills 配置
SKILLS_DIR=./skills
ENABLED_SKILLS=planning,research
# 从项目根目录运行
python examples/production_template/run.py
# 或进入目录运行
cd examples/production_template
python run.py
production_template/
├── run.py # 主程序
├── .env # 环境变量配置
├── skills/ # Skills 目录
│ └── custom.md # 自定义 Skill
└── .cache/ # 缓存目录
├── traces/ # Trace 存储
├── output/ # 结果输出
└── agent.log # 日志文件
统一管理所有配置项,从环境变量读取:
config = AgentConfig()
print(config.model) # anthropic/claude-sonnet-4.5
使用 @tool 装饰器定义工具:
@tool(description="你的工具描述")
async def your_tool(param: str, ctx: ToolContext = None) -> ToolResult:
# 你的业务逻辑
return ToolResult(title="成功", output="结果")
封装了 AgentRunner,提供简洁的 API:
agent = ProductionAgent(config)
result = await agent.run("你的任务")
自动记录到文件和控制台:
logger.info("信息日志")
logger.error("错误日志", exc_info=True)
在 run.py 中添加:
@tool(description="你的新工具")
async def new_tool(param: str, ctx: ToolContext = None) -> ToolResult:
try:
# 业务逻辑
result = do_something(param)
return ToolResult(
title="成功",
output=result,
data={"param": param, "result": result},
)
except Exception as e:
logger.error(f"工具执行失败: {e}", exc_info=True)
return ToolResult(
title="失败",
output=str(e),
error=True,
)
创建 skills/your-skill.md:
---
name: your-skill
description: 你的技能描述
---
# 你的技能
## 何时使用
- 场景1
- 场景2
## 使用指南
1. 步骤1
2. 步骤2
在 .env 中启用:
ENABLED_SKILLS=planning,research,your-skill
在 main() 函数中修改 task 变量:
task = """
你的任务描述
"""
result = await agent.run(task)
创建 Dockerfile:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "run.py"]
构建和运行:
docker build -t my-agent .
docker run --env-file .env my-agent
添加监控:
# 在 ProductionAgent 中添加
def _send_alert(self, message: str):
"""发送告警"""
# 集成你的告警系统(钉钉、企业微信等)
pass
# 在异常处理中调用
except Exception as e:
self._send_alert(f"Agent 执行失败: {e}")
# 1. 使用更快的模型
MODEL=anthropic/claude-haiku-4.5
# 2. 限制迭代次数
MAX_ITERATIONS=20
# 3. 启用 Prompt Caching
config = RunConfig(enable_prompt_caching=True)
async def run_with_retry(self, task: str, max_retries: int = 3):
"""带重试的运行"""
for attempt in range(max_retries):
try:
return await self.run(task)
except Exception as e:
if attempt == max_retries - 1:
raise
logger.warning(f"重试 {attempt + 1}/{max_retries}: {e}")
await asyncio.sleep(2 ** attempt) # 指数退避
# 设置日志级别为 DEBUG
logging.basicConfig(level=logging.DEBUG)
# 启动 API Server
python api_server.py
# 访问
http://localhost:8000/api/traces
# 增加最大迭代次数
MAX_ITERATIONS=100
# 或使用异步任务队列(Celery、RQ 等)