Code Agent Cost Reduction with Small Model Distillation: A Complete Guide
This article explains how to cut the cost of code agents by distilling a larger teacher model into a smaller student model for tool-calling code exploration. It covers why sub-agent calls dominate cost, why direct small-model replacement often fails, how to build distillation data and choose full-parameter supervised fine-tuning, which tools the student model should handle, the evaluation metrics that prove it is usable, published benchmark results, and a layered architecture that keeps a strong model for planning while delegating high-frequency exploration to a local small model. It also outlines risks and cases where distillation is not advisable.
1. Where the cost actually comes from
In the evolution of AI-assisted programming, the code agent has become the mainstream paradigm. Unlike traditional question-and-answer completion, a code agent emphasizes autonomous planning, multi-step execution, and closed-loop tool use: instead of emitting a single function body, it has to decide which file to read, which keyword to search, which tool to call, and whether a second round of verification is needed.
That capability is not free. A typical multi-layer agent system is made up of two roles:
Orchestrator (main agent)
Understands the request, breaks down the task, generates code, and decides the next action. It needs strong reasoning and planning, so it usually relies on a high-capability large model.Sub-agent (Explorer/Worker)
Finds clues in the codebase: locating relevant files, searching symbols, reading snippets, mapping directory structure, and running read-only commands. It is essentially a tool-calling task executor.
The problem is right here: most of what the sub-agent does is high-frequency, pattern-based, and enumerable. A task like “find every call site that uses a given configuration item” may expand into dozens of tool calls, and if every one of those calls goes to the same top-tier model, the cost scales linearly with the number of calls.
The cost structure can be abstracted as:
Total cost ≈ main model calls (low frequency, high value)+ sub-model calls (high frequency, low difficulty)+ repeated context transfer+ retries and error correction
Sub-model call cost is often the underestimated hidden bill. Moving that portion to a local small model can significantly reduce the total cost per task without touching the main agent.
2. Why distillation instead of just swapping in a small model?
A common misconception is: “If sub-agent tasks are simple, why not just drop in a 4B model?” In engineering practice, putting a small model straight into production usually runs into these issues:
- Unstable formatting: tool calls require structured output such as JSON, and small models tend to drop fields, misplace quotes, or produce illegal escapes.
- Wavering tool selection: failing to call retrieval when it should, or repeatedly calling irrelevant tools.
- Argument construction errors: paths, regexes, and command-line arguments get written wrong, so a single call fails outright.
- Broken multi-turn context: losing the goal across multiple tool interactions or repeating actions already completed.
So the question is not “small model or not”, but how to make a small model behave stably, predictably, and integrably in the narrow but critical domain of tool-calling code exploration.
This is exactly where knowledge distillation delivers value:
A stronger teacher model produces high-quality behavioral trajectories on the target task, and the small model learns the distributional characteristics of those trajectories, approaching the teacher’s performance within the defined task slice.
Compared with simply continuing to pre-train a small model on generic corpora, distillation offers:
- Goal alignment: training data comes directly from correct answers in the target scenario.
- Imitable behavior: the model learns not only what to say, but which tool to call first, what arguments to pass, and when to stop.
- Controllable output: data construction can reinforce structured-output constraints and improve parseability.
3. Key design of the distillation approach: from teacher model to a deployable small model
3.1 Role definition: teacher and student
A reproducible distillation setup clearly defines:
- Teacher: a larger model with strong code understanding and tool-use ability, used to generate high-quality demonstration trajectories.
- Student: a smaller model with lower deployment cost that can run locally, serving as the production sub-agent executor.
It is worth stressing that distillation does not require the small model to outperform the teacher on every task. It requires the model to meet an engineering-usable standard on a predefined task slice, especially:
- Whether a tool call happens at all (should it call)
- Whether the tool type matches (did it call the right one)
- Whether the output is structured and parseable (can the agent loop consume it)
- Whether the arguments are valid (will the call actually run)
3.2 Data construction: teach behavior, not answers
Distillation data quality sets the ceiling. For codebase exploration tasks, training samples should cover these dimensions:
Multi-turn dialogue structure
Full rounds including user request, assistant reasoning, tool call, tool result, and follow-up decisions, rather than single-turn Q&A.Tool call diversity
At minimum: file reading, regex/string search, path pattern matching, and read-only shell commands.Positive and negative sample balance
- Positive: a tool should be called, and it is called correctly.
- Negative: no tool should be called (for example, meta questions that can be answered directly), or a different tool should be used.
Argument validity reinforcement
Normalize annotations for paths, regexes, and command arguments so the model does not learn plausible-looking but failing forms.Structured output constraints
Unify tool calls into a parseable structured format (for example, one consistent JSON schema) and keep it strictly consistent across training data.
An illustrative sample structure (showing only how data is organized):
{"messages": [{"role": "system", "content": "You are a codebase exploration sub-agent and must emit structured tool calls."},{"role": "user", "content": "Find every place in the project that reads environment variables."},{"role": "assistant", "content": "{\"tool\":\"grep\",\"args\":{\"pattern\":\"getenv|environ\"}}"}]}
3.3 Training strategy: full-parameter supervised fine-tuning fits behavior alignment
Common fine-tuning options include parameter-efficient fine-tuning and full-parameter supervised fine-tuning. For tool-calling behavior alignment, full-parameter supervised fine-tuning usually has the edge:
- Better distribution fitting: small models have limited capacity, and updating all parameters helps them approximate the teacher’s output distribution in the target domain more closely.
- Stronger format constraints: structured output requires the model to form stable preferences across many token choices, and full-parameter fine-tuning converges more firmly.
- Unchanged inference cost: the small model still serves inference in production, so the training method does not change the deployment cost structure.
Engineering considerations also matter:
- Context length design: code exploration often carries directory trees, file snippets, and prior tool results, so the context length should cover the real task distribution.
- Training stability: structured-output tasks are sensitive to learning rate, batch size, and temperature sampling, so conservative configurations plus small-batch ablation checks are advisable.
4. Capability boundaries: which tool calls should the small model own?
When rebuilding the sub-agent around a local small model, narrow the capability surface to exploration rather than creation. A typical tool set abstracts into seven categories:
- Read: read file contents, the most basic information-gathering action.
- Grep: search the codebase by string or regex, the core means of locating symbols and configuration.
- Glob: find file paths by pattern, suitable for locating entry or test files by naming convention.
- Bash (read-only): run read-only commands such as
lsandfindfor structure exploration and metadata. - Write: create temporary or scaffolding files in assistive scenarios.
- Edit: make small-scope changes in assistive scenarios, with a strict allowlist and approval mechanism recommended.
- Task: spawn subtasks for further decomposition of complex problems (can be managed centrally by the upper agent).
Engineering recommendations:
- Write operations must be controlled: exploration sub-agents are read-only by default; if write/edit is enabled, restrict writable paths, limit command capability, and keep audit logs.
- Standardize tool descriptions: consistent names, parameter schemas, and return structures for every tool make it easier for the small model to learn stable mappings.
- Make failures recoverable: failed tool calls should return structured errors so the model learns to retry or switch tools instead of producing natural-language guesses.
5. Evaluation: how to prove the small model is usable
Whether distillation succeeded cannot be judged by subjective impression alone; it needs quantitative evaluation. For tool-calling code exploration, cover at least four metric groups:
5.1 Should-Call Accuracy
Measures whether the model calls a tool when it should and stays restrained when it should not. This directly affects agent loop efficiency: wrong calls lengthen the chain, missed calls stall the task.
5.2 Tool-Type Match@1
Measures whether the tool type chosen on the first attempt matches the label. This reflects decision correctness and is key to reducing retries.
5.3 JSON Validity
Measures whether the output parses into a legal structured object. This is the baseline for engineering integration: if parsing fails, argument validation and execution cannot even begin.
5.4 Argument Validity
Measures whether arguments satisfy schema constraints (path format, regex legality, complete command arguments, and so on). This determines whether a call actually runs and is central to lowering runtime failure rates.
6. Public benchmark reference: high stability on a specific task slice
Based on publicly reported distillation practice (the evaluation set consists of multi-turn dialogue samples covering several mainstream open-source codebases), results similar to the following can be observed:
| Metric | Distilled small model |
|---|---|
| Should-Call Accuracy | 100% (65/65) |
| Tool-Type Match@1 | 65.6% (40/61) |
| JSON Validity | 100% (76/76) |
| Argument Validity | 100% (76/76) |
On the engineering baseline metrics of valid structure and valid argument syntax, the small model reaches the same level as the teacher model (76/76 for both).
These numbers need careful interpretation:
- The small model does not beat the teacher across the board: Tool-Type Match@1 remains clearly below the ideal value, showing that complex decisions still need the main model or a stronger one.
- The small model is well suited as a stable execution layer: on format legality, argument executability, and call-timing judgment, it is already engineering-usable.
- The best architecture is layered collaboration: the main model handles strategy and code generation, the small model handles high-frequency exploration and tool execution.
7. Deployment architecture: embedding the small model into an existing agent loop
7.1 Recommended division of labor
User request↓Main agent (strong model): planning + code generation + key decisions↓Sub-agent (local small model): tool calls + codebase exploration↓Structured results returned to the main agent (summaries, file snippets, call-chain clues)
7.2 Engineering implementation points
Unified protocol layer
Use one structured schema for all tool calls to avoid a combinatorial explosion of parsing branches caused by different output formats from different models.Context compression strategy
Tool results are often long (file contents, search results). Summarize, truncate, or paginate returns to prevent context bloat.Task-level cost control
Package each exploration subtask as an independent session with a cap on maximum rounds and maximum tool calls to prevent infinite loops.Observability
Log the type, argument summary, latency, and failure reason of every tool call for continuous evaluation and regression.Security boundary design
Prefer read-only; write/edit tools need allowlists, approval, sandboxing, and auditing. For shell tools in particular, restrict the set of executable commands.
8. Combining with cloud engineering capabilities (general view)
When a “local small model + cloud strong model” hybrid architecture is used, general cloud capabilities can support robust operations:
- Container platform: package the small-model inference service with elastic scaling and canary releases.
- Object storage: keep evaluation sets, training data snapshots, and model version artifacts.
- Logging and monitoring with alerting: collect call success rate, structured-parse failure rate, and latency percentiles to close the loop.
- Message queue: decouple the main agent from the sub-agent and support task queuing, rate limiting, and peak shaving.
- Model service gateway: unify authentication, quotas, routing, and fallback policy (fall back to the strong model when the small model fails).
The core value of this combination is pushing high-frequency, low-difficulty tasks down to a low-cost inference layer while reserving low-frequency, high-value decisions for the strong-model layer, achieving a structural improvement in total cost of ownership (TCO).
9. Risks and boundaries: when not to use a distilled small model
Distilled small models are not a cure-all. Be cautious in these scenarios:
Insufficient cross-language/cross-framework generalization
If training data comes mainly from a few project structures, tool selection may drift when facing unfamiliar ecosystems.Complex long-tail tool calls
Build systems, package managers, and complex test frameworks have large argument spaces, and small models easily look right without being right.High-privilege operation risk
Without sandboxing and auditing, write/edit/command execution can create security and compliance risk.Insufficient evaluation coverage
Testing format legality alone does not prove usability; real task success rate and end-to-end latency evaluation must be added.
10. Conclusion: distillation is a key engineering lever for code agent cost reduction
The high cost of code agents essentially comes from running high-frequency exploration tasks and high-value decision tasks on the same expensive model. Distillation offers a clear path:
- Use the strong model to generate high-quality tool-calling trajectories;
- Use full-parameter supervised fine-tuning to make the small model behave stably within a defined task domain;
- Use structured output and strict evaluation to guarantee engineering integrability;
- Use a layered architecture so the strong model makes decisions and the small model does the exploring.
Public benchmark data shows that the distilled small model reaches very high stability on baseline metrics such as structural validity and argument legality, and achieves full alignment on call-timing judgment, while complex tool selection still has room for improvement. The most rational deployment is therefore not “replace the large model with a small one”, but build a master-sub agent system in which each model does what it is best at and most cost-effective at.
