Million-Token Context & AI Agents: A Developer's Guide to New LLMs
This article explores the practical implications of new LLMs offering million-token context windows and advanced agent capabilities. It covers how developers can leverage these features for whole-document analysis, long conversation memory, and repository-level coding tasks. Additionally, it provides actionable strategies for tiered model selection, building robust agent loops, and managing the cost and latency trade-offs associated with massive context processing.
1. From 128K to 1M: What Long Context Means
The context windows of previous mainstream models were generally around 128K tokens, roughly equivalent to a short-to-medium document. The new generation of models expands this window to the million-token level. Calculating 1M as approximately 1024K, the capacity is about eight times larger. As the window grows, the types of tasks the model can handle also increase, fundamentally changing how developers work.
In practical applications, there are three main types of changes.
First is whole-document analysis. A medium-to-long novel, a multi-hundred-page technical specification, or a medium-sized code repository can be placed into the context all at once. The model can perform global reasoning across chapters and files without relying on chunking and retrieval. The problem with chunking and retrieval is that the retriever might miss key paragraphs, forcing the model to guess the overall structure based on fragments.
Second is long conversation memory. In customer service or consulting systems, a user’s historical conversations over several days can be fully retained. Traditional solutions often rely on summarization or vector retrieval to maintain memory, where information is easily lost during compression. By retaining the full history, it is much easier for the system to maintain consistency.
Third is repository-level code tasks. When performing refactoring or debugging cross-module defects, the model can simultaneously view the contents of multiple files, understanding call relationships and dependency directions.
A larger window also brings new costs.
Attention computation grows with sequence length. Some implementations use sparse attention or KV cache compression to reduce overhead, but recall precision for long-tail positions may drop. The actual effect needs to be tested with your own data.
“Lost in the middle” is another common issue. Multiple studies have observed that models utilize information at the beginning and end of the context well, while the middle part is easily ignored. It is recommended to place important instructions and key data at the beginning or end, and repeat key constraints when asking questions.
The cost and latency of a single call cannot be ignored either. Even if the unit price drops, a million-token request is still relatively expensive and slow. Engineering-wise, two things are usually done. One is dynamic truncation, keeping only the parts relevant to the current question. The second is summary compression, compressing earlier content into a short summary before retaining it alongside recent messages.
Below is the schematic code for the truncation strategy, where count_tokens and summarize need to be implemented by yourself:
# Example code: count_tokens and summarize need to be self-implementeddef build_context(history, budget_tokens):kept, used = [], 0for i in range(len(history) - 1, -1, -1): # Take from the latest message backwardsn = count_tokens(history[i])if used + n > budget_tokens:older = history[: i + 1]kept.insert(0, summarize(older)) # Compress older messages exceeding the budget into a summarybreakkept.insert(0, history[i])used += nreturn kept
2. Tiered Model Selection: Flagship vs. Lightweight
The new versions generally adopt a dual-track strategy of a flagship model plus a lightweight model. The flagship model is geared towards complex reasoning, multi-step planning, and code generation, while the lightweight model targets latency-sensitive or cost-sensitive batch tasks. The gap between the two usually appears in complex multi-step reasoning. Performance in format conversion, summarization, classification, and common code completion is often very close.
Official capability improvement figures, such as how much Agent capabilities have improved compared to the previous generation, should be based on the official technical reports and public evaluations. This article does not cite unverified percentages. A more reliable approach when selecting a model is to conduct comparative tests using sample sets from your own business, recording three metrics: quality, latency, and cost.
A practical approach is cascade routing. Requests are first sent to the lightweight model, and the result quality is then evaluated through rule validation or self-consistency voting. If the result does not meet the standard, it is escalated to the flagship model for a retry. This approach can reduce average costs with acceptable quality loss, but the effectiveness depends on the accuracy of the validation rules.
Below is the schematic code for the routing logic. Model names and thresholds are example values and need to be adjusted based on your own evaluation results:
from dataclasses import dataclass@dataclassclass Task:complexity: str # "low" or "high"requires_agent: bool # Whether multi-step tool calling is requireddaily_volume: int # Average daily request volumedef choose_model(task: Task) -> str:# Complex reasoning, Agent orchestration, long doc analysis go to the flagship modelif task.complexity == "high" or task.requires_agent:return "pro"# Other tasks default to the lightweight model; large-scale batch processing prioritizes cost controlreturn "flash"
3. Agents: Completing Tasks via Feedback
An Agent refers to a model’s ability to understand task objectives, decompose them into multi-step plans, call external tools, and correct itself based on execution results until the task is complete. The new generation of models has improved the stability of tool calling formats and the continuity of long tasks. Developers can usually connect using the standard function calling interface without needing to parse the model’s text output format themselves.
A minimal Agent loop includes message history, a tool list, termination conditions, and safety boundaries. The schematic code below adds task completion checks, tool result returns, round limits, and error handling. Here, tools is a mapping of tool names to functions, and the corresponding parameter descriptions must also be provided to the model:
MAX_STEPS = 20 # Prevent infinite loopsdef run_agent(task_prompt, llm, tools):messages = [{"role": "user", "content": task_prompt}]for _ in range(MAX_STEPS):resp = llm.chat(messages, tools=tools)messages.append(resp.message)if not resp.tool_calls: # Model no longer calls tools, considered completereturn resp.textfor call in resp.tool_calls:try:result = tools[call.name](**call.arguments)except Exception as e: # Pass error back to the model for self-correctionresult = f"error: {e}"messages.append({"role": "tool","tool_call_id": call.id,"content": str(result),})raise RuntimeError("Exceeded max rounds, task incomplete")
The key is to let the model continuously receive real feedback within the loop, such as test results, compilation errors, and API return values. Without this feedback, the model can only rely on inference, and errors will gradually accumulate. Code-related tasks are most effective in scenarios with clear feedback, such as fixing errors iteratively or modifying code after running tests.
Once an Agent can call tools, it can also modify files or initiate network requests. Developers should restrict tool permissions, add human confirmation for operations like writing, deleting, and external sending, and log every step of the calls to facilitate tracing if an error occurs.
4. Cost Accounting: Look Beyond Unit Prices
Model pricing is typically billed separately for input and output, with unit prices usually calculated per million tokens.
