API成本优化技巧
使用大模型API时,成本是需要重点考虑的因素。本节介绍几种有效的成本优化方法。
成本构成
API费用 = 输入Token × 输入价格 + 输出Token × 输出价格
示例:使用Claude Sonnet处理一个请求
- 输入:1000 Token
- 输出:500 Token
- 费用 = 1000 × $3/1M + 500 × $15/1M = $0.0105优化策略
策略一:选择合适的模型
简单任务 → 用Haiku/GPT-3.5(便宜)
中等任务 → 用Sonnet/GPT-4o(平衡)
复杂任务 → 用Opus/o1(贵但强)策略二:使用提示缓存
python
# Claude 提示缓存
message = client.messages.create(
model="claude-sonnet-4-20250514",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": long_document, # 可被缓存
"cache_control": {"type": "ephemeral"}
},
{"type": "text", "text": "请总结"}
]
}
]
)
# 缓存命中可节省90%输入Token费用策略三:限制输出长度
python
# 不限制:AI可能输出几千字
response = client.chat.completions.create(
model="gpt-4o",
messages=[...]
)
# 限制:最多100个Token
response = client.chat.completions.create(
model="gpt-4o",
messages=[...],
max_tokens=100
)策略四:使用批处理
python
# OpenAI 批处理API,成本降低50%
batch = client.batches.create(
input_file_id="file-xxx",
endpoint="/v1/chat/completions",
completion_window="24h"
)策略五:精简提示词
❌ 冗长的提示词(消耗大量Token)
你是一个非常有经验的专业人士,你在这个领域已经工作了超过20年...
✅ 精简的提示词
你是一位资深专家,回答简洁专业。成本监控
python
def track_cost(response):
"""追踪API成本"""
input_tokens = response.usage.prompt_tokens
output_tokens = response.usage.completion_tokens
# Claude Sonnet 价格
input_cost = input_tokens * 3 / 1_000_000
output_cost = output_tokens * 15 / 1_000_000
total_cost = input_cost + output_cost
print(f"输入Token: {input_tokens}")
print(f"输出Token: {output_tokens}")
print(f"费用: ${total_cost:.6f}")
return total_cost小结
成本优化要点:
| 策略 | 效果 |
|---|---|
| 选择合适模型 | 节省50%-90% |
| 提示缓存 | 节省90%输入成本 |
| 限制输出 | 控制输出成本 |
| 批处理 | 节省50% |
| 精简提示词 | 节省10%-30% |
下一步
继续学习 LangChain框架基础。