Claude代理框架
一个模块化、生产就绪的框架,用于在自动化工作流程中运行Claude代理。非常适合cron作业、服务、数据处理、日志分析以及任何受益于AI自动化的任务。
特性
- 灵活的执行模式:运行一次(cron)、连续运行(service)、按计划运行或通过webhooks运行
- Webhook服务器:从外部事件触发代理(线性、GitHub、自定义集成)
- 条件路由:按字段值(受让人、优先级、状态等)过滤webhook事件
- 完全代理SDK支持:所有Claude Agent SDK功能,包括工具、子代理、MCP服务器
- AWS基岩集成:通过AWS Bedrock使用Claude,并提供完整的身份验证支持
- 全面配置:通过配置
.env、YAML或以编程方式 - 富途:用于配置管理的交互式终端界面
- 成本跟踪:通过预算执行监控代币使用和成本
- 完整日志记录:使用结构化日志记录完成代理跟踪
- Slack通知:通过webhook将结果发送到Slack
- 子代理支持:为复杂的工作流程定义专门的子代理
- MCP服务器集成:通过模型上下文协议连接外部工具
安装
# Install from source
pip install -e .
# Or install with development dependencies
pip install -e ".[dev]"需求
- Python 3.10+
- Claude代理SDK(
claude-agent-sdk>=0.1.12) - Anthropic API密钥或AWS Bedrock访问
快速开始
1.生成配置
# Generate .env template
caf config --generate-env
# Or use the interactive TUI
caf config --tui2.设置API密钥
# In .env file
ANTHROPIC_API_KEY=sk-ant-...
# Or for AWS Bedrock
CAF_BEDROCK__ENABLED=true
CAF_BEDROCK__REGION=us-east-13.运行你的第一个任务
# Simple one-off task
caf run "Analyze the Python files in this directory for code quality issues"
# From a prompt file
caf run -f prompts/daily_check.md
# With budget limit
caf run "Check database logs for errors" --max-budget 1.0执行模式
一次性执行(Cron模式)
非常适合通过cron执行计划任务:
# Run once and exit
caf run "Generate daily report from logs in /var/log/app"
# Example crontab entry (runs at 2 AM daily)
0 2 * * * cd /path/to/project && caf run -f prompts/daily_report.md服务模式
具有可配置间隔的连续执行:
# Run every hour
caf service "Monitor application health" --interval 3600
# Run every 30 minutes
caf service -f prompts/monitor.md -i 1800Cron计划模式
内置cron表达式支持:
# Run at 2 AM every day
caf cron "Daily backup verification" --schedule "0 2 * * *"
# Run every hour
caf cron -f prompts/hourly_check.md -s "0 * * * *"Webhook模式
从外部事件(如线性问题、GitHub PR或自定义Webhook)触发代理:
# Start webhook server
caf webhook
# With custom port and routes
caf webhook --port 8080 --routes webhook_routes.yaml
# Generate example routes
caf webhook --generate-routes示例:自动处理分配给“Claude”的线性问题
# webhook_routes.yaml
- event_pattern: Issue.update
conditions:
- field: assignee.name
operator: equals
value: Claude
- field: assignee
operator: changed
prompt_template: |
You've been assigned to: {title}
Use Linear MCP tools to:
1. Move to "In Progress"
2. Add acknowledgment comment
3. Work on the issue
4. Update with progress看 WEBHOOKS.md 获取完整的webhook文档和 示例/LINEAR_MCP_WEBHOOK_SETUP.md 用于线性积分指南。
配置
环境变量
所有设置都可以通过环境变量进行配置 CAF_ 前缀:
# Core Settings
ANTHROPIC_API_KEY=sk-ant-...
CAF_AGENT__NAME=my-agent
CAF_AGENT__MODEL=sonnet
CAF_AGENT__MAX_TURNS=50
CAF_AGENT__MAX_BUDGET_USD=10.0
# AWS Bedrock
CAF_BEDROCK__ENABLED=true
CAF_BEDROCK__REGION=us-east-1
CAF_BEDROCK__PROFILE=default
# Webhook Server
CAF_WEBHOOK__ENABLED=true
CAF_WEBHOOK__HOST=0.0.0.0
CAF_WEBHOOK__PORT=8000
CAF_WEBHOOK__LINEAR_WEBHOOK_SECRET=whsec_...
CAF_WEBHOOK__ROUTES_FILE=./webhook_routes.yaml
# Slack Notifications
CAF_SLACK__ENABLED=true
CAF_SLACK__WEBHOOK_URL=https://hooks.slack.com/...
CAF_SLACK__NOTIFY_ON_SUCCESS=true
CAF_SLACK__NOTIFY_ON_ERROR=true
# Logging
CAF_LOGGING__LOG_DIR=./logs
CAF_LOGGING__LOG_LEVEL=INFO
CAF_LOGGING__LOG_AGENT_TRACE=trueYAML配置
对于复杂的配置,请使用YAML文件:
# config.yaml
agent:
name: data-processor
model: sonnet
max_turns: 100
system_prompt_type: append
system_prompt_content: |
You are a data processing specialist.
Focus on accuracy and efficiency.
sub_agents:
- name: data-validator
description: Validates data quality and integrity
prompt: |
You are a data validation specialist.
Check for missing values, outliers, and inconsistencies.
tools:
- Read
- Grep
- Bash
slack:
enabled: true
webhook_url: ${SLACK_WEBHOOK_URL}
notify_on_success: true
include_cost: true
logging:
log_dir: ./logs
log_agent_trace: true
separate_trace_file: true交互式TUI
启动交互式配置界面:
caf config --tui
# Or directly
caf-tuiTUI提供:
- 可视化配置编辑
- 子代理管理
- MCP服务器设置
- Slack通知配置
- 配置测试
分代理
为复杂的工作流定义专门的子代理:
sub_agents:
- name: code-reviewer
description: Expert code reviewer for security and quality
prompt: |
You are an expert code reviewer.
Focus on security vulnerabilities and best practices.
tools:
- Read
- Grep
- Glob
model: sonnet
- name: log-analyzer
description: Analyzes application logs for errors
prompt: |
You are a log analysis expert.
Identify error patterns and root causes.
tools:
- Read
- Grep
- Bash内置代理模板
为常见用例使用预构建模板:
from claude_agent_framework.agents import (
CODE_REVIEWER_AGENT,
DATA_ANALYST_AGENT,
LOG_ANALYZER_AGENT,
SECURITY_AUDITOR_AGENT,
)
settings.sub_agents = [CODE_REVIEWER_AGENT, LOG_ANALYZER_AGENT]MCP服务器集成
通过MCP连接外部工具:
mcp_servers:
- name: filesystem
type: stdio
command: npx
args:
- "@modelcontextprotocol/server-filesystem"
env:
ALLOWED_PATHS: /data
- name: database
type: http
url: https://api.example.com/mcp
headers:
Authorization: Bearer ${DB_API_KEY}记录和跟踪
完整的执行跟踪会自动保存:
logs/
├── my-agent.log # Main log file
├── my-agent_trace.jsonl # Structured trace (JSONL)
├── session_20241201_trace.jsonl # Per-session trace
├── trace_abc123.json # Full execution result
└── costs.json # Cost tracking data日志配置
CAF_LOGGING__ENABLED=true
CAF_LOGGING__LOG_DIR=./logs
CAF_LOGGING__LOG_LEVEL=INFO
CAF_LOGGING__LOG_AGENT_TRACE=true
CAF_LOGGING__SEPARATE_TRACE_FILE=true
CAF_LOGGING__ROTATE_LOGS=true
CAF_LOGGING__MAX_LOG_SIZE_MB=10Slack通知
通过Slack接收执行结果:
CAF_SLACK__ENABLED=true
CAF_SLACK__WEBHOOK_URL=https://hooks.slack.com/services/...
CAF_SLACK__USERNAME=Claude Agent
CAF_SLACK__NOTIFY_ON_SUCCESS=true
CAF_SLACK__NOTIFY_ON_ERROR=true
CAF_SLACK__INCLUDE_COST=true
CAF_SLACK__INCLUDE_DURATION=true通知包括:
- 执行状态(成功/错误)
- 持续时间和成本
- 令牌使用情况
- 待办事项完成状态
- 代理响应预览
成本跟踪
监控成本:
# View cost report
caf costs
# Reset tracking
caf costs --reset设置预算限制:
CAF_AGENT__MAX_BUDGET_USD=50.0如果超出预算,代理将停止。
AWS基岩设置
通过AWS Bedrock使用Claude:
# Enable Bedrock
CAF_BEDROCK__ENABLED=true
CAF_BEDROCK__REGION=us-east-1
# Use AWS profile
CAF_BEDROCK__PROFILE=my-profile
# Or use environment credentials
AWS_ACCESS_KEY_ID=...
AWS_SECRET_ACCESS_KEY=...
# Specify model
CAF_BEDROCK__MODEL_ID=global.anthropic.claude-sonnet-4-5-20250929-v1:0程序化使用
在Python代码中使用该框架:
import asyncio
from claude_agent_framework import AgentRunner, Settings
async def main():
settings = Settings(
anthropic_api_key="sk-ant-...",
agent=AgentConfig(
name="my-agent",
model=ModelType.SONNET,
max_turns=50,
),
slack=SlackConfig(
enabled=True,
webhook_url="https://hooks.slack.com/...",
),
)
runner = AgentRunner(settings)
result = await runner.run_once(
prompt="Analyze the database for performance issues",
task_description="Daily DB Check",
)
print(f"Status: {result.status}")
print(f"Cost: ${result.total_cost_usd:.4f}")
print(f"Result: {result.get_final_message()}")
asyncio.run(main())示例用例
每日数据库运行状况检查
# prompts/db_health.md
Analyze the database logs at /var/log/postgresql/ for the last 24 hours.
Look for:
1. Slow queries (>1s execution time)
2. Connection errors
3. Lock contention
4. Disk space warnings
Provide a summary with recommendations.# Crontab: 6 AM daily
0 6 * * * cd /opt/agent && caf run -f prompts/db_health.md应用程序日志监控
caf service "Monitor /var/log/app/error.log for new errors. \
Alert if you find critical errors or unusual patterns." \
--interval 1800代码质量检查
caf run "Review all Python files in src/ for:
- Security vulnerabilities
- Code quality issues
- Missing error handling
- Performance concerns
Prioritize by severity."自动化线性问题工作流程
# Start webhook server with Linear integration
caf webhook --routes examples/webhook_routes_claude_assignee.yaml
# Now when you assign a Linear issue to "Claude":
# 1. Webhook triggers agent
# 2. Agent analyzes the issue
# 3. Agent uses Linear MCP to update issue
# 4. Agent works on the task
# 5. Agent posts progress updates看 示例/LINEAR_MCP_WEBHOOK_SETUP.md 获取完整的设置指南。
CLI 参考
# Run once
caf run
[options]
-f, --prompt-file Load prompt from file
-m, --model Override model (sonnet/opus/haiku)
-t, --max-turns Maximum conversation turns
-b, --max-budget Maximum budget in USD
-d, --cwd Working directory
-q, --quiet Minimal output
-j, --json Output as JSON
# Service mode
caf service
[options]
-i, --interval Interval between runs (seconds)
# Cron mode
caf cron
--schedule [options]
-s, --schedule Cron expression
# Webhook server
caf webhook [options]
-h, --host Host to bind to (default: 0.0.0.0)
-p, --port Port to listen on (default: 8000)
-g, --generate-routes Generate example routes file
-r, --routes Path to webhook routes YAML file
# Configuration
caf config [options]
-g, --generate-env Generate .env template
-s, --show Show current config
-t, --tui Launch interactive TUI
# Cost tracking
caf costs [options]
-r, --reset Reset cost tracking
# Authentication
caf auth Show authentication configuration
# Version
caf version发展
# Install dev dependencies
pip install -e ".[dev]"
# Run tests
pytest
# Type checking
mypy src/
# Linting
ruff check src/许可证
MIT许可证-有关详细信息,请参阅许可证文件。
贡献
欢迎投稿!请在提交PR之前阅读我们的投稿指南。
