Long Context and Long-Horizon Agents: An Engineering Guide for LLMs
As LLM applications evolve from simple single-turn Q&A to complex, multi-step tasks, developers face challenges in context management, error propagation, and evaluation. This article provides an engineering guide for building long-horizon agents, covering foundational concepts, layered context organization strategies, and retrieval and compression techniques with illustrative code.
1. Background: From Single-Turn Q&A to Long-Horizon Tasks
The way we use large language models (LLMs) is changing. Early use cases typically involved single-turn Q&A, where a user inputs a question, the model returns an answer, the context is relatively short, and the cost of errors is low. In the past two years, an increasing number of applications require models to read entire code repositories, process hundreds of pages of contracts or research reports, and complete retrieval, computation, external tool invocation, and result correction across dozens of steps. These types of tasks are generally referred to as long-horizon tasks, and the systems that carry them out are called agents.
When implementing these systems, developers typically encounter three types of problems:
- Overly long contexts lead to increased costs and slower responses, while critical information gets drowned out by irrelevant content;
- An error in a single step of a multi-step task causes a cascading failure in subsequent steps;
- Factual errors in model outputs are difficult to detect, lacking quantifiable evaluation methods.
This article discusses approaches to these problems from an engineering perspective and provides illustrative code.
2. Foundational Concepts
Context Window: The maximum input length a model can process in a single inference pass, typically measured in tokens. A token is the basic unit a model uses to split text; the tokenization ratio differs between Chinese and English. When estimating costs, you should use the corresponding model’s tokenizer rather than making rough estimates based on character counts.
Long-Horizon Task: A task that requires multiple rounds of reasoning, multiple tool invocations, and consistency across intermediate states. The criterion for identifying a long-horizon task is whether the number of steps exceeds the range that can be reliably completed in a single inference pass.
Agent: A system composed of a model, a set of tools, memory, and a control loop. The model is responsible for decision-making, the tools for execution, and the control loop for chaining the two together and deciding when to stop.
Factual Error: When the content stated by the model is inconsistent with verifiable sources. This is a different problem from an “incomplete answer” and should be evaluated separately.
3. Long Context Organization Strategies
A larger context window does not mean you can dump all materials into a single request at once. There are three reasons for this. First, the longer the input, the higher the latency and cost of a single request. Second, irrelevant content distracts the model’s attention from key information, leading to omissions. Third, the utilization quality of information at different positions within a long input may be inconsistent; when key information is located in the middle, it especially requires verification. Therefore, engineering practice typically adopts a layered organization approach.
3.1 Layered Context
Divide the context into four layers:
- System Layer: Role definition, output format, and safety constraints. The content is stable and suitable for placement at the very beginning.
- Task Layer: Current goals, acceptance criteria, and constraints.
- Working Layer: Relevant snippets retrieved or returned by tools in the current round, replaced as needed.
- History Layer: Summaries of completed steps, rather than the full raw conversation history.
The benefit of layering is that stable content is fixed in the prefix, while dynamic content is concentrated at the tail. This structure makes debugging easier and creates the conditions for cache reuse discussed later.
3.2 Retrieval and Compression
For ultra-long documents, the common approach is to split, then retrieve, and finally compress. When splitting, you should respect semantic boundaries, such as splitting by chapters or function definitions, rather than hard-splitting by a fixed character count. Retrieval can combine keyword matching with vector similarity, as the two are complementary: keyword matching is sensitive to proper nouns, while vector retrieval is more robust for synonymous expressions.
During the compression phase, traceability must be maintained. Every conclusion in the summary should be accompanied by its location in the original text for easy subsequent verification. Here is a simplified example:
from dataclasses import dataclass@dataclassclass Chunk:doc_id: strstart: intend: inttext: strdef split_by_paragraph(doc_id: str, text: str, max_chars: int = 2000) -> list[Chunk]:"""Split by empty lines into paragraphs, then merge into chunks not exceeding max_chars. Offsets are approximate."""chunks, buf, start, pos = [], "", 0, 0paragraphs = text.split("\n\n")for p in paragraphs:p = p.strip()if not p:continueif len(buf) + len(p) + 2 > max_chars and buf:chunks.append(Chunk(doc_id, start, pos, buf))buf = pstart = poselse:if buf:buf += "\n\n" + pelse:buf = ppos += len(p) + 2if buf:chunks.append(Chunk(doc_id, start, pos, buf))return chunks
