Engineering Million-Token Contexts and Multi-Agent Collaboration for LLMs

    This article explores the engineering practices required to run large language models in professional workflows, where input scale, long-running tasks, and execution determinism create pressure beyond what a larger model alone can solve. It covers layered context budgeting, retrieval-first evidence injection, hierarchical summarization, multi-agent role design with verifiable subtasks and shared memory, tool integration for office document generation, and the evaluation, security, and governance layers needed to keep the system auditable and stable. A phased adoption roadmap is included.

    1. Background: Three Pressures from Professional Use Cases

    Model iterations over the past two years have pushed large language models from “chat tools” toward “task executors.” In financial research, software engineering, and everyday office work, the pressure concentrates in three areas: input scale, task duration, and execution determinism.

    On input scale, a complete earnings report, a mid-sized code repository, or a contract with multiple layers of nested attachments can easily reach hundreds of thousands or even a million tokens. On task duration, a real agent task is rarely a single question-and-answer turn; it is a multi-step loop of “decompose - retrieve - call - verify - write back,” which requires the model to stay aligned with the goal over a long span. On execution determinism, professional settings tolerate very little error: a wrongly configured pricing formula can cause financial loss, and a single concurrency defect can stall an entire pipeline.

    These three pressures mean that a “bigger model” alone cannot solve the problem. Progress depends on the coordinated engineering of three main threads: context management, agent orchestration, and tool integration.

    2. Million-Token Context: From “Fits In” to “Usable”

    Extending the context window to a million tokens only solves the “can it fit” problem. The real challenge is using it accurately. In practice, treat context as a limited budget rather than an unlimited container.

    Budget layering. Divide context into four layers: system instructions and constraints; long-term knowledge (specifications, glossaries, past decisions); current task state (goals, completed steps, pending items); and raw material (document fragments, code files). Each layer uses a different eviction strategy: the first two stay resident, the third is compressed structurally, and the fourth is loaded on demand.

    Put retrieval and recall first. Do not inject all material at once. First use hybrid keyword and vector retrieval to locate candidate fragments, then inject them as “evidence blocks” with source identifiers so they can be cited and checked later.

    Layered compression and summarization. For long documents, use three levels of compression: paragraph summary, section summary, and full-document summary. For code repositories, use three levels of abstraction: file summary, module interfaces, and call graph. An illustrative budget allocation looks like this:

    1. def build_context(system, knowledge, state, evidence, limit):
    2. # Keep stable layers first; truncate the evidence layer by relevance
    3. fixed = system + knowledge
    4. remain = limit - len(fixed) - len(state)
    5. evidence = sorted(evidence, key=lambda e: e.score, reverse=True)
    6. picked, used = [], 0
    7. for e in evidence:
    8. if used + len(e.text) > remain:
    9. break
    10. picked.append(e)
    11. used += len(e.text)
    12. return fixed + state + picked

    Position and order matter too. Placing key constraints at the beginning and the end, with material in the middle, mitigates the problem of mid-context information being ignored in long contexts. In addition, long contexts increase latency and cost, so track two metrics continuously: context hit rate and token consumption per task.

    3. Multi-Agent Collaboration: Breaking Large Tasks into Verifiable Small Ones

    The essence of an “agent team” is task decomposition and role division, not simple parallelism. A practical orchestration includes four roles: a planner that decomposes goals and defines acceptance criteria; executors that retrieve, code, and compute; a reviewer that checks work against the acceptance criteria; and an aggregator that merges results and produces deliverables.

    Three decomposition principles apply. First, each subtask must be independently verifiable: “generate a function” is weaker than “generate a function that passes the given input-output test cases.” Second, keep coupling between subtasks low; share state through explicit intermediate artifacts rather than implicit dependencies. Third, set a budget cap for each subtask (steps, tokens, time) to prevent infinite loops.

    For shared memory, a “task board + artifact store” structure works well: the task board records the state machine (todo / in progress / in review / done / failed), and the artifact store holds intermediate files and structured results. For example:

    1. {
    2. "task_id": "T-102",
    3. "goal": "Add boundary cases to the parsing module",
    4. "acceptance": ["cover empty input", "cover overlong lines", "all cases pass"],
    5. "budget": {"steps": 12, "tokens": 200000},
    6. "status": "in_review",
    7. "artifacts": ["tests/parse_edge.py"]
    8. }

    Failure recovery is a key engineering concern. Give each subtask idempotent retries and a rollback point: record the artifact version before execution, and roll back to the last verified state on failure. After two consecutive failures, escalate to a human or switch strategy instead of retrying mechanically.

    4. Tool Calling and Office Document Integration

    The value of agentic tasks comes from the closed loop of “model + tools.” Consolidate the tool layer into four categories: retrieval (document stores, code indexes), computation (spreadsheet calculation, script execution sandboxes), writing (document and presentation generation), and validation (tests, static checks, data consistency checks).

    The key to office document generation is separating templates from structured data: first describe content and layout in a structured intermediate format such as JSON, then have a rendering layer map it to document styles. This avoids the uncontrolled results that come from letting the model manipulate layout directly. For spreadsheet calculation, manage formulas and data separately, and require review for formula changes to prevent problems like a wrongly configured pricing formula.

    Permissions and sandboxes must be designed up front: use least privilege for write operations, disable external side effects (sending, publishing, transferring funds) by default, and require explicit enablement with an audit log. Log every tool call uniformly as “input summary - output summary - duration - status” to form a traceable chain.

    5. Evaluation, Security, and Governance

    Evaluate at three levels: capability (accuracy of financial numeric calculations, correctness of code generation), agent (task completion rate, average number of steps, number of rollbacks), and business (manual review effort, delivery cycle time). Each level needs a fixed test set and a regression baseline; run the regression automatically after any model or prompt change, rather than relying on a “feels stronger” judgment.

    On security, focus on three points. First, prompt injection: instructional text inside external documents must be treated as data, not instructions. Second, artifact auditing: model-generated code and formulas need independent review and automated testing. Third, supply chain and compliance: define data sources, retention policies, and access boundaries, and place human gates on high-risk operations.

    Stability governance is equally important. If error rates rise or responses slow down in the early stage after launch, first investigate context bloat, tool timeouts, concurrency quotas, and version rollback records, and use monitoring alerts and log services to locate the bottleneck instead of attributing it directly to the model itself.

    Phase one: pick a single high-value scenario (such as long-document summarization or test case generation), get the “retrieve - generate - verify” loop working end to end, and establish baseline metrics. Phase two: introduce multi-agent division of labor and a task board, moving manual review points forward into the acceptance criteria. Phase three: expand tool integration and the permission system to form an auditable automated pipeline. Phase four: build up a domain knowledge base and evaluation set so that versions are comparable and results are regression-testable.

    Overall, million-token context, multi-agent collaboration, and tool integration are not independent feature points but a mutually constraining engineering system: the context budget determines input quality, task orchestration determines execution stability, and tools plus permissions determine how controllable the results are. Putting all three on the same design canvas is what lets a large language model become genuinely embedded in a professional workflow.