AI Agent Architecture: From Message Routing to Closed-Loop Learning

    This article compares two representative AI agent architecture patterns: centralized message routing and closed-loop learning. It explains how routing-based agents handle cross-platform conversations, why their stateless design limits knowledge reuse, and how closed-loop agents use prompt assembly, tool grouping, session storage, and full-text retrieval to retain experience across sessions. A side-by-side comparison, migration and compatibility considerations, and practical selection guidance help developers choose the right approach for their use case.

    1. Introduction: Why the “Next-Generation Agent” Deserves a Closer Look

    Every so often, a project appears in the community claiming to be the “next-generation AI assistant.” The pitch is almost always the same: install it with a single command, migrate with one click, and outperform the previous generation across the board. Most of these projects do have short lifespans, so a wait-and-see attitude is reasonable. But when similar projects start appearing in batches and offering different answers to the same set of architectural questions, the discussion has shifted from “is this particular tool any good?” to “how should agents be designed?”

    This article sets aside product-specific features and focuses on two representative technical approaches: agents centered on message routing and agents centered on closed-loop learning. The first solves “how conversations happen across platforms”; the second solves “how experience is retained and reused.” Understanding the difference between these two approaches has more long-term value than remembering any single project name.

    2. Approach One: The Centralized Message Routing Architecture

    2.1 Basic Shape

    The core of this kind of system is a message routing layer: it receives messages from various instant messaging channels, parses them uniformly, calls a large language model, and returns the result along the original path. The main pipeline can be abstracted as:

    1. message ingress → message parsing → context assembly → model call → tool execution → response routing → message egress

    2.2 Advantages

    • Low integration cost: Channel adapters hide protocol differences, so the business side only needs to care about intent and replies.
    • Clear pipeline: Each hop has a single responsibility, making it easy to locate failures and apply rate limiting and retries.
    • Easy horizontal scaling: The routing layer is usually stateless and can be deployed in multiple replicas directly.

    2.3 Structural Limitations

    The problem lies in the phrase “stateless.” In most implementations, each turn of conversation is an independent context. Once tool execution finishes, it is over. The reasoning behind intermediate decisions, lessons from failures, and user preferences are never persisted as searchable assets. As a result:

    1. The same mistakes recur, and the system never gets “smarter.”
    2. The context window becomes a hard constraint, and long-running tasks must be continued by external scripts.
    3. Knowledge is scattered across chat logs and cannot be queried programmatically.

    This is not an implementation flaw but an inevitable outcome of the architectural choice. Closing this gap requires adding persistence and retrieval subsystems outside the routing layer.

    3. Approach Two: The Closed-Loop Learning Architecture

    3.1 Layered View

    The closed-loop learning approach typically splits the system into three layers that revolve around a core conversation loop:

    1. ┌──────────────────────────────────────────────┐
    2. │ Agent core loop (session state machine + decision scheduling) │
    3. └──────────────────────────────────────────────┘
    4. │ │ │
    5. ▼ ▼ ▼
    6. prompt building tool registry session storage
    7. context assembly capability groups persistence + full-text retrieval

    3.2 Four Key Subsystems

    (1) The prompt construction layer. Instead of stitching together a static template, it dynamically assembles prompts for the current task: system constraints, long-term memory fragments, retrieved historical conclusions, and descriptions of available tools. Context changes from a “fixed cost” to something “loaded on demand.”

    (2) Tool registry and capability grouping. Once the number of tools grows, stuffing all of them into the prompt quickly consumes the context window and reduces selection accuracy. A common practice is to group tools by capability domain (such as file operations, network access, code execution, and schedules and messaging), select a group first and then a tool, forming two-level routing.

    (3) Session storage and full-text retrieval. An embedded relational database combined with a full-text index writes historical sessions, tool call records, and conclusion summaries to local storage, with support for keyword and synonym retrieval. This step is the prerequisite for the “closed loop” to hold: experience must be queryable before it can be reused.

    (4) Skill accumulation. Verified effective operation sequences are solidified into reusable units. The next time a similar task appears, they are called directly instead of being reasoned through again.

    3.3 Illustrative Code

    A minimal implementation of tool registration and grouping:

    1. from dataclasses import dataclass, field
    2. from typing import Callable, Dict, List
    3. @dataclass
    4. class Tool:
    5. name: str
    6. group: str
    7. handler: Callable[..., str]
    8. desc: str = ""
    9. class ToolRegistry:
    10. def __init__(self) -> None:
    11. self._tools: Dict[str, Tool] = {}
    12. def register(self, tool: Tool) -> None:
    13. self._tools[tool.name] = tool
    14. def groups(self) -> Dict[str, List[Tool]]:
    15. grouped: Dict[str, List[Tool]] = {}
    16. for t in self._tools.values():
    17. grouped.setdefault(t.group, []).append(t)
    18. return grouped
    19. def resolve(self, group: str, name: str) -> Tool:
    20. return self._tools[name]

    Skeleton for memory writes and retrieval:

    1. CREATE TABLE IF NOT EXISTS memory (
    2. id INTEGER PRIMARY KEY,
    3. session_id TEXT NOT NULL,
    4. content TEXT NOT NULL,
    5. created_at TEXT NOT NULL
    6. );
    7. CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts
    8. USING fts5(content, content='memory', content_rowid='id');

    4. A Direct Comparison of the Two Approaches

    Dimension Message Routing Closed-Loop Learning
    Core goal Cross-channel reachability Cross-session accumulation
    State management Mostly stateless Local persistence
    Tool strategy Full injection Grouping + two-level selection
    Knowledge reuse Relies on manual curation Retrieval-driven
    Deployment complexity Low Medium
    Data governance requirements Low High

    It is worth emphasizing that closed-loop learning does not win across the board. It introduces local storage, a retrieval pipeline, and new state consistency problems, and it imposes higher requirements on data classification, redaction, and cleanup policies. Meanwhile, the routing architecture remains more economical in scenarios where all you need is to “get messages in.”

    5. What Migration and Compatibility Really Mean

    The community often advertises “one-click migration of configuration, memory, skills, and keys.” From an engineering perspective, this kind of capability usually depends on two prerequisites: first, a unified configuration abstraction (model endpoints, key references, and channel credentials stored in layers); second, memory and skill storage formats that are generic enough to be serialized into portable structures. If the underlying layer is a local embedded database with a full-text index, migration is essentially a file-level export and index rebuild.

    Practical recommendations:

    • Do not let keys enter the memory store in plaintext; use environment variables or references to a key management service.
    • Run an export validation before migration to confirm the entry count and that the index can be rebuilt.
    • Keep a rollback path, and run the old and new configurations in parallel for a while before switching traffic.

    6. Selection Guidance

    1. Only cross-channel integration for customer service or notifications: The routing approach is sufficient; prioritize rate limiting, retries, and idempotency.
    2. Long-running tasks that need to accumulate domain experience: Choose closed-loop learning, and focus on evaluating retrieval quality and storage governance.
    3. Enterprise deployment: Regardless of the approach, attach unified logging services, monitoring and alerting, and object storage for auditing and archiving; let the container platform handle elastic scaling.
    4. Cost perspective: Closed-loop learning significantly increases storage and retrieval overhead, so define cleanup policies based on session retention periods.

    7. Conclusion

    “Who will beat whom” is a false question. Message routing solves reachability, and closed-loop learning solves accumulability. They are capabilities at different layers, and a mature system is often a combination of a “routing layer + learning layer.” For developers, the real question is not the project name but whether your scenario requires experience accumulation across sessions. Once that judgment is clear, the choice follows naturally.