Long-Context LLMs and Long-Horizon Agents: An Engineering Perspective

    Long-context processing and long-horizon agents address two connected challenges: using large amounts of information and maintaining consistent progress across multi-step tasks. This article explains attention and memory constraints, positional encoding, effective information recall, rolling summaries, and the planning and memory structures that support extended agent workflows.

    1. Why Long Context and Long-Horizon Tasks Matter

    Early large language model applications focused on single-turn interactions: a prompt went in, and an answer came out. As models take on software development, research, and content production, the nature of their tasks is changing.

    A code change may require understanding dependencies across dozens of files. An industry research report may draw on hundreds of pages of material. A content production workflow may span source organization, outlining, detailed drafting, and format validation.

    These tasks place two demands on a model:

    • It must accommodate and use large amounts of information within a single processing context.
    • It must maintain a consistent objective and trackable state across multiple steps.

    The first is generally called long-context capability. The second falls under long-horizon agent capabilities. The two are interdependent: insufficient context capacity limits the intermediate results an agent can retain, while poor task management can cause a model to lose direction after dozens of steps—even with a large context window.

    2. How Long-Context Processing Works

    2.1 Compute and GPU Memory Constraints

    The computational cost of standard self-attention scales quadratically with sequence length. Extending a sequence from 4K to 128K tokens increases its length by a factor of 32, making the theoretical computation required for attention approximately 1,024 times greater. This is a primary constraint on long-context processing.

    During inference, the model also caches key and value vectors for each layer in a KV cache. Its GPU memory footprint scales with sequence length, layer count, the number of key/value attention heads, and numerical precision.

    Common engineering approaches include:

    • Using exact attention kernels that process inputs in blocks and reduce GPU memory reads and writes.
    • Adopting grouped-query attention or multi-query attention to reduce KV cache size.
    • Quantizing the KV cache to save memory in exchange for a small loss of precision.
    • Introducing sparse attention or sliding windows to limit the range of tokens each token attends to.

    The choice depends on the application’s relative sensitivity to accuracy, latency, and GPU memory consumption.

    2.2 Positional Encoding and Length Extrapolation

    A model encounters only a limited range of token positions during training. When applied directly to much longer inputs, its positional representations may become unreliable, weakening its ability to connect information across long distances.

    A common approach is to interpolate or scale rotary positional embeddings so that relative positional relationships remain usable at longer sequence lengths. Continued training then helps the model adapt to the extended length.

    These methods must be evaluated on long-text validation sets. Simply increasing a configuration limit does not demonstrate reliable long-context capability.

    2.3 Effective Context Use and Information Loss in the Middle

    A larger context window does not mean that every part of the input is used effectively. Research has often found that models make better use of information near the beginning and end of an input, while recall may decline for information in the middle.

    Three practical measures can help:

    1. Place critical instructions and constraints near the beginning or end of the input.
    2. Rank retrieved evidence by relevance before assembling it into the context.
    3. Run targeted recall tests regularly—for example, insert known facts into a long document and ask the model to extract them.

    These tests assess actual information use rather than nominal context capacity.

    2.4 Example: Processing Text in Chunks

    When an input still exceeds the practically usable context length, a common approach is rolling summarization. In the following example, call_llm represents a function that calls a language model; the user must implement it.

    1. def rolling_summarize(chunks, call_llm, max_chars=2000):
    2. summary = ""
    3. for chunk in chunks:
    4. prompt = (
    5. "Below are an existing summary and new content. Update the summary, "
    6. "preserving all key figures, conclusions, and unresolved questions. "
    7. f"Keep it within {max_chars} characters.\n\n"
    8. f"Existing summary: {summary}\n\nNew content: {chunk}"
    9. )
    10. summary = call_llm(prompt)
    11. return summary

    This approach loses some detail, so it is suitable for producing overviews or maintaining state records, but not for tasks that require verbatim quotations. Critical data should be extracted separately and stored in a structured format.

    3. How Long-Horizon Agents Work

    3.1 The Basic Loop

    Long-horizon agents typically operate through a plan, execute, observe, and revise loop.

    The model first breaks the objective into subtasks, then calls tools one at a time. These tools might read files, run tests, query databases, or access retrieval interfaces. Each result is written back into the task state, which the model uses to decide its next action.

    The loop ends when the objective is achieved, the budget is exhausted, or repeated failures trigger termination.

    3.2 State and Memory Management

    One difficulty with long-running tasks is that state grows as the number of steps increases. In practice, memory is commonly organized into three layers:

    1. Working memory: The current input and tool outputs from the most recent steps, placed directly in the context.
    2. Task memory: The objective, subtask list, completed work, and pending work, maintained as structured text and updated each round.
    3. Long-term memory: Experience, guidelines, and historical conclusions stored externally, retrieved as needed, and added to the context.

    This layered structure avoids placing the entire history in the context while helping preserve important information across many rounds.

    3.3 Task Loop Example

    The following partial example shows task-state initialization, action selection, a completion check, and tool execution:

    1. def run_agent(goal, tools, call_llm, max_steps=30):
    2. state = {"goal": goal, "done": [], "todo": [], "notes": []}
    3. for step in range(max_steps):
    4. action = call_llm(build_prompt(state, tools))
    5. if action["type"] == "finish":
    6. return action["result"]
    7. result = tools[action["tool"]](**action["args"])

    The supplied example ends during the next operation, which begins recording the action in state["done"]; it does not include a complete implementation.