Core LLM Technologies for Agentic Programming
The programming paradigm is shifting from simple code completion to agentic collaboration. This article analyzes the key Large Language Model (LLM) technologies required for this transition, including long context understanding, multi-step planning, sparse attention, multi-token prediction, and Mixture of Experts (MoE). It also covers practical engineering aspects such as deployment, evaluation systems, and cost control.
I. The Shift from Code Completion to Agentic Collaboration
Early code assistance tools primarily focused on local completion, where developers typed a few lines of code and the tool predicted the next part. This was followed by a rapid prototyping approach driven by natural language prompts, where developers described requirements and the model directly generated runnable pages or scripts. While this method is suitable for validating ideas, it exposes significant issues in production environments: boundary conditions of the generated code lack verification, dependency relationships are prone to errors, and modification history is difficult to trace.
Agentic Engineering is a more mature direction. In this mode, the model undertakes multiple stages including planning, retrieval, editing, execution, and verification. It reads the code repository and requirement documents, splits tasks, calls tools to modify files, runs tests, reads error messages, and then iterates based on feedback. The developer’s role shifts from writing line-by-line to defining objectives, setting constraints, and reviewing results.
This transition imposes new requirements on the underlying models. The model needs to understand large-scale codebases, maintain state consistency across multi-step tasks, and perform verifiable operations using external tools. The following sections analyze these three key requirements.
II. Three Core Requirements for Agentic Programming
2.1 Long Context Understanding
A medium-sized service typically contains hundreds of files, and a complete call chain and configuration information might consume hundreds of thousands of tokens. If a model can only process a few thousand tokens, it can only see local fragments and is prone to making modifications that conflict with the global design. Therefore, the length of the context window directly determines whether the model can understand repository-level structures.
However, window length is just one metric. The model’s ability to locate key information within long texts—its long-range retrieval and reasoning capabilities—is equally important. When evaluating models, developers should pay attention to the information recall rate at intermediate positions in long documents, rather than just looking at the advertised maximum window size.
2.2 Multi-step Planning and Tool Calling
Agentic tasks typically involve a dozen to dozens of steps. For example, fixing a bug might require searching for the error location, reading the relevant functions, modifying the implementation, adding tests, running the test suite, and finally organizing the change description. The output of each step becomes the input for the next, meaning early minor errors can be progressively amplified.
The model needs to stably output structured tool-calling parameters, correctly parse the results returned by tools, and adjust its strategy upon failure, rather than repeating the same erroneous operation.
2.3 Verifiability
A major advantage of programming tasks is that results can be mechanically verified. Whether compilation passes, whether tests pass, and whether static checks report errors—these signals can be directly fed back to the model. The ability to organize these signals into a closed loop is one of the core metrics for measuring the quality of an agentic programming system.
III. Sparse Attention: Reducing Long-Sequence Computation Costs
The standard attention mechanism computes the relevance of each position with all other positions, causing both computation volume and memory usage to grow quadratically with sequence length. When the sequence expands from a few thousand to hundreds of thousands, this overhead becomes the primary bottleneck for inference.
The idea behind sparse attention is to allow each query position to focus only on a subset of key-value pairs. Common practices include:
- Sliding Window: Only attends to adjacent positions, suitable for texts with strong local dependencies;
- Chunking Strategy: Splits the sequence into blocks, which exchange information through a few global tokens;
- Relevance-based Selection: First estimates relevance using lightweight computation, then retains only the highest-scoring positions.
The trade-off of sparsification is the potential loss of crucial long-distance information. Engineering requires a balance between quality and speed, and the effect must be confirmed through task evaluation. Below is a schematic implementation logic to illustrate the “filter first, compute later” process:
def sparse_attention(query, keys, values, top_k):# Calculate relevance scores between the query and all keysscores = dot(query, keys) / sqrt(head_dim)# Retain only the top_k positions with the highest scoresselected = topk_indices(scores, top_k)weights = softmax(scores[selected])# Perform a weighted sum only on the selected positionsreturn weighted_sum(weights, values[selected])
This code omits batching and hardware optimization details, focusing on illustrating that the computation changes from relating to all positions to relating only to selected positions. In actual systems, the selection strategy usually needs to be jointly optimized with model training; otherwise, the filtered results might be inconsistent with the model’s true dependency relationships.
IV. Multi-Token Prediction: Training Signals and Inference Acceleration
Traditional language models predict only the next token at each position. Multi-token prediction allows the model to predict several subsequent tokens simultaneously, providing richer training signals at each position. This helps the model learn longer-range structures, such as bracket pairing in code blocks and the correspondence between function signatures and implementations.
This technique can also be used for inference acceleration. A common approach is to have an additional prediction head propose several candidate tokens first, which are then verified by the main model in one pass. The verified parts are directly accepted, reducing the number of sequential generations. The acceleration effect depends on the acceptance rate of the candidates, which in turn relates to the task type. Highly regular fragments in code completion usually have a high acceptance rate, while open-ended creation has a lower acceptance rate.
When evaluating inference performance, developers should measure the time to first token (TTFT) and the generation speed of subsequent tokens separately, and observe throughput under real-world workloads, rather than just looking at single-sample results.
V. Mixture of Experts (MoE): Total vs. Activated Parameters
Many large models adopt the Mixture of Experts (MoE) architecture. The model contains numerous expert subnetworks, and the routing module selects only a few experts to participate in computation for each token. Consequently, the model has two easily confused metrics:
- Total Parameters: Determines the storage space required for model weights, as well as the VRAM or memory needed to load the model;
- Activated Parameters: Determines the computation volume for a single token, directly affecting inference speed and single-call cost.
Both metrics must be considered when planning deployment. Total parameters determine the hardware threshold, while activated parameters determine throughput and cost. If only looking at activated parameters, VRAM requirements might be underestimated; if only looking at total parameters, inference costs might be overestimated.
The routing mechanism also brings load balancing issues. If most tokens are concentrated to a few experts, both training efficiency and inference parallelism will decline. In engineering practice, load balancing losses or capacity limits are usually added.
VI. Engineering Implementation and Costs of Long Context
The VRAM consumption for long-context inference mainly comes from the KV (Key-Value) cache. The cache size is proportional to the number of layers, attention heads, head dimension, and sequence length. The longer the sequence, the more VRAM a single request consumes, and the fewer concurrent requests that can be processed simultaneously.
Common engineering approaches to address this include:
- Segmented Processing: Splitting long documents for separate processing, then summarizing the conclusions;
- Retrieval-Augmented Generation (RAG): First retrieving relevant fragments from a knowledge base, and only placing the relevant content into the context;
- History Compression: In multi-round agentic tasks, periodically compressing early operation logs into summaries;
- Prefix Reuse: Caching fixed system prompts and codebase overviews to reduce redundant computation.
Developers should note that the number of tokens a window can accommodate does not equal the amount of information the model can effectively utilize. For critical tasks, it is recommended to test the model’s recall ability for information at different positions using proprietary samples before determining the context organization method.
VII. Training Pipeline: Data Scale and Reinforcement Learning
The scale of pre-training data for large models continues to grow. Increasing data volume can bring improvements in general capabilities, but data quality, deduplication, and proportioning are equally critical. Programming data requires handling license compliance, code quality filtering, and the impact of duplicate code.
After pre-training, programming and agentic capabilities are typically acquired through post-training. A common practice is to construct an executable task environment where the model generates solutions, receives rewards based on test results or rules, and then updates its policy using reinforcement learning. This type of training has high infrastructure requirements because the process of generating samples is time-consuming, and parameter updates must wait for sample collection.
Asynchronous training frameworks can allow generation and updates to run in parallel, reducing hardware idle time. The core lies in controlling the freshness of samples to avoid severe deviation from the current policy caused by samples generated by overly old policies, which would affect training stability.
VIII. Evaluation: Interpreting Benchmark Scores
Public evaluations usually cover the following types of tasks:
- Code Repair: Given a real repository and a bug description, the model needs to modify the code and pass tests;
- Command Line Operations: The model completes configuration, build, and troubleshooting tasks in a terminal environment;
- Web Retrieval: The model searches for and integrates information in a web environment;
- Tool Calling: The model calls external interfaces according to specifications to complete tasks;
- Simulation Management: The model makes long-term decisions and accumulates results in a virtual environment.
Three points should be noted when reading evaluation results. First, the scaffolding (prompt templates, tool sets, retry limits) varies greatly across evaluations, and scores cannot be directly compared across different benchmarks. Second, public data may enter the training corpus, leading to inflated scores. Third, a single score cannot reflect cost, latency, and failure modes.
Enterprises should establish internal evaluation sets covering their own codebases, tech stacks, and typical requirements. Recommended evaluation metrics include: first-pass rate, average repair rounds, cost per task, end-to-end latency, and failure cause distribution. The failure cause distribution can help the team determine whether the problem lies in understanding, planning, tool calling, or verification.
IX. Inference Deployment: Compute Adaptation and Cost Control
Large model inference can run on various AI accelerator chips. Adaptation work usually involves operator implementation, numerical precision selection, parallel strategies, and memory management. Different hardware varies significantly in peak compute, VRAM bandwidth, and communication capabilities; the throughput of the same model on different platforms can differ greatly.
Common optimization methods include:
- Quantization: Converting weights from high precision to low precision to reduce VRAM usage, requiring verification of whether the precision loss is acceptable;
- Tensor Parallelism: Splitting single-layer computation across multiple cards, suitable for scenarios where single-card VRAM is insufficient;
- Continuous Batching: Dynamically merging requests of different lengths to improve hardware utilization;
- KV Cache Management: Reducing VRAM fragmentation through paging or reuse.
In public cloud environments, such as on Baidu AI Cloud, teams can build inference services by combining general container orchestration, object storage, logging services, and monitoring/alerting capabilities. During deployment, the model service should be managed as a standard online system, with health checks, elastic scaling, and rate limiting policies in place.
Cost estimation can adopt the following logic:
def estimate_task_cost(input_tokens, output_tokens, calls,price_in, price_out):# Single call cost = input cost + output costper_call = input_tokens * price_in + output_tokens * price_out# Total task cost = single call cost * number of callsreturn per_call * calls
