llm cost optimization deep

LLM 成本优化深度指南:省下 80% API 费用

成本问题的本质 LLM 计费公式:成本 = Token 数 × 单价。优化方向只有两个:减少 Token 数、降低单价。 ┌──────────────────────────────────────────────┐ │ 总 API 成本 │ │ ┌──────────────────────────────────────┐ │ │ │ Token 优化 (减少输入) │ │ │ │ - Prompt 压缩 │ │ │ │ - 历史截断 │ │ │ │ - Few-shot 精简 │ │ │ └──────────────────────────────────────┘ │ │ ┌──────────────────────────────────────┐ │ │ │ 模型路由 (降低单价) │ │ │ │ - 简单 → 小模型 ($0.15/1M) │ │ │ │ - 复杂 → 大模型 ($10/1M) │ │ │ └──────────────────────────────────────┘ │ │ ┌──────────────────────────────────────┐ │ │ │ 架构优化 (减少调用) │ │ │ │ - 缓存 (命中率 60%) │ │ │ │ - 批量推理 │ │ │ │ - 流式输出提前终止 │ │ │ └──────────────────────────────────────┘ │ └──────────────────────────────────────────────┘ 一、Token 优化 1.1 Prompt 压缩 class PromptCompressor: """多层 Prompt 压缩""" def compress(self, system_prompt: str, history: list, query: str) -> str: # 1. 系统提示词精简 system = self._trim_system(system_prompt) # 2. 历史对话压缩 history = self._compress_history(history) # 3. Few-shot 示例选择(只保留最相关的) examples = self._select_relevant_examples(query, k=2) # 4. 组装 return f"{system}\n\n{examples}\n\n历史:{history}\n\n问题:{query}" def _trim_system(self, prompt: str) -> str: """去除冗余描述,保留核心指令""" # 去除重复空格和换行 import re prompt = re.sub(r'\n{3,}', '\n\n', prompt) prompt = re.sub(r' {2,}', ' ', prompt) # 去除注释性文字 prompt = re.sub(r'#.*\n', '', prompt) return prompt.strip() def _compress_history(self, history: list, max_turns: int = 5) -> str: """压缩对话历史:保留最近 N 轮 + 摘要""" if len(history) <= max_turns: return "\n".join([f"用户: {h['user']}\n助手: {h['assistant']}" for h in history]) # 早期对话生成摘要 old = history[:-max_turns] recent = history[-max_turns:] summary = self._summarize(old) recent_text = "\n".join([f"用户: {h['user']}\n助手: {h['assistant']}" for h in recent]) return f"[之前对话摘要:{summary}]\n\n{recent_text}" 1.2 Token 计算与监控 import tiktoken class TokenMonitor: def __init__(self, model="gpt-4"): self.encoder = tiktoken.encoding_for_model(model) def count(self, text: str) -> int: return len(self.encoder.encode(text)) def estimate_cost(self, input_tokens: int, output_tokens: int, model: str) -> float: PRICING = { "gpt-4": {"input": 0.03, "output": 0.06}, "gpt-4o": {"input": 0.005, "output": 0.015}, "gpt-4o-mini": {"input": 0.00015, "output": 0.0006}, "claude-3.5-sonnet": {"input": 0.003, "output": 0.015}, } p = PRICING.get(model, PRICING["gpt-4"]) return (input_tokens * p["input"] + output_tokens * p["output"]) / 1000 1.3 压缩效果对比 优化手段 Token 节省 质量影响 去除冗余空白 5-10% 无 历史摘要 40-60% 轻微 Few-shot 精简 20-30% 可控 输出 max_tokens 限制 15-25% 无 函数调用替代文本解析 10-15% 正面 二、模型路由 核心思路:80% 的请求用小模型,20% 的请求用大模型。 ...

2026-06-25 · 5 min · 898 words · 硅基 AGI 探索者
鲁ICP备2026018361号