关于 claude-cost-optimization
这项技能面向运营 Claude 部署并希望衡量和降低 Token 成本的团队。它提供五步流程,涵盖用量分析、优化方案、效果跟踪和投资回报报告。
主要功能
- 01跟踪 Token 用量与成本
- 02拆解成本驱动因素
- 03优化上下文与工具使用
- 04比较优化效果
- 05计算投资回报并预测预算
适用场景
- 01分析生产环境中的 Claude 开支
- 02定位高成本 Agent 操作
- 03部署前优化成本
- 04汇报节省金额与回本周期
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ adaptationio/ skrillz --skill claude-cost-optimization安装后在 Claude Code 中输入/claude-cost-optimization确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/cost-analysis.mdefficiency-measurement.mdoptimization-strategies.mdusage-tracking.md详细介绍
Claude 成本优化
概述
对于生产环境中的 Claude 部署,成本优化至关重要。一个设计低效的 Agent 每月可能耗费数百甚至数千美元,而经过优化的实现,在功能相同的情况下可降低 10%–90% 的成本。本技能提供了一套完整的工作流,用于衡量、分析和优化令牌成本。
为何重要:
- 令牌成本是 Claude 开销中占比最大的部分
- 微小改进经过数百万次 API 调用后会累积成显著收益
- 仅优化上下文,就能让长对话的成本降低 60%–90%
- 针对特定任务选择模型和 effort,可将成本降低 5–10 倍
可实现的关键节省:
- Effort 参数:减少 20%–70% 的令牌用量(同一模型,推理深度不同)
- 上下文编辑:长对话的令牌用量减少 60%–90%
- 工具优化:采用高级工具模式可减少 37%–85%
- 提示词缓存:重复内容的成本降低 90%
- 模型选择:不同模型之间的成本相差 2–5 倍
何时使用本技能
在以下情况下使用 claude-cost-optimization:
- 跟踪令牌成本:准确了解 Claude 实现的成本
- 识别高成本模式:找出哪些操作消耗的令牌最多
- 衡量投资回报率:计算 Claude 集成带来的业务价值
- 优化生产环境:在部署高成本 Agent 前降低开销
- 分析成本驱动因素:按模型、功能、端点或时间段拆分成本
- 规划预算:根据增长预测预估未来成本
- 实施优化:应用经过验证的技术(缓存、批处理、上下文编辑)
- 设置提醒:监控成本,并在出现异常或超出预算时收到通知
5 步优化工作流
第 1 步:衡量基准用量
在优化前,先确定当前的成本基准。
衡量内容:
- Total monthly tokens (input + output)
- Cost breakdown by model
- Top 10 most expensive operations
- Average tokens per request
- Peak usage times and patterns
衡量方法(使用 Admin API):
from anthropic import Anthropic
client = Anthropic()
# Get monthly usage
response = client.beta.admin.usage_metrics.list(
limit=30,
sort_by="date",
)
total_input_tokens = sum(m.input_tokens for m in response.data)
total_output_tokens = sum(m.output_tokens for m in response.data)
total_cost = (total_input_tokens * 0.000005) + (total_output_tokens * 0.000025)
print(f"Monthly cost: ${total_cost:.2f}")
从这里开始:参阅 references/usage-tracking.md,了解详细的 Admin API 集成说明
第 2 步:分析成本驱动因素
了解成本的实际来源。
识别高成本模式:
- 哪些操作使用的令牌最多?
- 哪些模型成本最高?
- 是否有效使用了缓存?
- 上下文窗口是否在不必要地增长?
- 是否发起了重复的 API 调用?
创建成本明细(示例):
Agent reasoning loops: 45% of costs
File analysis: 25% of costs
Web search: 15% of costs
Classification tasks: 10% of costs
Other: 5% of costs
需要计算的关键指标:
- 每笔交易的成本
- 每笔交易的令牌数
- 每项业务成果的成本
- 成本趋势(周环比)
第 3 步:应用优化
针对成本最高的驱动因素应用定向优化。
Effort 参数(使用 Opus 4.5 时):
- 复杂推理:高 effort(默认)
- 平衡型任务:中等 effort(节省 20%–40%)
- 简单分类:低 effort(节省 50%–70%)
上下文编辑(适用于长对话):
- 自动清除工具结果(节省 60%–90%)
- 客户端压缩(避免自动摘要)
- 集成记忆工具(支持无限长对话)
工具优化(适用于大型工具集):
- 使用工具搜索和延迟加载(支持 10K+ 工具)
- 以编程方式调用(数据处理的令牌用量减少 37%)
- 提供工具示例(将准确率从 72% 提高到 90%)
提示词缓存(适用于重复内容):
- 缓存系统提示词(缓存部分的成本降低 90%)
- 缓存重复的文件/文档
- 缓存工具定义
模型选择:
- Opus 4.5:输入 $5/M,输出 $25/M(复杂任务)
- Sonnet 4.5:(定价请参阅参考资料)
- Haiku 4.5:(定价请参阅参考资料)
第 4 步:跟踪改进情况
优化后监控成本下降和效率提升情况。
跟踪指标:
- 每笔交易的成本(优化前与优化后)
- 令牌总量减少百分比
- 质量影响(结果是更好还是更差?)
- 实施难度和耗时
衡量周期:每项优化跟踪 1–2 周,以观察其影响
影响示例:
Optimization: Client-side compaction on long research tasks
Before: 450K tokens/request, $11.25 cost
After: 180K tokens/request, $4.50 cost
Savings: 60% cost reduction
第 5 步:报告 ROI
计算优化带来的业务价值。
ROI 计算:
Monthly Savings = (Daily Cost × 30) - (Optimized Cost × 30)
Implementation Hours = Time to implement optimizations
Cost per Hour = $100-300 (your eng cost)
Payback Period = (Implementation Hours × Cost per Hour) / Monthly Savings
ROI 示例:
Monthly savings: $500/month
Implementation: 8 hours
Cost per hour: $150
Implementation cost: $1,200
Payback period: 2.4 months
First year ROI: 400%
快速入门 - 使用情况跟踪
5 分钟内开始使用 Admin API 跟踪成本:
import anthropic
from datetime import datetime, timedelta
client = anthropic.Anthropic()
def get_monthly_costs():
"""Get current month's token costs"""
# Get usage for last 30 days
now = datetime.now()
thirty_days_ago = now - timedelta(days=30)
response = client.beta.admin.usage_metrics.list(
limit=30,
sort_by="date",
)
total_input = sum(m.input_tokens for m in response.data)
total_output = sum(m.output_tokens for m in response.data)
# Opus 4.5 pricing: $5/M input, $25/M output
input_cost = total_input * 0.000005
output_cost = total_output * 0.000025
total_cost = input_cost + output_cost
print(f"Last 30 days:")
print(f" Input tokens: {total_input:,}")
print(f" Output tokens: {total_output:,}")
print(f" Input cost: ${input_cost:.2f}")
print(f" Output cost: ${output_cost:.2f}")
print(f" Total cost: ${total_cost:.2f}")
return {
"input_tokens": total_input,
"output_tokens": total_output,
"input_cost": input_cost,
"output_cost": output_cost,
"total_cost": total_cost
}
# Run the function
costs = get_monthly_costs()
快速入门 - ROI 计算
计算 Claude 实施方案的业务价值:
def calculate_roi(
monthly_cost: float,
monthly_transactions: int,
cost_before_claude: float = None,
quality_improvement: float = 1.0
) -> dict:
"""Calculate ROI metrics for Claude implementation"""
cost_per_transaction = monthly_cost / monthly_transactions
metrics = {
"monthly_cost": monthly_cost,
"monthly_transactions": monthly_transactions,
"cost_per_transaction": cost_per_transaction,
}
# If you had costs before Claude (manual process, previous tool, etc)
if cost_before_claude:
savings = cost_before_claude - monthly_cost
roi_percentage = (savings / cost_before_claude) * 100
metrics["previous_cost"] = cost_before_claude
metrics["monthly_savings"] = savings
metrics["roi_percentage"] = roi_percentage
# Account for quality improvements
effective_cost = monthly_cost / quality_improvement
metrics["quality_adjusted_cost"] = effective_cost
return metrics
# Example: Research agent replacing manual research
result = calculate_roi(
monthly_cost=500, # Claude costs
monthly_transactions=1000, # Requests processed
cost_before_claude=3000, # Manual research was $3k/month
quality_improvement=1.5 # Claude results are 50% better
)
print(f"Cost per transaction: ${result['cost_per_transaction']:.4f}")
print(f"Monthly savings: ${result['monthly_savings']:.2f}")
print(f"ROI: {result['roi_percentage']:.0f}%")
定价概览
当前 Claude 模型定价(截至 2025 年 11 月):
| 模型 | 输入 | 输出 | 适用场景 |
|---|---|---|---|
| Opus 4.5 | $5/M | $25/M | 复杂推理、Agent、编码 |
| Sonnet 4.5 | $3/M | $15/M | 性能与成本均衡 |
| Haiku 4.5 | $0.80/M | $4/M | 简单任务、高调用量 |
优化技术对成本的影响:
| 技术 | 节省幅度 | 实施难度 |
|---|---|---|
| Effort 参数(medium) | 20-40% | 简单(添加 2 行) |
| Effort 参数(low) | 50-70% | 简单(添加 2 行) |
| 上下文编辑 | 60-90% | 中等(需要设置) |
| 工具优化 | 37-85% | 中等(架构调整) |
| 提示词缓存 | 90% | 困难(基础设施) |
| 模型选择 | 50-75% | 困难(架构调整) |
成本对比示例(每月 100 万笔交易):
Scenario: Classification task
Opus 4.5, high effort:
- Input: 50M tokens @ $5/M = $250
- Output: 10M tokens @ $25/M = $250
- Total: $500/month
Opus 4.5, low effort:
- Input: 50M tokens @ $5/M = $250
- Output: 5M tokens @ $25/M = $125
- Total: $375/month (25% savings)
Haiku 4.5, high effort:
- Input: 50M tokens @ $0.80/M = $40
- Output: 10M tokens @ $4/M = $40
- Total: $80/month (84% savings)
优化决策树
START: Have high costs?
↓
Q1: Do you know what's causing the costs?
NO → Go to Step 2: Analyze Cost Drivers
YES → Q2: Have you tried effort parameter (Opus 4.5)?
NO → Apply effort parameter (medium/low)
Expect 20-70% savings, 2-4 hours implementation
YES → Q3: Do you have long conversations (>50K tokens)?
NO → Q4: Do you have 10+ tools in your agents?
NO → Q5: Can you cache repeated content?
YES → Implement prompt caching
Expect 90% savings on cached
NO → Consider model selection
Expect 2-5x cost reduction
YES → Implement tool search + deferred loading
Expect 85% context savings
YES → Implement context editing
Expect 60-90% savings on long tasks
常见优化场景
场景 1:将 Agent 成本降低 50%
优化前:
- Opus 4.5,使用 high effort
- 推理循环冗长
- 始终加载全部 20 多个工具
- 每月成本:$2,000
优化措施(按影响大小排序):
- Effort 参数:切换到 medium effort → 节省 30%($600)
- 工具优化:使用工具搜索 + 延迟加载 → 节省 20%($400)
- 上下文编辑:清除旧的工具结果 → 节省 10%($200)
- 总计:成本降低 60%,降至每月 $800
所需时间:实施需 20-30 小时
场景 2:将分类成本降低 80%
优化前:
- Opus 4.5,使用 high effort(分类任务用它大材小用)
- 简单的“是/否”决策
- 每月成本:$1,000
优化措施:
- 模型选择:切换到 Haiku 4.5 → 节省 80%($800)
- Effort 参数:使用 low effort → 在 Haiku 上额外节省 20%
- 提示词缓存:缓存分类规则 → 缓存部分节省 90%
- 总计:成本降低 85%,降至每月 $150
所需时间:实施需 5-10 小时
相关技能
如需深入了解特定优化领域,请参阅:
- claude-opus-4-5-guide:Effort 参数的权衡及 Opus 4.5 的能力
- claude-context-management:上下文编辑策略(长对话可节省 60-90%)
- claude-advanced-tool-use:工具优化模式(效率提升 37-85%)
- anthropic-expert:Admin API 参考和提示词缓存基础知识
如需完整的优化策略、成本预测模型和 ROI 衡量框架,请参阅 references/ 目录。