AI 成本优化:100x Token 怎么省?

一家中型企业每月 AI 调用花费 5 万美元,其中 60% 是可以省的。本文详解 12 种实战优化技巧。

一、为什么 AI 成本是个问题

1.1 真实成本示例

典型企业 AI 应用:
- 日均请求:10,000 次
- 平均每次输入:2,000 tokens
- 平均每次输出:500 tokens
- 使用 GPT-4o:$2.5/M 输入 + $10/M 输出

月度成本 = 10000 × 30 × (2000×2.5 + 500×10) / 1,000,000
         = 10000 × 30 × 0.010
         = **$3,000/月**

听起来不贵?加上 RAG、长上下文、Agent 调用:
- 长上下文:100K tokens/请求
- Agent:10 次 LLM 调用/任务
- 月成本可能:**$30,000-50,000**

1.2 哪些是浪费的

1. 系统 Prompt 每次都发(占 5-10% 成本)
2. RAG 检索内容过多(10K vs 实际需要 1K)
3. 输出比需要的长(写 500 tokens 实际只要 100)
4. 用顶级模型做简单任务
5. 重复请求相似内容
6. 没有缓存机制

二、优化技巧(按效果排序)

技巧 1:模型路由(节省 50-80%)

不同任务用不同模型:

def smart_route(task):
    """根据任务复杂度选择模型"""
    if task.complexity == "simple":
        # 简单任务:分类、提取、翻译
        return "gpt-4o-mini"  # $0.15/M 输入
    elif task.complexity == "medium":
        return "gpt-4o"  # $2.5/M 输入
    else:
        return "gpt-5"  # $1.25/M 输入
    
    # 路由示例:
    # - "提取这段文字的邮箱" → gpt-4o-mini
    # - "写一篇文章" → gpt-4o
    # - "复杂推理" → gpt-5

效果:智能路由可节省 50-80% 成本。

技巧 2:Prompt 压缩(节省 30-50%)

# 优化前(废话多)
prompt = """
You are a highly intelligent and helpful AI assistant.
Your task is to carefully read the following text and provide
a comprehensive summary that captures all the key points.
Please be thorough and detailed in your response.

Text to summarize:
{text}

Please provide your summary below:
"""

# 优化后(精简)
prompt = "Summarize:\n{text}"

实测对比:

  • 冗长 prompt:150 tokens
  • 精简 prompt:5 tokens
  • 节省 96%

但注意:不能过度精简,否则模型理解错误。

技巧 3:缓存(节省 30-90%)

重复请求是非常常见的:

import hashlib
from functools import lru_cache

# 精确缓存
@lru_cache(maxsize=10000)
def cached_generate(prompt: str) -> str:
    return ai.generate(prompt)

# 语义缓存(更强大)
class SemanticCache:
    def __init__(self):
        self.cache = {}  # embedding -> response

    def get(self, query):
        query_emb = embed(query)
        for cached_emb, response in self.cache.items():
            if cosine_similarity(query_emb, cached_emb) > 0.95:
                return response
        return None

    def set(self, query, response):
        self.cache[embed(query)] = response

# 用法
cache = SemanticCache()

def smart_generate(prompt):
    cached = cache.get(prompt)
    if cached:
        return cached

    response = ai.generate(prompt)
    cache.set(prompt, response)
    return response

典型场景:

  • FAQ 机器人:相同问题问 100 次,99 次命中缓存
  • 文档摘要:相同文档 100% 命中
  • 翻译:常见句子 50% 命中

技巧 4:RAG 优化(节省 50-80%)

# 问题:默认 RAG 检索 10 个 chunks
retrieved = vector_db.search(query, k=10)  # 10 × 500 = 5000 tokens

# 优化:智能检索
# 1. 先粗筛(便宜模型)
relevant_docs = []
for doc in candidate_docs[:50]:
    score = cheap_model.score(query, doc)
    if score > 0.7:
        relevant_docs.append(doc)

# 2. 只保留 top 3
top_docs = relevant_docs[:3]
# 3 × 500 = 1500 tokens

# 节省 70%

技巧 5:流式响应(节省 30%)

# 非流式:用户等 5 秒,AI 写完 500 tokens
response = ai.generate(prompt)

# 流式:用户第 1 秒看到前 100 tokens
for chunk in ai.stream(prompt):
    print(chunk, end="", flush=True)

# 优势:
# - 用户体感快(TTFB 低)
# - 可提前停止(如果用户已满意)
# - Token 浪费少

技巧 6:截断输出(节省 20-40%)

# 强制限制输出长度
response = ai.generate(
    prompt,
    max_tokens=200  # 限制最多 200 tokens
)

# 或在 prompt 里说:
"用 100 字以内回答"

技巧 7:批处理(节省 20-50%)

# 单个请求 100 次 = 100 次 API 调用
for item in items:
    response = ai.generate(f"Process: {item}")

# 批处理:1 次 API 调用处理 100 个
batch_prompt = "请处理以下 100 项,每项一行:\n" + "\n".join(items)
responses = ai.generate(batch_prompt).split("\n")
# 节省 80% 调用成本(但 prompt token 增加 50%)
# 净节省约 30-50%

技巧 8:微调小模型(节省 10-100x)

# 场景:每次都用 GPT-4 做"提取邮箱"任务
# 但 GPT-4o-mini 也能做,且便宜 17 倍

# 解决方案:
# 1. 用 GPT-4 生成 1000 个训练样本
# 2. 微调 Llama 3 8B 或 Qwen2 1.5B
# 3. 部署成本几乎为 0
# 4. 性能 95% 接近 GPT-4

# 单次成本对比:
# GPT-4: $0.005 / 任务
# 微调 1.5B 模型: $0.00001 / 任务
# 节省 500x

技巧 9:上下文窗口管理(节省 50%+)

# 问题:长对话累计所有历史
# Token 越来越多,单次请求越来越贵

# 解决方案:上下文压缩
def compress_context(messages):
    if len(messages) > 10:
        # 用 AI 总结前 N 轮对话
        summary = ai.summarize(messages[:8])
        # 保留最近几轮 + 早期总结
        return [
            {"role": "system", "content": f"对话历史:{summary}"}
        ] + messages[-2:]
    return messages

技巧 10:本地模型(节省 100%)

# 高频调用 + 简单任务
# 用 Ollama + Llama 3 8B 完全本地

import ollama

def local_generate(prompt):
    response = ollama.chat(
        model="llama3",
        messages=[{"role": "user", "content": prompt}]
    )
    return response['message']['content']

# 成本:$0
# 速度:本地推理,比 API 快 2-10 倍
# 限制:模型能力较弱

技巧 11:早期停止(节省 30%+)

def generate_with_early_stop(prompt, target_length=200):
    response = []
    for chunk in ai.stream(prompt):
        response.append(chunk)
        if len(response) > target_length:
            # 检查是否"说完了"
            if "。" in chunk[-10:] or "\n" in chunk:
                break
    return "".join(response)

技巧 12:监控 + 告警

# 实时监控成本
class CostMonitor:
    def __init__(self, budget):
        self.budget = budget  # 月度预算

    def log_call(self, input_tokens, output_tokens, model):
        cost = self.calc_cost(model, input_tokens, output_tokens)
        if self.month_total() + cost > self.budget * 0.8:
            alert("成本超过 80% 预算!")

三、组合优化策略

3.1 通用 AI 应用优化清单

✅ 模型路由(按复杂度选模型)
✅ Prompt 压缩(去除废话)
✅ 缓存(重复请求直接返回)
✅ RAG 优化(少而精的 chunks)
✅ 流式响应
✅ 截断输出
✅ 批处理
✅ 本地小模型(高频简单任务)
✅ 上下文管理
✅ 监控告警

预计节省:60-90%

3.2 真实案例

案例 1:客服机器人

优化前:
- GPT-4 + RAG (10 chunks) + 长 prompt
- 每次成本:$0.05
- 月成本:$15,000

优化后:
- 模型路由 + GPT-4o-mini + 缓存 + RAG 优化
- 每次成本:$0.003
- 月成本:$900

节省:94%

案例 2:内容生成

优化前:
- GPT-4 生成文章
- 每次成本:$0.20
- 月成本:$6,000

优化后:
- GPT-5 (便宜 80%) + 流式 + 截断
- 每次成本:$0.02
- 月成本:$600

节省:90%

四、成本监控仪表板

4.1 关键指标

- 日 / 周 / 月成本
- 按模型 / 用户 / 功能的成本拆分
- 平均每次请求成本
- Token 使用趋势
- 异常告警

4.2 推荐工具

  • OpenAI Usage Dashboard:官方
  • LangSmith:LLM 应用监控
  • Helicone:开源 LLM 监控
  • Portkey:生产级 LLM 网关
  • 自建 Prometheus + Grafana

五、何时不要优化

5.1 优化是有成本的

- 模型路由:路由逻辑本身的开发成本
- 缓存:缓存一致性、内存成本
- 本地模型:GPU 服务器成本

# 公式
优化价值 = 节省成本 - 优化成本

如果优化价值 > 0:值得
否则:先做好产品,再考虑优化

5.2 优先级

1. **先正确**:功能正确 > 优化
2. **再快**:性能达标 > 极致优化
3. **后省**:成本可控 > 极限压缩

不要过早优化!

六、2025 年 AI 成本趋势

6.1 价格下降

  • GPT-5 比 GPT-4o 便宜 50%
  • 开源模型零成本
  • 推理专用芯片(Groq、Cerebras)让便宜 10x

6.2 预测

2025 年:Token 价格再降 50%
2026 年:开源模型 90% 场景替代 API
2027 年:AI 调用成本 < 电力成本

到那时,"成本"不再是 AI 应用的瓶颈。

七、行动清单

今天

  • [ ] 计算你当前的 AI 月成本
  • [ ] 设置月度预算和告警

本周

  • [ ] 实现模型路由(按任务复杂度)
  • [ ] 启用 prompt 压缩
  • [ ] 加缓存层

本月

  • [ ] RAG 优化
  • [ ] 上下文窗口管理
  • [ ] 监控仪表板

持续

  • [ ] 测试新模型(更便宜)
  • [ ] 微调垂直模型
  • [ ] 探索本地部署
AI 成本优化是技术活,更是商业竞争力。

>

同样的功能,你的成本是对手的 1/10 = 你的利润率是对手的 10 倍。

现在就开始优化!