Sooua
登录
返回文章列表
Claude Code··8 分钟阅读

成本管理与优化

Claude Code 按 token 计费:

目标:理解 Claude Code 的计费方式,掌握降低使用成本的方法
预计时间:20 分钟
对应官方文档:CostsModel Config


计费原理

Claude Code 按 token 计费:

  • 输入 token:你发送的文字 + 加载的文件内容
  • 输出 token:Claude 生成的回复

模型价格对比

模型输入 ($/M token)输出 ($/M token)特点
Claude Opus$15$75最强能力,最贵
Claude Sonnet$3$15均衡选择,推荐日常
Claude Haiku$0.25$1.25最快最便宜,简单任务

价格可能变动,以 Anthropic 官网 为准。


查看实时消耗

当前会话

> /cost

Session usage:
  Input tokens:  45,230  (~$0.14)
  Output tokens: 8,920   (~$0.13)
  Total:         ~$0.27

历史统计

claude usage --last-week
 
Daily breakdown:
  2025-06-10: $12.50 (45K input, 12K output)
  2025-06-11: $8.30  (32K input, 8K output)
  ...

成本优化策略

1. 选择合适的模型

# 简单任务用 Sonnet(默认)
claude config set model sonnet
 
# 复杂架构设计用 Opus
claude config set model opus
 
# 快速查询用 Haiku
claude config set model haiku

在会话中临时切换:

> /model sonnet

2. 精简上下文

问题: 加载太多无关文件浪费 token。

解决:

# 只添加需要的文件
> /add src/auth.py src/models/user.py

# 移除不需要的文件
> /drop src/legacy/

# 定期压缩历史
> /compact

3. 使用 Prompt Caching

Claude Code 自动缓存 CLAUDE.md 和常用文件,后续请求复用缓存,成本降低 90%

> /cost

Cache hit rate: 85%  ✅
Saved: ~$5.20 (vs no caching)

保持缓存高效:

  • 不要在会话中频繁修改 CLAUDE.md
  • 大文件尽量用 @引用 而非 /add

4. 限制上下文窗口

// ~/.claude/settings.json
{
  "contextWindow": {
    "maxFiles": 20,
    "maxTokensPerFile": 4000
  }
}

5. 批量处理

不要多次问类似的问题:

❌ 低效:
> 解释函数 A
> 解释函数 B
> 解释函数 C

✅ 高效:
> 请解释以下三个函数的作用和关系:
> - @src/a.py::func_a
> - @src/b.py::func_b
> - @src/c.py::func_c

团队成本管理

设置预算限制

企业管理员可以:

// server-managed-settings.json
{
  "usageLimits": {
    "dailyBudget": 100,
    "monthlyBudget": 2000,
    "alertThreshold": 0.8
  }
}

查看团队用量

> /usage

Team usage (this month):
  Total: $1,245 / $2,000 (62%)
  
  Top users:
    1. [email protected]: $340
    2. [email protected]: $285
    ...
  
  Top projects:
    1. backend-api: $520
    2. mobile-app: $310

企业计费

云提供商渠道

通过 AWS/GCP/Azure 使用 Claude Code:

Zero Data Retention (ZDR)

企业版可选 ZDR:

  • 请求和响应不保留在 Anthropic 服务器
  • 部分功能受限
  • 参考:ZDR

成本检查清单

每日自查:

  • /cost 查看当前会话消耗
  • /compact 压缩过长历史
  • 确认使用的模型合适
  • 移除不需要的上下文文件
  • 团队是否接近预算上限

补充:成本优化决策流程与自动化

Token 消耗与成本优化决策流程

完整配置与脚本示例

示例 1:完整 ~/.claude/settings.json(成本优化版)

{
  "model": "sonnet",
  "contextWindow": {
    "maxFiles": 15,
    "maxTokensPerFile": 4000,
    "autoCompactThreshold": 0.8
  },
  "caching": {
    "enablePromptCaching": true,
    "persistentCacheDir": "~/.claude/cache"
  },
  "costControl": {
    "sessionBudgetAlert": 5.0,
    "dailyBudgetAlert": 20.0,
    "defaultToHaikuForSimpleQueries": true,
    "autoSwitchModel": {
      "enabled": true,
      "simpleQueryKeywords": ["explain", "what is", "how to", "documentation"],
      "complexQueryKeywords": ["design", "refactor", "architect", "optimize algorithm"]
    }
  },
  "ignorePatterns": [
    "node_modules/",
    "dist/",
    "build/",
    "*.min.js",
    "*.lock",
    "vendor/",
    ".git/",
    "coverage/",
    "*.log"
  ],
  "telemetry": {
    "enabled": false
  }
}

示例 2:模型切换策略脚本(Shell)

#!/bin/bash
# smart-model.sh - 根据任务描述自动建议模型
 
TASK="$1"
 
# 转换为小写
task_lower=$(echo "$TASK" | tr '[:upper:]' '[:lower:]')
 
# 定义关键词
simple_keywords="explain|what is|how to|documentation|summary|translate|find"
complex_keywords="design|refactor|architect|optimize algorithm|complex|debug difficult|security audit"
 
echo "任务: $TASK"
echo "---"
 
if echo "$task_lower" | grep -Eq "$simple_keywords"; then
    echo "建议模型: Haiku (快速、低成本)"
    echo "预估成本: ~$0.01-0.05"
    echo "切换命令: claude config set model haiku"
elif echo "$task_lower" | grep -Eq "$complex_keywords"; then
    echo "建议模型: Opus (最强推理能力)"
    echo "预估成本: ~$0.50-2.00"
    echo "切换命令: claude config set model opus"
else
    echo "建议模型: Sonnet (均衡选择)"
    echo "预估成本: ~$0.10-0.50"
    echo "切换命令: claude config set model sonnet"
fi

使用方式:

chmod +x smart-model.sh
./smart-model.sh "解释这段代码的作用"
# 输出:建议模型: Haiku ...
 
./smart-model.sh "设计一个支持百万并发的缓存架构"
# 输出:建议模型: Opus ...

示例 3:成本监控与告警脚本

#!/bin/bash
# cost-monitor.sh - 定时检查 Claude Code 使用成本
 
DAILY_LIMIT=20.0      # 每日预算(美元)
SESSION_LIMIT=5.0     # 单会话预算(美元)
ALERT_WEBHOOK="${SLACK_WEBHOOK_URL}"  # 可选:Slack/钉钉告警
 
# 获取今日用量(假设 claude usage 支持 JSON 输出)
today_cost=$(claude usage --today --json | jq -r '.totalCost // 0')
session_cost=$(claude --current-session-cost 2>/dev/null || echo "0")
 
echo "$(date '+%Y-%m-%d %H:%M:%S') 成本检查"
echo "今日累计: \$${today_cost} / \$${DAILY_LIMIT}"
echo "当前会话: \$${session_cost} / \$${SESSION_LIMIT}"
 
# 每日预算告警
if (( $(echo "$today_cost > $DAILY_LIMIT * 0.8" | bc -l) )); then
    msg="⚠️ Claude Code 成本告警:今日已使用 \$${today_cost}(预算 \$${DAILY_LIMIT})"
    echo "$msg"
    if [ -n "$ALERT_WEBHOOK" ]; then
        curl -s -X POST -H 'Content-type: application/json' \
            --data "{\"text\":\"$msg\"}" "$ALERT_WEBHOOK"
    fi
fi
 
# 单会话预算告警
if (( $(echo "$session_cost > $SESSION_LIMIT" | bc -l) )); then
    msg="🚨 单会话成本超限:当前会话 \$${session_cost},建议 /compact 或新建会话"
    echo "$msg"
    if [ -n "$ALERT_WEBHOOK" ]; then
        curl -s -X POST -H 'Content-type: application/json' \
            --data "{\"text\":\"$msg\"}" "$ALERT_WEBHOOK"
    fi
fi

添加到 crontab 每 30 分钟检查:

*/30 * * * * /home/user/scripts/cost-monitor.sh >> /home/user/logs/claude-cost.log 2>&1

实战场景

场景一:日常开发成本控制(Sonnet 为主,Haiku 辅助)

背景:一个 5 人团队使用 Claude Code 辅助开发,第一个月费用高达 $800,远超预期。经分析发现:所有会话都使用默认 Opus 模型,且大量简单查询(如"这个函数什么意思")也消耗了高额 token。

步骤

  1. 团队统一将默认模型改为 Sonnet:claude config set model sonnet
  2. 制定内部规范:简单查询(解释代码、查找文件、翻译注释)先用 Haiku
  3. ~/.claude/settings.json 中开启 autoSwitchModel,让 Claude 自动判断
  4. 每个开发者养成习惯:长会话超过 50 轮就 /compact
  5. 将大文件(如 package-lock.json、历史日志)加入 .claudeignore

结果

  • 次月总费用降至 $220,降低 72%
  • 响应速度反而提升(Haiku/Sonnet 比 Opus 更快)
  • 只有在设计复杂算法和架构时才手动切换 Opus,确保关键时刻有最强能力
  • Prompt Caching 命中率从 30% 提升到 78%,进一步节省成本

场景二:月度预算预警(团队成本管理)

背景:公司预算部门要求研发团队将 Claude Code 月度费用控制在 $500 以内,但需要提前预警而非月底才发现超支。

步骤

  1. 运维部署 cost-monitor.sh 脚本到团队共享的开发服务器
  2. 配置每日预算 20(月度20(月度 500 按工作日均摊),告警阈值 80%
  3. 脚本每 30 分钟读取 claude usage 数据,超阈值时发送 Slack 通知到 #dev-alerts
  4. 团队约定:收到告警后,当天剩余时间优先用 Haiku,复杂任务推迟到次日
  5. 每周五回顾用量分布,识别"高消费"项目,针对性优化上下文加载策略

结果

  • 连续 3 个月费用控制在 450450-500 区间,无超支
  • 告警机制让团队在当天就能调整行为,而非月底被动接受账单
  • 通过回顾发现某成员习惯 /add . 加载整个项目,针对性培训后该成员个人用量下降 55%
  • 团队形成了"成本意识",Prompt 写得更加精炼,减少无效迭代

下一步

08. 最佳实践与工作流程

分享

评论

登录 后参与讨论。

加载中…

相关文章