AI Agent Architecture: From Message Routing to Closed-Loop Learning
This article examines two dominant AI agent architecture patterns and what actually drives migration cost. It contrasts stateless, centralized message-routing designs with closed-loop learning architectures built around a prompt builder, a tool registry, and a session store. It also breaks down the four layers of migration risk, offers a four-dimension framework for choosing an architecture, and outlines a practical security baseline for deployment.
1. The Problem: Why “Next-Generation AI Assistants” Deserve a Closer Look
Every few months, a new batch of projects appears in the community under the label “next-generation AI assistant.” The pitch is remarkably consistent: install with a single command, migrate existing configuration seamlessly, and cover everyday collaboration scenarios. For developers, the value is not the hype itself but the architectural direction that the hype reveals.
Over the past two years, open-source agent implementations have diverged significantly. One group is built primarily on scripting languages, with a low barrier to installation and extension and a fast community iteration cycle. This article does not benchmark any specific project. Instead, it abstracts the phenomenon into two technical questions:
- Is an agent a stateless message relay, or a stateful continuous learner?
- Does migration cost actually come from configuration, memory, or the tool ecosystem?
2. Pattern One: The Centralized Message-Routing Architecture
The core of this architecture is a message-routing layer. It receives events from instant messaging, collaboration platforms, email, or webhooks, parses them uniformly, calls a large language model, and returns the result along the original path. The main flow can be summarized as:
Message ingress -> Event parsing -> Context assembly -> Model call -> Tool execution -> Response routing -> Message egress
The advantages are clear: a short path, well-defined semantics, easy fault localization, and horizontal scaling that only requires adding stateless instances. It fits “one question, one answer” scenarios such as customer service notifications, alert broadcasts, and group Q&A.
The limitations are equally clear:
- Session context is bound to a single request and released when the request ends, so experience cannot accumulate.
- Tool call results are not stored in a structured way, so repeated questions repeatedly consume inference cost.
- Without a unified memory layer, personalization can only be patched together with an external database.
- Permissions, auditing, and quotas are often scattered across individual access channels, making centralized governance difficult.
3. Pattern Two: The Closed-Loop Learning Architecture
Another design splits the agent into three subsystems that can evolve independently, forming a “build-execute-retain” loop:
┌──────────────────────────────┐│ Agent main loop (dialog and decision) │└──────────────────────────────┘│ │ │┌──────┘ ┌──────┘ └──────┐▼ ▼ ▼Prompt builder Tool registry Session storeContext assembly Capability and constraints Persistence + full-text search
The responsibilities and engineering priorities of the three subsystems are as follows.
1. Prompt Builder: Treat Context as an Orchestrated Resource
Context is not a simple concatenation of the system prompt and message history. It is assembled by priority: identity and boundary constraints, long-term memory summaries, the current task instruction, retrieved external knowledge, and available tool descriptions. In practice, it is advisable to set a budget cap and an eviction policy for each context segment to prevent critical information from being diluted in long conversations.
2. Tool Registry: From a “Function Collection” to “Capability Governance”
Mature implementations typically provide dozens of built-in tools, grouped into tool sets by task domain (such as file operations, retrieval, code execution, network access, and task scheduling). What matters is not the number but the governance: each tool should declare its input schema, permission level, timeout and retry policy, idempotency, and fallback path on failure. The more tools there are, the more essential least-privilege authorization and call auditing become.
3. Session Store: Make Experience Searchable
An embedded relational database paired with a full-text search index is a common and pragmatic combination in the industry. Key design points include: separate tables for sessions and messages, inverted indexes on searchable fields, source and timestamp metadata on memory entries, and encryption or masking of sensitive fields. Retrieval quality directly determines whether “learning” actually happens.
4. Main Loop: A State Machine, Not an Infinite Loop
The main loop should be explicitly modeled as a state machine: plan, call, observe, reflect, converge. It must enforce a maximum step count, a per-step timeout, repeated-action detection, and human confirmation checkpoints. Otherwise, typical problems such as repeated tool calls and runaway cost will appear.
4. What Migration Cost Really Consists Of
In marketing language, “seamless migration” is often reduced to a single command. In engineering terms, it involves at least four layers:
| Layer | What migrates | Common risks |
|---|---|---|
| Configuration | Model parameters, prompt templates, channel credentials | Plaintext key residue |
| Memory | Historical sessions, user preferences, summaries | Incompatible structure, broken retrieval |
| Tools | Custom functions, permission declarations | Semantic drift, privilege escalation |
| Runtime | Scheduled tasks, callback URLs, logs | Duplicate triggers, broken audit trails |
Conclusion: migration feasibility depends on whether the target architecture provides stable data contracts, not on how short the command is.
5. A Framework for Making the Choice
Score across four dimensions rather than chasing hype:
- State requirements: whether cross-session memory and personalization are needed.
- Governance requirements: whether fine-grained permissions, auditing, and quotas are required.
- Ecosystem requirements: the extension cost of integrating tools and channels.
- Operations requirements: deployment model, observability, and upgrade/rollback capability.
If the scenario is mainly notifications and Q&A, the routing architecture offers better cost-performance. If it involves long-term collaboration or code and data operations, the closed-loop learning architecture is a better fit. Most production systems eventually converge on a hybrid form: the routing layer handles ingress and rate limiting, while the learning layer handles memory and tool governance.
6. Implementation Practice and Security Baseline
- Host keys centrally; never write them into code or images, and replace plaintext with references during migration.
- Run tool execution in an isolated sandbox, with file and network access following least privilege.
- Log prompt versions, tool input summaries, and latency across the full chain, and connect to a logging service with monitoring and alerting.
- Use general-purpose cloud services for model and vector capabilities as needed (such as container platforms, object storage, message queues, and logging services) to avoid tight coupling with business logic.
- Design expiration and revocation mechanisms for memory entries to meet compliance and explainability requirements.
7. Conclusion
The essence of the architecture debate is a debate over where state lives. Whether context, tools, and experience can be turned into governable, searchable, and rollback-capable assets determines whether an agent is a short-term toy or long-term infrastructure. For most teams, the lowest-risk evolution path is to first validate memory and tool governance in a small closed loop within an environment such as Baidu AI Cloud, then gradually expand channel integrations.
