Programming Agents with Large Models: Million-Token Context and Engineering Best Practices
This article examines the shift from conversational large language models to agent-based programming systems, focusing on the role of million-token context windows and effective engineering practices. It covers parameter scaling (total vs. active parameters), the practical costs of long contexts, four core capabilities for coding agents, how to correctly interpret evaluation metrics, a reference engineering architecture, and considerations for model selection, security governance, and phased rollout.
From Conversational Models to Agents: A Shift in Capability Boundaries
Large language models were primarily used for Q&A and text generation in the past. As task complexity grows, the industry’s focus is shifting toward agents. An agent does not merely output text—it must decompose goals, call tools, read environmental feedback, and adjust its next actions accordingly. When evaluating whether a model can serve as the foundation for an agent, three factors typically matter: whether it can maintain task context over long workflows, whether it can reliably produce structured tool-call parameters, and whether it can detect and correct its own errors during multi-step execution.
Programming is the most representative application scenario for agents. Code tasks are highly verifiable: whether code compiles, whether tests pass, and whether interfaces conform to specifications can all be checked automatically by programs. This makes programming an ideal environment for assessing agent capabilities, which is why related benchmarks are widely adopted.
Understanding Parameter Counts: Total vs. Active Parameters
Model introductions often cite both “total parameters” and “active parameters.” These mean different things, and conflating them leads to inaccurate estimates of cost and capability.
The Mixture of Experts (MoE) architecture splits the feed-forward network into multiple expert sub-networks, with a router selecting a small number of experts per input token for computation. This allows a model to maintain a large total parameter capacity while activating only a portion of parameters per forward pass, thereby controlling per-inference computational cost.
Consider a hypothetical example. Suppose a model has 100 billion total parameters and activates 20 billion per token. The computation per token is roughly comparable to a 20-billion-parameter dense model, while the knowledge capacity available to the model comes from all 100 billion parameters. Note that actual inference costs are also affected by GPU memory footprint, inter-node communication, batching strategies, and server-side scheduling. Inferring latency and cost solely from the active-parameter ratio is often unreliable.
Parameter size also cannot be equated with task performance. Model selection should be driven by evaluation results on your target tasks; parameter counts are only a reference.
Million-Token Context: Capability and Cost
The context window determines how much information a model can process at once. For programming agents, a larger window means more room for relevant source files, API documentation, conversation history, compilation errors, and test logs simultaneously, reducing errors caused by missing information.
Long context is not free. Standard attention computation scales quadratically with sequence length, while KV cache memory usage grows linearly. In high-concurrency scenarios, these two factors directly raise latency and cost. Common mitigation strategies include the following four approaches:
- Hierarchical context: Keep persistent content limited to project descriptions, coding standards, and current task objectives; load detailed files on demand.
- Retrieval augmentation: Build symbolic and vector indexes over the codebase first, then feed task-relevant functions and classes into the context.
- History compression: Compress completed steps into structured summaries, discarding verbose raw tool outputs.
- Prefix caching: Cache fixed system prompts and project background to reduce redundant computation.
Window size also does not equal effective utilization. In extremely long text, a model’s recall of information in middle positions may degrade. Therefore, critical constraints should be placed near the task instruction and re-confirmed at key decision points.
Four Core Agent Capabilities
When evaluating an agent, capabilities can be broken down into four interrelated dimensions:
- Task planning: Decompose the overall goal into verifiable sub-tasks with clear dependencies. Good planning ensures every step produces a checkable artifact—for example, “modify the interface definition” followed by “run the interface tests.”
- Tool invocation: Generate arguments that conform to the schema and correctly handle error codes and exceptions returned by tools. Missing arguments or type errors are common causes of agent failure; strict validation should be performed at the execution layer.
- Environmental feedback utilization: Read compilation errors, test failures, and command output to diagnose issues before deciding the scope of changes. Seeing only “failure” without analyzing the cause leads to repetitive trial-and-error.
- Convergence and termination: Recognize when a task is complete and proactively switch strategies or request human intervention when the same error recurs. Agents without a convergence mechanism can fall into unproductive loops and consume excessive compute.
All four capabilities are essential. A model that performs well on single-turn Q&A may still fail to reliably complete multi-step tasks.
How to Correctly Interpret Evaluation Metrics
Benchmark results are an important input for model selection, but every metric has a specific definition and boundary.
Pass@1 and Pass@k: Pass@1 is the proportion of problems where the model passes the test on the first generation. Pass@k is the probability that at least one of k samples passes. Sampling temperature and inference configuration must be unified across comparisons; otherwise, results are not comparable.
Code generation benchmarks: Most consist of algorithmic problems that test reasoning and implementation at the standalone function level. Their difference from real engineering lies in the fact that real projects contain extensive existing code, implicit conventions, and complex dependencies.
Software repair benchmarks: These require the model to fix defects corresponding to issue tickets in real code repositories and pass pre-existing tests. Such metrics are closer to engineering scenarios, but results depend heavily on test-suite quality. If test coverage is insufficient, pass rates may overestimate actual repair capability.
Retrieval and browsing benchmarks: These measure a model’s ability to gather information through multiple searches and page navigations. They test information retrieval and synthesis, a different dimension from coding ability.
Data contamination risk: If training data already contains benchmark problems, scores will be inflated. Using private question sets or problems dated after the training data cutoff can reduce this risk.
Inference budget impact: Some models support adjustable thinking length or inference budget. The same model can perform very differently under different budgets. Budget settings must be documented when comparing numbers from different sources; otherwise, they cannot be directly compared.
In summary, no single number captures overall capability. It is recommended to cover at least four categories of metrics: code generation, real-world defect repair, tool-call success rate, and average number of steps.
An Engineering Framework for Programming Agents
A production-grade programming agent typically includes the following components: model gateway, context manager, tool registry, sandboxed execution environment, permission and audit module, and a regression evaluation pipeline.
Below is a simplified agent loop that highlights several key design decisions: tool permission checking, treating tool outputs as data, and a step limit.
def run_agent(task, llm, tools, max_steps=20):history = [{"role": "user", "content": task}]for _ in range(max_steps):reply = llm.generate(history, tools=tools.schemas())# No tool call requested: treat as final answerif reply.tool_call is None:return reply.textname = reply.tool_call.nameargs = reply.tool_call.arguments# Permission checks at execution layer, not left to the modelif not tools.is_allowed(name):observation = {"error": "tool not authorized"}else:observation = tools.invoke(name, args) # return value recorded as data onlyhistory.append({"role": "assistant", "content": reply.raw})history.append({"role": "tool", "content": observation})raise RuntimeError("Step limit exceeded; terminate and escalate to human")
This code demonstrates three principles. First, permission decisions are enforced by the program, not delegated to the model’s judgment. Second, tool output is written into the history purely as an observation, not executed as a new instruction. Third, a step limit is set, with escalation to human handling when exceeded, preventing runaway costs from infinite loops.
In a production system, additional controls are needed: timeouts, retry policies, per-task budget limits, and complete call logging.
Selecting Between Open-Source and Closed-Source Models
Model selection should cover these dimensions: task effectiveness, unit cost, latency, data compliance, controllability (private deployment and fine-tuning options), service stability, and compatibility with existing toolchains.
No single model is optimal for every scenario. A common practice is model routing: route complex tasks like architectural design and difficult defect localization to stronger models, while routing routine tasks such as format conversion, unit-test completion, and documentation generation to lower-cost models. Routing rules can be dynamically adjusted based on task type, context length, and historical failure rates.
Migration cost should also be factored in. If business logic is tightly coupled to a vendor-specific interface format, switching models can require significant rework. Wrapping call protocols in a unified model gateway keeps replacement costs at the configuration level.
Security and Governance
Agents with tool-calling capabilities carry higher security risks than standard Q&A systems. Governance should be built around the following five areas:
- Credential management: Secrets are injected via environment variables or a secrets manager, never written into code, prompts, or logs. Sandboxes should not be able to read production credentials.
- Least privilege: File-system access, network access, and database write permissions are granted per task and revoked promptly after task completion.
- Prompt injection defense: Repository comments, web content, and tool output may contain malicious instructions. The system must treat all such content as data to be analyzed, with the prompt design clearly distinguishing instructions from data sources.
- Human approval: Irreversible operations such as merging code, deploying to production, and deleting data must require human sign-off.
- Audit logs: Record the name, arguments, return summary, and duration of every tool invocation to support post-hoc review and compliance auditing.
Security measures should match the risk profile. Read-only code analysis tasks and deployment tasks with write permissions require clearly different levels of control.
A Staged Rollout Roadmap
A four-phase rollout is recommended, with quantifiable exit criteria for each phase.
Phase 1: Build the evaluation set. Select representative tasks from real engineering scenarios that cover code generation, defect repair, tool invocation, and multi-step workflows. Establish baseline scores with authoritative models to provide a uniform reference.
Phase 2: Run pilots. Choose low-risk, high-frequency scenarios for controlled deployment. Key metrics to track include task completion rate, average number of steps, tool-call success rate, and human intervention rate. Compare these against baseline data to quantify stability and cost efficiency.
Phase 3: Expand gradually. Roll out to broader developer groups after stability passes the threshold. Strive to standardize permission models, audit specifications, and rollback procedures before scaling up.
Phase 4: Continuously optimize. Introduce model routing to match task difficulty with model capability. Maintain the evaluation set and update it as requirements evolve. Each model upgrade must pass the full regression suite before promotion to production.
