首页 教程 常见问题

Agent SDK 成本追踪

追踪和优化 Agent SDK 代理的 API 使用成本。

成本构成

Claude API 的成本基于 token 数量:

类型说明
输入 Token发送的消息和工具结果
输出 TokenClaude 的回复和工具调用
缓存创建创建缓存输入
缓存读取使用缓存输入(更便宜)

追踪成本

# 模型定价(示例,请查看最新定价)
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}")

优化成本

预算控制

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

下一步