Long Context and Long-Running AI Agents: Engineering Practices for Large Language Models

    This article examines how to evaluate and engineer large language model systems with million-token context windows and multi-step agent workflows. It covers context organization, token budgeting, prefix reuse, agent state management, sandboxed tool execution, validation loops for code and 3D modeling, and practical metrics for measuring factual accuracy and task cost.

    1. Background: Evaluating Long Context and Long-Running Agents

    Large language model context windows have grown from a few thousand tokens to the million-token range. A single context window can now contain an entire code repository, multiple long documents, or hundreds of pages of financial materials. This creates new engineering questions: Does the model actually use the information in a larger window? Can costs remain under control? Can multi-step tasks stay reliable over time?

    A single composite score is often insufficient for evaluating these capabilities. Developers should separate at least three metrics:

    • Task completion rate
    • Factual accuracy
    • Cost per task

    These metrics involve trade-offs. Improving one may negatively affect another.

    2. Organizing Long-Context Inputs

    A large context window does not mean that all available content should be inserted into a single request. In practice, three common strategies are useful.

    1. Semantic chunking: Split content by functions, sections, or paragraphs instead of cutting through the middle of a sentence.
    2. Hierarchical summarization: Generate a summary for each chunk, then summarize those summaries to create a global view.
    3. Preserving structural information: Include metadata such as heading hierarchy, file paths, and table headers with the content. This helps the model locate relevant information.

    Example pseudocode:

    1. function build_context(documents, budget):
    2. chunks = []
    3. for doc in documents:
    4. for section in split_by_structure(doc):
    5. chunks.append({
    6. path: doc.path,
    7. heading: section.heading,
    8. text: section.text
    9. })
    10. ranked = rank_by_relevance(chunks, task)
    11. selected = []
    12. used = 0
    13. for chunk in ranked:
    14. if used + token_count(chunk) > budget:
    15. break
    16. selected.append(chunk)
    17. used += token_count(chunk)
    18. return format(selected)

    The key principle is budget control. Every request should have an explicit token limit. When the limit is exceeded, content should be truncated according to relevance rather than relying on the model to ignore irrelevant material on its own. The more unrelated content the request contains, the harder it becomes for the model to find critical information, and the less stable the output is likely to be.

    Prefix Reuse and Cost

    Most inference services support reuse of intermediate computation for requests with identical prefixes. Stable content such as system instructions, fixed documents, and tool definitions should appear at the beginning of the request, while dynamic questions should be placed at the end. This can improve prefix-cache hit rates.

    The billing rules for writing to a cache and reading from a cache are typically different. The expected benefit should therefore be calculated from actual request patterns rather than estimated by intuition alone.

    3. Designing Tasks for Long-Running Agents

    A long-running agent uses tools, reads feedback, and continues working toward a goal across multiple steps. Unlike a single-turn question-answering system, it requires explicit state management and error recovery.

    Four elements should be defined during design:

    • Goal and completion criteria: Specify what counts as completion, and make the completion state automatically verifiable whenever possible.
    • Tool set: Define each tool’s input and output formats, permission scope, and timeout.
    • State records: Persist every action, result, and intermediate artifact so that the workflow can be inspected and debugged.
    • Termination conditions: Set maximum step counts and limits on consecutive failures to prevent infinite loops.

    Example pseudocode:

    1. state = init_state(goal)
    2. for step in range(MAX_STEPS):
    3. action = model.plan(state)
    4. if action.type == "finish":
    5. break
    6. result = run_tool(action.tool, action.args, timeout=TIMEOUT)
    7. state.append(action, truncate(result, LIMIT))
    8. if state.consecutive_failures >= FAIL_LIMIT:
    9. escalate_to_human(state)
    10. break

    Restricted Terminal Environments

    When tasks run in a restricted command-line environment, the system should provide sandbox isolation, command allowlists, timeout controls, and output truncation. Commands generated by the model should first pass static checks. High-risk operations such as deletion, overwriting files, or external network access should require human confirmation.

    Success should be determined by an independent validation script rather than by the model’s own claim that the task succeeded.

    4. Validation Loops for Code and 3D Modeling Tasks

    Code generation quality depends on a reliable validation loop. A robust workflow includes generation, parsing or compilation, unit testing, result checking, returning failure information to the model, and generating another revision. Delivering code after a single generation step generally results in a higher error rate.

    Parametric modeling follows the same principle. Design constraints such as dimensions, hole positions, and tolerances should be represented as parameters. A script can then generate the geometry from those parameters, followed by geometric checks—such as volume, bounding-box, and interference checks—to confirm that the result meets the requirements.

    Example pseudocode:

    1. function build_bracket(width, height, thickness, hole_diameter):
    2. assert width > 0 and height > 0
    3. assert hole_diameter < min(width, height) / 2
    4. body = create_box(width, height, thickness)
    5. body = subtract(body, create_cylinder(hole_diameter, thickness, at=center))
    6. return body
    7. part = build_bracket(width=40, height=60, thickness=5, hole_diameter=6)
    8. check_bounding_box(part, max_size=(50, 70, 10))

    For game-engine integration, the main challenge is often resource consistency. Naming conventions, coordinate systems, and unit systems must be standardized. These issues can take more time to resolve than the modeling itself. They should be documented at the beginning of the project and enforced through automated checks.

    5. Measuring Factual Accuracy

    Two metrics are easy to confuse when evaluating factuality:

    • Per-statement error rate: The proportion of incorrect statements among all statements. This reflects the model’s basic reliability.
    • Answer-level error rate: The proportion of answers containing at least one error. This better reflects how frequently users encounter an incorrect answer.

    These metrics cannot be directly converted into one another. Their relationship can only be estimated approximately under assumptions such as independence between individual statements within an answer.