Engineering Long-Context LLMs and AI Agents: A Practical Guide

    This guide covers how to put large language models with long context windows and AI agents into production. It explains what a context window is and how to estimate input size before a request. It compares three ways to handle long text: full input, retrieval-augmented generation, and hierarchical summarization. It also outlines the basic structure of an agent, common failure modes and how to guard against them, and a method for estimating cost and building an evaluation set.

    1. Background: How Long Context and Agents Are Changing Things

    The capability limits of large language models have shifted noticeably over the past two years. The input length a model can accept at once has grown from a few thousand tokens to hundreds of thousands, and in some cases to around a million. Models can now process a complete code repository, a long technical document, or a multi-turn conversation log in a single pass. Models also no longer only generate text. They can call external tools to run queries, edit files, and execute tests. Systems that pursue a goal and plan their own steps are commonly called AI agents.

    For developers, the real question is how to integrate these capabilities reliably into business workflows. As context windows get longer, cost, latency, and accuracy are affected in different ways. Once an agent can take actions, the cost of errors rises as well. This article therefore covers three areas: how to use long context, how to structure an agent, and how to evaluate cost and effectiveness quantitatively.

    2. Long Context: Capacity Is Sufficient, but Usage Still Matters

    2.1 What the context window means

    A context window is the total length of input and output a model can handle in a single inference. It is usually measured in tokens, the basic units a model uses to split text. English words, Chinese characters, and punctuation are split differently, so the same passage can produce noticeably different token counts across tokenizers. Estimates should use the counting method provided for the target model, not a simple conversion from character count.

    2.2 Estimate input size before submitting

    Estimating input size before sending a request helps you avoid exceeding the window limit and makes it easier to control costs. The following is a general estimation example. Replace the estimation function with the actual tokenizer’s count:

    1. def estimate_tokens(text: str, chars_per_token: float = 1.5) -> int:
    2. # Rough estimate for capacity planning only; use the model's own tokenizer for exact counts
    3. return int(len(text) / chars_per_token)
    4. def fits_in_window(documents: list[str], window_size: int,
    5. reserved_output: int = 4096) -> bool:
    6. total = sum(estimate_tokens(d) for d in documents)
    7. return total + reserved_output <= window_size

    reserved_output sets aside space for the model’s response. Many developers count only the input, and their results get truncated when the model generates a long answer. Reserving output space is a necessary step.

    2.3 Three common long-text strategies

    (a) Full input. Pass all material to the model at once. This gives the most complete reasoning across sections and suits tasks that require global understanding, such as checking a whole design document for consistency. The drawbacks are higher cost, slower responses, and the risk that key information gets buried under unrelated content.

    (b) Retrieval-augmented generation (RAG). First use a retrieval method to find passages in the material store that relate to the question. Then pass those passages to the model. The input is shorter, so cost is lower, and updating the knowledge base does not require retraining the model. The drawback is that retrieval quality sets the ceiling on results. If the relevant passages are not retrieved, the model cannot answer correctly.

    (c) Hierarchical summarization. Generate a summary for each section, then complete the overall task based on those summaries, returning to the original text when necessary. This approach suits overview tasks on very long material. Summaries lose detail, so numbers, citations, and conclusions should keep references to their location in the source text for verification.

    In practice, these three strategies are often combined. Retrieval narrows the scope, full input supports deep reasoning within that scope, and summaries maintain the state of long sessions.

    2.4 State management in long sessions

    In multi-turn conversations, the message history keeps occupying the context window. A reasonable approach is to keep the original text of the most recent several turns, compress earlier content into a structured summary, and store key facts separately, such as user preferences and confirmed decisions. This keeps input length under control and reduces the chance that the model gives contradictory answers because older information interferes.

    3. Engineering Structure of an Agent

    3.1 Core components

    A usable agent typically includes five parts:

    • Goals and constraints: Define the expected output, prohibited actions, and completion conditions.
    • Context assembly: Decide which information the model receives at each step.
    • Tool set: Describe callable functions in a structured way, including parameter types and permission scopes.
    • Execution loop: The model proposes an action, the system validates and executes it, and the result is fed back to the model.
    • Termination and audit: Log each action, and end the run when the conditions are met or the step limit is reached.

    3.2 Execution loop example

    The following pseudocode shows a minimal execution loop. The key point is that every step is validated, and a step limit is enforced:

    1. MAX_STEPS = 10
    2. ALLOWED_TOOLS = {"read_file", "run_tests", "search_docs"}
    3. def run_agent(task: str, model, tools: dict) -> str:
    4. history = [{"role": "user", "content": task}]
    5. for step in range(MAX_STEPS):
    6. action = model.next_action(history) # Model proposes the next action
    7. if action.type == "final":
    8. return action.content # Task complete
    9. if action.tool not in ALLOWED_TOOLS: # Allowlist check
    10. history.append(error_msg("Tool is not in the allowed list"))
    11. continue
    12. result = tools[action.tool](**validate(action.args)) # Validate arguments before execution
    13. history.append({"role": "tool", "content": truncate(result)})
    14. raise RuntimeError("Maximum steps exceeded; task not completed")

    This code reflects three principles. Tool permissions are managed with an allowlist. Arguments are validated before execution. Tool output is truncated before it is fed back, so oversized results do not crowd out the rest of the context.

    3.3 Common failure modes and safeguards

    • Infinite loops: The model repeatedly calls the same tool without making progress. Set a step limit and detect consecutive repeated actions.
    • Unauthorized actions: The model calls an interface it should not have access to. Follow the principle of least privilege, and require separate confirmation for write operations.
    • Result hallucination: The model claims a step is complete when it was not actually executed. Treat the real results returned by tools as the source of truth, and require verifiable evidence for critical steps, such as test output or file checksums.
    • Instruction injection: External documents may contain text that tries to make the model perform additional actions. Treat content returned by tools as data rather than instructions, and require secondary confirmation for high-risk operations.

    4. Quantitative Evaluation of Cost and Effectiveness

    4.1 Cost model

    For most pay-as-you-go model services, fees have two parts: input tokens and output tokens. Output tokens are usually priced higher than input tokens. The cost of a single request can be expressed as:

    Cost = input tokens × input price + output tokens × output price

    An agent task calls the model multiple times, so its total cost is the sum across all steps. As context accumulates with each step, later inputs keep growing, and cost often rises faster than expected.

    4.2 Estimation example

    1. def task_cost(steps: int, avg_input: int, avg_output: int,
    2. price_in: float, price_out: float) -> float:
    3. # price_in and price_out are prices per million tokens, in the same currency unit
    4. total_in = steps * avg_input
    5. total_out = steps * avg_output
    6. return (total_in * price_in + total_out * price_out) / 1_000_000

    Suppose a task averages 8 steps, with 20,000 input tokens and 1,000 output tokens per step. Substituting the prices gives the cost of that task. These figures only illustrate the calculation method. Use the provider’s current pricing table for actual prices.

    4.3 Build your own evaluation set

    Public parameter specifications and leaderboard scores only reflect general model capability. They cannot replace evaluation on your own business tasks. Draw 50 to 200 task samples from real business workflows, covering common scenarios and edge cases, and for each task sample