AI Agent Architecture Explained: A Code-Level Breakdown Beyond the Hype
This article breaks down how AI agents actually work, stripping away the hype to show that reliable output comes from software engineering rather than model magic. You will learn the minimal agent loop, a six-layer architecture, context engineering priorities, tool design principles, the four stability switches of termination, retry, idempotency and rollback, and how evaluation turns optimization into experiments. A practical rollout path is included for building controllable automation.
1. Drop the Hype: There Is No Magic in Agents
Many teams start their first agent project expecting that a few prompts will automatically complete a development workflow. After wiring up the tool chain and running automated tests, they usually reach the opposite conclusion: agents are not magical, and their stable output comes almost entirely from surrounding software engineering rather than the model’s own “insight.”
The essence can be summarized in one sentence: an agent is a large language model wrapped in multiple layers of engineering constraints. The only organ with real reasoning ability is the core model. Everything else, including context management, tool protocols, state persistence, permission boundaries, retries and evaluation, exists to keep this “high-IQ but unstable” core working continuously.
A fitting analogy: you hire a new lead who is extremely intelligent and speaks several languages, but lacks common sense, confidently fabricates facts, and may perform high-risk operations. To turn that person into business value, you do not rely on repeated motivational prompts; you provide assistants, an execution team, and strict rules. This is the root cause of many failed projects: treating the agent as a magician, when what it really needs is a “construction organizer” who understands the business.
2. The Minimal Core: A Loop, Not a Single Q&A
With all the packaging removed, the core control flow of an agent can be written as a very short loop. The complexity lies not in the loop itself, but in the engineering facilities around it.
# Illustrative pseudocode: the minimal agent coredef run_agent(goal, tools, model, max_steps=12):state = State(goal=goal, messages=[system_prompt(), user(goal)])for step in range(max_steps):resp = model.generate(state.messages, tools=tools.schema())if resp.tool_calls:for call in resp.tool_calls:result = tools.execute(call) # controlled executionstate.append(tool_result(call.id, result))continueif resp.is_final:return finalize(resp.text, state)state.append(assistant(resp.text))return escalate(state) # step limit exceeded: escalate to a human or a fallback strategy
This code reveals three engineering facts:
- Agents “think” in the present and “see” only the past: at each step the model can only see what is inside the context window, so “what to put into the context” is the first-principles design problem of an agent.
- Action relies on protocols, not hints: tools must be exposed to the model as structured schemas (name, description, parameter constraints); the model emits a structured call intent, and the host program performs the actual execution.
- It must be terminable: a loop without a step limit, budget limit and timeout control is equivalent to a source of failures in production.
3. Layered Architecture: Naming Each “Garment”
A maintainable agent is usually divided into six layers, and layers communicate through explicit contracts, avoiding stuffing all logic into one giant prompt.
- Core reasoning layer: responsible for planning, selection and generation, caring only about “what to do next.”
- Context layer: assembles the prompt, including system constraints, task goals, history summaries, retrieved snippets and tool results.
- Tool and execution layer: standardizes external capabilities (script execution, retrieval, database queries, message notifications, file reads and writes) into callable interfaces, with parameter validation and timeout isolation.
- State and memory layer: stores intermediate artifacts and long-term knowledge so tasks can be interrupted, resumed and audited.
- Governance layer: least-privilege permissions, second confirmation for sensitive operations, audit logs, cost and rate limits.
- Evaluation and observability layer: uses offline evaluation sets and online tracing together to judge whether “changing the prompt actually made things better.”
The most worthwhile engineering investments are not prompt techniques, but layers three, four and six. Vague tool descriptions lead the model to pick the wrong tool; state that is not persisted means one exception forces a restart from scratch; without evaluation, any optimization is only a subjective feeling.
4. Context Engineering: The Real Variable That Decides Success
Context is the agent’s only “field of view.” In practice it is usually assembled in priority order and trimmed by policy when limits are exceeded:
- Non-negotiable constraints (safety rules, output format, forbidden actions);
- The current task goal and acceptance criteria;
- Key intermediate conclusions and confirmed facts;
- Retrieved reference material (with sources and timestamps);
- Recent tool calls and results (large results must be summarized or persisted with a reference passed in);
- General background knowledge (trimmed first).
A rule of thumb: move large artifacts out of the context and keep only references and summaries. For example, test reports, logs and build output should be written to files or object storage, with only the path, status code and key failure lines kept in context. This avoids filling the window with noise and lets later steps look things up by reference, preserving traceability.
5. Tool Calls and Planning: Caging Uncertainty
Tool design follows three principles: single semantics, strongly constrained parameters, parseable results. A counter-example is providing a “do-everything” tool whose parameter is a natural-language instruction; this pushes uncertainty back into the model and loses engineering control.
{"name": "run_unit_tests","description": "Run unit tests for a specified module and return a failure summary","parameters": {"module": "string, required, module path","timeout_seconds": "integer, default 120, maximum 600"}}
For planning, short tasks only need a single “think-call-observe” loop; long tasks should first be decomposed into an explicit step list, then executed step by step with state filled back in. The decomposition result should be reviewable and editable by a human, which is the key step in pulling high-risk automation back into a controllable range.
6. Four Switches for Stability: Termination, Retry, Idempotency, Rollback
- Termination conditions: steps, time, token budget, and repeated-action detection (interrupt when the same tool with the same parameters appears consecutively).
- Retry strategy: apply exponential backoff only to retryable errors (timeouts, rate limiting, network jitter); for parameter errors or insufficient permissions, fail immediately and return a readable reason.
- Idempotent design: write operations carry a business unique key to avoid duplicate submissions from retries; delete and migration operations should be rehearsed first.
- Rollback and compensation: define an inverse operation for every side-effecting action, and compensate in reverse order on failure to return the system to a consistent state.
This comes with governance: least privilege by default, mandatory human confirmation for high-risk actions (deleting data, modifying production configuration, sending messages externally), and a complete record of “who did what with which parameters and when.”
7. Evaluation and Cost: Turning Optimization from Hype into Experiments
An agent project without an evaluation set cannot converge. Prepare at least three kinds of samples: regular tasks, boundary tasks, and adversarial tasks (including attempts to induce privilege escalation and prompt injection). Metrics should look beyond final answer accuracy to tool selection accuracy, average steps, failure recovery rate and cost per task.
On the online side, build unified observability: use a trace identifier to link each inference and tool call, and record prompt version, model version and result differences. With this data you can tell whether a gain came from a model upgrade, a context adjustment or a tool refactor. If elastic inference and batch tasks are involved, a container platform can host execution sandboxes, a message queue can buffer tasks, object storage can hold intermediate artifacts, and logging, monitoring and alerting services can provide observability; such general capabilities have corresponding categories available for selection on platforms such as Baidu AI Cloud.
8. A Checklist of Common Mistakes
- Treating the prompt as the only lever while ignoring tool contracts and state design;
- Letting the model output the final answer directly without validation, lacking a deterministic validation layer;
- Stuffing large logs into the context, raising cost and diluting attention;
- No step or budget limits, causing infinite loops on exceptions;
- Demonstrating only the success path, with no failure recovery or human takeover channel;
- Replacing evaluation with subjective experience, making it impossible to attribute optimization effects.
9. A Practical Rollout Path
Step one, pick a high-frequency scenario with clear boundaries and automatically verifiable results. Step two, implement a deterministic version first (a pure code flow) and confirm the acceptance criteria. Step three, introduce the model only at nodes that need semantic judgment. Step four, add state persistence, permissions and auditing. Step five, build an evaluation set and an observability dashboard, then iterate in small steps.
The core idea of this path is: engineering first, intelligence second. When the loop, tools, state, governance and evaluation are all in place, every improvement in model capability can be absorbed stably; otherwise, even the strongest model is just building on sand. Understanding this is what turns you from “someone who writes prompts” into an engineering lead who can design automation systems.
