Agent 系列(18):成本与性能优化——省钱且更快
Agent 的钱花在哪里一次 Agent 调用的成本拆解:输入 Token 构成: 系统提示 固定,每次调用都付 工具定义(Schema) 固定,注册多少工具就付多少 对话历史 随轮次线性增长 检索内容 动态 输出 Token: 模型思考过程 ReAct 的 Thought 部分 工具调用参数 每次工具调用 最终回复 用户看到的答案 延迟构成: LLM 推理时间 占绝大部分(通常 90%) 工具执行时间 通常 10%,但串行叠加可观优化方向只有两个:减少 Token 数和减少等待时间。本文用四个实验量化每种策略的实际收益。Demo 1:Token 成本拆解——系统提示瘦身系统提示在每次调用时都会发送给模型,是最容易被忽视的固定成本。两版系统提示对比:MINIMAL_PROMPT="You are a helpful assistant."# → 6 tokensVERBOSE_PROMPT="""You are an extremely helpful, knowledgeable, and professional AI assistant for WonderLab's enterprise software platform. You specialize in providing accurate weather information... Always be thorough, comprehensive, and leave no important detail unexplained."""# → 107 tokensToken 对比:Minimal ( 6 tokens): 'You are a helpful assistant.' Verbose (107 tokens): 'You are an extremely helpful...' 每次调用多付: 101 tokens101 tokens 听起来不多。按 GPT-4o 输入 $2.50/1M tokens 计:每天 1 万次调用 → 每天多花 $0.25每天 100 万次调用 → 每天多花 $25,每月 $750延迟测量(2 次采样,同一 Query):Agent Run 1 Run 2 Avg Answer Minimal 6.90s 3.39s 5.15s The current weather in Beijing is 25°C... Verbose 3.10s 4.21s 3.66s The current weather in Beijing is 25°C...Verbose 的平均延迟反而比 Minimal 更低——这是反直觉的结果。原因:2 次采样完全不足以测量 LLM 延迟。API 返回时间受服务端负载影响,波动区间通常是 ±50%。要得到可靠的延迟数据,至少需要 10-20 次采样后取中位数。这条系统提示延迟差异本质上是噪声。系统提示精简的收益是Token 成本,不是延迟。延迟优化需要别的手段。Prompt Caching(进阶):Claude API 和 OpenAI API 支持显式的提示缓存。在 Claude 中:response=client.messages.create(model="claude-sonnet-4-6",system=[{"type":"text","text":LARGE_SYSTEM_PROMPT,"cache_control":{"type":"ephemeral"},# 标记为可缓存}],messages=[...],)# 首次调用:写入缓存(正常计费)# 后续同前缀调用:命中缓存,约 90% 成本折扣print(response.usage.cache_read_input_tokens)# 命中数print(response.usage.cache_