token-optimization

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Token Optimization — Claude Code

Token 优化 — Claude Code

Overview

概述

Token overconsumption in Claude Code stems from four main sources:
  1. Cache miss — uncached or invalidated requests
  2. Context bloating — unnecessarily growing context window
  3. Wrong model / wrong effort — reasoning overuse
  4. Verbose input format — overly verbose data injected into context

Claude Code 中的 Token 过度消耗主要源于 四个主要来源:
  1. 缓存未命中 — 未缓存或缓存已失效的请求
  2. 上下文膨胀 — 上下文窗口无必要地不断增长
  3. 模型选择错误 / 推理力度错误 — 过度使用推理
  4. 输入格式冗长 — 向上下文中注入过于冗长的数据

Phase 1: Initial Session Audit

阶段 1:初始会话审计

Before any work, run these two commands:
bash
/context   # Shows loaded MCPs and tokens already consumed
/plugin    # Lists active plugins
Systematic actions:
  • Disable all MCPs not needed for current project
  • Disable all unused plugins
  • One project ≠ one global config → customize per project
Real example: empty session with Canva + Gmail + Google Calendar MCPs loaded = 23,000 tokens consumed before first keystroke.
Red flags to check:
  • More than 3 MCPs loaded
  • Plugins unrelated to current work
  • Base token count >10,000 on empty session

开始任何工作前,运行以下两个命令:
bash
/context   # Shows loaded MCPs and tokens already consumed
/plugin    # Lists active plugins
系统性操作:
  • 禁用当前项目不需要的所有 MCP
  • 禁用所有未使用的插件
  • 一个项目 ≠ 一份全局配置 → 按项目定制
实际示例:空会话加载 Canva + Gmail + Google Calendar MCP = 在首次按键前就消耗了 23,000 个 Token。
需要检查的危险信号:
  • 加载的 MCP 超过 3 个
  • 插件与当前工作无关
  • 空会话的基础 Token 数量 >10,000

Phase 2: Cache Management

阶段 2:缓存管理

Principle

原则

Claude Code caches: system instructions (CLAUDE.md), tool/MCP list, and message history. Any modification during session invalidates this cache, causing complete re-billing of affected tokens.
Claude Code 会缓存:系统指令(CLAUDE.md)、工具/MCP 列表和消息历史。会话期间任何 修改 都会使此缓存失效,导致相关 Token 被完全重新计费。

Imperative rules

强制规则

  • Never add a tool, MCP, or model mid-session. Configure everything before starting, or in a dedicated setup session.
  • If a critical addition is required mid-session (heavy skill, MCP, critical command):
    1. Compact the session (
      /compact
      )
    2. Start new session with compacted summary as starting point
  • Treat cache like HTTP cache: changing a header invalidates everything downstream.
  • 切勿在会话中途添加工具、MCP 或模型。 在开始前配置好所有内容,或者在专门的设置会话中配置。
  • 如果中途必须添加关键内容(重型 skill、MCP、关键命令):
    1. 压缩会话(
      /compact
      )
    2. 开启新会话,并以压缩后的摘要作为起点
  • 像对待 HTTP 缓存 一样对待缓存:更改标头会使其下游全部失效。

Cache invalidation hierarchy

缓存失效层级

┌─────────────────────────────────────────────┐
│ BASE SYSTEM INSTRUCTIONS (CLAUDE.md + tools)│  ← Invalidated if tool added
├─────────────────────────────────────────────┤
│ SESSION STATE (project files, memory)       │  ← Invalidated if file changes
├─────────────────────────────────────────────┤
│ MESSAGE HISTORY                             │  ← Invalidated if message edited
│  msg 1 → msg 2 → msg 3 → ...                │     (invalidates everything after)
└─────────────────────────────────────────────┘
What invalidates cache:
ActionLayer invalidatedImpact
Add MCP mid-sessionBase instructionsVery high
Add tool (tool calling)Base instructionsVery high
Modify CLAUDE.mdBase instructionsVery high
Edit message in middle of historyMessage history (from that point)Moderate
Load new file into contextSession stateModerate
Optimal session strategy:
1. Full configuration (MCP, tools, CLAUDE.md) → BEFORE starting
2. Work session → NEVER modify configuration
3. If modification needed → /compact → new session
4. Agents → context fork → isolated work → result only
For technical details on cache issues, see
references/cache-deep-dive.md
.

┌─────────────────────────────────────────────┐
│ BASE SYSTEM INSTRUCTIONS (CLAUDE.md + tools)│  ← Invalidated if tool added
├─────────────────────────────────────────────┤
│ SESSION STATE (project files, memory)       │  ← Invalidated if file changes
├─────────────────────────────────────────────┤
│ MESSAGE HISTORY                             │  ← Invalidated if message edited
│  msg 1 → msg 2 → msg 3 → ...                │     (invalidates everything after)
└─────────────────────────────────────────────┘

Phase 3: Context Window Optimization

哪些操作会使缓存失效

Reduce default context window

—
The 1M token window is tempting but dangerous: it encourages bad habits and overloads child agents.
Conditional recommendation:
  • Small/medium codebase → limit to ~200,000 tokens in
    settings.json
    :
    json
    { "contextWindow": 200000 }
    (not committed by default — use local file)
  • Very large codebase → keep 1M, but optimize practices below even more aggressively.
RAM analogy: having 32GB RAM doesn't justify poor memory management. A constrained window forces better discipline.
操作失效的层级影响
会话中途添加 MCP基础指令极高
添加工具(工具调用)基础指令极高
修改 CLAUDE.md基础指令极高
编辑消息历史中间的消息从该位置起的消息历史中等
将新文件加载到上下文会话状态中等

Context forking and isolated agents

最佳会话策略:

Agents inherit parent context at spawn time. The longer you wait, the heavier they start.
Target behavior:
  • Call each skill or agent in a forked context (
    context: fork
    in parameters)
  • Agent works in its own window → at completion, returns only the result, not full history
  • When agent is destroyed, main context hasn't moved
Systematic use cases to isolate in subagent:
TaskWhy isolate
Web searchMarkdown history of visited pages pollutes main window
PDF / audio transcriptionHigh-volume output, unnecessary in main context
Planning / test generationLong work, clean context
Codebase explorationNative
explore
agent (uses IQ) already optimized for this
Prompt to add to CLAUDE.md:
For any web search, systematically delegate to isolated subagent.
Return only extracted relevant information, not full history.
1. Full configuration (MCP, tools, CLAUDE.md) → BEFORE starting
2. Work session → NEVER modify configuration
3. If modification needed → /compact → new session
4. Agents → context fork → isolated work → result only
有关缓存问题的技术细节,请参阅
references/cache-deep-dive.md
。

Compaction and Rewind

阶段 3:上下文窗口优化

—

缩小默认上下文窗口

  • Automatic compaction: triggers when agent reaches ~80% of window. Desirable for agents, not for main session.
  • Rewind (double
    Esc
    ): allows returning to previous conversation and deleting unnecessary context branch. Use immediately when going in wrong direction.

100 万 Token 的窗口很诱人,但也很危险:它会助长不良习惯,并使子 Agent 过载。
有条件建议:
  • 小型/中型代码库 → 在
    settings.json
    中限制为约 200,000 个 Token:
    json
    { "contextWindow": 200000 }
    (默认不提交 — 使用本地文件)
  • 超大型代码库 → 保留 1M,但需更加严格地执行以下优化实践。
RAM 类比:拥有 32GB RAM 并不意味着可以疏于内存管理。受限的窗口能强制养成更好的使用纪律。

Phase 4: Model & Reasoning Effort Selection

上下文分叉与隔离 Agent

Reasoning effort

—
The effort system loops on the prompt to verify response quality. Each loop = additional tokens.
SituationRecommended effort
Clear, well-defined taskMedium (default)
Complex reasoning, architecture, designHigh
Simple task, known commandLow / none (
think
unnecessary)
Rule: if the answer is clear in your mind, use
medium
. Ask Claude to think with you, not for you.
Agent 在创建时继承父级上下文。等待得越久,其启动时携带的上下文就越重。
目标行为:
  • 在分叉上下文中调用每个 skill 或 Agent(在参数中使用
    context: fork
    )
  • Agent 在自己的窗口中工作 → 完成后仅返回结果,而不是完整历史
  • Agent 被销毁时,主上下文不会发生变化
适合通过子 Agent 隔离的系统性用例:
任务隔离原因
网络搜索已访问页面的 Markdown 历史会污染主窗口
PDF / 音频转录输出量大,主上下文中并不需要
规划 / 测试生成工作时间长,需要干净的上下文
代码库探索原生
explore
Agent(使用 IQ)已经针对此场景优化
可添加到 CLAUDE.md 的提示词:
For any web search, systematically delegate to isolated subagent.
Return only extracted relevant information, not full history.

Model choice

压缩与回退

  • Claude Code subscription → use native Anthropic models (Sonnet / Opus). No proxy.
    • Opus: prefer for complex tasks despite latency
    • Sonnet: fast tasks, common code generation
  • Proxy to other LLMs (GLM, Kimi...): only relevant if using SDK/API directly, not in standard Claude Code. Proxies are unstable and unoptimized.
Add to CLAUDE.md:
markdown
undefined
  • 自动压缩:当 Agent 达到窗口约 80% 时触发。对于 Agent 而言是可取的,但对于主会话并非如此。
  • 回退(Rewind)(连按两次
    Esc
    ):允许返回之前的对话并删除不需要的上下文分支。走错方向时应立即使用。

Reasoning effort

阶段 4:模型与推理力度选择

—

推理力度

  • Simple task / known command → minimal effort, no
    think
  • Design / architecture task → medium effort
  • Complex unsolved problem → high effort only on explicit request Never over-reason a simple task.

---
推理力度系统会循环处理提示词,以验证响应质量。每次循环 = 额外 Token。
情况建议的推理力度
明确、定义充分的任务Medium(默认)
复杂推理、架构、设计High
简单任务、已知命令Low / 无(无需
think
)
规则:如果答案在你脑中已经明确,就使用
medium
。让 Claude 与你一起思考,而不是替你思考。

Phase 5: Input Format Optimization

模型选择

Browser automation: DOM over screenshots

—
Native Claude Code browser agent takes screenshots at each step → very costly in tokens and time.
Recommended alternative: Stagehand / Agent Browser (Vercel)
  • Operates directly on DOM (invisible, no screenshots)
  • Installation: open new Claude Code instance →
    Install [stagehand URL]
  • Result: 10× faster, drastically reduced tokens
  • Claude Code 订阅 → 使用原生 Anthropic 模型(Sonnet / Opus)。不使用代理。
    • Opus:复杂任务优先使用,尽管延迟较高
    • Sonnet:适用于快速任务和常见代码生成
  • 代理到其他 LLM(GLM、Kimi...):仅在使用 SDK/API 直接调用时相关,而不适用于标准 Claude Code。代理不稳定且未优化。
添加到 CLAUDE.md:
markdown
undefined

Filter verbose CLI output

Reasoning effort

Commands like
git status
,
git diff
are extremely verbose once injected into context.
Recommended tool: RTK (developed by French developer)
  • Filters command output before context window injection
  • Example:
    git status
    goes from ~50 lines to ~5 essential lines → ~80% savings on this command
  • Global installation:
    bash
    # Run in Claude Code
    npx rtk init --global
  • Simple task / known command → minimal effort, no
    think
  • Design / architecture task → medium effort
  • Complex unsolved problem → high effort only on explicit request Never over-reason a simple task.

---

Concise responses: Caveman Skill / CLAUDE.md

阶段 5:输入格式优化

—

浏览器自动化:使用 DOM 而非截图

By default, Claude Code is very verbose. Drastically reduce response volume:
Directives to add to CLAUDE.md:
markdown
undefined
Claude Code 原生浏览器 Agent 每一步都会截取屏幕截图 → 在 Token 和时间方面的成本很高。
推荐的替代方案:Stagehand / Agent Browser (Vercel)
  • 直接在 DOM 上操作(不可见,无截图)
  • 安装:打开新的 Claude Code 实例 →
    Install [stagehand URL]
  • 结果:快 10 倍,Token 大幅减少

Response style

过滤冗长的 CLI 输出

Ultra-concise responses. Remove articles, politeness phrases, reformulations. Get to the point. Format: short bullet points. No intro, no conclusion.

**Caveman Skill** (available on GitHub, ~50k stars): ready-to-use directives to integrate directly into CLAUDE.md. See `references/claude-md-templates.md` for examples.
git status
、
git diff
等命令一旦注入上下文,内容就会非常冗长。
推荐工具:RTK(由法国开发者开发)
  • 在注入上下文窗口前过滤命令输出
  • 示例:
    git status
    从约 50 行缩减为约 5 行必要内容 → 该命令节省约 80%
  • 全局安装:
    bash
    # Run in Claude Code
    npx rtk init --global

Specify file paths explicitly

简洁响应:Caveman Skill / CLAUDE.md

Don't let Claude discover files on its own in commands:
undefined
默认情况下,Claude Code 的响应非常冗长。可大幅减少响应量:
可添加到 CLAUDE.md 的指令:
markdown
undefined

❌ Costly: Claude will list, explore, read

Response style

"Update project memory"
Ultra-concise responses. Remove articles, politeness phrases, reformulations. Get to the point. Format: short bullet points. No intro, no conclusion.

**Caveman Skill**(GitHub 上可用,约 5 万星标):提供可直接集成到 CLAUDE.md 的即用指令。示例见 `references/claude-md-templates.md`。

✅ Optimal: explicit paths in command

明确指定文件路径

"Update ./docs/memory.md and ./CLAUDE.md with following items: ..."

**Template for memory commands:**

```markdown
不要让 Claude 在命令中自行查找文件:
undefined

Memory/Learning commands

❌ Costly: Claude will list, explore, read

/learn
command: updates ONLY the following files:
  • ./docs/project-memory.md
  • ./CLAUDE.md (section "Project Context") Do not scan other files unless explicitly instructed.

---
"Update project memory"

Phase 6: Validation & Monitoring

✅ Optimal: explicit paths in command

Check context consumption

—
After implementing optimizations, verify:
bash
/context    # Check current token count
Success criteria:
  • Base session <5,000 tokens (with necessary MCPs only)
  • After 10 interactions: <30,000 tokens
  • No agents exceeding 50,000 tokens for isolated tasks
"Update ./docs/memory.md and ./CLAUDE.md with following items: ..."

**记忆命令模板:**

```markdown

Team monitoring

Memory/Learning commands

For teams needing consumption tracking:
  • Local dashboard tool (created by reference article author): displays sessions, called models, tokens per session
  • More useful for managers/leads than solo developers
  • See references below for link
Documented concrete result: went from $750/month to $100/month with these optimizations (source: article linked in reference video).

/learn
command: updates ONLY the following files:
  • ./docs/project-memory.md
  • ./CLAUDE.md (section "Project Context") Do not scan other files unless explicitly instructed.

---

Troubleshooting

阶段 6:验证与监控

High token count despite optimizations

检查上下文消耗

Diagnosis steps:
  1. Run
    /context
    → identify which MCPs are loaded
  2. Check
    settings.json
    → verify contextWindow setting
  3. Review recent commands → identify verbose outputs
  4. Check agent spawns → verify context forking
Common fixes:
  • Disable unused MCPs
  • Add RTK filtering for git commands
  • Move to subagents for research tasks
  • Reduce contextWindow if codebase allows
实施优化后,验证:
bash
/context    # Check current token count
成功标准:
  • 基础会话 <5,000 Token(仅加载必要的 MCP)
  • 10 次交互后:<30,000 Token
  • 隔离任务中的 Agent 均不超过 50,000 Token

Cache invalidation happening frequently

团队监控

Diagnosis:
  1. Check if skills are being loaded mid-session
  2. Verify CLAUDE.md isn't changing
  3. Look for tool additions in session
Fixes:
  • Preload all needed skills at session start
  • Lock CLAUDE.md configuration
  • Use dedicated setup session for config changes
对于需要跟踪 Token 消耗的团队:
  • 本地仪表板工具(由参考文章作者创建):显示会话、调用的模型以及每个会话的 Token 数
  • 对经理/负责人比个人开发者更有用
  • 链接见下方参考资料
有记录的实际结果:通过这些优化,费用从 $750/月降至 $100/月(来源:参考视频中链接的文章)。

Agents consuming too many tokens

故障排查

—

优化后 Token 数量仍然很高

Diagnosis:
  1. Check if agents inherit bloated parent context
  2. Verify agents aren't loading unnecessary MCPs
  3. Look for verbose tool outputs in agent history
Fixes:
  • Spawn agents earlier (lighter parent context)
  • Use
    context: fork
    parameter
  • Return only results, not full agent history

诊断步骤:
  1. 运行
    /context
    → 确认加载了哪些 MCP
  2. 检查
    settings.json
    → 验证
    contextWindow
    设置
  3. 审查最近执行的命令 → 找出冗长输出
  4. 检查 Agent 创建情况 → 验证是否使用了上下文分叉
常见修复:
  • 禁用未使用的 MCP
  • 为 git 命令添加 RTK 过滤
  • 将研究任务移至子 Agent
  • 如果代码库允许,缩小
    contextWindow

Examples

缓存频繁失效

Example 1: Project setup with token optimization

—
User says: "Set up new project with optimal token configuration"
Actions:
  1. Create minimal CLAUDE.md with concise response directives
  2. Configure contextWindow based on codebase size
  3. Enable only essential MCPs for project type
  4. Add RTK filtering for git commands
  5. Define subagent delegation rules
  6. Verify base session <5,000 tokens
Expected result: Optimized session configuration, documented in project CLAUDE.md
诊断:
  1. 检查是否在会话中途加载了 skill
  2. 确认 CLAUDE.md 没有发生变化
  3. 查找会话期间新增的工具
修复:
  • 在会话开始时预加载所有必要的 skill
  • 锁定 CLAUDE.md 配置
  • 使用专门的设置会话修改配置

Example 2: Diagnosing high token consumption

Agent 消耗的 Token 过多

User says: "My sessions are consuming too many tokens, help diagnose"
Actions:
  1. Run
    /context
    to audit current state
  2. Check loaded MCPs and plugins
  3. Review recent command outputs for verbosity
  4. Identify cache invalidation patterns
  5. Generate optimization recommendations
  6. Implement fixes prioritized by impact
Expected result: Identified root causes, implemented fixes, reduced token consumption by 50-80%
诊断:
  1. 检查 Agent 是否继承了膨胀的父级上下文
  2. 确认 Agent 未加载不必要的 MCP
  3. 检查 Agent 历史中是否记录了冗长的工具输出
修复:
  • 更早派生 Agent(父级上下文更轻量)
  • 使用
    context: fork
    参数
  • 仅返回结果,不返回完整的 Agent 历史

Example 3: Web research task

示例

—

示例 1:使用 Token 优化配置项目

User says: "Research best practices for React Server Components"
Actions:
  1. Spawn isolated subagent with context fork
  2. Subagent performs web searches
  3. Subagent extracts key findings only
  4. Return summary to main context (not full search history)
  5. Main context receives ~500 tokens instead of ~5,000
Expected result: Research completed with 90% token savings vs direct search

用户说:“使用最佳 Token 配置搭建新项目”
操作:
  1. 创建精简版 CLAUDE.md,其中包含简洁响应指令
  2. 根据代码库大小配置
    contextWindow
  3. 仅为项目类型启用必要的 MCP
  4. 为 git 命令添加 RTK 过滤
  5. 定义子 Agent 委派规则
  6. 验证基础会话 <5,000 Token
预期结果: 获得优化的会话配置,并记录在项目的 CLAUDE.md 中

References

示例 2:诊断高 Token 消耗

For detailed technical information:
  • references/cache-deep-dive.md
    — Cache behavior and invalidation patterns
  • references/claude-md-templates.md
    — Ready-to-use CLAUDE.md configuration blocks
  • references/tools.md
    — External tools (Stagehand, RTK) setup guides
External resources:

用户说:“我的会话消耗了太多 Token,请帮我诊断”
操作:
  1. 运行
    /context
    审计当前状态
  2. 检查已加载的 MCP 和插件
  3. 审查最近的命令输出是否冗长
  4. 识别缓存失效模式
  5. 生成优化建议
  6. 按影响程度实施修复
预期结果: 找出根本原因、实施修复,并将 Token 消耗降低 50–80%

Quality Checklist

示例 3:网络研究任务

Before completing optimization:
  • Base session <5,000 tokens
  • Only essential MCPs loaded
  • CLAUDE.md includes concise response directives
  • Context forking configured for research tasks
  • RTK or equivalent filtering installed for verbose commands
  • contextWindow set appropriately for codebase size
  • Team members trained on cache invalidation rules (if applicable)
用户说:“研究 React Server Components 的最佳实践”
操作:
  1. 创建带上下文分叉的隔离子 Agent
  2. 子 Agent 执行网络搜索
  3. 子 Agent 仅提取关键发现
  4. 将摘要返回主上下文(而不是完整搜索历史)
  5. 主上下文接收约 500 Token,而不是约 5,000 Token
预期结果: 相比直接搜索,节省 90% Token

—

参考资料

—
有关更详细的技术信息:
  • references/cache-deep-dive.md
    — 缓存行为与失效模式
  • references/claude-md-templates.md
    — 可直接使用的 CLAUDE.md 配置块
  • references/tools.md
    — 外部工具(Stagehand、RTK)设置指南
外部资源:

—

质量检查清单

—
完成优化前:
  • 基础会话 <5,000 Token
  • 仅加载必要的 MCP
  • CLAUDE.md 包含简洁响应指令
  • 已为研究任务配置上下文分叉
  • 已为冗长命令安装 RTK 或同类过滤工具
  • 已根据代码库大小合理设置
    contextWindow
  • 团队成员已接受缓存失效规则培训(如适用)