AI Agent Layered Architecture: A Practical Guide to a Thin Core with Pluggable Components
This article explains why all-in-one agent frameworks become hard to maintain and how to restructure an agent system into a thin core plus pluggable components. It defines the core responsibilities of scheduling, approval, and plan maintenance, then details the contracts for five component types: model, tool, memory, sandbox, and agent. It also covers risk-based approval gates, recoverable plan state, unified quota and cost governance, a four-step adoption path, and common pitfalls.
AI Agent Layered Architecture: A Practical Guide
1. Background: Why All-in-One Agent Frameworks Are Hard to Maintain
Over the past two years, most agent application projects have followed the same detour: pick a feature-complete framework, then hand it everything—model calls, tool registration, memory reads and writes, execution environments, and workflow orchestration. Early development is extremely fast, but once the business enters its second year, the problems arrive together:
- When you need to switch model providers, prompt templates, tool-calling protocols, and retry logic are scattered everywhere, and the rework cost approaches a rewrite.
- After the tool count grows from 10 to 200, tool descriptions conflict, parameter names become inconsistent, and call permissions are unclear, so the probability of the model picking the wrong tool rises sharply.
- The memory module is coupled to business table structures, so you cannot use different storage strategies for “short-term conversation context” and “long-term user profiles.”
- Agents hold excessive execution permissions; a single wrong decision can delete data or send messages externally, with no way to trace it afterward.
- When a long task fails halfway, there is no recoverable plan state, so it has to start over.
- Multiple components are subscribed and billed separately, so costs cannot be attributed to a single task or a single tenant.
The common root cause is not “not enough features” but responsibilities that are not layered. The approach discussed here refactors the agent system into a “thin core + pluggable components” structure.
2. Core Design Principle: Subtract from the Core, Add to the Components
In an agent system that can evolve sustainably, the core should keep only three responsibilities that cannot be simplified further:
- Scheduling: the decision-and-execution loop that breaks a user request into decisions about which model to call, which tools to use, which memory to read or write, and which execution environment to run in.
- Approval: pausing the flow before an irreversible or high-impact operation, requesting human confirmation, and feeding the confirmation result back as context.
- Plan maintenance: maintaining a structured task plan that records goals, steps, dependencies, states, and artifacts, making long tasks observable and recoverable.
Everything else—model integration, tool implementation, memory backends, sandbox forms, and agent policies—should be a plugin that satisfies a unified contract. This brings three direct benefits: replacement cost drops from “change everything” to “change one adapter layer”; capability expansion no longer requires modifying core code; and system behavior can be composed into different forms through configuration instead of forking the codebase.
“Thin” does not mean “weak.” A thin core means complexity is placed explicitly into replaceable components rather than hidden in the implicit conventions of a large framework.
3. Contract Design for Five Types of Pluggable Components
The key to componentization is not directory structure but whether contracts are stable and versionable. Each component should expose only a small set of clearly defined methods.
3.1 Model Component
The model component translates a unified inference request into a specific provider’s protocol. The contract should include inference (with streaming output), structured output (returning an object that conforms to a given schema), and tool-call declaration. Engineering must explicitly handle three differences: context window limits, the degree of support for structured output, and concurrency and rate-limiting policies. The recommended approach is to declare capabilities (capability flags) in the adapter layer, and have the core filter available models by capability during scheduling, instead of writing conditional branches in business code.
class ModelPlugin(Protocol):capabilities: set[str] # {"stream", "json_schema", "tool_call"}max_context: intdef infer(self, req: InferRequest) -> InferResponse: ...
3.2 Tool Component
Tools are the only entry point through which an agent interacts with the outside world, so the contract must describe both “how to call” and “how much risk is involved.” Each tool should declare: name and purpose, parameter schema, whether it is idempotent, whether it requires approval, timeout and retry limits, and the scope of resources it can access. Writing “whether approval is required” into tool metadata rather than scattering it across prompts is the prerequisite for automated control later.
As the number of tools grows, introduce grouping and retrieval: group by business domain, use lightweight retrieval to select a candidate subset, then let the model choose. This significantly reduces both misselection and prompt length.
3.3 Memory Component
Memory should not be one large repository but layered: short-term context within a session, intermediate artifacts at the task level, and long-term knowledge across sessions. The three layers have completely different write policies, retrieval methods, and expiration rules. The contract should distinguish four operations—write, retrieve, archive, and purge—and allow different layers to bind to different backends (in-memory, relational database, object storage, vector retrieval service). The key constraint is that writing to long-term memory must pass an explicit policy decision, so temporary noise is not solidified as “fact.”
3.4 Sandbox Component
The sandbox determines where tool code executes. The contract should cover: filesystem view, network egress policy, resource quotas (duration, memory, process count), and snapshot and rollback capabilities. In production, deny outbound network access by default and allow it selectively via a whitelist; keep all writes in a disposable working directory, and move artifacts into persistent storage through an explicit export step.
3.5 Agent Component
The agent is the policy layer: it defines the system prompt, the available tool subset, how plans are generated, and termination conditions. On the same core, a “research agent,” an “execution agent,” and a “review agent” can run in parallel; they share models and sandboxes and differ only in policy.
4. Approval Mechanism: Turning High-Risk Operations into Controlled Gates
Approval is not a simple “confirmation popup” but an explicit state in the flow. Recommended implementation points:
- Risk tiers: classify into low/medium/high based on reversibility, scope of impact, and whether there are external side effects; only medium and high tiers enter approval.
- Sufficient context: the approval request must include the operation to be executed, its parameters, the affected objects, and the rollback plan, so a human can decide within seconds.
- Timeout policy: on approval timeout, default to deny rather than allow.
- Result feedback: both approval and rejection are written back into the plan as structured results, and the model adjusts subsequent steps accordingly.
- Full audit trail: approval records are linked to operation logs to support post-hoc auditing and accountability.
5. Plan Maintenance: Making Long Tasks Observable and Recoverable
The plan is the core’s most valuable state asset. Use an explicit state machine for each step: pending → running → waiting_approval → done / failed / skipped, and record dependencies and artifact paths. This yields three capabilities: observability, so the frontend can render progress in real time; recoverability, so the process can resume from the last completed step after a restart; and replayability, so a failed step can be rerun individually after fixing parameters without affecting completed parts.
plan:goal: generate quarterly data briefsteps:- id: s1 desc: pull metrics data state: done- id: s2 desc: compute YoY and MoM state: done- id: s3 desc: write to production DB state: waiting_approval- id: s4 desc: render charts and export state: pending depends_on: [s3]
6. Cost, Quotas, and Governance
Replaceable components bring an easily overlooked benefit: cost can be governed centrally. The practical recommendation is to make “quota” a first-class citizen of the core: validate the budget before scheduling, deduct after each model call and tool execution, and attribute consumption along two dimensions—task and tenant. When models, tools, memory, and sandboxes come from different sources, unified quota deduction is easier to account for and to cap than separate subscriptions; in related practice at Baidu AI Cloud, such unified quota and budget views are typically implemented through the cloud platform’s cost management and monitoring/alerting capabilities, with the log service completing call-chain auditing.
The governance checklist should include: a per-task cost cap, a per-tenant daily quota, a model fallback chain (switch to a backup model when the primary exceeds limits), tool call rate limits, and two-person review for sensitive operations.
7. Adoption Roadmap and Common Pitfalls
Proceed in four steps: first, implement only the three core responsibilities, using minimal model and tool implementations to close the loop; second, add the approval mechanism and the plan state machine to make “controllable” real; third, expand tools and layer memory by business domain; fourth, introduce multi-agent policies and cost governance.
There are four common pitfalls: putting approval into prompts, which makes it impossible to enforce; keeping plan state only in memory, which makes it unrecoverable; missing risk annotations in tool metadata, which prevents automatic tiering; and lacking a policy for memory writes, which lets long-term knowledge be polluted by noise. All of them point to the same principle—anything that needs to be governed must be explicit, structured, and versionable.
In summary, the long-term maintainability of an agent system does not depend on initial feature coverage but on whether the core is thin enough, whether component contracts are stable enough, and whether state and permissions are explicit enough. Evolving along this structure makes replacing models, extending tools, and adjusting policies local changes rather than global refactors.
