Long-Context Engineering Practices for LLMs in Code and Agent Scenarios
This article explains the core engineering principles behind large language models designed for code generation and AI agent workloads. It covers Mixture-of-Experts architecture, the costs and limits of million-token context windows, sparse attention and token-level compression, capability requirements for agentic coding, API integration considerations, and practical guidance for model selection, deployment, and risk evaluation.
1. Background: From General Chat to Code and Agents
LLM applications are shifting from single-turn Q&A to multi-step tasks. In scenarios such as code generation, bug localization, document analysis, and automated operations, models must read large amounts of context, call external tools, and maintain consistent state across multiple turns of interaction. These tasks impose three requirements on models: stronger reasoning and coding capability, longer effective context, and lower inference cost.
This article focuses on these three requirements. Rather than discussing the marketing claims of any specific product, it examines the general technical principles behind these capabilities and the trade-offs engineering teams should consider when selecting and deploying models.
2. Mixture of Experts: Total Parameters vs. Activated Parameters
The Mixture of Experts (MoE) architecture splits feed-forward networks into multiple “expert” sub-networks, with a router selecting a small number of experts for each input token. The total parameter count determines the model’s capacity ceiling, while the number of parameters actually involved in each forward pass—the activated parameters—determines the computational cost per inference.
The core benefit of this structure is decoupling capacity from cost. If a model has N experts and each token activates only k of them, the per-token feed-forward computation is roughly k/N of a dense model, while the model as a whole retains a much larger knowledge capacity. The trade-offs include unbalanced routing, high memory usage, and increased cross-device communication. Practical implementations typically require load-balancing losses and expert parallelism strategies.
The following pseudocode illustrates the basic logic of top-k routing:
def moe_forward(x, experts, router, top_k=2):scores = router(x) # routing score for each expertidx = topk_indices(scores, top_k) # select the k experts with highest scoresweights = softmax(scores[idx]) # normalize scores of selected expertsout = 0for i, w in zip(idx, weights):out += w * experts[i](x)return out
When evaluating an MoE model, you should consider total parameters, activated parameters, and task quality per unit of cost together—none of the three can be ignored.
3. Million-Token Context: Benefits and Costs
With larger context windows, a model can process an entire code repository, a long contract, or a complete log file in one pass. But longer context introduces two types of cost.
The first is attention computation cost. Standard full attention scales roughly quadratically with sequence length n. When the sequence grows from 100K to 1M tokens, attention computation increases by about 100x.
The second is the memory footprint of the key-value cache (KV Cache). During inference, the model must cache key and value vectors for every layer. The memory required can be estimated as:
kv_cache_bytes = 2 × num_layers × num_kv_heads × head_dim × seq_length × bytes_per_element × concurrent_requests
The factor of 2 accounts for both key and value caches. This formula shows that the bottleneck of long-context serving is often not computation but memory capacity and bandwidth. Engineering mitigations include cache quantization, paged memory management, and request scheduling.
Long-context capability also has boundaries. Models may recall information in the middle of the window less accurately than information at the beginning or end. Critical information should therefore be placed in prominent positions in the prompt, assisted by retrieval or segmented summarization.
4. Sparse Attention and Token-Level Compression
Sparse attention reduces complexity from n² to near-linear by letting each query interact with only a subset of key-value pairs. Common approaches include:
- Sliding window, attending only to nearby tokens;
- Block sparsity, computing attention selectively by block;
- Content-based dynamic selection, where a lightweight indexer picks the tokens most relevant to the current query.
Token-level compression reduces cache size at the storage layer—for example, by merging representations of adjacent tokens or applying low-rank projection to cached vectors. Combined, these techniques reduce both computation and memory footprint.
Simplified logic for dynamic selection:
def sparse_attention(q, K, V, indexer, budget=2048):cand = indexer(q, K) # lightweight indexer scores candidate positionsidx = topk_indices(cand, budget) # keep only tokens within the budgetk_sel, v_sel = K[idx], V[idx]return attention(q, k_sel, v_sel) # run standard attention on the subset
Sparsification may miss distant information relevant to the current task, so before going live you should evaluate recall with targeted long-range retrieval tests rather than relying on average perplexity alone.
5. Capability Requirements for Agentic Coding
A typical agentic coding workflow is: understand the requirement, plan the steps, read files, invoke tools to run commands, fix the code based on feedback, and repeat until tests pass. The model plays the decision-making role in this loop and therefore needs the following capabilities:
- Reliable tool-call output formatting, with parameter structures matching their declarations;
- Maintaining the task goal and the state of completed steps across long conversations;
- Recognizing error messages returned by tools and adjusting strategy accordingly;
- Controlling output length under resource constraints to avoid unproductive loops.
A minimal agent loop looks like this:
def agent_loop(task, model, tools, max_steps=20):history = [{"role": "user", "content": task}]for _ in range(max_steps):reply = model.chat(history, tools=tools)if reply.tool_call is None:return reply.content # model decides the task is completeresult = tools[reply.tool_call.name](**reply.tool_call.args)history.append({"role": "tool", "content": str(result)})raise RuntimeError("max steps exceeded, task not completed")
Loop limits, tool timeouts, and sandbox isolation are mandatory guardrails. Operations involving file deletion, network requests, or permission changes in particular should require human confirmation.
6. API Compatibility and Engineering Integration
Two mainstream formats are common for model serving APIs today: the chat completion format based on a message list, and the message format based on content blocks. A service supporting multiple formats lowers migration costs, allowing existing applications to switch models without major code changes.
A typical chat completion request looks like this:
{"model": "<model identifier>","messages": [{"role": "system", "content": "You are a code review assistant"},{"role": "user", "content": "Check the boundary conditions of the following function"}],"max_tokens": 4096,"temperature": 0.2}
Keep the following in mind during integration:
- Parameter names and valid ranges should follow the official documentation of the service you use; support for
max_tokens, streaming output, and tool definitions varies across services; - API keys should be stored in environment variables or a key management service, never in code or logs;
- Requests should have timeout and retry policies, with exponential backoff for rate-limit responses;
- Input should be length-validated to prevent failures caused by exceeding the context window.
7. Recommendations for Selection and Deployment
When choosing a model and deployment approach, evaluate in this order:
- Clarify the task type: code completion, code review, document Q&A, or multi-step agents each have different requirements for context length and tool capability;
- Build an evaluation set: construct samples from real business data, covering long texts, edge cases, and failure cases;
- Measure cost: track input/output token counts, latency, and memory usage per request, and convert them into per-task cost;
- Design fallbacks: when long-context requests time out or exceed cost limits, switch to retrieval plus short context;
- Monitor continuously: record quality metrics and anomalous requests, and re-test regularly, since model version updates can change behavior.
8. Risks and Evaluation Points
Long context and agent capabilities amplify several categories of risk. First, information leakage: inputs may contain sensitive data and should be sanitized before entering the model. Second, erroneous execution: commands or code generated by the model should go through static checks and sandboxed validation. Third, prompt injection: content from web pages, files, or tool responses may contain adversarial instructions, and the system should treat such content as data rather than instructions.
For evaluation, consider functional correctness, long-range information recall, response latency, per-unit cost, and safety interception rate together. Only when a model meets business requirements across all these metrics is it ready for production.
In summary, MoE, long context, and sparse attention jointly address the tension among capacity, length, and cost. Engineering teams should design evaluations and guardrails around their specific tasks, turning technical capability into stable, controllable business value.
