Agent Layered Architecture: A Practical Guide to Building Lightweight AI Agents
This guide explains how to design a layered architecture for AI agents that keeps the core minimal while letting capabilities grow through replaceable components. It covers the core design principles, five pluggable slots (model, tool, data, memory, and sandbox), a minimal viable setup, approval and task-planning constraints, common anti-patterns, and a four-stage adoption roadmap. Readers will learn how to keep an agent framework maintainable, safe, and controllable as complexity increases.
1. Background: Why Agent Frameworks Get Heavy Fast
In real projects, the complexity of an agent system often grows faster than the complexity of the business itself. It starts as a model plus a few prompts. Then, to make the agent actually do work, teams keep adding retrieval, database access, file operations, code execution, and long-term memory. A few months later, the codebase is full of conditional branches: a tool that only works with a specific model, memory-writing logic tightly coupled to one retrieval implementation, a high-risk operation temporarily enabled to meet a deadline. The end result is that the framework itself becomes the biggest maintenance burden.
The industry is converging on a shared judgment: an agent’s capabilities should come from replaceable components, while the orchestration skeleton should stay minimal. An agent can be abstracted as a formula:
Agent = Model + Harness
The Model provides reasoning and generation. The Harness (the carrying and constraining skeleton) is responsible for applying the model’s capabilities to real tasks safely and in an orderly way. The core topic of this article is how to design this skeleton so it is thin and stable enough while still allowing capabilities to grow freely.
2. Design Principles: Keep the Core as Thin as Possible
A healthy agent core should have its responsibilities strictly limited to three things, with everything else pushed down into plugins.
- Orchestrate models and tools: Select a model based on the current task state, assemble context, parse tool calls, and write results back into the conversation and plan. The core does not preset “which tools exist”; it only maintains a capability registry.
- Request approval before high-risk operations: Set human confirmation points for irreversible or costly operations (deleting data, sending externally, bulk writes, executing arbitrary code). Approval is a core responsibility because it must sit above any plugin.
- Maintain a task plan: Break the goal into trackable steps and record the status, dependencies, and outputs of each step. The plan is the single source of truth for where the agent currently stands.
Beyond the core, five categories of capability are fully pluggable:
| Slot | Problem it solves | Typical failure mode (without this slot) |
|---|---|---|
| Model slot | Reasoning, generation, multimodal understanding | A single model lacks capability and cannot route by task |
| Tool slot | Interacting with the external world | The model can only answer from parametric memory, with stale facts |
| Data slot | Obtaining authoritative structured data | Piecing numbers together with general search, with inconsistent definitions |
| Memory slot | Maintaining continuity across sessions | Every conversation starts from zero, preferences are reconfirmed repeatedly |
| Sandbox slot | Safely executing code and file operations | Either afraid to execute, or unable to clean up afterward |
This layering brings direct benefits: replacing any component does not require changing the core; new capabilities can roll out gradually as plugins; permissions and auditing have a single collection point.
3. Startup and Minimal Viable Form
A usable agent skeleton should have a very low startup cost. The ideal state is: install and use, listen on the local loopback address by default, and open a local port in the browser to enter the interactive interface. Example (the command is only illustrative of the form, not a specific product):
# Install and start the local agent consolenpx <agent-harness-cli> web# Default access at http://127.0.0.1:<port>/
Binding to the loopback address by default is an important secure default: an agent has file read/write and command execution capabilities, so exposing it to the public network by default is equivalent to opening host control to any visitor. If remote access is truly needed, it should at least layer on transport encryption, authentication, and source restrictions, and keep the approval switch on.
The minimal viable form should enable only three slots: one general-purpose chat model, one file tool constrained by an allowlist, and one in-memory task plan. After getting the loop “receive goal → generate plan → execute step by step → stop at high-risk points and wait for confirmation” working end to end, gradually add retrieval, data, and persistent memory.
4. Capability Layer Practice: How to Wire the Five Slots
4.1 Model Slot: Route by Task Instead of Chasing One Do-It-All Model
Omni-modal capabilities (text generation, image generation, video generation, vectorization) are usually spread across different models. In practice, a more effective approach is not to find the single “strongest model” but to build a routing strategy: use a long-window model for long-context summarization, a model with stable instruction following for structured extraction and tool calls, a dedicated embedding model for vectorization, and multimodal models for vision and video tasks. Connect them at the configuration layer as “custom provider + endpoint address + key”, and read keys only from environment variables or a key management service, never writing them into the repository or config files.
4.2 Tool Slot: Let the Agent Verify Facts Online
Parametric memory in models has a knowledge cutoff, while tasks are often about the present. A web search plugin should at least support: authoritative source filtering, time-range filtering, automatic query rewriting, and multi-turn follow-up. Three engineering points to note: first, annotate search results with source and timestamp so the model can judge credibility; second, truncate and deduplicate search results to avoid filling the context with noise; third, set quotas on search frequency to prevent loop calls from amplifying cost.
4.3 Data Slot: Vertical Structured Data Cannot Be Assembled from General Search
Content like public company financial reports, business registration and judicial risk information, academic literature, product configuration parameters, and macro indicators can almost never get trustworthy answers from general search. A reasonable design is a routing layer: parse the query intent, determine the vertical domain, then call the corresponding data source, and finally return structured fields rather than paragraph text.
query: "ROE change for an industry over the past three years"route: financial-registry -> structured metric series (with reporting period, definition)query: "chassis parameters for a certain device model"route: spec-registry -> structured configuration items (with version, source)
The key constraint is consistent definitions and traceability: the same metric may be defined differently across sources, so returned results must carry a definition note and data time, otherwise the model will treat the difference as a factual contradiction.
4.4 Memory Slot: Design Memory Like a File System
Cross-session continuity is the dividing line between an agent going from “toy” to “tool”. A relatively mature industry practice is to unify memory, resources, and skills as files, building a “virtual file system + semantic retrieval” context database that loads in layers and recalls on demand. It can be divided into four layers:
- Working memory: current session context, small capacity and short lifecycle;
- Short-term memory: recent task summaries and unfinished items, archived when the task closes;
- Long-term memory: user preferences, domain conventions, historical conclusions, with an importance check before writing;
- Skill memory: reusable operation routines and scripts, stored as callable units.
The write strategy affects experience more than the retrieval strategy. It is recommended to set a clear threshold: only information that is confirmed by the user, verified multiple times, or affects later decisions is promoted to long-term memory; the rest stays in the short-term layer and expires with the task. At the same time, three actions—view, modify, and forget—must be provided so users have control over memory, which is also a basic compliance requirement.
4.5 Sandbox Slot: Deny by Default, Allow on Demand
Code execution and file operations are capability amplifiers and also risk entry points. Sandbox design should follow deny-by-default: limit file access to an allowlisted root directory, open network egress on demand, set clear execution time and memory limits, and clean up temporary files after the session ends. All write operations and external calls go into a unified audit log recording the caller, parameter summary, result, and approval status for later traceability.
5. Approval and Planning: Two Hard Constraints of the Core
Approval should not be a disruptive popup but a tiered policy. Operations can be divided into three tiers by reversibility and impact: reversible and locally scoped (reading files, retrieval) is allowed automatically; reversible but with larger impact (bulk writes, deployment previews) is logged and sampled for review; irreversible or involving external parties and funds (deletion, sending, production changes) requires mandatory human confirmation. An approval request must carry enough context: the action to be executed, the affected targets, the estimated cost, and the rollback method.
The task plan solves the “long-task drift” problem. The plan should be an explicit data structure, not hidden in the conversation history:
{"goal": "Generate a quarterly business analysis report","steps": [{"id": 1, "action": "collect_metrics", "status": "done", "deps": []},{"id": 2, "action": "query_vertical_data", "status": "running", "deps": [1]},{"id": 3, "action": "render_report", "status": "pending", "deps": [2], "needs_approval": true}]}
The output of each step is persisted and can be referenced by later steps; on failure, it supports replaying from the most recent successful node instead of starting the whole thing over.
6. Common Anti-Patterns and Governance Advice
- Core bloat: Writing business judgment into the orchestration layer. The fix is to ask, every time you add a branch, “does it belong to some slot?”
- Memory without eviction: Long-term memory only grows and never shrinks, and retrieval is polluted by outdated preferences. The fix is to set expiration and conflict-resolution rules.
- Approval in name only: Allowing everything by default for efficiency. The fix is to make approval policy configurable and include it in audit metrics.
- No context budget: Stuffing all search results into the prompt. The fix is to set a context budget and priorities.
- Lack of evaluation: Judging whether a change is good by feel. The fix is to build a fixed task set and track task completion rate, number of human interventions, cost per task, and rollback rate.
7. Adoption Roadmap and Summary
A four-stage approach is recommended: the first stage builds a thin core and gets the plan and approval loop working; the second stage adds retrieval and vertical data to solve factuality and definition issues; the third stage integrates layered memory and a sandbox to form cross-session productivity; the fourth stage establishes routing, quotas, and an evaluation system to enter continuous optimization.
In related practice at Baidu AI Cloud, this kind of capability is usually carried by combinations of general cloud product categories: model services provide reasoning and vectorization, object storage holds task outputs, message queues decouple long tasks, container platforms run sandboxes, and log services with monitoring and alerting support auditing and cost observability. The core conclusion is a single sentence: make the skeleton thin, make the components thick, and consolidate permissions—only then can an agent both do work and stay controllable.
