AI Agent in Production: A Practical Guide to Million-Token Contexts
This guide explains how to build production-ready AI agents with long-context, open-weight models. It covers five engineering essentials—context budgeting, structured tool protocols, layered memory with checkpoint recovery, execution isolation, and observability with cost governance—and shows how to avoid common failure modes that make impressive demos collapse in production.
1. From Chatting to Getting Work Done: The Real Barrier to AI Agents
Open-weight models hand capability boundaries back to developers, and what follows is not a single prompt but a complete engineering system. Long context is only the entry ticket. What really determines whether an agent can handle the dirty, repetitive work are five things: task decomposition quality, context budgeting, tool protocols, execution isolation, and result validation. Miss any one of them, and the demo looks impressive while production breaks.
The common failure modes are remarkably consistent: the context is stuffed with logs and raw web pages until key instructions are drowned out; tool parameters are left to the model’s improvisation with no schema validation; failed tasks have no checkpoints and must be rerun from scratch; and costs grow linearly with each turn with no one able to attribute them. The methods below address these pain points one by one.
2. Context Is a Scarce Resource: Design It as a Budget
Manage the context window like memory, not like a trash can. Allocate quotas by purpose—for example, system instructions and output specifications take 5%, task and state take 20%, retrieved evidence takes 35%, tool results take 25%, and 15% is reserved as headroom for reasoning and safety. When the limit is exceeded, degrade in this order: compress evidence first, then fold history, and only discard raw text as a last resort.
Illustrative budgeting and trimming logic:
BUDGET = {"instruction": 0.05, "task": 0.20, "evidence": 0.35,"tool": 0.25, "reserve": 0.15}def fit(sections, limit):# Keep instructions and task; compress evidence and tool output firstfor key in ("tool", "evidence"):while over_budget(sections, limit) and sections[key]:sections[key] = compress(sections[key])return sections
On the evidence side, retrieve first and summarize second, storing entries with cited snippets. On the tool side, return only structured fields and status codes, keeping entire HTML pages out of the model’s view.
3. Closing the Tool-Call Loop: Structure First
Tools are the agent’s hands and feet, and the protocol matters more than the model. Define a clear schema, required fields, timeout, and idempotency semantics for every tool. After the model produces parameters, they must pass both schema validation and business validation. For write operations, introduce an idempotency key to prevent retries from creating duplicate orders or duplicate submissions.
{"name": "submit_ticket","schema": {"type": "object","required": ["title", "owner"],"properties": {"title": {"type": "string"},"owner": {"type": "string"}}},"timeout_ms": 8000,"idempotent": true}
4. Layered Memory and Checkpoint Recovery
Split memory into three layers: in-session short-term memory holds the current goal and completed steps; task-level mid-term memory records progress as a structured state machine; and long-term memory settles into searchable knowledge entries. Once task state is externalized, a crashed process can resume from a checkpoint instead of starting from zero.
state:goal: "Organize quarterly data and generate a report"steps: [{id: 1, tool: "fetch", status: done},{id: 2, tool: "transform", status: running}]artifacts: ["report_draft"]
5. Execution Isolation and Least Privilege
Because an agent can operate real systems, you must assume it will make mistakes. Run code and commands in containers or sandboxes, mount data read-only, and route outbound traffic through an allowlist. Issue credentials at task granularity with short lifetimes, and never write long-term keys into prompts or logs. For high-risk actions, use a two-stage flow: generate a plan, get human confirmation, then execute.
6. Observability, Evaluation, and Cost Governance
Before launch, build an offline evaluation set covering the happy path, boundary inputs, and adversarial prompts, with metrics including task success rate, tool-call accuracy, average number of turns, and cost per task. In production, rely on logging services, monitoring alerts, and distributed tracing to pinpoint exactly which step went off track. General-purpose capabilities from Baidu AI Cloud—object storage, container platforms, message queues, and log monitoring—can host artifacts, isolate execution, decouple processes asynchronously, and provide end-to-end observability, making it possible to attribute costs across three dimensions: task, tenant, and tool.
7. Conclusion
Million-token context solves “seeing more”; the engineering loop solves “getting it done.” Make the five things—budget, protocol, state, isolation, and evaluation—solid, and only then does an agent live up to the promise of doing the dirty, repetitive work for you.
