AI API 成本控制:我是怎么把月费从 $800 砍到 $120 的
上个月收到账单的时候,我差点把咖啡喷到键盘上。
$800。
就因为我用 GPT-4 跑了一些"看起来很简单"的任务。
今天分享一下我是怎么把成本砍掉 85% 的,全是实战经验,没有废话。
问题出在哪
先看看我的调用模式:
# 之前的代码
def process_document(doc):
# 每次都调用 GPT-4
summary = call_gpt4(f"Summarize: {doc}")
keywords = call_gpt4(f"Extract keywords: {doc}")
sentiment = call_gpt4(f"Analyze sentiment: {doc}")
return summary, keywords, sentiment问题很明显:
1. 三次调用:一个文档要调三次 API
2. 都用 GPT-4:不管任务复杂度,一律用最贵的
3. 没有缓存:相同内容重复调用
优化 1:合并请求
把三个任务合并成一个:
def process_document_v2(doc):
prompt = f"""Analyze this document and return JSON:
{{
"summary": "brief summary",
"keywords": ["keyword1", "keyword2"],
"sentiment": "positive/negative/neutral"
}}
Document: {doc}
"""
result = call_gpt4(prompt)
return json.loads(result)效果:调用次数减少 66%,成本直接降 2/3。
优化 2:模型分级
不是所有任务都需要 GPT-4:
def process_document_v3(doc):
# 摘要用 GPT-4(需要理解能力)
summary = call_gpt4(f"Summarize: {doc}")
# 关键词用 GPT-3.5(简单提取)
keywords = call_gpt35(f"Extract keywords: {doc}")
# 情感分析用 GPT-3.5(模式匹配)
sentiment = call_gpt35(f"Sentiment: {doc}")
return summary, keywords, sentiment成本对比:
- GPT-4: $30/M tokens
- GPT-3.5: $0.5/M tokens
效果:2/3 的调用成本降低 98%。
优化 3:缓存策略
相同内容不重复调用:
import hashlib
import redis
cache = redis.Redis()
def cached_call(model, prompt, ttl=3600):
# 生成缓存 key
key = hashlib.md5(f"{model}:{prompt}".encode()).hexdigest()
# 检查缓存
cached = cache.get(key)
if cached:
return cached.decode()
# 调用 API
result = call_api(model, prompt)
# 存入缓存
cache.setex(key, ttl, result)
return result效果:重复内容调用减少 40%。
优化 4:Prompt 压缩
减少 token 消耗:
# 之前的 prompt(~100 tokens)
prompt = """
Please analyze the following document and provide a comprehensive summary
that captures all the main points and key details. The summary should
be concise but thorough, covering all important aspects of the document.
Document: {doc}
"""
# 优化后的 prompt(~20 tokens)
prompt = "Summarize: {doc}"效果:每个请求节省 80 tokens,日均 1000 请求 = 节省 80K tokens/天。
优化 5:批量处理
利用 batch API:
def batch_process(docs):
# 批量请求,价格打 5 折
results = call_batch_api([
{"prompt": f"Summarize: {doc}"}
for doc in docs
])
return results效果:非实时任务成本再降 50%。
最终效果
| 优化项 | 成本降低 |
|--------|----------|
| 合并请求 | 66% |
| 模型分级 | 65% |
| 缓存策略 | 40% |
| Prompt 压缩 | 15% |
| 批量处理 | 50%(非实时) |
综合效果:月费从 $800 降到 $120。
成本控制检查清单
1. 审计调用频率:哪些任务可以合并?
2. 评估模型需求:哪些任务真的需要 GPT-4?
3. 实现缓存:相同内容是否重复调用?
4. 压缩 Prompt:能否用更少的 token 表达同样的意思?
5. 批量处理:非实时任务能否批量化?
写在最后
AI API 成本控制的本质是:用对的工具做对的事。
不是所有任务都需要最贵的模型,不是所有请求都需要实时响应。
希望这些经验能帮你省下一笔钱。
标签:#AI #API成本 #GPT-4 #成本控制 #开发经验
读者评论 2