Agent Layered Architecture: A Practical Guide to Building a Thin-Kernel Agent Framework

    This article explains why a thin-kernel design is becoming the default choice for agent frameworks, and how to structure an agent system around a stable core plus five pluggable layers: model, tool, memory, sandbox, and agent. It covers the three responsibilities the kernel must keep, a unified model abstraction for chat, structured output, embedding, and multimodal generation, dual-path tool design for general retrieval and vertical data queries, layered memory loading, sandbox isolation with a three-tier approval policy, and a resumable task plan as the kernel's only required state. A four-step rollout path and common anti-patterns are included to help teams reduce switching costs and evolve agents safely under real traffic.

    Agent Layered Architecture: A Practical Guide

    1. Why the “Thin Kernel” Is Becoming the Default in Agent Frameworks

    Two years of hands-on agent engineering keep pointing to the same conclusion: what determines whether an agent can run for the long haul is not how many features are packed into the kernel, but whether the kernel is stable and whether its components are replaceable. Model capabilities iterate quickly, the tool ecosystem keeps expanding, and memory and retrieval approaches appear constantly. Compile all of that volatile surface into the kernel and every upgrade ripples through the entire chain, making regression costs extremely high.

    As a result, an architectural pattern has become widely adopted across the industry: keep the kernel thin, keep the capabilities thick. The kernel retains only three responsibilities that cannot be outsourced — orchestrating models and tools, requesting human approval before high-risk actions, and maintaining a traceable task plan. Everything else, including model integration, the tool set, the memory backend, the execution sandbox, and even how agents are organized, exists as plugins that are composable, replaceable, and extensible.

    The direct payoff: swapping an embedding model requires no business code changes, adding a retrieval tool requires no kernel restart, and switching memory backends requires no rewrite of context assembly logic. For teams, this significantly spreads the risk of technology selection.

    2. Layer Breakdown: The Kernel and Five Pluggable Component Classes

    An agent system built to evolve over time typically splits into six layers. The kernel sits at the center, with five component classes orbiting it.

    Layer Responsibility boundary Common reason to replace
    Kernel Orchestration, approval, planning Rarely changes
    Model layer Understanding and generation, embedding Cost, latency, modality coverage
    Tool layer Interacting with the external world Data source changes, tighter permissions
    Memory layer State persistence across sessions Recall quality, storage cost
    Sandbox layer Isolating side effects of execution Security compliance, resource limits
    Agent layer Role orchestration and collaboration Business process reorganization

    The kernel must stay thin because it is the only part that is both stateful and hard to replace: it holds the task plan, the approval queue, and the invocation context. Moving volatile logic outward is what keeps the kernel stable.

    3. Model Layer: Hide Modality Differences Behind One Abstraction

    What matters in the model layer is not how many models you integrate, but whether a single abstraction can cover text generation, image generation, video generation, and embedding, while leaving upper-layer code indifferent to the differences. In practice, abstract four base actions: chat completion, structured output, embedding computation, and multimodal generation.

    Integrating a custom provider usually requires three pieces of configuration: the invocation endpoint, authentication credentials, and a capability declaration. The capability declaration determines whether the kernel can route a given task to a model that actually supports the required modality.

    1. provider:
    2. name: custom-llm
    3. endpoint: <fill in on your side>
    4. credential: <injected from environment variables, never committed to the repository>
    5. capabilities: [chat, structured_output, embedding, image]
    6. routing:
    7. chat: primary
    8. embedding: primary
    9. image: fallback

    Three engineering disciplines matter here: read credentials only from environment variables or a key management service; configure primary and fallback routing for each capability so a single point of jitter does not fail the whole chain; and enforce schema validation on structured output, retrying on parse failure instead of passing dirty data downstream.

    4. Tool Layer: Give Agents Two Legs — Fact Retrieval and Specialized Query

    A model’s knowledge has a time boundary, while tasks often demand current facts. The tool layer must solve at least two classes of problems.

    The first is general retrieval. A competent retrieval tool should support authoritative source filtering, time range filtering, and query rewriting. Query rewriting matters especially: colloquial user questions often lack constraint terms, and rewriting before retrieval improves both hit rate and explainability.

    The second is vertical data queries. Structured data such as financial reports, business registry information, judicial risk records, academic literature, configuration parameters, and macroeconomic indicators cannot be answered credibly by general retrieval. The reasonable approach is a routing layer that dispatches by query intent to the corresponding data interface, and enforces structured fields in the response rather than free text.

    1. def resolve(query: str) -> dict:
    2. intent = router.classify(query) # finance | registry | legal | paper | spec | macro
    3. if intent == "finance":
    4. return finance_api.query(metrics=extract_metrics(query),
    5. period=extract_period(query))
    6. if intent == "spec":
    7. return spec_api.query(model=extract_model(query))
    8. return search_api.query(rewrite(query), time_range="recent")

    Tool invocation must be uniformly wrapped with permissions and quotas: read-only by default, write operations off by default, rate limits set per caller, and complete invocation audit records retained.

    5. Memory Layer: Treat Context as a Loadable, Layered File System

    Cross-session memory is where agents are most easily built wrong. The common mistake is stuffing all historical conversation into the context, which raises cost, adds noise, and degrades recall.

    A more robust abstraction treats memory, external resources, and learned skills uniformly as “files,” loaded in layers and recalled on demand: the first layer is a minimal always-resident index, the second is topic-segmented summaries, and the third is raw fragments. Retrieval first coarse-filters by topic, then re-ranks fragments, and finally injects only the few hits into the context.

    1. /memory
    2. /index # always resident, topics and pointers only
    3. /sessions/2026-xx # summaries archived per session
    4. /skills/retry-policy # distilled reusable strategies
    5. /resources/spec-db # integration notes for external data sources

    Three supporting mechanisms are needed: deduplicate and resolve conflicts before writing, so multiple versions of the same fact do not coexist; attach freshness labels to memory and down-weight expired content; and mask or encrypt sensitive fields at rest, with support for complete erasure on a per-user basis.

    6. Sandbox Layer and Approval: Constrain “Getting Work Done” Within “Always Recoverable”

    Once an agent can execute, the risk escalates from saying the wrong thing to doing the wrong thing. The sandbox layer isolates side effects: file reads and writes are limited to designated directories, network access goes through an allowlist, processes and resource quotas are capped, and all artifacts are persisted with a trace.

    The approval mechanism handles high-risk actions. Recommended practice is to classify operations into three tiers: auto-approved, approved after logging, and requiring human confirmation. Four actions — deleting data, sending externally, incurring charges, and changing permissions — should default to the third tier.

    1. policy:
    2. auto: [read_file, search, embed]
    3. log_then_run: [write_file_in_workspace]
    4. require_approval: [delete, external_send, paid_api, permission_change]
    5. approval:
    6. timeout: 300s
    7. on_timeout: deny # deny on timeout, never approve by default
    8. evidence: [diff, target, estimated_cost]

    Approval requests must carry enough evidence — the change diff, the target, the estimated cost — so a human can decide in seconds. The timeout policy must be deny; that is the security baseline.

    7. Task Plan: The Only State the Kernel Must Own

    The plan is the contract between the kernel and the agents. The recommended structure includes the goal, steps, dependencies, status, and artifact locations. Update the status after each completed step so execution can resume after an interruption; on step failure, preserve the scene so it is easy to tell whether the cause is the model, the tool, or permissions.

    1. {
    2. "goal": "Produce a first draft of the quarterly business analysis",
    3. "steps": [
    4. {"id": 1, "action": "retrieve", "status": "done"},
    5. {"id": 2, "action": "query_finance", "status": "running"},
    6. {"id": 3, "action": "draft", "status": "pending", "depends_on": [1, 2]},
    7. {"id": 4, "action": "export", "status": "pending", "approval": true}
    8. ]
    9. }

    Surfacing the plan adds another layer of value: users can see what the agent is doing and where it is stuck, so trust and controllability improve together.

    8. Rollout Path and Common Anti-Patterns

    A four-step progression is recommended: first get a minimal kernel running (orchestration + approval + plan), then integrate models and embedding, then add retrieval and vertical data, and finally add memory and the sandbox. Each step should be premised on being rollback-able.

    Anti-patterns to watch for include: writing business rules into the kernel; memory that is written but never cleaned; tools with no quota and no audit; approval that defaults to pass on timeout; and plan state that lives only in memory. These problems are hard to spot in a demo but amplify quickly under real traffic.

    When running on the cloud, common building blocks can be reused: a container platform hosts the sandbox runtime, object storage holds artifacts, a message queue decouples scheduled tasks, and logging plus monitoring and alerting cover auditing and anomaly detection. If you use the relevant general capabilities from Baidu AI Cloud, the same “replaceable components” principle applies — avoid coupling them tightly to the kernel.

    The value of a thin kernel ultimately shows up in switching costs: only when models, tools, memory, and the sandbox can each be upgraded independently does an agent system genuinely gain the ability to evolve over the long term.