追踪和优化 Agent SDK 代理的 API 使用成本。
成本构成
Claude API 的成本基于 token 数量:
| 类型 | 说明 |
|---|---|
| 输入 Token | 发送的消息和工具结果 |
| 输出 Token | Claude 的回复和工具调用 |
| 缓存创建 | 创建缓存输入 |
| 缓存读取 | 使用缓存输入(更便宜) |
追踪成本
# 模型定价(示例,请查看最新定价)
PRICING = {
"claude-sonnet-4-20250514": {
"input": 3.00, # $/百万 token
"output": 15.00, # $/百万 token
"cache_read": 0.30,
"cache_write": 3.75
}
}
def calculate_cost(usage, model):
"""计算 API 调用的成本。"""
prices = PRICING.get(model, {})
cost = (
usage.input_tokens * prices.get("input", 0) +
usage.output_tokens * prices.get("output", 0)
) / 1_000_000
return round(cost, 6)
# 使用
response = client.messages.create(...)
cost = calculate_cost(response.usage, response.model)
print(f"成本: ${cost}")
优化成本
- 使用缓存:重复的系统指令和长上下文可以缓存
- 选择合适的模型:简单任务用 Sonnet,复杂任务用 Opus
- 减少不必要的工具调用:优化提示词减少冗余调用
- 限制最大 token:避免过长的回复
- 定期审查日志:监控成本趋势
预算控制
class BudgetTracker:
def __init__(self, daily_budget=10.0):
self.daily_budget = daily_budget
self.spent = 0.0
def check_budget(self, estimated_cost):
if self.spent + estimated_cost > self.daily_budget:
raise ValueError(f"超出预算: {self.spent + estimated_cost:.2f} > {self.daily_budget:.2f}")
self.spent += estimated_cost