Token成本是AI应用的隐形杀手许多团队在构建AI应用的早期阶段不太关注成本——MVP阶段用户量小每月的API费用是个位数美元不值得花时间优化。但当应用规模化之后成本问题往往来得猝不及防日活一万用户、平均每天10次对话、每次对话平均2000个token一个月下来光GPT-4o的费用就是几千美元。这篇文章梳理了一套系统性的成本优化方案实践中综合应用这些方法可以将Token成本降低50-70%同时对用户体验的影响可以控制到最小。## 第一层优化精准测量优化的前提是知道钱花在哪里。很多团队没有细粒度的成本追踪只知道总费用很高不知道是哪个功能在烧钱。### 建立Per-Feature成本追踪pythonimport functoolsfrom openai import OpenAIfrom dataclasses import dataclass, fieldfrom collections import defaultdictclient OpenAI()dataclassclass CostTracker: # 按功能/用户/模型分类的成本记录 feature_costs: dict field(default_factorylambda: defaultdict(float)) # GPT-4o的价格美元/1K tokens2026年参考价 PRICING { gpt-4o: {input: 0.0025, output: 0.01}, gpt-4o-mini: {input: 0.00015, output: 0.0006}, gpt-3.5-turbo: {input: 0.0005, output: 0.0015}, } def track(self, model: str, input_tokens: int, output_tokens: int, feature: str): pricing self.PRICING.get(model, {input: 0.01, output: 0.03}) cost (input_tokens * pricing[input] output_tokens * pricing[output]) / 1000 self.feature_costs[feature] cost return cost def report(self): total sum(self.feature_costs.values()) sorted_features sorted( self.feature_costs.items(), keylambda x: x[1], reverseTrue ) print(f\n 成本报告 ) print(f总成本: ${total:.4f}) for feature, cost in sorted_features: print(f {feature}: ${cost:.4f} ({cost/total*100:.1f}%))tracker CostTracker()def tracked_completion(feature: str): 装饰器自动追踪API调用成本 def decorator(func): functools.wraps(func) async def wrapper(*args, **kwargs): response await func(*args, **kwargs) if hasattr(response, usage) and response.usage: tracker.track( modelresponse.model, input_tokensresponse.usage.prompt_tokens, output_tokensresponse.usage.completion_tokens, featurefeature ) return response return wrapper return decoratortracked_completion(featuredocument_summarization)async def summarize_document(text: str) - str: response await client.chat.completions.create( modelgpt-4o-mini, messages[{role: user, content: f总结这段文字{text}}] ) return response.choices[0].message.content## 第二层优化模型分级路由不是所有任务都需要最强的模型。建立任务难度→模型选择的路由机制是降成本最直接的方法。pythonfrom enum import Enumclass TaskComplexity(Enum): SIMPLE simple # 分类、简单提取、短文本改写 MEDIUM medium # 摘要、问答、代码补全 COMPLEX complex # 复杂推理、长文档分析、多步规划class ModelRouter: COMPLEXITY_TO_MODEL { TaskComplexity.SIMPLE: gpt-4o-mini, TaskComplexity.MEDIUM: gpt-4o-mini, TaskComplexity.COMPLEX: gpt-4o } # 成本比: gpt-4o-mini比gpt-4o便宜约17倍 async def classify_task_complexity(self, task: str) - TaskComplexity: 用轻量模型判断任务复杂度 response await client.chat.completions.create( modelgpt-4o-mini, # 用mini模型做分类成本极低 messages[{ role: user, content: f 判断以下任务的复杂度 任务{task} 复杂度定义 - simple: 简单分类/提取/改写不需要推理 - medium: 需要理解和整合信息中等难度 - complex: 需要深度推理/创作/多步规划 只输出simple/medium/complex }], max_tokens10 ) label response.choices[0].message.content.strip().lower() return TaskComplexity(label) if label in [simple, medium, complex] \ else TaskComplexity.MEDIUM async def route_and_complete(self, task: str, messages: list[dict]) - str: complexity await self.classify_task_complexity(task) model self.COMPLEXITY_TO_MODEL[complexity] response await client.chat.completions.create( modelmodel, messagesmessages ) return response.choices[0].message.contentrouter ModelRouter()## 第三层优化Prompt压缩System Prompt往往是最大的Token开销来源。每次API调用都需要发送完整的System Prompt如果Prompt很长成本直接翻倍。### LLMLingua压缩开源方案python# pip install llmlinguafrom llmlingua import PromptCompressorcompressor PromptCompressor( model_namemicrosoft/llmlingua-2-bert-base-multilingual-cased-meetingbank, use_llmlingua2True)def compress_system_prompt(prompt: str, target_ratio: float 0.5) - tuple[str, float]: 压缩System Prompt目标压缩到原来的50% result compressor.compress_prompt( prompt, ratetarget_ratio, force_tokens[\n, ?] # 保留换行和问号 ) compressed result[compressed_prompt] actual_ratio result[ratio] return compressed, actual_ratio# 示例600 tokens的prompt压缩到300 tokensoriginal_prompt 你是一个专业的客服助手服务于一家企业级SaaS软件公司...compressed, ratio compress_system_prompt(original_prompt)print(f压缩比{ratio:.2f}x节省了{(1-1/ratio)*100:.0f}%的tokens)### 缓存策略Prompt CachingOpenAI和Anthropic都支持Prompt Caching对于有固定System Prompt的场景缓存可以降低50-90%的输入Token成本python# Anthropic的Prompt CachingClaude模型import anthropicclaude_client anthropic.Anthropic()def create_with_caching(system_prompt: str, user_message: str) - str: 使用Anthropic的Prompt Caching response claude_client.messages.create( modelclaude-3-5-sonnet-20241022, max_tokens1024, system[ { type: text, text: system_prompt, cache_control: {type: ephemeral} # 启用缓存 } ], messages[{role: user, content: user_message}] ) # 查看缓存命中情况 usage response.usage print(f输入tokens: {usage.input_tokens}) print(f缓存命中tokens: {usage.cache_read_input_tokens}) print(f缓存创建tokens: {usage.cache_creation_input_tokens}) return response.content[0].text## 第四层优化语义缓存对于重复的或语义相似的用户问题不需要每次都调用LLMpythonimport numpy as npfrom dataclasses import dataclassdataclassclass CachedResponse: query: str embedding: list[float] response: str hit_count: int 0class SemanticCache: def __init__(self, embedder, similarity_threshold: float 0.92): self.embedder embedder self.threshold similarity_threshold self.cache: list[CachedResponse] [] def get(self, query: str) - str | None: 如果有足够相似的历史问题返回缓存结果 if not self.cache: return None query_emb np.array(self.embedder.embed_query(query)) for item in self.cache: cached_emb np.array(item.embedding) # 余弦相似度 similarity np.dot(query_emb, cached_emb) / ( np.linalg.norm(query_emb) * np.linalg.norm(cached_emb) ) if similarity self.threshold: item.hit_count 1 print(f缓存命中相似度: {similarity:.3f}节省了一次LLM调用) return item.response return None def set(self, query: str, response: str): 缓存新的问答对 embedding self.embedder.embed_query(query) self.cache.append(CachedResponse( queryquery, embeddingembedding, responseresponse )) def get_cache_stats(self) - dict: total_hits sum(item.hit_count for item in self.cache) return { cache_size: len(self.cache), total_hits: total_hits, estimated_savings: f${total_hits * 0.01:.2f}假设每次调用$0.01 }## 第五层优化Output长度控制LLM的输出Token往往比输入贵2-4倍。通过明确的指令控制输出长度可以大幅降低成本pythondef build_cost_aware_prompt(task: str, max_words: int 150) - str: 构建成本感知的Prompt return f {task} 要求 - 回答控制在{max_words}字以内 - 不要重复问题 - 不要客套语如很好的问题、我来帮你 - 直接给出结论必要时才展开解释 # 对比不加约束 vs 加约束的Token消耗# 典型场景客服问答# 不加约束平均450 tokens输出# 加约束平均160 tokens输出# 节省约65%的输出token## 综合效果评估将上述五层优化综合应用一个典型的企业级AI应用的成本变化| 优化层 | 降成本效果 | 对质量影响 ||--------|-----------|-----------|| 精准测量发现浪费点 | 识别20-30%无效调用 | 无 || 模型分级路由 | 降低30-40% | 轻微5%质量下降 || Prompt压缩 | 降低20-30%输入成本 | 轻微 || Prompt Caching | 降低50-90%有重复内容时 | 无 || 语义缓存 | 降低10-30%取决于重复率 | 无 || 输出长度控制 | 降低30-50%输出成本 | 取决于场景 |综合应用后总成本降低50-70%是完全可以实现的目标而对用户体验的影响通常在可接受范围内。成本工程不是一次性的工作而是随着业务规模扩大需要持续关注的工程领域。建立监控、定期审查高成本调用、持续优化Prompt是AI应用长期健康运营的必要条件。