AI Agent Architecture and Context Management: A Practical Guide

    This article presents a vendor-neutral framework for building AI agents, centered on a four-part loop of planning, memory, tool use, and reflection. It then examines three engineering priorities in detail: context management techniques such as summarization, layered retrieval, externalized state, and multi-agent isolation; data flow design for observability and replay; and technology selection driven by task constraints rather than hype. Common failure modes and their countermeasures are included, along with pseudocode and a sample context budget to help readers build stable, extensible, and auditable agent systems.

    1. Introduction: From Answering to Acting

    An AI agent is not a new model category. It is an engineering paradigm that places a large language model inside a goal–action–feedback loop. Since agents first emerged, mainstream implementations have differed in how they manage context, structure data flows, and make technology choices. This article abstracts and restructures those differences: it first defines a vendor-neutral framework, then expands on three engineering priorities—context, data flow, and selection—and closes with a layered architecture and code example that can be put into practice.

    A workable definition: an agent is a system that uses a model as its decision-making core, can decompose goals, maintain state, call tools, and verify results, and continuously adjusts its actions based on feedback from the environment. What fundamentally separates it from a single question-and-answer exchange is that it is stateful and can act on feedback.

    2. Core Principles: A Four-Part Loop

    2.1 Planning

    Planning breaks a high-level goal into executable steps. Common approaches include one-shot decomposition, step-by-step ReAct-style alternation between thought, action, and observation, and hybrid methods that build a task graph first and then schedule locally. The engineering recommendation is to produce an explicit plan object containing steps, dependencies, acceptance criteria, and rollback strategies. This avoids leaving the plan only in natural language, where it cannot be validated.

    2.2 Memory

    Memory falls into three categories: working memory (the current context window), short-term memory (process state for the current task), and long-term memory (cross-session preferences, domain knowledge, and historical conclusions). Long-term memory is usually stored in vector retrieval systems, structured databases, or document collections in object storage, and relevant content is injected into the context on demand through retrieval augmentation.

    2.3 Tool Use

    Tools are the agent’s hands and feet for reaching the real world: retrieval, computation, database queries, code execution, and external API calls. The key is not whether a tool can be called, but whether it can be governed. This requires schema-based parameter definitions, timeouts and retries, idempotent design, permission isolation, and auditing.

    2.4 Feedback and Reflection

    Execution results must return to the decision loop. Feedback can be structured execution status, error codes, or test pass rates, or it can be model self-assessment. Mature implementations make failure-cause classification explicit—for example, parameter errors, insufficient permissions, missing information, or environment failures—and map each category to a different repair strategy.

    Illustrative pseudocode:

    1. state = init_state(goal)
    2. plan = planner.make_plan(goal, context=state.working_memory)
    3. for step in plan.steps:
    4. obs = executor.run(step, tools=registry, policy=guardrail)
    5. state.update(step, obs)
    6. if obs.needs_replan:
    7. plan = planner.replan(goal, state, reason=obs.failure_type)
    8. final = verifier.check(goal, state)

    3. Context Management: The First Problem of Agent Stability

    Context is the agent’s desk: too small and nothing fits, too large and attention is diluted. Mainstream practices fall into four categories.

    1. Compression and summarization: produce rolling summaries of completed steps, keeping conclusions, constraints, and open items while discarding verbose intermediate output. Summaries should be structured—for example, known facts, tools used, lessons from failures, and to-dos.

    2. Layered retrieval injection: do not stuff all knowledge in at once. Assemble the context in the order of system constraints, task description, retrieved snippets, historical summary, and current observation, with a budget cap for each segment.

    3. Externalized structured state: keep long state in external storage and retain only pointers and summaries in the context. This both breaks the window limit and makes auditing and replay easier.

    4. Isolation and multi-agent division of labor: give different subtasks independent contexts and exchange only conclusions through explicit message contracts. This significantly reduces cross-contamination.

    A practical budget allocation example (illustrative):

    1. Total budget: 32k tokens
    2. System and safety constraints: 1k
    3. Task and acceptance criteria: 1k
    4. Long-term memory retrieval: 6k
    5. Historical rolling summary: 4k
    6. Current observation and tool results: 16k
    7. Reserved for output: 4k

    4. Data Flow Design: Making the Process Observable and Replayable

    An agent’s data flow contains at least five paths: input and intent, planning and decisions, tool calls and results, state changes, and final output and evaluation. Engineering recommendations:

    • Eventify the full chain: record every step as an event (timestamp, input summary, output summary, duration, error type) so it is easy to pinpoint exactly which step went off track.
    • Replayability: events together with external state form snapshots that support replay from any node, which is critical for post-mortems on production issues.
    • Quality evaluation: introduce metrics such as task success rate, step redundancy, tool error rate, and average number of steps to form a closed optimization loop.
    • Security and compliance: redact sensitive information before it enters logs, apply least privilege to tool permissions, and require human confirmation for high-risk actions.

    When deploying in the cloud, these needs can be carried by general product categories: message queues for event buffering and decoupling, object storage for snapshots and datasets, container platforms for execution sandboxes and elastic scaling, logging and monitoring/alerting services for observability, and relational or vector databases for state and retrieval. Baidu AI Cloud offers corresponding capabilities in these general categories, and they can be combined freely according to the architecture above.

    5. Technology Selection: By Constraints, Not by Hype

    Selection should return to four constraints: task determinism, latency budget, cost ceiling, and compliance requirements.

    • High determinism, fixed steps: prioritize rules and workflow orchestration, with the model making only local judgments.
    • Strong exploration, uncertain paths: require stronger planning and reflection, and accept a higher number of steps and costs.
    • Latency-sensitive: shorten the context, call tools in parallel, and cache retrieval results.
    • Strict compliance: prioritize private deployment and auditing capabilities, and use a whitelist for tool calls.

    At the model layer, a multi-tier approach is recommended: strong models handle planning and difficult decisions, while lightweight models handle summarization, classification, and formatting, with routing to reduce costs. At the tool layer, insist on schema-first design and version management to avoid unpredictable agent behavior caused by interface drift.

    6. Common Failure Modes and Countermeasures

    • Goal drift: force the original goal and acceptance criteria to be written back every round.
    • Context contamination: isolate subtasks and keep only conclusions in summaries.
    • Tool abuse: set step limits, detect repeated calls, and add a cost circuit breaker.
    • Hallucinated completion: introduce verifiers and executable checks (tests, queries, reconciliation), and fall back to replanning if they fail.
    • Lack of observability: without events there is no optimization, so logging and tracing must be designed in from the start.

    7. Conclusion

    The principles behind AI agents are not mysterious: a model serves as the decision-making core, and planning, memory, tools, and feedback form a loop. The engineering difficulty concentrates on context budget management and data flow observability, and technology selection should follow task constraints and compliance requirements. Get these three things solid, then combine general cloud categories—compute, storage, messaging, databases, logging, and monitoring—to build a stable, extensible, and auditable agent system.