From Code Completion to Agent Engineering: LLM Coding in Practice
Large language models are shifting software development from line-by-line code completion to multi-step agent execution. This article explains why coding tasks now require agent capabilities, how to move from ad-hoc prompting to engineering-grade agent workflows, and the key techniques behind them—sparse attention, mixture-of-experts architectures, multi-token prediction, long context windows, and asynchronous reinforcement learning. It also covers how to interpret evaluation results responsibly, practical deployment considerations such as hardware adaptation and KV cache cost control, and a sample execution loop with human approval gates, along with essential security practices.
1. Background: Why Coding Tasks Need Agent Capabilities
Software development is moving from “humans writing code line by line” toward “humans defining goals while models handle multi-step execution.” Early code completion tools could only predict the next snippet from context, and developers still had to review everything line by line. As model capabilities improved, models began to take on the full workflow: breaking down requirements, reading the codebase, running tests, modifying files, and iterating based on error messages. This class of capabilities is generally referred to as agent capabilities.
This shift raises two new problems. First, task cycles become longer. The correctness of a single generation no longer represents the overall outcome, and small errors made early can accumulate and amplify across later steps. Second, the model’s scope of operation expands, requiring supporting mechanisms such as tool calling, permission control, and result validation. Therefore, evaluating a coding model requires looking beyond the quality of single-question generation—you must assess whether it can complete tasks consistently and reliably in a real engineering environment.
2. From Ad-Hoc Coding to Engineering-Grade Agents
Many developers have used an “ad-hoc” coding style: describing ideas in natural language, quickly accepting generated code, and moving on as long as it runs. This works for prototyping but cannot sustain long-term maintenance. Without specifications, test coverage, and code review, defects and security issues accumulate over time.
The core of engineering-grade agent development is integrating the model into existing software engineering processes. This can be implemented at four levels:
- Specification first: Describe requirements in a structured form, including interface contracts, input/output boundaries, exception cases, and acceptance criteria. The clearer the task the model receives, the lower the chance it drifts off target.
- Verifiable execution: Every change should produce an observable feedback signal—unit tests, type checks, static analysis, or build results. Feedback lets the model correct itself based on facts rather than self-assessment.
- Context management: Provide only relevant files, dependency documentation, and relevant error history to the model. Flooding the context with unrelated content dilutes attention and increases the risk of unintended changes.
- Human gates: Operations such as deleting data, releasing versions, or modifying permissions must go through human confirmation. The higher the level of automation, the more important explicit boundaries become.
3. Core Technical Mechanisms
Understanding agent coding capabilities requires familiarity with several common supporting techniques. The following describes industry-general principles, not the specific parameters of any particular model.
3.1 Sparse Attention
Standard self-attention scales quadratically with sequence length—the longer the sequence, the faster compute and memory costs grow. Sparse attention reduces this by computing only a subset of query-key combinations, or by first filtering candidate positions by importance and then performing fine-grained computation on those. This can significantly lower the cost of long-context inference.
The difficulty lies in the selection strategy. If the filtering step misses a critical dependency—such as a function definition referenced across files or a configuration item far away—the model may produce results that look plausible but are inconsistent with the codebase. When evaluating sparse strategies, focus on long-range dependency scenarios rather than average metrics.
3.2 Mixture-of-Experts Architecture
A Mixture of Experts (MoE) architecture splits a model’s feed-forward networks into multiple experts, with each input token routed to only a few of them. The total parameter count can be very large, but only a fraction is activated per inference.
Sparsity can be roughly measured as “the number of activated experts divided by the total number of experts.” This design partially decouples model capacity from inference cost, but it introduces two engineering challenges. First, routing may be unbalanced—some experts become overloaded while others are barely used—so load-balancing constraints are usually needed during training. Second, even when only a few parameters are activated, all expert weights must reside in GPU memory or RAM, making storage and communication costs at deployment nontrivial.
3.3 Multi-Token Prediction
Traditional language models predict only the next token during training. Multi-token prediction trains the model to predict several subsequent positions simultaneously, providing denser learning signals per training sample and improving the modeling of structured text such as code. At inference time, this design can be combined with techniques like speculative decoding—generating multiple candidate tokens at once and then verifying them together.
Note that the actual benefit of multi-token prediction depends on training configuration, decoding strategy, and hardware environment. It cannot be converted into a fixed speedup factor out of context. Evaluate real throughput and latency under your target workload.
3.4 Long Context Windows
The context window determines how much code, documentation, and conversation history a model can hold at once. For large repositories, a longer window reduces the information fragmentation caused by splitting content into segments. However, a long window does not mean all information is effectively used. Research and practice consistently show that information in the middle of the context is more likely to be overlooked. Retrieval augmentation, segmented summarization, and placing key information up front therefore remain necessary.
3.5 Asynchronous Reinforcement Learning Training
When training agents with reinforcement learning, trajectory lengths vary widely. Synchronous training must wait for all samples to finish before updating parameters, and long trajectories leave compute resources idle. Asynchronous training runs sampling and parameter updates in parallel, improving resource utilization. The trade-off is that samples may come from an older policy; importance sampling corrections or limits on policy lag are needed to control bias.
4. How to Interpret Evaluation Results
Evaluations of agent coding models typically cover the following task categories:
- Code repair: Given a repository and an issue description, the model must generate a patch that passes existing tests. These tasks assess cross-file editing and understanding of project structure.
- Terminal operations: The model performs dependency installation, configuration changes, log investigation, and similar tasks in a restricted command-line environment. These tasks assess multi-step planning and error recovery.
- Tool calling: These evaluate the model’s ability to select the right function, construct correct arguments, and parse returned results.
- Long-horizon tasks: Simulating multi-round decisions—such as business simulations or project planning—to assess whether the model maintains goal consistency over long time spans.
When interpreting these results, keep three points in mind. First, a single leaderboard score does not represent business outcomes; public benchmarks and enterprise codebases differ in distribution. Second, look at the distribution of failure cases. Whether failures cluster around dependency resolution or logical reasoning determines the direction of future optimization. Third, evaluations must be reproducible—record the model version, decoding parameters, tool configuration, and test environment, or results cannot be compared across runs.
Teams are advised to build internal evaluation sets. Select real defect fixes, feature development, and refactoring tasks from the past six months, define inputs, expected outputs, and acceptance tests, and run them regularly as regression checks. Such data reflects actual needs far better than public leaderboards.
5. Deployment Considerations
5.1 Hardware and Inference Framework Adaptation
Different accelerator cards differ in operator implementations and numerical behavior. When deploying a model to a new hardware platform, verify output consistency, including precision deviations, stability over long sequences, and handling of abnormal inputs. Performance testing should cover single-card, single-node, and multi-node scales—do not make decisions based on peak metrics alone.
When deploying in public cloud environments such as Baidu AI Cloud, you can choose between on-demand and reserved resources based on concurrency and latency requirements. Workloads with obvious traffic spikes suit elastic resources, while sustained high loads are better served by reserved capacity.
5.2 Controlling Long-Sequence Costs
The main cost of long-sequence inference usually comes from the memory footprint of the key-value cache (KV Cache). Common optimization approaches include:
- Caching and reusing repeated prefixes, such as system prompts and project descriptions for the same codebase;
- Using continuous batching to improve device utilization;
- Quantizing weights or caches to reduce memory requirements within an acceptable accuracy loss;
- Applying segmented retrieval for very long contexts, feeding only relevant fragments to the model.
5.3 Balancing Latency and Throughput
Agent tasks involve multiple rounds of model calls, and the first-token latency of each round accumulates into the total elapsed time. Interactive scenarios should therefore prioritize first-token latency, while batch offline tasks should focus on overall throughput. These two metrics can conflict, so trade-offs must be made according to business priorities.
6. Example Code: An Execution Loop with Approval Gates
The following example shows the basic structure of an agent execution loop. It is for illustration only and omits details such as sandbox isolation, timeout handling, and error handling.
from dataclasses import dataclass@dataclassclass Step:action: strargs: dict# Low-risk operations that can run automaticallyAUTO_TOOLS = {"read_file", "apply_patch", "run_tests"}# High-risk operations that require human approvalAPPROVAL_TOOLS = {"delete_file", "deploy"}def run_agent(task, model, tools, ask_human, max_steps=20):history = [{"role": "user", "content": task}]for _ in range(max_steps):step = model.next_step(history)if step.action == "finish":return historyif step.action not in AUTO_TOOLS | APPROVAL_TOOLS:history.append({"role": "tool", "content": "unknown action, rejected"})continueif step.action in APPROVAL_TOOLS and not ask_human(step):history.append({"role": "tool", "content": "rejected by reviewer"})continueresult = tools.execute(step.action, step.args)history.append({"role": "tool", "content": result})raise RuntimeError("reached step limit without finishing")
This code embodies three principles. First, tools must be explicitly whitelisted—the model cannot invoke unregistered operations. Second, high-risk actions must pass through a separate confirmation function. Third, the loop has a step limit to prevent the model from wasting resources on ineffective retries.
7. Security and Risk Control
Because agents have execution capabilities, security concerns are amplified. Keep the following in mind when deploying them:
- Least privilege: File, network, and credential permissions granted to an agent should cover only what the current task requires.
- Sandbox isolation: Code execution should run in an isolated environment so that failures or malicious behavior cannot affect the host system.
