Building a Hierarchical Coding Agent with a 12B Open-Source Model
This article presents a practical architecture for a hierarchical coding agent built on a 12B open-source instruction model. It explains how to split work across three tiers—Sol, Terra, and Luna—using routing and degradation rules, and how to add two augmented reasoning modes: max for deep reasoning and ultra for parallel subagents. It also covers layered security controls, authorized automated red-team testing, prompt caching with explicit breakpoints and tenant isolation, deployment and fine-tuning considerations, quality metrics, and common pitfalls. Readers will learn how to balance capability, latency, and cost while measuring each claimed benefit under reproducible conditions.
1. Why a Hierarchical Design Is Needed
Large language models are already widely used for code generation, automated debugging, and intelligent agents. Developers often have to trade off two goals: stronger models cost more to run, while lighter models struggle with complex multi-step tasks. A 12B instruction model is easier to deploy and faster to run than models with tens of billions of parameters. However, if every request is sent to it, success rates on complex tasks may be insufficient, while simple high-frequency requests waste compute.
A hierarchical system addresses this by routing requests to model instances with different capability and cost profiles based on task difficulty and call frequency. These instances share the same base weights and differ through fine-tuning data, inference parameters, and deployment strategies. The approach discussed here does not depend on a specific commercial platform; the techniques involved include general model fine-tuning, routing design, and engineering optimization.
2. Three Model Tiers: Sol, Terra, and Luna
The three tiers are organized as follows.
| Tier | Typical tasks | Configuration direction | Main cost |
|---|---|---|---|
| Sol | Cross-file refactoring, automated bug localization, multi-tool orchestration | Longer context, higher sampling quality, targeted fine-tuning for tool use and multi-turn planning | High latency, high compute consumption |
| Terra | Function implementation, unit test generation, code review, documentation generation | Default working tier, moderate quantization, batching | Moderate per-call cost |
| Luna | Code completion, naming suggestions, log classification, simple regex generation | Lightweight or low-precision deployment, limited generation length and temperature | Limited quality on complex tasks |
The Sol tier only handles tasks that lower tiers cannot complete reliably. Its latency and compute consumption are the highest, so routing should minimize the number of requests that enter this tier.
The Terra tier is the daily workhorse. Its coding capability should be measured with public benchmarks. A fixed version of HumanEval or MBPP is recommended, with pass@1 reported and sampling temperature, top_p, prompt template, and evaluation environment specified. Until these measurements are complete, Terra should not be directly compared with any closed-source service.
The Luna tier is used for high-frequency, low-risk requests with easily verifiable results. Its response-time target can be set to within a few hundred milliseconds. A common approach is prefill plus dynamic batching to improve hardware utilization. If the configuration budget and service-quality policy allow, most lightweight requests can enter this tier. The specific proportion should be based on online traffic statistics.
3. Routing and Degradation Strategy
The router selects a tier based on request features. Common features include input length, number of tool calls, expected output quality, and user level. Thresholds need to be calibrated with your own business data; the table below provides starting examples.
| Feature | Example threshold | Action |
|---|---|---|
| Input length | Exceeds a certain proportion of the target context | Prefer Sol |
| Number of tool calls | Greater than or equal to 3 | Enter Sol or Terra |
| Single-turn simple completion | Short and verifiable output | Enter Luna |
| User marked as high priority | Not applicable | Retain a higher tier |
The degradation mechanism includes two rules. First, when Sol times out or lacks resources, the request is degraded to Terra. Second, when Terra fails repeatedly, the request is degraded to Luna while quality loss is recorded, avoiding silent degradation that affects results. Outputs after degradation should have validation steps, such as running tests or performing syntax checks. Otherwise, system availability improves, but quality issues are harder to detect.
4. Dual Augmented Reasoning Modes
A single model has limited context and single-pass reasoning capability, so two augmentation modes can be introduced. Both can be enabled dynamically on the same tier or provided as independent services.
4.1 max Mode: Deep Reasoning
In max mode, the model decomposes the problem, lists candidate solutions, performs step-by-step self-checks, and returns to earlier steps when it finds errors before giving the final answer. This is usually implemented with prompt templates and sampling parameters, for example by asking the model to list its reasoning first and then verify step by step, with temperature set to a lower value. Such settings increase the probability that the model expands its reasoning, but they do not guarantee that it will trigger consistently every time. Therefore, the system needs to do three things:
- Limit the maximum number of thinking steps and output tokens to control cost.
- Perform verifiable checks on the final result, such as running unit tests or static analysis.
- When a check fails, fall back to normal mode and record the reason.
max mode is suitable for mathematical derivation, complex algorithm design, and architecture review. For simple questions, it only adds latency and does not improve quality.
4.2 ultra Mode: Parallel Subagents
In ultra mode, the task is split into independently completable subtasks, assigned to multiple subagents for parallel processing, and then summarized by a main agent. A typical flow is as follows:
- The main agent analyzes the task and lists subtasks and dependencies.
- Subtasks without dependencies enter a parallel queue.
- Each subagent returns a structured result and confidence score.
- The main agent resolves conflicts. For code results, for example, test-passing status should be the deciding factor.
- If the aggregated result does not meet preset metrics, a second round is started.
Confidence is a value provided by the model itself and is not equal to the true probability of correctness. Before use, it should be calibrated on a validation set by observing the relationship between confidence and actual accuracy. In addition, the claim that parallel processing is “3 to 5 times faster than serial processing” is only a target to be verified. Actual gains depend on the independence of subtasks, queue scheduling overhead, and aggregation cost. Take API migration as an example: if parsing, generating calls, updating tests, and modifying documentation have few dependencies, parallel gains will be obvious; if the steps depend on each other, gains will be small.
Mode selection can be automated based on task features. Tasks with long inputs and a high estimated number of steps should prefer max mode; tasks with high parallelizability should prefer ultra mode. Users can also explicitly specify the mode through the interface and set parameters such as thinking steps and parallelism.
5. Layered Security Controls
Once a model has code-generation and tool-calling capabilities, misuse can have more serious consequences. A single filtering rule cannot cover all cases, so multiple layers of protection are needed.
The first layer is the model’s own refusal capability. Safety alignment samples can be added during fine-tuning so the model can identify and refuse clearly high-risk requests. This layer blocks most direct requests, but it cannot cover every phrasing.
The second layer is an independent input/output classifier. The classifier is deployed separately from the main model and can detect categories such as code injection, sensitive information leakage, hate speech, and instructions for illegal activity. Because it is independent of the main model, its rules can be updated separately without retraining the main model.
The third layer is account-level risk monitoring. The system can record signals such as changes in request frequency, the proportion of sensitive tool calls, historical violation records, and anomalous context, and adjust access levels accordingly. High-risk accounts can be moved to manual review or limited in the model tiers they can use.
The fourth layer is differentiated access control. Read-only users cannot trigger code modifications, and ordinary developers cannot call production deployment interfaces. A policy engine can use RBAC or PBAC to bind model output to specific operations for verification. Even if the model generates a dangerous instruction, the system will not execute it directly.
6. Automated Red-Team Testing
Manually constructing adversarial samples is costly and has limited coverage. Automated red-team testing can expand coverage, but it must be conducted with explicit authorization and in a controlled environment.
Before testing, the following preparations are required:
- Obtain written authorization and define the scope and responsible parties.
- Run in an isolated sandbox without connecting to production data or real external services.
- Desensitize test samples and logs, and retain complete audit records.
- Handle discovered vulnerabilities according to the internal vulnerability disclosure process, and do not spread details externally before fixes are made.
- Report only high-level risk categories internally, such as jailbreak, injection, and information leakage. Do not store or share attack samples that can be directly reused.
Test metrics should be calculated on a fixed test set. For example, the same batch of samples can be used to compare safety violation rates across model versions, with bootstrap used to estimate confidence intervals so that random fluctuations are not mistaken for improvements. Test scale is determined by the team’s compute budget; any specific compute numbers in this article are illustrative only.
The purpose of test results is to form a closed loop. Discovered vulnerabilities can be used to supplement safety alignment data, update classifier rules, and adjust account risk weights. After each fix, regression tests should verify that no new degradation has been introduced. Because new attack methods continue to appear, red-team testing should run regularly rather than as a one-time exercise.
7. Prompt Caching
Similar requests often appear in coding scenarios, such as repeated modifications to the same file. Prompt caching can reuse computation results for common prefixes, reducing latency and compute consumption.
7.1 Explicit Cache Breakpoints
Unlike implicit caching, which only caches complete prefixes, explicit cache breakpoints allow positions to be marked in the prompt. The system caches the key-value vectors before the breakpoint. Later requests that share the same prefix can reuse them directly. Multiple breakpoints can be set to enable partial reuse. This design is suitable for structures such as “fixed system instructions plus changing code snippets,” because the changing part is placed after the breakpoint and does not break the earlier cache.
7.2 TTL and Isolation
Cache TTL should differ by content type. High-frequency tool descriptions can have a longer TTL, while user-private code should have a shorter TTL and be isolated by tenant to prevent data leakage between users. The minimum 30-minute TTL mentioned here is only a starting point. A longer TTL increases hit rate but also consumes more VRAM, so a balance must be found between the two.
7.3 Cache-Aware Routing and Two-Level Storage
In a distributed deployment, requests can be routed by prefix hash to the node that holds the corresponding cache. Caching is divided into two levels: local memory cache (L1) and distributed shared cache (L2). Clear write and invalidation rules are needed between the two levels. For example, after code changes, related prefixes should be actively invalidated to avoid returning stale results. Hash collisions also need a handling strategy, such as comparing the full prefix before reuse.
7.4 Conditions for Measuring Results
Claims such as “first-token latency reduced by more than 40%, compute consumption reduced by about 35%, and hit rate of 82%” are meaningful only when measurement conditions are provided. At minimum, the following should be recorded:
- Model version, quantization method, and inference engine version
- Batch size and concurrency
- Input and output sequence length distributions
- Hardware model and VRAM usage
- Cache TTL, capacity limit, and eviction policy
- Test task types and sample count
Before measurement is complete, these numbers should be treated as targets to be verified. Readers can replay the same traffic with caching enabled and disabled, measure the metrics separately, and then compare the differences.
8. Engineering Deployment and Tuning
8.1 Hardware and VRAM Estimation
For a 12B model quantized to INT8, weights occupy about 12 GB of VRAM. A single 24 GB GPU can hold the weights, but the remaining space must accommodate KV cache, activations, and runtime overhead. As a result, the maximum usable context length and concurrency will be limited. Actual values need to be calculated based on the target model’s layer count, attention head count, and hidden dimension, and confirmed through stress testing. Do not directly apply data from other models.
8.2 Organizing Fine-Tuning Data
Hierarchical fine-tuning requires separate data for each tier:
- Sol tier: multi-step reasoning chains, tool-call records, and repository-level annotations.
- Terra tier: instruction-code pairs covering common languages such as Python, Java, and Go.
- Luna tier: high-confidence automatically generated comment pairs to reduce manual labeling.
The data volume, source, deduplication, and desensitization method for each tier should be documented. Data volume should be determined by validation-set performance rather than fixed in advance.
The following fine-tuning parameters can serve as a starting point: use LoRA with rank between 16 and 64, and set alpha to usually one to two times the rank. Use a learning rate around 1e-4 with cosine annealing. Training epochs are generally 1 to 3, with validation-set monitoring for overfitting. These are examples and need to be adjusted for actual data.
8.3 Quality Evaluation Metrics
In addition to general metrics such as BLEU and CodeBLEU, the following metrics should also be tracked:
- Task success rate: the proportion of tool calls or tasks completed as a whole.
- Multi-step execution accuracy: the proportion of chains in which every step is correct.
- Safety violation rate: the violation proportion on a fixed safety test set.
- P95 end-to-end latency: a measure of tail latency that reflects user experience better than averages.
Each metric should specify test-set size, passing threshold, statistical method, and failure criteria. For example, differences in task success rate should be judged for significance using confidence intervals. Regular A/B testing can verify whether hierarchical routing actually brings benefits.
9. Common Mistakes
- Looking only at average latency and ignoring P95, which leads to a worse experience during peak periods.
- Copying routing thresholds from others without calibrating them against your own team’s traffic.
- Increasing cache hit rate while output quality declines, without monitoring both together.
- Treating model-provided confidence as the probability of correctness.
- Failing to log after degradation, so quality problems remain undetected for a long time.
10. Conclusion
Three-tier layering, dual augmented reasoning, layered security controls, controlled red-team testing, and prompt caching together form a coding agent system that can run under limited compute. Its value comes from sound routing and degradation design and from reproducible measurement of each benefit. For readers, a realistic approach is to first validate routing and caching effects with a small amount of traffic, then gradually expand the scope. This approach applies not only to coding assistants but also to general agent tasks such as data analysis and automated operations.
