AI Agent Architecture: Principles and a Practical Guide to Building Custom Agents

    This article explains why architecture, rather than model capability alone, determines whether an AI agent is production-ready. It breaks down a five-layer agent architecture—model, orchestration, tools, memory, and governance—and contrasts it with the fragile "prompt plus plugins" approach. Readers will learn five dimensions of custom agent development (role design, tool permissions, memory management, loop control, and evaluation) along with engineering best practices for observability, cost control, security, deployment, and release management, plus common pitfalls and a recommended learning path.

    1. Why Architecture Matters More Than the Model

    When agent projects underperform, teams often blame the model. In practice, post-mortems usually reveal architectural problems instead: tool calls without permission boundaries, unbounded context growth, missing fallbacks for failure paths, and non-reproducible behavior. The industry has converged on a consensus: an agent is a systems engineering problem, and the model is just one replaceable component. What determines whether an agent can reach production is whether the architecture has clear layering, explicit contracts, and observability.

    So the right order to learn agents is: first understand the architectural layers, then understand each layer’s responsibilities and interaction protocols, and only then move on to customization and tuning.

    2. A General Layered Architecture for Agents

    A maintainable agent system can typically be abstracted into five layers:

    1. Model layer: Handles reasoning, planning, and generation. A unified abstraction lets you plug in models of different sizes so you can route by cost and latency.
    2. Orchestration layer: Controls the multi-turn loop, task decomposition, subtask scheduling, and termination decisions—the agent’s “control plane.”
    3. Tool layer: Wraps external capabilities (retrieval, computation, code execution, business APIs) as atomic, schema-defined operations with attached permissions and quotas.
    4. Memory layer: Distinguishes short-term context, working memory, and long-term memory, deciding what to remember, when to recall, and how to evict.
    5. Governance layer: Covers identity and authorization, audit logs, content safety, cost limits, and regression evaluation.

    The value of layering is contractual: layers communicate only through well-defined data structures, so any layer can be replaced without breaking the whole. This is the core criterion for judging whether an agent design is practical—it should let you swap models, add or remove tools, or adjust memory strategy without touching the backbone.

    3. How This Differs from “Prompt Plus Plugins”

    Early approaches stuffed all logic into one long prompt and attached a few plugins. This works for demos, but has three structural flaws:

    • Uncontrollable state: Context only grows, so long sessions inevitably hit truncation and information loss.
    • Non-reproducible behavior: Small prompt tweaks cause global drift, with no versioning or regression control.
    • Indivisible permissions: All tools share one identity, making least privilege impossible.

    A layered architecture replaces implicit conventions with explicit state objects, explicit tool contracts, and explicit policy configuration—turning “alchemy-style tuning” into engineering iteration.

    4. Five Dimensions of Building Custom Agents

    4.1 Role and Instructions: Structured, Not Prose

    Split the role definition into four parts: goal, constraints, output contract, and failure handling. Constraints must be decidable—avoid unverifiable phrases like “be as accurate as possible.”

    1. role:
    2. goal: Answer technical questions using the provided materials and cite evidence
    3. constraints:
    4. - Use only retrieved passages; no external assumptions
    5. - Explicitly state when information is insufficient for citation
    6. output_contract: {type: object, fields: [answer, citations, confidence]}
    7. on_failure: Return a structured error and request additional information

    4.2 Tools and Permissions: Schema First, Least Privilege

    Every tool should declare its name, purpose, input schema, side-effect level, and quota. Read-only tools and tools with side effects should be authorized separately; the latter require explicit confirmation or secondary validation.

    1. def register_tool(name, schema, handler, side_effect=False, quota=None):
    2. TOOLS[name] = {
    3. "schema": schema, "handler": handler,
    4. "side_effect": side_effect, "quota": quota or 60,
    5. }
    6. register_tool(
    7. "search_docs",
    8. {"query": "string", "top_k": "int"},
    9. search_docs_handler,
    10. side_effect=False,
    11. quota=120,
    12. )

    4.3 Memory and Context: Layered Recall and Active Eviction

    Use a “budget” approach for context management: set separate token budgets for system instructions, retrieved passages, conversation history, and tool results. When limits are exceeded, evict by priority and keep compressed summaries of evicted content. Before writing to long-term memory, deduplicate and resolve conflicts; on recall, rank jointly by relevance and recency.

    4.4 Orchestration and Loop Control: Explicit Termination Conditions

    The agent loop must explicitly define a maximum step count, per-step timeout, repeated-action detection, and budget limits to prevent infinite tool calls.

    1. def run(task, max_steps=8, budget=2000):
    2. state = State(task=task, step=0, used=0)
    3. while state.step < max_steps and state.used < budget:
    4. action = plan(state)
    5. if action.type == "final":
    6. return action.payload
    7. if action in state.history[-3:]:
    8. return escalate("Repeated action; escalate to human or switch strategy")
    9. result = dispatch(action, TOOLS) # includes permission and quota checks
    10. state = observe(state, result)
    11. state.step += 1
    12. return escalate("Step or budget limit exceeded")

    4.5 Evaluation and Observability: Turn Quality into Metrics

    Custom capabilities must come with an evaluation set: fixed inputs, expected outputs, and decision rules, covering normal paths, edge cases, and adversarial inputs. In production, log the tool-call chain, latency, token consumption, and failure reason for every decision to build traceable audit data.

    5. Engineering Considerations for Production

    • Observability: Standardize logging and tracing fields so any task can be reconstructed as a readable execution tree.
    • Cost control: Route model sizes by task complexity, cache frequent retrieval results, and enforce hard budgets.
    • Security boundaries: Run tools in isolated environments, apply content safety checks on both inputs and outputs, and audit sensitive operations.
    • Deployment topology: Run stateless orchestration services on container platforms with elastic scaling; decouple long-running tasks through message queues with retries; store large assets in object storage; feed runtime metrics into logging and monitoring services for a closed feedback loop.
    • Release strategy: Version prompts, tool schemas, and policy configs; use staged rollouts with one-click rollback.

    6. Common Pitfalls

    First, over-pursuing autonomy and handing irreversible operations to the agent. Second, overly coarse tool granularity, which confuses model selection and compounds errors. Third, building only offline demos with no regression evaluation. Fourth, writing all business logic into prompts, making the system impossible to split or reuse.

    Step one: get the minimal plan–act–observe loop working. Step two: add permissions, budgets, and termination conditions. Step three: introduce layered memory and retrieval. Step four: build an evaluation set and tracing infrastructure. Step five: split into multiple collaborating agents based on your business scenario. Following this order, you can build a controllable and scalable agent system without depending on any specific product, and use general-purpose cloud capabilities—such as container, storage, messaging, and monitoring services offered by platforms like Baidu AI Cloud—to complete production deployment.