Long Context and Long-Running Agents: Capability Boundaries and Deployment Practices

    Before choosing a model or agent configuration, validate two capabilities with representative internal data: whether important information can be reliably retrieved from long contexts, and whether the agent can maintain state across multi-step tasks. Only then should you optimize for latency and throughput by selecting a faster version. This article explains the engineering implications of long contexts, how to evaluate long-running agents, how to benchmark model variants, and where human review and compliance controls are required.

    1. Start with the Conclusion

    When selecting a model, first use your own samples to validate two capabilities:

    1. Can the model accurately retrieve critical information from a long context?
    2. Can the agent maintain state throughout a multi-step task?

    After these capabilities are validated, choose a faster version based on latency and throughput requirements. The order matters. If speed is prioritized first, quality often suffers on complex reasoning tasks, creating higher rework costs later.

    2. Why Long Context and Long-Running Agents Matter

    The evaluation criteria for large language models are changing. Previously, evaluations focused mainly on whether the model could answer a single question correctly. Today, it is increasingly important to determine whether a model can remain reliable during long-running, multi-step tasks.

    There are two main reasons.

    First, enterprise documents can span hundreds of pages, codebases can contain thousands of files, and financial reports and contracts are often lengthy. The amount of information a model can process in one request determines whether it can see the complete context at once.

    Second, agents are increasingly responsible for querying data, calling tools, modifying files, and repeatedly validating their work. These tasks may run for a long time and contain many intermediate states, which places greater demands on planning and memory.

    Model evaluation therefore cannot rely on single-question scores alone. You should also check whether the model:

    • Forgets constraints introduced earlier in the task
    • Can correct itself after a failure
    • Can accurately locate critical information after the context has been heavily populated

    3. The Engineering Meaning of Long Context

    A context window is the total amount of input and output tokens that a model can process during a single inference request. A larger window does not mean that all information will be used equally well. In practice, three issues require particular attention.

    1. Cost: Attention computation and cache usage generally increase with input length. Longer inputs increase time to first response and request costs.
    2. Retrieval: The position of critical information can affect retrieval reliability. Information in the middle of the context may be cited less accurately than information at the beginning or end. This behavior must be tested with your own samples rather than assumed.
    3. Organization: Placing an entire codebase or financial report into the context is not necessarily better than retrieving relevant sections first and then sending only those sections to the model.

    A hybrid strategy is commonly used in production. First, use retrieval or indexing to narrow the search space. Then place the most relevant content into the long context, using headings, numbers, and delimiters to identify the source of each section. This allows the model to cite sources in its response and makes manual verification faster.

    The following code estimates input size and splits content according to a token budget. When a section exceeds the budget, it is split by line. If an individual line still exceeds the budget, the function raises an error instead of silently truncating the content. The estimate is intended only for capacity planning; the exact count should come from the service-side tokenizer.

    1. def estimate_tokens(text: str) -> int:
    2. # Rough estimate: count CJK characters as 1 token and other characters
    3. # as approximately 1 token per 4 characters.
    4. cjk = sum(1 for ch in text if "\u4e00" <= ch <= "\u9fff")
    5. other = len(text) - cjk
    6. return cjk + other // 4
    7. def split_oversized(text: str, budget: int) -> list[str]:
    8. """Split oversized sections by line; raise if a single line exceeds the budget."""
    9. if estimate_tokens(text) <= budget:
    10. return [text]
    11. pieces, buf = [], ""
    12. for line in text.splitlines(keepends=True):
    13. if estimate_tokens(line) > budget:
    14. raise ValueError("A single line exceeds the budget; split it manually or increase the budget")
    15. if buf and estimate_tokens(buf + line) > budget:
    16. pieces.append(buf)
    17. buf = ""
    18. buf += line
    19. if buf:
    20. pieces.append(buf)
    21. return pieces
    22. def split_by_budget(sections: list[str], budget: int) -> list[list[str]]:
    23. flat: list[str] = []
    24. for sec in sections:
    25. flat.extend(split_oversized(sec, budget))
    26. batches, current, used = [], [], 0
    27. for sec in flat:
    28. cost = estimate_tokens(sec)
    29. if current and used + cost > budget:
    30. batches.append(current)
    31. current, used = [], 0
    32. current.append(sec)
    33. used += cost
    34. if current:
    35. batches.append(current)
    36. return batches

    4. Breaking Down Long-Running Agent Capabilities

    Agent capabilities can be divided into four areas and evaluated separately.

    • Planning: Break the goal into executable steps and identify dependencies between those steps.
    • Tool calling: Call external functions according to their parameter requirements and correctly parse their return values.
    • State maintenance: Record completed steps, confirmed facts, and unresolved questions.
    • Error recovery: Identify the cause of a failure, use an alternative approach, or request human intervention when necessary.

    State maintenance is the area most likely to be overlooked. If progress is stored only in the conversation history, the system cannot reliably resume after the context is truncated. A more robust approach is to store state in a structured object managed by the program. The model decides what to do next, while the program records what has already been done.

    Tool calls should use an allowlist and parameter validation. Tool names and parameters generated by the model must be treated as untrusted input. The following code checks the tool name and parameter fields before execution. Requests outside the allowed scope are recorded in the error list.

    1. import json
    2. from dataclasses import dataclass, field
    3. ALLOWED_TOOLS = {
    4. "read_file": {"path"},
    5. "query_db": {"table", "limit"},
    6. }
    7. @dataclass
    8. class TaskState:
    9. goal: str
    10. done: list[str] = field(default_factory=list)
    11. facts: dict[str, str] = field(default_factory=dict)
    12. errors: list[str] = field(default_factory=list)
    13. max_steps: int = 20
    14. max_errors: int = 3
    15. def validate_step(step: dict) -> None:
    16. tool = step.get("tool")
    17. if tool not in ALLOWED_TOOLS:
    18. raise PermissionError(f"Tool is not allowlisted: {tool}")
    19. args = step.get("args", {})
    20. illegal = set(args) - ALLOWED_TOOLS[tool]
    21. if illegal:
    22. raise ValueError(f"Unauthorized parameters: {sorted(illegal)}")
    23. def run_agent(state, plan_step, execute_tool) -> TaskState:
    24. for _ in range(state.max_steps):
    25. if len(state.errors) >= state.max_errors:
    26. break # Stop and hand off to a human when the error threshold is reached
    27. step = plan_step(state) # The model returns the next step; None means the task is complete
    28. if step is None:
    29. break
    30. key = json.dumps(step, ensure_ascii=False, sort_keys=True)
    31. try:
    32. validate_step(step)
    33. result = execute_tool(step)
    34. state.done.append(key)
    35. state.facts[key] = str(result)
    36. except Exception as exc:
    37. state.errors.append(f"{key}: {exc}")
    38. return state

    The loop sets a maximum number of steps to prevent the agent from running indefinitely. Execution stops when the error threshold is reached, and the caller can inspect state.errors to determine whether the task should be handed off to a human.

    Write operations, transactions involving money, and actions that send information externally should always require human confirmation. They should not rely only on an error counter.

    Use the following checklist when accepting an agent implementation:

    • Planning: Steps and dependencies can be restated, and there are no circular dependencies.
    • Tool calling: Every call passes through an allowlist, and its parameters are validated.
    • State maintenance: The task can resume from structured state after interruption without relying on conversation history.
    • Error recovery: A failure triggers an alternative path or a human escalation path.

    5. Choosing a Faster Model Version

    A model family may offer multiple versions with different reasoning speeds. When two versions have similar capabilities and differ mainly in output speed, the choice should be based on business requirements for latency and throughput.

    Scenario Priority metric Selection tendency Main risk
    Interactive use cases, such as code completion and online Q&A Time to first token and output tokens per second Prefer the faster version It may handle simple tasks well but be less reliable on complex reasoning
    Batch workloads, such as offline summarization and bulk classification Total throughput at a given cost Use the faster version or a batch interface Errors can be amplified across the batch and require sampling-based review
    Complex reasoning, such as architecture decisions and financial modeling Accuracy of conclusions Prioritize quality rather than speed The faster version may miss implicit conditions

    Speed multipliers published by vendors are reference values only. Actual performance depends on concurrency, input length, network conditions, and service load.

    Before selecting a version, use internal data to validate whether the two versions are genuinely comparable for the target tasks. A practical evaluation process is:

    1. Extract a fixed sample from real business workloads. A recommended sample contains at least 200 items and covers long inputs, short inputs, and boundary cases.
    2. Define the evaluation criteria for every sample. Use rules where possible; for tasks that are difficult to formalize, use human-labeled reference answers.
    3. Run both versions under the same concurrency, input-length, and network conditions, recording the complete response time for every sample.
    4. Calculate accuracy, mean latency, and 90th-percentile latency. Then convert total cost using the cost per unit.
    5. For task types where the accuracy gap exceeds a predefined threshold, select the higher-quality version directly.

    The following code implements steps 3 and 4. It calls the model sequentially and measures accuracy and latency. This measures complete response time; time to first token requires a separate measurement through a streaming interface.

    1. import statistics
    2. import time
    3. def percentile(values: list[float], p: float) -> float:
    4. ordered = sorted(values)
    5. idx = min(len(ordered) - 1, round(p * (len(ordered) - 1)))
    6. return ordered[idx]
    7. def benchmark(call_model, cases, check, warmup: int = 3) -> dict:
    8. """cases is a list of (prompt, expected); check(output, expected) returns bool."""
    9. if not cases:
    10. raise ValueError("cases must not be empty")
    11. for prompt, _ in cases[:warmup]:
    12. call_model(prompt) # Warm up to exclude one-time connection overhead
    13. correct, latencies = 0, []
    14. for prompt, expected in cases:
    15. start = time.perf_counter()
    16. output = call_model(prompt)
    17. latencies.append(time.perf_counter() - start)
    18. if check(output, expected):
    19. correct += 1
    20. return {
    21. "n": len(cases),
    22. "accuracy": correct / len(cases),
    23. "latency_mean_s": statistics.mean(latencies),
    24. "latency_p90_s": percentile(latencies, 0.9),
    25. }

    6. Deployment Methods and Risk Boundaries by Use Case

    Software Engineering

    Integration approach: Build an index for the codebase, retrieve relevant files by module or dependency relationship, and then place the candidate files into the long context. This approach is suitable for cross-file refactoring, interface migrations, and test completion.

    Suitable conditions: The code has test coverage, and modifications can be reviewed through a diff. For legacy code without tests, model-generated changes should be treated only as drafts.

    Failure modes: An outdated index may omit call sites; the model may reference a deleted function; or the modification scope may exceed the task requirements.

    Human review points: Submit all modifications as diffs for engineer review. Tests must actually run locally or in the CI pipeline; a verbal conclusion from the model is not sufficient.

    3D Content Creation

    Integration approach: Have the model generate scene descriptions, asset metadata, or modeling scripts, and then execute them through controlled rendering tools. The model should not directly operate on the production asset library.

    Suitable conditions: The project has clear standards for coordinate systems, units, and scale, and the output can be validated through a rendering preview.

    Failure modes: Mixing units can produce incorrect dimensions; coordinates may fall outside scene boundaries; or the licensing status of assets may be unclear.

    Human review points: Render a preview of each generated batch and have an artist verify scale and style. Check licensing terms before using any asset.

    Financial Research

    Integration approach: Split annual reports, prospectuses, and similar long documents by chapter and table, then send the sections to the model separately. Require every number to include its page reference.

    Suitable conditions: The documents are publicly disclosed materials or have passed internal compliance approval. Non-public research materials must not be sent to an unauthorized service.

    Failure modes: Table-parsing errors may shift values into adjacent columns; accounting periods or currencies may be confused; and the model may generate plausible but nonexistent citations.

    Human review points: Verify critical figures against the original page. Conclusions involving investment recommendations must be signed off by an analyst. Model output must not be used directly as an external conclusion.

    7. Data Compliance and Risk Controls

    Before enterprise documents, codebases, or financial reports are sent to a model, complete the following steps:

    • Redaction: Remove personal information, customer names, secrets, and internal account identifiers. Keep secrets in environment variables or a secret management service; do not place them in prompts or logs.
    • Access control: Limit the model’s data access to the minimum required for the current task. Keep data from different departments in separate retrieval scopes.
    • Audit trails: Record input sources, model versions, tool-call parameters, and outputs for later investigation.
    • Tool allowlists: Expose only approved tools. Write, delete, and external-send operations must include a human confirmation step.

    8. Frequently Asked Questions

    Is a long context window sufficient?
    Test it with your own samples. Place critical information at different positions and measure citation accuracy. If accuracy drops significantly for information in the middle, switch to retrieval combined with segmentation.

    How can an agent avoid forgetting?
    Store the goal, confirmed facts, and unresolved questions in structured state. At every step, read from that state instead of relying on conversation history.

    How should a faster version be selected?
    First determine whether the task involves complex reasoning. If it does, prioritize quality. Otherwise, compare accuracy and latency on a fixed sample, and choose the faster version only after it meets the required thresholds.

    9. Summary

    Long contexts and long-running agents both have clear capability boundaries. In production, validate information retrieval and state maintenance first, then select the appropriate model version for each use case and define human review points for every task category. Evaluation based on internal data is more reliable than relying on reference figures alone.