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

    This article compares two common AI agent architectures: centralized message routing and closed-loop learning. It breaks down what each approach can and cannot do, explains the three supporting layers of closed-loop learning (prompt construction, tool registration, and session storage), and offers a practical framework for evaluating migration claims, controlling cost and latency, and running agents reliably in production. Use it to identify your real bottleneck and choose an architecture that can be verified, measured, and rolled back.

    1. The Technical Question Behind the Trend

    A new category of agent tooling has been appearing frequently in developer discussions. The common selling points are “install with a single command” and “migrate seamlessly from an existing setup.” Neither claim is new by itself. The more useful question is this: once basic capabilities such as channel integration, model invocation, and tool execution become largely standardized, what will actually differentiate one agent from another?

    Setting aside product names and command-line details, two distinct technical routes emerge. The first is centered on message routing: it receives requests from channels such as instant messaging, team collaboration tools, and email, performs lightweight parsing, passes the request to a large language model, and sends the result back to the original channel. The second is centered on closed-loop learning: beyond the conversation loop, it maintains three additional layers, prompt construction, tool registration, and session storage, so that historical interactions can be retrieved, reused, and reprocessed.

    This article does not rank specific tools. Instead, it reduces both routes to a general architecture problem and provides a practical framework for evaluation and implementation.

    2. Centralized Message Routing: Strengths and Limits

    The value of centralized routing lies in integration breadth. Its processing pipeline can usually be abstracted as:

    1. channel adapter → message normalization → context assembly → model call → tool execution → response routing → channel write-back

    The advantage of this pipeline is clear boundaries and easy troubleshooting. The channel adapter layer flattens differences in payload formats, authentication methods, and message length limits across platforms, so the business layer only deals with a unified internal message structure. The response routing layer returns results along the original path and, when necessary, degrades the format (for example, converting rich text to plain text).

    The limitations are equally clear:

    • Short context lifecycle. Most implementations treat a single request and single response as the transaction boundary and release the session afterward. Continuity across days or across channels depends on an external database that you must fill in yourself.
    • Tool results are not retained. The output of a query or a file parsing task is discarded when the transaction ends, so the same intent consumes tokens and latency again next time.
    • Extending capabilities requires code changes. Adding a tool often means modifying the routing layer and prompt templates, which raises regression cost.

    This architecture is therefore better suited to scenarios with a unified entry point, simple logic, and a focus on notifications and question answering.

    3. The Three Pillars of Closed-Loop Learning

    Closed-loop learning does not reject routing. It adds a continuously running loop around it. The skeleton can be broken into three pillars.

    3.1 Prompt Construction Layer: Context as an Orchestrated Resource

    The prompt is no longer a fixed string. It is assembled from system instructions, long-term memory fragments, retrieved relevant documents, and the current tool list. In engineering terms, this usually involves four steps: define the base persona and constraints; recall memory entries by relevance; trim to the token budget; and finally inject tool descriptions and invocation specifications.

    The key design decision is budget allocation. A reusable strategy is to reserve a fixed allowance for system constraints, set an upper ratio for retrieved content, leave the remaining budget for conversation history, and, when the limit is exceeded, evict the memory fragments that have gone unreferenced the longest.

    3.2 Tool Registration Layer: From Hardcoding to Discovery

    As the number of tools grows, the real difficulty is not implementation but letting the model know which tool to use and when. A common approach is to organize tools into several toolsets and load them by scenario, instead of stuffing every description into the context at once. A sample structure:

    1. TOOLSETS = {
    2. "file": ["read_text", "write_text", "list_dir"],
    3. "search": ["keyword_search", "semantic_search"],
    4. "net": ["fetch_url", "extract_main_text"],
    5. "system": ["run_shell", "check_env"],
    6. }
    7. def build_tool_prompt(active: list[str], budget: int = 2000) -> str:
    8. lines = []
    9. for name in active:
    10. for tool in TOOLSETS[name]:
    11. lines.append(f"- {tool}: {SPEC[tool]['desc']}")
    12. budget -= len(SPEC[tool]['desc'])
    13. if budget <= 0:
    14. return "\n".join(lines)
    15. return "\n".join(lines)

    Loading by scenario saves context and reduces the probability of wrong tool calls. Combined with parameter validation and timeout control, the tool layer becomes production-ready.

    3.3 Session Storage Layer: Making Memory Retrievable

    The core evidence of a closed loop is that data is retained and can be found again. A lightweight approach uses a relational database to store sessions and messages, plus a full-text search index for keyword recall. A more advanced approach adds vector retrieval for semantic recall. Retrieval quality depends on chunking granularity and metadata design. In practice, it is recommended to attach a timestamp, source channel, task identifier, and confidence score to each memory entry to support later filtering and invalidation.

    It is worth stressing that more memory is not always better. A memory store without an eviction mechanism keeps amplifying prompt noise and can actually degrade answer quality, so expiration and deduplication policies are mandatory.

    4. Migration Evaluation: Turning “Seamless” into Verifiable Items

    When facing a claim of smooth migration, the rational move is to run a small-scale validation first rather than switching everything at once. Score the candidate across five dimensions:

    1. Configuration portability: whether keys, model parameters, and channel credentials are carried in standard environment variables or configuration files, and whether they can be exported and imported in one step.
    2. Memory portability: whether historical sessions have a structured export format and can be replayed as new memory entries.
    3. Tool equivalence: whether existing tools have corresponding implementations in the new architecture, and whether missing pieces can be covered by generic scripting capabilities.
    4. Runtime environment constraints: some installation scripts target Unix-like environments, and on Windows you typically need to prepare a virtualized Linux subsystem first, so this operational cost should be counted during evaluation.
    5. Rollback cost: whether the old pipeline can run in parallel and whether you can switch back within minutes when something goes wrong.

    A pragmatic migration order is: first connect read-only scenarios (queries, summarization) in parallel and verify memory recall accuracy; then gradually open write operations and external side effects; finally decommission the old pipeline.

    5. Cost and Stability: The Hidden Overhead of Closed-Loop Architecture

    Closed-loop learning is not free. Multi-round retrieval, memory injection, and feeding tool results back into the loop all increase the context length of each request, which raises latency and invocation cost. Control measures include: reranking retrieval results and keeping only the top few; building a result cache for high-frequency repeated intents; pre-routing classification and extraction tasks that a small model can handle; and setting a maximum number of rounds and an overall timeout for tool calls to avoid looping invocations.

    For stability, make memory writes idempotent and prepare regular backups for the storage layer. At the same time, apply whitelists and audit logs to tools with side effects, such as outbound calls, file writes, and command execution.

    6. General Practices for Production Deployment in the Cloud

    Whichever route you choose, productionization relies on a few general cloud capabilities: use a container platform to host the agent runtime and scale it elastically; use object storage for session exports and tool artifacts; use a message queue to smooth traffic spikes and decouple channel integration; and use logging services and monitoring alerts to track the call chain, failure rate, and token consumption. In this type of scenario, Baidu AI Cloud is commonly used to host these general components, but the specific selection should still be evaluated against business scale and compliance requirements.

    7. Conclusion

    Message routing solves the reach problem; closed-loop learning solves the accumulation problem. The former wins on simplicity and control, the latter on long-term efficiency, at the cost of higher complexity and expense. For most teams, the answer is not to pick one of the two, but to first identify your own bottleneck: if the pain point is fragmented channels, unify the entry point first; if the pain point is repeated work and knowledge loss, then introduce memory and retrieval. The standard for any technology choice remains whether it can be verified, measured, and rolled back.