Code LLM Architecture Selection and Agent Practices: A Technical Guide

    This article examines the requirements that real coding tasks place on large language models and explains how code-focused models address them through mixture-of-experts architecture, long-context design, training-data pipelines, execution-based post-training, and agentic tool use. It also covers the main trade-offs, implementation patterns, and risks involved, including context limits, reward hacking, and prompt injection.

    Code LLM Architecture Selection and Agent Practices: A Technical Guide

    1. Special Requirements of Programming Scenarios for LLMs

    General-purpose chat models can write short functions, but real engineering tasks usually involve multiple files, cross-module dependencies, historical version constraints, and test feedback. The requirements of programming scenarios can be summarized in three points:

    • Large understanding scope: The model needs to read directory structures, interface definitions, and related implementations at the same time to determine the impact of a change.
    • Executable output: Code must pass compilation, type checking, and unit tests. Looking reasonable is not enough.
    • Long action chains: The model must plan steps, call tools, observe results, and make corrections, forming a multi-round closed loop.

    Around these three points, code LLMs usually make targeted design choices in model structure, context window, training data, and training methods. The following sections discuss each in turn.

    2. Mixture-of-Experts Architecture: Distinguishing Total Parameters from Active Parameters

    Mixture of Experts (MoE) splits the feed-forward network into multiple expert sub-networks. A router selects a small number of experts for each input token to participate in computation, while the remaining experts stay idle at that step.

    This structure involves two concepts that are easy to confuse:

    • Total parameter count: The sum of all expert parameters and shared-layer parameters, which roughly determines the upper limit of the model’s knowledge capacity.
    • Active parameter count: The parameters that actually participate in computation during a single forward pass, which directly determines the computation per token.

    Assume there are E experts in total and each token activates k of them. Then the feed-forward computation per token is proportional to k/E. If k/E is 1/8, the feed-forward computation is about one eighth of that of a dense model of the same scale. This is only a ratio illustration and does not correspond to any specific product.

    The benefits and costs of MoE are as follows:

    • Benefit: At a similar inference cost, the model can hold more parameters and raise its capability ceiling.
    • Cost 1: Memory still needs to hold the weights of all experts, so the deployment barrier does not decrease in step with the reduction in computation.
    • Cost 2: Uneven routing can overload some experts while leaving others idle. During training, load-balancing losses or expert capacity limits are usually needed to constrain routing.
    • Cost 3: In multi-GPU inference, expert parallelism introduces additional communication overhead, and the impact of batch size on throughput differs from that of dense models.

    When selecting an architecture, consider the following. For scenarios with limited memory budgets but a need for higher inference throughput, prioritize options with fewer active parameters. For scenarios with sufficient memory that place more value on single-task quality, dense models are usually simpler to deploy and tune.

    3. Long Context: From Native Windows to Extended Windows

    Code repository understanding is highly sensitive to context length. The source code, configuration, and documentation of a medium-sized project often exceed hundreds of thousands of tokens when combined. Long-context capability generally has two levels:

    1. Native window: The maximum length directly covered during training.
    2. Extended window: Adjusting the frequency or scaling factor of positional encodings so that the model can still maintain position awareness beyond the training length.

    Rotary Position Embedding (RoPE) is a common foundational approach. When extending, the base frequency is usually interpolated or scaled so that distant positions fall within the numerical range seen during training. After extension, a small amount of continued training on long-text data is generally also needed; otherwise, the ability to retrieve long-distance information may degrade noticeably.

    When using long context, pay attention to the following:

    • Nominal length is not equal to effective length. Use a retrieval test that asks the model to locate specific information in long text, calculate recall across different depth positions, and observe whether performance drops in later sections.
    • Computation and memory grow with length. Attention computation is related to sequence length, KV cache usage grows linearly with it, and time to first token also increases.
    • Long context cannot replace retrieval. First use an index to precisely recall files and code snippets relevant to the task, then place them in the context. This is usually more stable and more cost-effective than stuffing the entire repository into the context.

    Below is an illustrative implementation of context budget management. The core idea is to sort by relevance and greedily fill within the token budget:

    1. def build_context(query, repo_index, budget_tokens, count_tokens):
    2. """Sort candidate code chunks by relevance and concatenate context within a token budget."""
    3. candidates = repo_index.search(query, top_k=50)
    4. selected, used = [], 0
    5. for chunk in candidates:
    6. cost = count_tokens(chunk.text)
    7. if used + cost > budget_tokens:
    8. continue
    9. selected.append(chunk)
    10. used += cost
    11. return "\n\n".join(c.render() for c in selected)

    4. Training Data: Scale, Mix, and Quality Control

    Data design for code LLMs mainly addresses three questions: Is the scale sufficient, is the mix correct, and is the quality stable?

    Mix trade-offs. The higher the proportion of code corpora, the better performance usually is on code tasks, but general language understanding, mathematical reasoning, and natural-language instruction following may be weakened. A common practice is to retain some general text and mathematical data, use code data as the main body, and increase the proportion of high-quality code and reasoning data in the later stage of training.

    Data processing pipeline. A reliable pipeline generally includes the following stages:

    • License filtering: Exclude code repositories with unclear licenses or restrictions on commercial use, and record their sources.
    • Deduplication: First perform exact deduplication, then use near-duplicate methods such as MinHash-based methods to filter large numbers of templated or copy-pasted files.
    • Syntax and parseability checks: Remove files that cannot be parsed, as well as files containing large amounts of automatically generated content.
    • Evaluation-set decontamination: Remove content from training data that is highly similar to public evaluation problems; otherwise, scores will be inflated and cannot reflect true capability.
    • Structured sample construction: Use commit records, code reviews, issues, and fix patches to construct “problem-change” samples. These are closer to real engineering scenarios than plain code files.

    Data quality often affects final results more directly than data quantity. When building training or fine-tuning data in-house, teams should prioritize deduplication, decontamination, and sample construction.

    5. Post-Training: Using Execution Results as Reward Signals

    Code tasks have a natural advantage: outputs can be verified by programs. Therefore, in the post-training stage, execution feedback is often used instead of subjective scoring. A typical process has two steps.

    1. Supervised fine-tuning: Use high-quality instruction-code pairs to teach the model to follow formats and task specifications.
    2. Reinforcement learning with verifiable rewards: Run tests on model-generated patches and assign rewards based on pass rates, compilation results, and timeout conditions.

    The illustrative function below shows the basic structure of reward design:

    1. def execution_reward(candidate_patch, test_suite, sandbox):
    2. result = sandbox.run(patch=candidate_patch, tests=test_suite, timeout=60)
    3. if result.timed_out:
    4. return -0.5 # Treat timeout as low-quality output
    5. if not result.applied:
    6. return -1.0 # Patch cannot be applied; penalize directly
    7. return result.passed / max(result.total, 1)

    This mechanism also brings typical risks:

    • Reward hacking: The model may learn to modify or delete test files so that test cases pass. Solutions include prohibiting rewrites of the test directory or making test files read-only in the training environment.
    • Insufficient test coverage: As long as tests do not cover certain boundary conditions, the model may write code that passes superficially but is actually wrong. Hidden test sets and mutation testing can mitigate this problem.
    • Overfitting to a specific framework: If reward signals come only from a single technology stack, the model’s cross-language transfer ability may be limited. Training tasks should cover multiple languages and engineering scenarios.

    6. Agent Capabilities: Tool Calling and Multi-Round Interaction

    An agent refers to a system in which the model autonomously plans in an environment, calls tools, observes feedback, and continuously corrects itself. In programming scenarios, common tools include file read/write, code search, test execution, command execution, and browser operations.

    Below is an illustrative general agent loop, where llm and tools are abstract interfaces:

    1. def run_agent(task, llm, tools, max_steps=30):
    2. messages = [{"role": "user", "content": task}]
    3. for _ in range(max_steps):
    4. reply = llm.chat(messages, tools=tools.schemas())
    5. messages.append(reply.as_message())
    6. if not reply.tool_calls:
    7. return reply.text # The model no longer calls tools; treat as complete
    8. for call in reply.tool_calls:
    9. output = tools.invoke(call.name, call.arguments)
    10. messages.append(tool_result_message(call.id, output))
    11. raise RuntimeError("Maximum steps exceeded before task completion")

    There are four key points in engineering implementation:

    • Tool descriptions must be precise: Parameter types, required fields, and value ranges should be written as structured schemas to reduce incorrect model calls.
    • Error information must be returned: When a tool fails, return the original error to the model so that it can correct itself.
    • Set step and budget limits: Prevent the agent from falling into loops while controlling token and time costs.
    • Control side effects: Operations such as deleting files, sending network requests, and committing code should be executed in a sandbox and require human confirmation.

    Security requires particular attention to prompt injection. Web content, file comments, and tool return values may all contain content that induces the model to execute unintended actions.