模块 15:成本工程
让 Agent 用得起 —— Token 预算、成本优化、ROI 计算
1. 成本构成
Agent 运行成本
├── LLM API 调用(通常占 80%+)
│ ├── 输入 Token(System Prompt + 对话历史 + 工具定义)
│ └── 输出 Token(Agent 回复 + 工具调用参数)
│
├── 工具调用成本
│ ├── 搜索 API(Tavily: $0.005/次)
│ ├── 向量数据库(Qdrant Cloud: $0.001/千次查询)
│ └── 其他第三方 API
│
├── 基础设施成本
│ ├── 服务器(计算 + 存储)
│ ├── 数据库
│ └── CDN / 网络
│
└── 隐性成本
├── 开发调试(大量 LLM 调用)
├── 评估测试(自动化评测)
└── 失败重试(错误消耗)
2. 主流模型定价
| 模型 |
输入 ($/1M tokens) |
输出 ($/1M tokens) |
缓存命中 |
| Claude Opus 4 |
$15.00 |
$75.00 |
$1.50 (10%) |
| Claude Sonnet 4 |
$3.00 |
$15.00 |
$0.30 (10%) |
| Claude Haiku 4.5 |
$0.80 |
$4.00 |
$0.08 (10%) |
| GPT-4o |
$2.50 |
$10.00 |
$1.25 (50%) |
| GPT-4o-mini |
$0.15 |
$0.60 |
$0.075 (50%) |
| DeepSeek-V3 |
$0.27 |
$1.10 |
- |
| Qwen2.5-72B |
$0.35 |
$1.20 |
- |
3. 成本估算
class CostEstimator:
"""Agent 成本估算器"""
PRICES = {
"claude-opus-4-20250514": {"input": 15.0, "output": 75.0, "cached_input": 1.5},
"claude-sonnet-4-20250514": {"input": 3.0, "output": 15.0, "cached_input": 0.3},
"claude-haiku-4-5-20251001": {"input": 0.8, "output": 4.0, "cached_input": 0.08},
"gpt-4o": {"input": 2.5, "output": 10.0, "cached_input": 1.25},
"gpt-4o-mini": {"input": 0.15, "output": 0.60, "cached_input": 0.075},
}
def estimate_query_cost(
self,
model: str,
system_tokens: int,
history_tokens: int,
output_tokens: int,
cached_ratio: float = 0.0
) -> dict:
"""估算单次查询成本"""
prices = self.PRICES[model]
input_tokens = system_tokens + history_tokens
cached_tokens = int(input_tokens * cached_ratio)
uncached_tokens = input_tokens - cached_tokens
input_cost = (cached_tokens * prices["cached_input"] + uncached_tokens * prices["input"]) / 1_000_000
output_cost = output_tokens * prices["output"] / 1_000_000
return {
"input_cost": round(input_cost, 6),
"output_cost": round(output_cost, 6),
"total_cost": round(input_cost + output_cost, 6),
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"cached_tokens": cached_tokens
}
def estimate_daily_cost(
self,
queries_per_day: int,
avg_cost_per_query: float
) -> dict:
"""估算日成本"""
daily = queries_per_day * avg_cost_per_query
return {
"daily": round(daily, 2),
"monthly": round(daily * 30, 2),
"yearly": round(daily * 365, 2)
}
4. 成本优化策略
4.1 Prompt Caching(最大收益)
# Anthropic Prompt Caching
# System Prompt + 工具定义缓存后,后续请求只计 10% 费用
# 优化前:每次 1000 Token System Prompt × $3/M = $0.003
# 优化后:首次 $0.003 + 后续 $0.0003/次
# 100 次请求节省:$0.003 × 99 × 90% = $0.267
# 实际收益计算
def caching_savings(
system_tokens: int,
queries_per_day: int,
model: str = "claude-sonnet-4-20250514"
) -> dict:
prices = {"input": 3.0, "cached_input": 0.3}
uncached_daily = system_tokens * queries_per_day * prices["input"] / 1_000_000
cached_daily = system_tokens * (1 * prices["input"] + (queries_per_day - 1) * prices["cached_input"]) / 1_000_000
return {
"uncached_daily": round(uncached_daily, 4),
"cached_daily": round(cached_daily, 4),
"savings": round(uncached_daily - cached_daily, 4),
"savings_ratio": f"{(1 - cached_daily / uncached_daily) * 100:.1f}%"
}
4.2 模型路由(大小模型分流)
class ModelRouter:
"""智能模型路由"""
def __init__(self):
self.classifier = None # 小模型做分类
async def route(self, query: str, context: dict) -> str:
# 用小模型判断复杂度
complexity = await self.classify_complexity(query)
if complexity == "simple":
return "claude-haiku-4-5-20251001" # $0.80/M
elif complexity == "medium":
return "claude-sonnet-4-20250514" # $3.00/M
else:
return "claude-opus-4-20250514" # $15.00/M
async def classify_complexity(self, query: str) -> str:
# 用 Haiku 做分类(成本极低)
response = await call_llm(
model="claude-haiku-4-5-20251001",
prompt=f"判断问题复杂度:{query}\n回答 simple/medium/complex"
)
return response.strip().lower()
4.3 语义缓存
class SemanticCache:
"""语义缓存 - 相似问题直接返回缓存结果"""
def __init__(self, vector_db, threshold=0.95):
self.db = vector_db
self.threshold = threshold
async def get_or_compute(self, query: str, compute_fn) -> tuple[str, bool]:
# 查缓存
embedding = get_embedding(query)
cached = await self.db.search(embedding, limit=1)
if cached and cached[0].score > self.threshold:
return cached[0].response, True # 缓存命中
# 计算
response = await compute_fn(query)
# 写缓存
await self.db.store(embedding, response)
return response, False # 缓存未命中
4.4 Token 预算控制
class TokenBudget:
"""Token 预算管理"""
def __init__(self, daily_budget: int = 1_000_000):
self.daily_budget = daily_budget
self.used_today = 0
def check(self, estimated_tokens: int) -> bool:
"""检查是否超出预算"""
return self.used_today + estimated_tokens <= self.daily_budget
def record(self, tokens: int):
"""记录使用量"""
self.used_today += tokens
def get_status(self) -> dict:
return {
"budget": self.daily_budget,
"used": self.used_today,
"remaining": self.daily_budget - self.used_today,
"usage_ratio": f"{self.used_today / self.daily_budget * 100:.1f}%"
}
4.5 上下文压缩
async def compress_context(messages: list, max_tokens: int) -> list:
"""压缩上下文以减少 Token 消耗"""
total = count_tokens(messages)
if total <= max_tokens:
return messages
# 策略1:滑动窗口(保留最近 N 轮)
system = messages[0]
recent = messages[-6:] # 最近 3 轮
middle = messages[1:-6]
# 策略2:摘要压缩中间部分
summary = await summarize(middle)
return [
system,
{"role": "assistant", "content": f"[历史摘要] {summary}"}
] + recent
4.6 批量处理
# OpenAI Batch API(50% 折扣)
# 适用于不需要实时响应的场景
# 评估、数据处理、批量分析等
batch_requests = [
{"custom_id": f"task-{i}", "method": "POST", "body": {...}}
for i in range(1000)
]
# 提交批量任务
batch = client.batches.create(
input_file_id=batch_file.id,
endpoint="/v1/chat/completions",
completion_window="24h"
)
5. 成本监控
class CostMonitor:
"""成本监控"""
def __init__(self):
self.metrics = {
"total_cost": 0,
"by_model": {},
"by_feature": {},
"by_user": {}
}
def record(self, model: str, input_tokens: int, output_tokens: int,
feature: str = None, user_id: str = None):
cost = self.calculate_cost(model, input_tokens, output_tokens)
self.metrics["total_cost"] += cost
# 按模型统计
self.metrics["by_model"].setdefault(model, 0)
self.metrics["by_model"][model] += cost
# 按功能统计
if feature:
self.metrics["by_feature"].setdefault(feature, 0)
self.metrics["by_feature"][feature] += cost
# 按用户统计
if user_id:
self.metrics["by_user"].setdefault(user_id, 0)
self.metrics["by_user"][user_id] += cost
# 告警检查
self.check_alerts()
def check_alerts(self):
if self.metrics["total_cost"] > 100: # 日成本超过 $100
send_alert("Agent 日成本超过 $100!")
6. ROI 计算
def calculate_roi(
monthly_agent_cost: float,
monthly_human_cost_saved: float,
quality_improvement: float = 0.0
) -> dict:
"""计算 Agent ROI"""
net_savings = monthly_human_cost_saved - monthly_agent_cost
roi = (net_savings / monthly_agent_cost) * 100
return {
"monthly_cost": round(monthly_agent_cost, 2),
"monthly_savings": round(monthly_human_cost_saved, 2),
"net_savings": round(net_savings, 2),
"roi": f"{roi:.1f}%",
"payback_period": f"{monthly_agent_cost / net_savings:.1f} 月" if net_savings > 0 else "无法回本"
}
# 示例
# 客服 Agent:月成本 $500,替代 2 个人工客服(月成本 $6000)
# ROI = (6000 - 500) / 500 × 100 = 1100%
7. 延伸阅读
小码提示: 成本是 Agent 产品的生死线。Prompt Caching + 模型路由 + 语义缓存,三板斧下去能省 70%+ 的成本。上线前一定要做成本估算,别等到账单来了才傻眼。