Effective Token Usage Guide · V1.0
Preface
As AI-assisted coding becomes the norm, tokens have become an explicit compute cost, not background noise that can be ignored.
The real problem for many teams is not that they do not know they should reduce usage, but that:
- The bill keeps rising, yet nobody can identify which task type, Skill, person, or workflow is consuming the money;
- They optimize many Prompts, only to find that the bill barely changes;
- They adopt a new tool that is "supposed to save a lot," only for the total cost to increase.
There is only one root cause: without measurement, there is no optimization.
In engineering practice, this is no different from defining monitoring, alerting, and SLI/SLOs on day zero.
That is why measurement is Chapter 1 — every optimization in the chapters that follow must build on the measurement baseline established here.
Glossary
This guide assumes that readers are familiar with common AI coding tools such as Claude Code, CodeBuddy, Cursor, and Copilot. The following terms recur throughout the guide and are defined here to avoid ambiguity.
| Term | Alias / Meaning | Brief explanation |
|---|---|---|
| Token | Token | The smallest billable unit of text processed by an LLM. Rough estimate: one Chinese character ≈ 1–2 tokens; one English word ≈ 1.3 tokens. |
| Input / Output | Input / Output | All content sent to the model in a request / all content returned by the model. They are billed separately at different rates. |
| Context | Context window | Everything actually sent to the model in one request: System Prompt + history + user request + tool definitions + retrieval results, and so on. |
| System Prompt | System instructions | Fixed instructions placed at the beginning of the context on every turn, usually including roles, rules, and tool descriptions. |
| Session | Continuous conversation | All turns from the start of a conversation until /clear or the session is closed share the same history context. |
| Prompt Cache | Prefix cache | Caches the computation for a request prefix so it can be reused. A hit is billed as Cache read (about one-tenth of Input in Anthropic's case); a miss or initial write is billed as Cache write. |
| TTL | Time to live | How long a cache entry remains valid. For example, Anthropic defaults to 5 minutes and optionally supports 1 hour; other vendors use different mechanisms. |
| Thinking / Reasoning | Reasoning tokens | The model's intermediate reasoning before its final answer. This also consumes tokens and is counted as output by Anthropic. |
| Skill | Skill | Reusable workflow instructions composed of Description + Instructions + Examples, such as code-review or commit-message. |
| Rules | Rules | Global or project-level behavioral constraints, such as coding conduct and token efficiency, usually sent with the System Prompt on every turn. |
| Agent | Agent | An execution unit capable of calling tools autonomously. It can have its own model, Skills, and toolset. |
| Subagent | Subagent | An independent Agent delegated a task by the main Agent. It has an isolated, one-time context and returns only its conclusion to the main Agent. |
| Command | Command | A fixed-template task triggered with /xxx, such as /commit, /clear, /compact, or /cost. |
| MCP | Model Context Protocol | A standardized protocol that connects AI tools to external systems such as databases, APIs, and file systems. |
| Tool Definition | Tool schema | A schema describing a tool's capabilities, parameters, and return values. It is sent with the context on every turn. |
| RAG | Retrieval-Augmented Generation | Retrieves external knowledge first, then inserts the retrieved content into the context. |
| Learnings | Captured knowledge | Lessons and best practices accumulated by a team, usually injected into the context only when recalled. |
| SLI / SLO | Service Level Indicator / Service Level Objective | Observable metrics used for measurement and governance (SLIs), and their target values (SLOs). |
Quick command reference:
/cost(view usage for the current turn),/compact(compress history),/clear(clear the current session).
Chapter 1: Measure First — Without Measurement, There Is No Optimization
Quantify first. If it cannot be measured, do not do it.
1.1 If You Do Not Know What Is Expensive, You Do Not Know What to Save
The Real-World Problem
AI coding tools usually provide only aggregate billing figures:
- Total tokens for the month
- Total cost for the month
- Totals by model
But they do not tell you:
- Which tokens were spent on Input
- Which were spent on Output
- How many came from Prompt Cache hits
- How many came from Cache writes
- How many came from Thinking / Reasoning
- Which came from tool round-trips
- Which came from retries
The result is that intuition is often wrong.
1.2 Token Profile of a Single Request
To understand where the money goes, you must first understand the token composition of a single request.
| Field | Meaning | Cost characteristics |
|---|---|---|
| Input | Input tokens: System Prompt + history + context + user request, including the portion served from cache | Base cost; strongly affected by prefix stability |
| Output | All tokens generated by the model | Usually more expensive than Input and easy to let grow out of control |
| Cache read | Input tokens served from the Prompt Cache | About one-tenth of the Input price; unavailable after the cache expires |
| Cache write | Tokens written to the cache for the first time | An initial cost amortized over later reuse; cache expiration still matters |
| Thinking | Tokens consumed during reasoning, such as Claude's thinking budget | High value, but also high cost |
How to Obtain This Data
- CodeBuddy / WorkBuddy / Codex / Claude Code
- Use the
/costcommand - Enable telemetry to obtain a per-request breakdown
- Use the
Incorrect Example
The developer looks only at total cost, not its composition:
- Output has a high share, so they assume the model is too verbose;
- In reality, the Prompt does not constrain the output format, so the model responds freely;
- The optimization effort targets the wrong problem.
Correct Example
After every critical task, the developer routinely checks `/cost`:
- They notice that the proportion of cache-read tokens remains below 20% for a certain task type;
- They check whether the prefix changes frequently or a Skill is reloaded every time;
- After adjustment, the Cache hit rate remains above 70%;
- Input cost for the same task falls to one-third of its previous level.
1.3 Key Metrics and Target Values
Based on the five fields above, we define a set of SLIs that the team must monitor continuously.
1. Cache Hit Rate
Definition: Cache read tokens / Input tokens (Input means total input, including the cache-hit portion; see the five-field table in Section 1.2).
| Range | Assessment | Recommended action |
|---|---|---|
| > 70% | Healthy | Maintain the current state and review it periodically |
| 40%–70% | Warning | Check prefix stability and the frequency of Skill/Rules changes |
| < 40% | Critical | Temporarily stop adding new Skills and prioritize context restructuring |
Note: These are reference ranges. Each team should calibrate them against its actual operating baseline.
Why so strict?
Prompt Cache is currently the most cost-effective "free lunch." A hit rate below 40% usually means:
- The prefix changes frequently
- Session management is chaotic
- Skills / Rules are poorly designed
2. Output / Input Ratio
Definition: Output tokens / Input tokens
- Too high (> 3)
- The model is "chatting" rather than producing the requested deliverable
- Common causes: no output constraints, no prefill, and unconstrained responses
- Too low (< 0.3)
- The model may be overly conservative, or retries and formatting failures may be frequent
- Reasonable range
- Coding tasks are usually within 0.5–1.5
- Pure reasoning or planning tasks may use a wider range
3. Average Tokens per Task
- Definition: Total tokens consumed by one task, such as one bug fix or one feature implementation
- Uses:
- Identify outliers that deviate significantly from the average
- Provide a baseline metric for SLOs
Incorrect Example
The team looks only at total monthly cost and does not track the metrics above:
- Cache hit rate remains around 30%;
- The Output/Input ratio reaches 5;
- Nobody notices because total cost is still within budget;
- By the time the budget becomes tight, substantial structural waste has accumulated.
Correct Example
The team reviews three metrics in every weekly meeting:
- Cache hit rate: 78%
- Output/Input ratio: 1.2
- Average tokens per task: p50 = 45K, p95 = 180K
Outliers, such as a Skill that suddenly raises p95, receive focused remediation.
Within six months, token cost falls by 55% for the same workload.
1.4 Team-Level Billing Attribution
Aggregate totals are nowhere near enough. Costs must be attributed across multiple dimensions.
Recommended Four-Dimensional Attribution Model
- By person
- Who is consuming tokens?
- Do any team members show abnormal usage patterns?
- By project
- Which project is the cost center?
- Does the cost match the project's phase, such as early exploration versus stable maintenance?
- By Skill / Agent
- Which Skill / Agent is the most expensive?
- Are there any high-cost, low-value Skills / Agents?
- By model
- Is each model's share of cost reasonable?
- Are there obvious mismatches, such as using Opus to write unit tests?
Implementation Recommendations
- Generate a team token dashboard every week
- Include at least the four dimensions above
- Mark period-over-period changes and abnormal fluctuations
- Use the dashboard as:
- A standing agenda item in weekly meetings
- An important input to Skill / Prompt reviews
Chapter 2: Where the Bill Goes
Tokens do not disappear. They flow through a fixed cost chain — from your request, to the System Prompt, to conversation history, to tool round-trips, and finally to model output.
2.1 Your Request Is Usually the Cheapest Part
A Typical Token Distribution
| Component | Typical token volume | Cost role |
|---|---|---|
| System Prompt | 3K–10K | Fixed cost paid on every turn |
| Skill / Instructions | 5K–30K | Increases as Skills are loaded |
| Tool Definitions | 5K–20K | Increases with the number of MCP servers and tools |
| Session history | 10K–200K+ | Grows linearly with the number of turns |
| Retrieved content (RAG / search) | 5K–50K | Depends on the retrieval strategy |
| Code files / Patch | 5K–100K | Depends on read granularity |
| User query | 50–500 | A very small share |
Core formula:
Total cost ≈ fixed prefix + session history + runtime retrieval + tool round-trips + model output
Incorrect Example
A one-line request: "Build a login feature." "Fix bug."
Result:
- The model misunderstands and enters multiple rounds of clarification;
- The number of tool calls doubles;
- Output grows and retries increase;
- Total cost rises instead.
**Root cause**: saving money in the wrong place.
Correct Example
"Please fix this bug. The reproduction steps are..."
- Compress 20K of Skill instructions to 8K by removing filler and merging duplicate rules;
- Limit the number of lines returned by tools (`head -n 100`);
- Reference the exact file with `@path/to/file` instead of making the model search blindly.
✅ Rule of thumb: Rather than shortening the user request, reduce System / Skill / Tool / History.
2.2 "It Remembers" Is an Illusion
LLMs have no memory.
When it appears that the model remembers, what actually happened is that all previous content was sent again.
Three Key Implications
- The longer the context, the higher the cost
- The cost of turn 10 is not simply ten times the cost of turn 1
- Every turn pays for all preceding turns again
- The more tools, the heavier the load
- Every tool comes with a "manual": its schema and description
- These manuals are reloaded into the context on every turn
- Tool calls create a cost loop
User request
↓
Model decision
↓
Tool call
↓
Tool result (large!)
↓
Model processing
↓
Next tool call...
2.3 Five Types of Cost
In addition to Input and Output, three other types of cost are often underestimated.
| Cost type | When it occurs | How easy it is to overlook | Impact |
|---|---|---|---|
| Input cost | System Prompt, history, files | Low | ⭐⭐ |
| Output cost | Model-generated content | Low | ⭐⭐⭐ |
| Thinking cost | Reasoning / thinking budget | High | ⭐⭐⭐⭐ |
| Tool round-trip cost | Tool calls + returned results | Very high | ⭐⭐⭐⭐⭐ |
| Retry cost | Formatting errors, unclear instructions, tool failures | Very high | ⭐⭐⭐⭐⭐ |
Tool Round-Trips: The Most Underestimated Cost Sink
Tool round-trip cost = tool definition + returned content + context reassembly + additional model reasoning
A typical grep call:
- Tool definition: ~300 tokens
- Returned results: ~2,000 tokens
- Context reassembly: ~500 tokens
- Model processing: ~1,000 tokens
A single tool call can easily exceed 3,500 tokens.
If the model hesitates and makes five consecutive tool calls, cost can quickly spiral out of control.
2.4 Prompt Cache: The Foundation of Optimization
Prompt Cache caches the computation of a prefix, not the answer.
Three Key Facts
- The prefix is what gets cached
- Only an identical prefix can produce a hit
- Changing even one character may invalidate the cache
- TTL is commonly 5 minutes
- Reuse within 5 minutes: Cache read, about one-tenth of the price, depending on the model
- After 5 minutes: another full-price Cache write
Note: Cache expiration differs by model. Anthropic supports 5m and 1h options; OpenAI, DeepSeek, and GLM use different cache mechanisms.
- Caches are not shared across models
- Caches for DeepSeek / GLM / GPT / Opus / Sonnet are not interoperable
- Mixing models within one workflow means giving up cache reuse
Three Implications for Cache Optimization
- Reuse is what saves money: The same prefix becomes cheaper only from the second use onward
- Keep the prefix stable: Frequently changing Rules / CLAUDE.md files are cache killers
- Cache optimization = context governance: Stabilize prefixes, reduce noise, and isolate sessions
2.5 Quality Degradation in Long Contexts — Not Just More Expensive, but Less Effective
An excessively long context imposes three penalties:
1. Needle-in-a-Haystack Effect
The model struggles to find critical information among large amounts of irrelevant content.
2. Context Poisoning
Once incorrect information enters the context, the model may repeatedly rely on it, contaminating subsequent output.
3. Lost in the Middle
The model pays significantly less attention to the middle of the context and tends to focus on the beginning and end.
Decision Tree: Continue vs. /compact vs. Restart
Has the current session exceeded 20 turns?
├─ No → Is Context usage above 50%?
│ ├─ No → Continue
│ └─ Yes → Run /compact
└─ Yes → Can you still locate the critical information clearly?
├─ Yes → Run /compact
└─ No → Start a new session
2.6 Five-Layer Cost-Governance Model
| Layer | Theme | Core objective | Related chapter |
|---|---|---|---|
| Layer 1 | Usage habits | Reduce meaningless context | Chapter 3 |
| Layer 2 | Model routing | Reserve expensive models for high-value reasoning | Chapter 4 |
| Layer 3 | Context engineering | Stabilize prefixes and reduce repeated transmission | Chapter 5 |
| Layer 4 | Agent architecture | Context isolation + parallel execution | Chapter 6 |
| Layer 5 | Organizational reuse | Capture once, reuse many times | Chapter 7 |
Chapter 3: Usage Habits — The Cheapest and Most Underestimated Optimization
3.1 Session Isolation
[Required] Each session must serve one clear objective. Do not mix fundamentally different tasks in the same session.
Session length grows with conversation history, so every subsequent request becomes more expensive. Create a separate session for each type of task.
Correct Example 1 — Open Multiple CodeBuddy Sessions
# Session 1: Fix a nil-pointer dereference in the order module
# Session 2: Refactor the authentication logic in the user service
# Session 3: Add unit tests for the auth module
Correct Example 2 — Run /clear After Completing a Task
User: Fix bug: http://github.com/project/issues/xxx
AI: [Bug fix completed]
User: /clear
User: Create an implementation plan for the new requirement at http://github.com/project/issues/xxx
Incorrect Example
# In the same session:
# Fix a nil-pointer dereference in the order module → review an auth-module PR → write a technical
# plan for a new requirement → add unit tests
# Task types are mixed and the history context keeps growing
3.2 Compress Long Histories
[Required] When a session exceeds 20 turns, or when the history context has grown significantly and Context usage exceeds 50%, run /compact or create a new session.
The model does not need the complete trial-and-error process. It actually needs only the current objective, completed work, paths already ruled out, the current blocker, and the next steps.
Correct Example
AI: [Completes one phase]
User: /compact
User: Continue with the second phase
Incorrect Example
# Dozens of failed attempts remain in the history during debugging
# After the bug is fixed, unrelated work continues in the same session
# Every subsequent request carries the irrelevant debugging history
3.3 Externalize Information
[Recommended] Persist long-lived information in the file system rather than relying on session memory.
Store long-lived information in the appropriate location:
- Project documentation such as README and CONTRIBUTING
- Memory files such as CODEBUDDY.md / CLAUDE.md
- Summary files / decision records
- Task lists / Issues
A session should carry only the current working state, not the complete history of the project.
Correct Example
# Record the database selection decision in docs/decisions/001-database-selection.md
# Record the team's API naming conventions in CODEBUDDY.md / CLAUDE.md
# Discuss only the interface currently being changed in the session
Incorrect Example
# Discuss database selection, API conventions, and exception-handling strategy
# in detail within the session
# Depend on the Agent to reference these discussions automatically later
# The session keeps growing, and other team members cannot easily find the decisions
3.4 Skill Management
[Required] Follow the principle "keep always-loaded Skills to a minimum; load infrequently used Skills at the project level." Do not install a large number of Skills indiscriminately at the user level.
Every Skill includes a Description, Instructions, Examples, and trigger logic. If this information remains resident in the context, it contributes to token usage on every request.
Correct Example
# User-level resident Skills: frequently used general-purpose Skills such as
# commit, code-review, and unit-test
# Project-level Skills: framework-specific workflows such as gRPC code generation,
# or tool-specific workflows such as database migration scripts
# Periodic cleanup: remove Skills that have not been used for more than two weeks
Incorrect Example
# Install 30+ user-level Skills at once, covering Python, Go, Rust, frontend,
# operations, and other technology stacks
# Only commit, code-review, and unit-test are used in day-to-day work
# Definitions for all other Skills remain in the context and continuously consume tokens
3.5 MCP Management
[Required] Keep the MCP toolset to the minimum necessary. Every additional MCP server adds another Tool Definition and increases tool-selection overhead.
Too many tools do more than increase the volume of definition text. They also:
- Expand the choice space and increase decision latency
- Increase the probability of incorrect tool calls
- Add to the definition payload carried by every request
Correct Example
# User-level resident tool: Headroom context compression
# Project level: no more than five MCP servers for the current project's core business
# Disable or remove: infrequently used MCP servers unrelated to the current project
Incorrect Example
# Install GitHub, Notion, TAPD, Gongfeng, Browser, Kubernetes, Docker, and multiple
# internal-system MCP servers at the user level
# The nominal feature set is comprehensive, but only Filesystem and Git are used frequently
3.6 Choosing Between CLI and MCP
[Required] Use MCP by default. Fall back to a CLI only when that CLI appears extensively in AI training data, as is the case for mainstream tools such as git, gh, kubectl, docker, npm, and pip.
The central tradeoff is this: a CLI avoids the cost of loading a Tool Definition, reducing tokens per turn. However, when the AI lacks reliable prior knowledge of a CLI, it can easily misspell a flag, use the wrong subcommand, or invent an argument, triggering a retry. As described in Chapter 2, one retry costs approximately one complete request (⭐⭐⭐⭐⭐), usually far more than the Tool Definition that was saved. MCP spends a small number of definition tokens on each turn in exchange for standardized parameter schemas, clearer descriptions, and fewer incorrect calls and retries.
Selection Guidelines
| Scenario | Prefer | Reason |
|---|---|---|
| Mainstream CLI extensively represented in AI training data, such as git / gh / kubectl / docker / npm / pip | CLI | Low loading overhead and a high probability of correct calls |
| Niche / proprietary / internal CLI, such as team operations scripts or private business commands | MCP | Standardized schemas reduce hallucination and avoid retries caused by incorrect calls |
| Structured, machine-readable results are required for a subsequent decision chain | MCP | Avoids the cascading cost of output parsing, cleanup, and retries |
| Permission boundaries and centralized authentication are required | MCP | Meets security and audit requirements |
How to Evaluate Whether an AI Knows a CLI
"Mainstream and familiar to AI" is not an exact standard, but the criteria below can help. If uncertain, use MCP by default. The cost of a mistake is asymmetric: treating an obscure CLI as mainstream can trigger retries with ⭐⭐⭐⭐⭐ cost, while treating a mainstream CLI as obscure and using MCP adds only a few kilobytes of Tool Definition.
| Criterion | CLI-safe range | MCP-safe range |
|---|---|---|
| Direct test: ask the AI to perform a typical operation with the CLI, write the command, and explain each argument | The command is correct, and the argument explanations are confident and consistent | The AI misspells flags, invents subcommands, or sounds uncertain |
| GitHub Stars | > 10K | < 1K |
| Dedicated publications, such as books from O'Reilly or Manning | Available | None |
| Number of Stack Overflow questions | > 5,000 | < 100 |
| Whether the tool's first release predates the model's training cutoff by more than one year | Yes | No, or close to the cutoff |
| Weekly package-manager downloads | > 1 million | < 10,000 |
Supporting indicators such as Stars and download counts are references only and should not determine the choice by themselves. A direct test has the highest priority and takes only one message.
Correct Example — CLI Wins
# Inspect Git changes; the AI is highly familiar with git
git diff --stat
git log --oneline -10
# Create a PR; gh is extensively represented in training data
gh pr create --title "feat: add batch query for UserService" --body "..."Correct Example — MCP Wins
# The AI has no prior knowledge of a proprietary internal release-system CLI
# and can easily misspell a flag and trigger a retry
# Wrap it as an MCP Tool with a standardized schema describing its parameters and behavior
# The AI must make a structured decision based on the previous result
# Example: query inventory → decide whether to scale based on the structured result
# → call the scaling API
# MCP's structured return value avoids cascading retries caused by CLI-output parsing failures
Incorrect Example
# Mature CLIs such as gh and kubectl are already highly familiar to the AI,
# yet GitHub and Kubernetes MCP servers are installed as well
# The context gains several kilobytes of Tool Definitions without improving call accuracy
# A proprietary internal CLI is called directly without an MCP wrapper
# Every call becomes a gambling loop: guess arguments → receive an error
# → interpret the error → guess again; retry cost becomes uncontrolled
3.7 Reference Files with Full Paths (@path)
[Required] When referencing a file, use @ followed by its full or relative path. Do not provide only a filename and make the Agent search for it.
A filename alone triggers a "search → possibly confirm multiple times → read" workflow. A full path allows the file to be located and read directly. The larger the project, the more expensive the search.
Correct Example
Review the transaction-handling logic in CreateOrder at @src/order/service.go
Modify the token-validation logic in @internal/auth/middleware.go
Incorrect Example
Review the transaction-handling logic in service.go
Modify the token-validation logic in middleware.go
# The Agent must traverse the project tree, find files with the same name,
# confirm the intended target, and then read it
3.8 State the Complete Intent
[Required] State the complete task objective, context, and acceptance criteria in a single message. Avoid piecemeal, back-and-forth requests.
Every interaction consumes tokens by reassembling the context, reloading history, and reconfirming state. A complete request in one message is significantly more efficient than multiple rounds of incremental confirmation.
Correct Example
Review the CreateOrder function in @src/order/service.go, identify potential defects,
fix them, and write unit tests for the corrected function.
Incorrect Example
User: Take a look at the CreateOrder function
AI: What aspects should I check?
User: See whether it has any bugs
AI: Inventory deduction is not protected by a transaction. Should I fix it?
User: Fix it
AI: The fix is complete. Should I add tests?
User: Yes, add them
3.9 Prefer Tools to LLM Reasoning
[Required] Select the execution method in this order: use an existing specialized tool > write a script > rely on LLM reasoning.
The core value of an LLM is handling uncertainty — tasks that require understanding context, reasoning, judgment, and tradeoffs. For mechanical operations with deterministic workflows and explicit rules, prefer specialized tools or scripts.
Correct Example
# Existing specialized tool: code linting
golangci-lint run ./...
# Existing specialized tool: code formatting
gofmt -w ./src
# Existing specialized tool: database migration
alembic upgrade headIncorrect Example
User: Check whether this Go code has formatting problems
AI: Reads every file → analyzes indentation, naming, and import order line by line
→ outputs modification suggestions
# golangci-lint can do this with one command; Agent reasoning is both inefficient
# and vulnerable to misjudgment
User: I need the number of paid machines over the past 30 days, every day
AI: Re-reads the table schema and sample data every day → estimates the count
# Instead, have the AI generate a fixed script and execute it to obtain the result
3.10 Lazy-Load Tools
[Recommended] Configure tools that are not used frequently for deferred loading with Defer, so their definitions do not remain resident in the context.
By default, the definitions of all registered tools are injected into the context of every request. The more tools there are, the greater the resident token cost. CodeBuddy supports the Defer(...) modifier for marking nonessential tools for lazy loading. Their definitions do not appear in the model's tool list and are loaded and called only when the model actively discovers them through ToolSearch.
Correct Example — Agent
# .codebuddy/agents/code-reviewer.md
---
name: code-reviewer
description: Code review agent
tools:
- Read
- Grep
- Bash
- Defer(Glob) # Lazy-loaded: discovered through ToolSearch only when file search is needed
- Defer(WebFetch) # Lazy-loaded: triggered only when online documentation is needed
---Correct Example — CodeBuddy
# Specify lazy-loaded tools when starting the CLI
codebuddy --tools "Read,Edit,Bash,Defer(Glob),Defer(Grep),Defer(WebFetch)"Correct Example — MCP
{
"mcpServers": {
"mcp-server-tapd": {
"command": "uvx",
"args": ["mcp-server-tapd"],
"defer_loading": true
}
}
}Incorrect Example
---
name: research-agent
description: Conduct research through multiple web search engines
# Omitting a tools declaration enables many built-in CodeBuddy tools by default
---
XXX contentChapter 4: Model Routing — Do Not Use Expensive Models for Cheap Work
4.1 Match the Task First; Do Not Simply Choose the Cheapest Model
Model routing does not mean "always use the cheapest model." It means classifying the task correctly first:
- Complex task → powerful model
- Simple task → inexpensive model
- Repetitive task → stable model
Architecture design requires multi-step reasoning, so use an expensive model when needed. An inexpensive model is entirely sufficient for writing unit tests, adding comments, or generating commit messages. Large-scale classification and summarization are better suited to low-cost models or offline batch processing.
4.2 Task-to-Model Mapping
[Required] Select an appropriate model tier based on task complexity. Do not use the strongest model by default for every task.
| Task type | Recommended model tier | Reason |
|---|---|---|
| Bulk classification / summarization | Low-cost model or batch processing | High volume and high cost sensitivity |
| Writing unit tests | Lightweight model | Stable patterns, highly templated, and immediately verifiable |
| Generating commit messages | Lightweight model | Summarizes a diff, produces short output, and carries low risk |
| Code formatting / adding comments | Lightweight model | Explicit rules and mechanical transformation |
| Variable renaming / simple refactoring | Lightweight model | Primarily pattern matching with high determinism |
| Generating API documentation | Lightweight model | Extracts interface definitions from code into a templated output |
| Code Review | Mid-to-high-tier model | Must understand code intent and identify deeper issues such as concurrency safety and transaction boundaries |
| Architecture design | High-performance model | Must compare alternatives, consider scalability and edge cases, and perform multi-step reasoning |
| Complex defect analysis | High-performance model | Requires multiple hypotheses: infer the root cause → validate paths → eliminate distractions → design a fix |
| Technical design review | High-performance model | Must assess feasibility, identify potential risks, and propose alternatives |
| Cross-module refactoring | High-performance model | Requires a global view of dependencies across services and modules |
| Performance optimization analysis | High-performance model | Must identify bottlenecks, infer causes, and evaluate the benefits of different optimization strategies |
Decision rule: If correctness can be verified immediately after the work is produced, use a lightweight model. If the result requires repeated analysis and tradeoffs, use a high-performance model.
4.3 Bind Models to Skills / Agents / Commands
Model routing should not exist only as a mental rule in the main chat. It should be implemented in execution units.
Bind models to Skills: Explicitly bind inexpensive models to Skills for writing unit tests, generating commits, fixing formatting, and producing boilerplate code.
In CodeBuddy, for example, the frontmatter of a SKILL.md file can declare the model and context strategy directly:
---
name: XXX
description: XXXX
context: fork
model: deepseek-v4-pro
---The model field specifies the model used by the Skill. context: fork runs this fixed workflow in an isolated execution context, which is appropriate for a Skill with clear boundaries that can complete its task independently. This allows low-complexity Skills to use inexpensive models automatically without carrying the complete history of the main session.
Bind models to Agents: Agents also support model binding through the model parameter. Set the model in the Agent definition so that everyone on the team uses the intended tier by default instead of having to remember to switch.
Planner → Mid-to-high tier
Coder → Mid tier
UnitTest → Inexpensive
Reviewer → Powerful
Note: In CodeBuddy, the lite keyword represents an inexpensive or lightweight model. It automatically selects the lower-cost counterpart of the model selected by the user. For example, if the user selects deepseek-v4-pro, the lite model is deepseek-v4-flash. Users can also set the CODEBUDDY_SMALL_FAST_MODEL="hy3-ioa" environment variable to specify the concrete model represented by lite.
The following frontmatter defines an Agent that uses a lightweight model:
---
name: AgentName
description: XXXX
model: lite
tools: Read, Grep, Glob, Bash
---Bind models to Commands: Many Commands, such as /commit and /check-ci-status, follow fixed templates and are well suited to a preset inexpensive model.
Once this design is encoded, cost governance changes from "remember to switch models" to "the system is cost-efficient by default." The following is an example of Command frontmatter:
---
description: "XXX"
argument-hint: "[message]"
allowed-tools: Bash(git:*)
model: lite
---Chapter 5: Context and Output Governance — Make Every Layer More Efficient
5.1 Karpathy's CLAUDE.md: Automated Trimming and Anti-Hallucination Anchors
[Recommended] If the team has not established an alternative convention, consider adopting Andrej Karpathy's CLAUDE.md where appropriate for the project.
Positioning: A high-quality CLAUDE.md template developed by the community. Through a predefined rule set, it requires the model to trim context, reduce filler, suppress hallucinations, and enforce engineering conventions.
Andrej Karpathy's CLAUDE.md addresses how the model should think. It embeds an efficient reasoning protocol at the System Prompt layer to reduce unnecessary token generation at the source.
5.1.1 Core Value: Why Use Karpathy's CLAUDE.md?
A conventional CLAUDE.md often contains only a project introduction. The Karpathy version is a "constitution for token economics":
- Enforce concise output (Anti-Bloat)
- Prohibit meaningless greetings, self-congratulation, and repeated confirmation
- Require lists and tables instead of lengthy prose
- Require the model to ask itself before responding: "Is this information necessary to complete the task?"
- Context-trimming instructions
- Explicitly tell the model to ignore irrelevant file fragments, such as
node_modulesand build artifacts - For long files, use
grep/rgto locate relevant content first; do not casuallyReadthe entire file
- Explicitly tell the model to ignore irrelevant file fragments, such as
- Anti-hallucination grounding
- Require tool calls such as Read / Search whenever the model is uncertain; never invent function signatures or API usage from memory
- Hallucination is one of the largest causes of retries. Karpathy's rules can significantly reduce the cost of retries caused by confidently fabricated information
- Codify engineering conventions
- Put code style, commit conventions, and testing requirements into the prefix so they do not have to be explained repeatedly, improving the Cache Hit Rate
5.1.2 Obtaining and Installing It
Andrej Karpathy's CLAUDE.md is an open-source resource that continues to evolve through community contributions.
Source: https://github.com/multica-ai/andrej-karpathy-skills/blob/main/CLAUDE.md
Installation:
- Project level (recommended): Copy the content into
CLAUDE.mdorCODEBUDDY.mdin the project root, or into therulesdirectory; - Global level: Merge the content into a global configuration file, such as
~/.claude/CLAUDE.md, so it applies to every project.
Note: Because this file changes the model's default behavior, check for updates once a month.
5.1.3 Typical Rule Examples — Excerpts
The following snippets illustrate how Karpathy-style rules use constraints to save tokens:
---
# Global response strategy
- Minimalism: Unless an explanation is requested, output only code blocks. Do not
include pleasantries such as "Okay" or "Let me help you."
- Determinism: If the Read tool returns empty or no results, stop and report an
error immediately. Do not guess the file contents.
- Tools first: When a task concerns file content, code definitions, or Git status,
call a tool. Never guess based on memory.
# Context management
- Search before reading: In an unfamiliar codebase, use Grep/Glob before deciding
what to Read.
- Line limits: When reading a file, specify `offset` and `limit`; read no more than
200 lines by default.
- Focus changes: After modifying code, show only the relevant diff. Do not repeat
the entire file.
# Output format
- Present information with Markdown lists and tables.
- Include necessary comments in code snippets, but remove redundant sample output.
---
# Project-specific rules: insert the project's architecture, technology stack,
# and special conventions here5.2 RTK — Rust Token Killer
[Recommended] Quickly reduce tool-output volume and token usage.
Positioning: Intercepts shell command output and compresses it before the Agent sees it. It compresses only CLI output, not prompts or code.
5.2.1 Installing RTK
# 1. Install the internal fork; Rust must already be installed
git clone https://git.woa.com/godwinchen/rtk.git
cd rtk && cargo install --path .
rtk init --global --agent codebuddy # Install the hook to intercept all commands transparently
rtk gain # Confirm that savings data is available5.2.2 Using RTK
Example request: Push the code changes
Normal output (~80 tokens):
Enumerating objects: 15, done.
Counting objects: 100% (15/15), done.
Delta compression using up to 10 threads
Compressing objects: 100% (8/8), done.
Writing objects: 100% (8/8), 2.34 KiB | 2.34 MiB/s, done.
Total 8 (delta 5), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (5/5), completed with 3 local objects.
To github.com:org/repo.git
abc1234..def5678 main -> main
RTK output (3 tokens):
ok main
Example request: Check whether the tests passed
Normal output (~2,500 tokens):
PASS src/utils.test.ts
PASS src/config.test.ts
...
PASS src/chain.test.ts
FAIL src/order.test.ts > should handle empty cart
AssertionError: expected 400 got 500
at Object.<anonymous> (src/order.test.ts:42:17)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Promise (src/order.test.ts:38:3)
at async Context.<anonymous> (src/order.test.ts:35:5)
FAIL src/auth.test.ts > expired token
Error: timeout of 2000ms exceeded
at Object.<anonymous> (src/auth.test.ts:18:12)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Promise (src/auth.test.ts:14:3)
Test Suites: 2 failed, 43 passed, 45 total
Tests: 2 failed, 178 passed, 180 total
Snapshots: 0 total, 0 failed
Time: 12.345 s
Ran all test suites.
RTK output (~30 tokens):
FAIL 2/45 tests
src/order.test.ts > should handle empty cart → expected 400 got 500
src/auth.test.ts > expired token → timeout
5.3 Caveman
Caveman is an output-compression plugin for AI coding Agents. Prompt rules make the model respond like a "smart caveman": remove filler and social niceties while preserving technical facts.
5.3.1 Installing Caveman
If you are using an AI coding tool other than Claude Code or Codex, install Caveman with the following command:
# macOS · Linux · WSL · Git Bash
curl -fsSL https://raw.githubusercontent.com/JuliusBrussee/caveman/main/install.sh | bash
# Windows · PowerShell 5.1+
irm https://raw.githubusercontent.com/JuliusBrussee/caveman/main/install.ps1 | iexCodeBuddy does not yet have official support, so use the fork. Run the following command in CodeBuddy:
/plugin marketplace add https://github.com/studyzy/caveman
# Select the caveman plugin after running the command. The system returns:
# ⎿ ✓ Added marketplace: caveman
# ⎿ ✓ Installed caveman. Restart CodeBuddy Code to load new plugins.
5.3.2 Using Caveman
After Caveman is installed correctly, CodeBuddy displays the following when it starts:
Hook SessionStart
CAVEMAN MODE ACTIVE — level: full
Respond terse like smart caveman. All technical substance stay. Only fluff die.
……
Caveman has four modes with progressively stronger compression:
/caveman lite: Removes filler while retaining articles and a professional style, suitable for formal output/caveman(full, default): Removes articles and uses sentence fragments to balance compression and readability/caveman ultra: Extreme compression usingA → B → Ccausal chains/caveman wenyan: Classical Chinese mode, theoretically the most token-efficient written style
Example effect in full mode:
Question: Why does a React component keep re-rendering?
Normal output (69 tokens):
The reason your React component is re-rendering is likely because you're creating a new object reference on each render cycle...
Caveman output (19 tokens):
New object ref each render. Inline object prop = new ref = re-render. Wrap in useMemo.
5.4 Ponytail
The core of Ponytail is not "how to write code," but what to consider before writing code. It defines a strict decision sequence:
Level 1: Does this really need to be built? (YAGNI)
Level 2: Does the codebase already contain it? Reuse it
Level 3: Can the standard library do it? Use it
Level 4: Does the browser / operating system provide it natively? Use it
Level 5: Is it available in an already-installed dependency? Use it
Level 6: Can it be done in one line? Write one line
Level 7: Only if none of the above works, write the minimum amount of new code
Each level is a gate. Reaching Level 7 means genuinely starting to write code, but most requirements are stopped at earlier levels. An experienced engineer does not create a new file immediately — they first grep the codebase for an existing solution.
5.4.1 Installing Ponytail
Run the following command in the CodeBuddy or Claude Code command line:
/plugin marketplace add https://github.com/studyzy/ponytail
# After adding the marketplace, select the ponytail plugin.
# If you did not select it, run:
/plugin install ponytail@ponytail
5.4.2 Using Ponytail
Ponytail is fundamentally a prompt-engineering tool. It injects prompts into the current context to remind the LLM not to waste tokens by generating redundant code.
Ponytail does more than encourage writing less code. It also provides a practical set of subcommands:
| Command | Purpose |
|---|---|
/ponytail-review |
Review current changes for overengineering and produce a list of code that can be removed |
/ponytail-audit |
Scan the entire repository for overengineering — effectively a codebase health check |
/ponytail-debt |
List all technical debt marked by ponytail: comments and the path for resolving it |
/ponytail-gain |
Show quantified savings from Ponytail, including code, cost, and time |
/ponytail-help |
Display a quick reference for all available commands |
These subcommands expand Ponytail from "prevent overengineering while writing code" to "review code + manage technical debt + quantify benefits." It is no longer just a prompt, but a toolchain for continuous code-quality improvement.
5.5 Comparison of the Four Tools
| Tool | Positioning | What it compresses | Layer | Cost impact |
|---|---|---|---|---|
| Karpathy's CLAUDE.md | Behavioral rules and anti-hallucination anchors | The model's reasoning approach, output tendencies, and retrieval strategy | System Prompt, the upstream layer | Reduces Output and retries; improves Cache Hit Rate |
| RTK | Shell-output filter | CLI output such as git status, test, ls, and docker |
Tool Output layer | Greatly reduces tool round-trip cost |
| Caveman | AI response-style compressor | Filler, pleasantries, and repeated explanations in model output | Output layer | Reduces Output and history overhead |
| Ponytail | Code-volume minimization engine | Code that should not be generated, acting as a YAGNI enforcer | Logic / Generation layer | Reduces Output and maintenance cost |
In one sentence each:
- Karpathy's CLAUDE.md makes the Agent think clearly before acting
- RTK compresses what the Agent sees
- Caveman compresses what the Agent says
- Ponytail compresses the code the Agent writes
The four tools cover different dimensions of compression and can be combined into a complete pipeline:
Agent calls a command
↓
RTK (first stage: compress CLI command output)
↓
LLM receives clean input
↓
Ponytail (controls what to write: do not write unnecessary code)
+
Caveman (controls how to say it: remove unnecessary prose)
↓
Compressed output is returned to the user
Chapter 6: Multi-Agent Collaboration — Clear Boundaries Save Tokens
6.1 Why a Single Agent Becomes More Expensive over Time
Core reason: Transformers have no memory.
The Transformer architecture used by LLMs has no memory across turns. On every turn, the complete "System Prompt + conversation history + current input" must be sent to the model again. This means:
Turn 1: Context = System Prompt
Turn 2: Context = System Prompt + turn 1
Turn 3: Context = System Prompt + turn 1 + turn 2
...
Turn N: Context = System Prompt + all previous N-1 turns
Adding too much irrelevant information also reduces response quality. Research has repeatedly demonstrated this through the "Lost in the Middle" phenomenon: models pay the least attention to information in the middle of the context. Good Context Engineering is not about inserting as much as possible; it is about carefully choosing the information needed right now.
6.2 Subagents: The Lowest-Cost Form of Task Isolation
Why do Subagents save tokens?
Core mechanism: A Subagent has a one-time, isolated context. Quadratic growth is contained within the Subagent, while the main Agent's history grows linearly.
LLM APIs are stateless, and every tool call resends the complete history. How history accumulates therefore determines whether token usage grows linearly or quadratically.
Incorrect Example
Do not delegate; perform everything in the main Agent conversation:
Main Agent: Poll N×K times → read entire large files → process intermediate artifacts
Every message resends all preceding history
⇒ Main history is O(N×K), and every turn resends it in full
⇒ Total tokens ≈ O((N×K)²), quadratic growth
Correct Example
Delegate heavy work to a Subagent:
Subagent: Poll N×K times → read entire large files → process intermediate artifacts
This remains in the Subagent's one-time context and does not enter main history
Main Agent: Receive only a concise result for each task, with no intermediate artifacts
⇒ Main history is O(N), adding only one result per task
⇒ Total tokens ≈ O(N), linear growth
Risks Introduced by Subagents
Saving tokens means assigning heavy work to a "black-box" Agent. The main Agent cannot see its intermediate process, which magnifies the impact of failures or false reports. There are four categories of risk and corresponding controls:
- Silent failure: The Subagent encounters an environment problem, such as a process not starting or an empty artifact, but returns a normal-looking completion message. The main Agent accepts an invalid result that falsely appears successful.
- → Run a health gate for every task: the main Agent independently verifies that the artifact exists, is nonempty, and has the expected completion marker. Do not trust the Subagent's prose alone.
- Unsupported assertion: The Subagent says "done" without objective evidence, making the result impossible to verify.
- → Every result must include verifiable evidence, such as an existing file, an exit code, or a status line. Do not claim completion until the evidence is present.
- Parallel dispatch without unified completion handling: Launching multiple synchronous subtasks in parallel is valid, but results can become distorted or lost if they are not verified individually and closed out together.
- → Parallel delegation is allowed; the key is unified completion handling. Verify each result after dispatch, then produce an overall summary. Do not accept Subagent self-reports without verification.
- Blind fallback: Automatically redelegating or retrying after failure causes the same root cause to fail repeatedly and continue consuming tokens.
- → On failure, decide first instead of falling back automatically. If the failure is systematic, stop the workflow and prevent further retries. Use fallback only for occasional, recoverable failures, and define hard limits in advance: no more than two retries, a maximum polling duration, and a rule to skip the task when a limit is reached. Keep the effort required to obtain a result bounded rather than trying endlessly to revive the task.
Governance principle: Decide first, then apply fallback, and enforce hard limits. Whichever branch is taken, token waste remains linear and bounded.
Chapter 7: Team Collaboration — From Individual Savings to Organizational Savings
7.1 The Ceiling of Individual Optimization
Token-optimization techniques available to an individual are already quite mature:
| Technique | Principle | Savings per use |
|---|---|---|
| Precise file reads with line ranges | Avoid dumping an entire file into the context | 500–2,000 tokens |
| Delegate large searches to a Subagent | Keep the processing in the Subagent and return only the conclusion | 3,000–10,000 tokens |
| Continue working within 5 minutes | Prompt Cache hit reduces Input cost to one-tenth | 80%–90% of Input cost |
Filter command output with head / grep / jq |
Narrow the returned content | 500–5,000 tokens |
These produce linear gains. Each person independently explores the best Prompt, encounters the same pitfalls, and accumulates the same knowledge. On a team of ten, the same pitfall may be encountered ten times and the same best practice may be independently rediscovered ten times.
Leverage formula for team collaboration:
Team savings = one-time optimization investment × number of users × average daily usage frequency
If a Skill takes two hours to refine and ten people each use it three times per day, that two-hour investment delivers value across 30 uses every day.
7.2 Build and Share Team Assets
7.2.1 Six Types of Shared Assets
| Asset type | Definition | Lifecycle | Token impact |
|---|---|---|---|
| Skills | Reusable workflow instructions such as TDD, Code Review, and Deep Research | Maintained over the long term | Loads ~500–3,000 tokens each time it is triggered |
| Rules | Behavioral constraints such as coding conduct and token efficiency | Stable and infrequently changed | Sent with the System Prompt on every turn |
| MCP | Protocol for external tool services, such as database queries, API calls, and file-system access | Configured by project / workspace and relatively stable | Tool schemas remain in the System Prompt; call results are inserted into context |
| Plugins | Extensions to IDE / Agent runtime capabilities or result-processing modules | Installed / enabled on demand and updated periodically | Plugin declarations are usually resident; execution results are inserted on demand |
| Docs | Reference documentation such as architecture diagrams and API specifications | Updated as needed | Loaded only when referenced |
| Learnings | Captured lessons and best practices | Accumulated continuously | Inserted only when recall finds a match |
7.2.2 Mechanisms That Make Shared Assets Work
To produce organization-wide value, shared assets must do more than solve "store it, distribute it, and make it searchable." The system must also ensure that new experience continues to enter the shared layer. It therefore needs to cover five capabilities:
- Centralized storage: Manage shared assets in one repository
- Version control: Make every change traceable and reviewable
- Low-cost distribution: Let team members obtain the latest assets automatically
- On-demand recall: Surface historical experience within a specific task
- Incremental capture: Discover and refine lessons from day-to-day work, then add them to the shared team asset pool
7.2.3 Introduction to TeamAI CLI for Managing and Distributing Team Assets
TeamAI CLI illustrates how these five mechanisms can be implemented. It not only synchronizes and reuses team assets, but also continuously captures new knowledge generated through day-to-day engineering work.
GitHub: https://github.com/Tencent/teamai-cli
Comparison of team asset management and distribution approaches:
| Operation | TeamAI CLI | Alternative |
|---|---|---|
| Pull team assets | teamai pull |
Git submodule + manual copying |
| Contribute a new Skill | teamai push |
Open a PR directly against the team repository |
| Share a learning | teamai contribute --title "..." --file ./learning.md |
Write a Wiki page + notify the group chat |
| Search team knowledge | teamai recall "keyword" |
Search Confluence |
| Subscribe across teams | teamai source add <name> <repo-url> |
Fork + cherry-pick |
7.2.3.1 Distribution and Storage Mechanism
Team member A contributes a Skill
↓ push (creates a PR, merged after review)
Team Repo (Git repository)
↓ pull (triggered automatically at CodeBuddy SessionStart)
AI tools used by team members B/C/D... automatically receive the Skill
Core design: Git is the database. All shared assets are stored with version history in one Git repository. push / pull provide bidirectional flow, and PR review provides quality control.
7.2.3.2 Token Benefit Model
- Skill reuse: Avoid repeated Prompt trial and error by every person. A mature Skill saves about 2,000 tokens per use by removing rounds of experimentation, adjustment, and reruns. In a ten-person team with three uses per person per day, that is 60,000 tokens per day.
- Rules injection: Unified behavioral constraints reduce rework rounds by about 40%. Every rework round resends the complete context, approximately 8,000–20,000 tokens.
- Learnings recall: Automatically recalls previous experience and avoids duplicate debugging. A typical debugging session uses 5–10 turns × 15,000 tokens per turn = 75,000–150,000 tokens. If recall allows the team to skip it, the entire amount is saved.
7.2.3.3 Incremental Capture of Experience
Manually summarizing experience and writing Wiki documentation requires substantial human effort. Version and format control are also difficult, so many lessons do not naturally make their way into documentation or a Wiki and simply disappear after troubleshooting, fixing, or debugging.
TeamAI provides an automatically triggered contribute-check hook that detects learnings worth preserving and prompts the user to contribute them. It can also generate learnings from session history, reducing the effort required to capture new knowledge. This allows the team knowledge base not only to distribute existing assets, but also to absorb new knowledge continuously.
Chapter 8: Conclusion
8.1 Five Principles
- Measure first, then optimize
- Never solve again what can be captured as an asset
- A stable prefix is essential to effective caching
- Context quality matters more than context quantity
- Team consistency matters more than individual perfection
8.2 Revised Core Formula
Lower cost =
less repeated context
+ more appropriate model routing
+ more precise code retrieval
+ clearer Agent responsibilities
+ measurable, continuous optimization
+ organization-wide asset reuse
8.3 Three Long-Term Recommendations
- Make measurement part of the team's muscle memory
- Make asset capture the default action
- Base optimization decisions on data, not intuition
License
This document is licensed under the MIT License.
💬 Questions? Help build this
Engagement corner: raise an Issue with any error or suggestion, or open an MR to share your own token-optimization practices.