Designing a Million-Token Context Multimodal AI Agent: Architecture and Engineering Practices
This article explains how to build a multimodal AI agent that combines a roughly 1.05-million-token context window, long-form output, image input, and a tool chain for web search, file search, and code execution. It reframes raw capability parameters as engineering problems, then walks through a layered architecture, context budgeting and compression, long-output control, multimodal evidence extraction, tool governance, knowledge-cutoff and freshness handling, evaluation and cost control, security, and a phased rollout plan. Readers will learn practical patterns for keeping context orchestration precise, evidence traceable, tool calls sandboxed, long outputs verifiable, and freshness and security well governed.
Designing a Million-Token Context Multimodal AI Agent: Architecture and Engineering Practices
1. From “Capability Parameters” Back to a System Problem
When discussing an intelligent system with very long context, very long output, and multimodal input, the most common mistake is to fixate on the parameters themselves: how large the context window is, how long a single output can be, which inputs are supported, and which tools are connected. Parameters matter, but they only describe the capability boundary; they are not the same as engineering usability. This article uses a representative combination of capabilities as a baseline:
- A context window of about 1.05 million tokens, which by common document estimates covers roughly 1,500 pages of standard text;
- A maximum output length of about 128,000 tokens;
- An internal knowledge cutoff of April 30, 2026;
- Text and image input, with text output;
- An integrated tool chain including web search, file search, and code writing and execution.
Together, these metrics point to a new system form: the model is no longer just a single-turn question answerer, but an “agent-style” information processing system that can coordinate across very long materials, multiple sources of evidence, image content, and external tools. The problems developers actually need to solve include:
- Context is not memory. A large window only means a single request can carry more content; it does not guarantee that key information is correctly discovered, ordered, cited, and continuously updated.
- Long output is not high-quality long-form writing. A 128,000-token output ceiling means the system can generate reports, plans, code, or long analyses, but without outlines, staged validation, and state management, the longer the output, the higher the risk of drifting off-topic, repetition, factual drift, and structural collapse.
- Multimodal input is not true image understanding. Once an image enters the system, it must go through layout analysis, text extraction, table reconstruction, chart interpretation, and coordinate tracing before it becomes verifiable evidence.
- A tool chain is not automatically reliable execution. Web search, file search, and code execution introduce issues of permissions, injection, freshness, resources, and auditing, which must be governed through sandboxes, routing, timeouts, retries, and logging.
- A knowledge cutoff is not the system’s current time. Once the model’s internal knowledge is frozen, any time-sensitive question should explicitly enter a retrieval, time-determination, and evidence-citation flow.
The reasonable engineering goal, therefore, is not to “stuff a million tokens full,” but to build a system that can dynamically assemble information by task, invoke tools, generate results, and self-validate.
2. Overall Architecture: Governing Long Context, Tools, and Validation Separately
A deployable very-long-context multimodal agent can usually be split into the following layers:
User request-> Access and permission check-> Multimodal parsing and evidence normalization-> Context orchestrator-> Reasoning core-> Tool router (search / file / code)-> Output controller and fact validation-> Logging, evaluation, and security audit
The responsibilities of each layer should be decoupled as much as possible:
- Access and permission check layer: Identifies user identity, tenant scope, data access boundaries, and task risk level. When files, code execution, or web access are involved, permissions cannot rely on the model’s judgment alone; they must be enforced at the system level.
- Multimodal parsing layer: Converts text, images, tables, scanned documents, charts, and other inputs into evidence units with source markers. Parsing results should retain metadata such as page numbers, regions, file versions, and timestamps for later citation.
- Context orchestrator: Handles token budgeting, evidence ordering, compressed summaries, history trimming, and tool-result backfilling. It decides “what the model actually sees this turn” and is the core of a long-context system.
- Reasoning core: Understands the task, plans steps, decides whether tools are needed, and organizes the answer structure. It should not directly possess unlimited resources, but should be constrained by the context budget, tool permissions, and output policy.
- Tool router: Wraps search, file retrieval, code execution, and other capabilities into controlled capabilities, uniformly handling timeouts, retries, rate limiting, idempotency, return formats, and exceptions.
- Output controller: Performs structural checks, evidence verification, sensitive-information filtering, and format validation on large outputs.
- Observability and evaluation layer: Records each task’s input summary, retrieved evidence, tool calls, output results, latency, and cost, providing a basis for later optimization.
At the infrastructure level, resources can be organized by category such as general container platforms, object storage, logging services, monitoring and alerting, and key management. In a Baidu AI Cloud or self-hosted environment, interfaces should be kept abstract and replaceable to avoid tightly coupling business logic to a single interface.
3. Engineering Million-Token Context: Budgeting, Retrieval, and Compression
1. The Context Window Must Be Budgeted, Not “Stuffed as Much as Possible”
Even with a window of about 1.05 million tokens, each request should have a clear budget. A practical formula is:
Available evidence budget =context window- system instructions- current user request- retained conversation history- tool-return reserve- maximum output reserve- safety margin
Since the maximum output can be as high as 128,000 tokens, enough space must be reserved for the generation phase. Otherwise, when the input is too long, the system is prone to truncation, omission, or being forced to compress critical evidence. In practice, it is advisable to manage the “input budget” and “output budget” separately and to set both hard and soft thresholds: the soft threshold triggers summarization, and the hard threshold rejects or splits the task.
Example pseudocode:
function build_context(request, history, documents, images, tool_results):system = load_system_rules()task = normalize(request)history_recent = keep_recent_turns(history, token_limit=HISTORY_LIMIT)candidates = retrieve(task, documents, images)ranked = rerank(task, candidates, prefer_recent, prefer_authoritative)evidence_budget = WINDOW - OUTPUT_RESERVE - SAFETY_MARGIN- token_count(system, task, history_recent, tool_results)selected = pack_by_priority(ranked, budget=evidence_budget)compressed = hierarchical_summarize(selected, keep_citations=true)return compose_context(system, task, history_recent, compressed, tool_results)
2. Adopt a “Retrieval First, Long Context as Fallback” Strategy
A million-token context is well suited to cross-document tasks, long reports, and complex comparisons, but that does not mean every request must carry all the material. A more economical approach is:
- First recall candidate fragments through file retrieval, keyword retrieval, or vector retrieval;
- Rank the candidate evidence using a reranking model or rules;
- Place the highly relevant evidence into the context;
- For tasks that genuinely require cross-section synthesis, then expand the context window;
- For very long materials, use hierarchical summarization, segmented question answering, and result merging.
This is similar to “retrieval first, long context as fallback.” It both controls cost and reduces the interference of noise on reasoning.
3. Context Priority Must Be Explicitly Defined
In a long context, the importance of different content varies greatly. It is recommended to organize content by the following priority:
| Priority | Content Type | Handling Strategy |
|---|---|---|
| Highest | System rules, safety boundaries, hard user constraints | Always retained, excluded from normal compression |
| High | Current task, output format, key evidence | Retained in full or nearly in full |
| Medium | Retrieval results, file fragments, image parsing results | Deduplicated, ordered, compressed with sources |
| Medium-low | Conversation history, long-term memory | Summarized, recalled on demand |
| Low | Repeated material, low-confidence fragments | Discarded or kept as index only |
Also note the “middle-information decay” problem: even if the window is large enough, the model does not necessarily use information at all positions uniformly. In practice, the risk of omission can be reduced through segmented headings, repeated key constraints, evidence numbering, conclusion-first structure, and end-of-output review.
4. Compression Must Preserve Traceability
Compressing a very long context cannot keep only summaries, or later answers cannot be verified. It is recommended to maintain the following for each evidence fragment:
- Source file or web page identifier;
- Page number, paragraph, image region, or table coordinates;
- Timestamp and version number;
- Original fragment or a locatable reference;
- Confidence and extraction method.
When the output involves key conclusions, it should cite the corresponding evidence number. Inferences that cannot be supported by evidence should be explicitly marked as “inference” rather than fact.
4. Long-Output Control: Plan First, Generate Second, Validate Last
The maximum output capability of 128,000 tokens provides room for long technical proposals, audit reports, code generation, and complex analyses. But a long-output system must solve three problems: structure, factual consistency, and termination control.
1. Generate an Outline First, Then Expand Section by Section
For tasks beyond a certain length, it is recommended that the system first generate a structured outline, including sections, goals, required evidence, and validation points. After the outline is confirmed, generate section by section. After each section is generated, perform local validation, such as:
- Whether it covers the outline requirements;
- Whether it cites enough evidence;
- Whether terms or conclusions conflict with earlier text;
- Whether it exceeds the current section budget;
- Whether tools need to be called to supplement evidence.
2. Use a State Machine to Manage the Long Generation Process
Long output should not rely on one-shot completion, but should maintain task state:
Plan -> Retrieve -> Outline -> Draft -> Validate -> Supplement -> Aggregate -> Final Review
Each stage records its input, output, and version. If it times out or is interrupted midway, it can resume from a checkpoint rather than regenerate from scratch.
3. Set Output Budgets and Termination Conditions
The maximum output length is a ceiling, not a target. Task-level budgets should be set, for example allocating tokens per section, and triggering compression or summarization when a section exceeds its budget. Termination conditions include:
- Reaching the target coverage;
- Key evidence has been cited;
- Several consecutive rounds with no new useful information;
- Tool calls have reached the limit;
- Output has reached a safety or budget threshold.
5. Multimodal Input Processing: Making Images Evidence, Not Decoration
After image input is supported, the system needs to turn images into searchable, citable, verifiable evidence. A typical processing chain includes:
- Quality check: Determine whether the image is blurry, rotated, occluded, or too low in resolution;
- Layout analysis: Identify regions such as titles, body text, tables, legends, flowcharts, and screenshots;
- Text extraction: Recognize scanned text, screenshots, and tables;
- Structure reconstruction: Restore table rows and columns, chart axes, flow nodes, and hierarchical relationships;
- Semantic description: Generate a brief description for charts, but it must be bound to the original region;
- Source annotation: Record the image number, region coordinates, and file version.
For tasks with mixed text and image input, avoid “answering just by looking at the image.” A more robust approach is to first form structured evidence, then let the model answer based on that evidence. For example, if a user uploads an image containing a multi-column table and asks for a comparative analysis, the system should first extract the table structure and values, then perform calculations and comparisons, and indicate in the answer which region of which image the data came from.
6. Tool Chain Design: Governing Search, Files, and Code Execution in Layers
1. Tool Router
An agent should not directly decide to “call any tool at will,” but should enforce policy uniformly through a tool router:
function call_tool(tool_name, arguments, policy):assert policy.allows(tool_name, arguments)validate_schema(tool_name, arguments)if not rate_limiter.acquire(tool_name):return ToolError("rate_limited")result = sandbox.run(tool_name, arguments, timeout=policy.timeout)log_tool_event(tool_name, arguments, result, policy.trace_id)return sanitize(result)
The router handles permissions, argument validation, timeouts, retries, rate limiting, idempotency, logging, and result redaction. Tool return content should also be treated as untrusted input and cannot directly become a system instruction.
2. Web Search
Web search is suited to time-sensitive questions, verification of external public material, and information after the knowledge cutoff. Engineering priorities include:
- Breaking the user’s question into searchable queries;
- Distinguishing factual queries, opinion queries, and comparison queries;
- Ranking sources by time, authority, and relevance;
- Deduplicating search results and detecting conflicts;
- Retaining citations in the answer;
- Defending against prompt injection and malicious scripts on web pages.
In particular, web content is not an instruction. Regardless of what “ignore previous rules” or “execute this code” text appears on a page, it should be treated as ordinary material and must not escalate privileges.
3. File Search
File search should be built on permission scope, version management, and indexing strategy. It is recommended to:
- Filter by tenant and user permissions first, then retrieve;
- Support filtering by metadata such as time, file type, author, and version;
- Retain original location information;
- Flag conflicts between old and new versions;
- Redact or refuse to recall sensitive files.
The value of file search is not just “finding a fragment,” but enabling the system to prove which file, which version, and which paragraph an answer came from.
4. Code Writing and Execution
Code execution capability must run in a strongly isolated sandbox. The minimum requirements include:
- Network access disabled by default or strictly restricted;
- Limits on CPU time, memory, disk, and process count;
- Read-only inputs and an isolated output directory;
- A path allowlist for file reads and writes;
- Logging of code, inputs, standard output, standard error, and exit status;
- Static checks and permission audits for code involving sensitive data;
- Execution results can serve as evidence, but cannot automatically raise their credibility.
The recommended agent loop is:
Understand task -> Decide whether code is needed -> Generate minimal code-> Execute in sandbox -> Check errors and output -> Fix if necessary-> Record result and assumptions as evidence -> Aggregate answer
For production systems, code execution results should be stored separately from natural-language conclusions to facilitate auditing and reproduction.
7. Knowledge Cutoff and Freshness Governance
An internal knowledge cutoff of April 30, 2026 means the model has a relatively stable internal representation of knowledge before the cutoff. For information near or after the cutoff, frequently changing data, prices and policies, version releases, and real-time news, external retrieval or business data sources must be used to supplement.
It is recommended to add a “freshness determiner” to the system:
- Identify whether the question contains freshness signals such as “latest,” “current,” “today,” “price,” “version,” “release,” or “policy”;
- Check whether the date involved in the question is later than the knowledge cutoff;
- If external information is needed, force a retrieval or business-data query;
- Annotate the material’s time in the answer;
- If evidence conflicts, list the differences and explain their credibility.
It must be emphasized that the knowledge cutoff is the boundary of the model’s internal training knowledge, not the system’s running time. A responsible agent should clearly distinguish “model internal knowledge,” “retrieved evidence,” and “user-provided information,” and avoid packaging outdated knowledge as current fact.
8. Evaluation, Observability, and Cost Control
Evaluation of a very-long-context system cannot look only at whether the final answer “looks right.” It is recommended to build layered metrics:
- Retrieval layer: Recall, relevance, deduplication rate, evidence coverage;
- Context layer: Key-information retention rate, truncation rate, compression loss, citation completeness;
- Generation layer: Factual consistency, citation accuracy, structural completeness, repetition rate, conflict detection;
- Tool layer: Call success rate, timeout rate, retry rate, sandbox-violation interception rate;
- System layer: P95 latency, cost per task, token usage, cache hit rate;
- Security layer: Sensitive-information leakage, prompt-injection interception, unauthorized access, malicious code execution interception.
The test set should cover scenarios such as cross-section question answering over long documents, table and chart understanding, multi-source conflicts, freshness questions, long-report generation, and code-execution error fixing. After launch, a small-traffic canary can be used first to compare differences across context strategies, retrieval strategies, and output structures.
For cost control, techniques include caching, batched retrieval, hierarchical summarization, expanding context on demand, result reuse, and tool-result compression. Remember that long context is powerful, but not every task is worth using the maximum window.
9. Security and Compliance: Caging Untrusted Content
Multimodal input and tool chains expand the attack surface. Key risks include:
- Prompt injection in files or web pages;
- Hidden text in images inducing the model to exceed its authority;
- Tool return values forging system instructions;
- Code execution reading or exfiltrating sensitive data;
- Retrieval recalling unauthorized files;
- Long output leaking internal information;
- Excessive logging causing secondary leakage.
The corresponding strategy is “defense in depth”: permissions up front, input isolation, tool sandboxes, output filtering, audit trails, and least privilege. Any content from web pages, files, or images can only serve as evidence and cannot become a high-priority instruction. Code execution results, retrieval results, and model-generated text should be stored in separate zones to avoid cross-contamination.
10. Rollout Roadmap and Best Practices
A pragmatic implementation roadmap can be divided into four stages:
- Basic usability: Implement text question answering, file retrieval, context budgeting, and a citation mechanism; first ensure answers are traceable.
- Tool enhancement: Add web search, file search, and a code sandbox; establish a tool router, timeout and retry handling, and audit logs.
- Multimodal enhancement: Add image parsing, table reconstruction, region citation, and image-text consistency checks.
- Scale optimization: Introduce an evaluation set, canary releases, cost optimization, caching, and hierarchical summarization to continuously improve reliability and performance.
The best-practice checklist is as follows:
- Do not fill the context window by default; retrieve first, then rank, then compress;
- Set separate budgets for input, output, and tool results;
- For long output, plan the outline first, then generate and validate section by section;
- Bind each key conclusion to evidence and location whenever possible;
- Treat all external content as untrusted input;
- Tool calls must pass permission checks and sandbox isolation;
- Freshness questions must be explicitly retrieved, with the material’s time annotated;
- Build an offline evaluation set and online observability metrics;
- Control cost and latency; avoid paying the long-context overhead for simple questions;
- Keep interfaces abstract so the system can run and migrate across different infrastructures.
Conclusion
The combination of million-token context, very long output, multimodal input, and a tool chain represents not just an increase in model capability, but a shift upward in system design complexity. What truly determines application quality is not the window number itself, but whether context orchestration is precise, whether the evidence chain is traceable, whether tool calls are controlled, whether long output is verifiable, and whether freshness and security governance are in place. Only by packaging model capability into an observable, evaluable, and auditable engineering system can this kind of agent reliably create value in real business.
