Building Production-Ready LLM Agent Architecture: A Practical Guide

    This article breaks down the core engineering challenges of moving LLM agents from prototypes to production into five reusable modules: layered memory management, long-term task scheduling, hot-pluggable capability packs, external tool protocol integration, and sandboxed code execution. It provides implementation details, code examples, and practical caveats for teams looking to build reliable and extensible agent systems.

    Introduction: From “It Runs” to “It Ships”

    Most teams can quickly get retrieval-augmented generation, conversational memory, and basic function calling working in a demo. Problems surface once the application hits production: context is lost after a process restart, long-running tasks have nowhere to live, expanding capabilities requires downtime for a release, integrating external tools leads to reinventing the wheel, and model-generated code lacks security boundaries. Rather than recommending or comparing specific frameworks, this article abstracts these unavoidable engineering problems into five general-purpose modules and provides transferable design methods and implementation details.

    1. Memory Management: Blending Short-Term and Long-Term Layers

    The biggest flaw of a single in-memory session cache is that its lifecycle is tied to the process—it loses everything on restart and cannot accumulate facts across sessions. A more mature approach is to split memory into two layers that share the same workspace directory.

    Layer Written By Storage Location Injection Method
    Short-term conversation history Framework interceptor automatically Per-session files under the workspace (e.g., structured text format) Automatically injected before each request turn
    Long-term factual memory Model decides autonomously Root-level instruction file and multiple entry files in the memory directory System prompt informs the read path; retrieved on demand

    The key to fusion is the shared workspace: the short-term layer is handled by the framework, with every message appended automatically; the long-term layer is managed by the model, which decides when to write, how to name, and how to organize entries. The two do not conflict.

    For the short-term layer, it is recommended to implement a file-based memory repository with one file per session. The header records metadata such as creation and update timestamps, and the body contains the message list. This makes it easy to view and correct entries directly in an editor, and also facilitates auditing and replay.

    1. // Example: File-based chat memory repository
    2. public class FileChatMemoryRepository implements ChatMemoryRepository {
    3. private final Path workspace;
    4. public void saveAll(String conversationId, List<Message> messages) {
    5. Path f = workspace.resolve("conversations/chat-" + conversationId + ".yaml");
    6. // Write metadata such as timestamps in the header, message list in the body
    7. writeYaml(f, messages);
    8. }
    9. public List<Message> findById(String conversationId) {
    10. return readYaml(workspace.resolve("conversations/chat-" + conversationId + ".yaml"));
    11. }
    12. }

    Practical caveats: First, set capacity limits and a rolling strategy for memory files; otherwise, a single bloated file will slow down injection. Second, long-term memory must support deduplication and conflict resolution to avoid repeatedly writing the same fact. Third, sensitive information requires redaction and deletion mechanisms to meet compliance requirements.

    2. Long-Term Task Scheduling: Giving Agents Cross-Session Execution Power

    Conversational interaction only covers immediate requests, but real-world business involves many tasks with one-time delays, fixed intervals, or cron-expression schedules. Pushing task capabilities down into an independent scheduling component is a common and reliable choice.

    Design points include: decoupling tasks from agent sessions, with each task carrying only the minimum necessary context rather than the entire history; a task state machine covering pending, running, succeeded, failed, and abandoned, with support for retries and idempotency; writing execution results back to the workspace so they can be read in the next session, naturally connecting with long-term memory.

    1. // Example: Register a retryable recurring task
    2. scheduler.scheduleRecurrently("daily-report", reportJob, cron("0 0 8 * * *"));

    Note: The scheduler must be deployed separately from the business process to avoid task loss when the application restarts; failed tasks need alerting and a manual intervention entry point.

    3. Hot-Pluggable Capability Packs: Switching Skills Without Restarting the Process

    Bundle a set of prompts, scripts, and resources into a “capability pack,” describing its name, purpose, and entry point via directory conventions or a manifest file. At runtime, scanning the directory dynamically registers or unregisters packs, enabling per-request selection of capability combinations.

    Key practices: keep capability packs loosely coupled and interacting through standard input/output; establish versioning and canary mechanisms to validate on a small traffic share first; declare permissions for each capability pack to specify the scope of resources it can access.

    4. External Tool Protocol Integration and Dynamic Registration

    Instead of hand-writing an adapter for every external system, adopt the industry-common Model Context Protocol approach: use a unified client to describe tools, parameters, and return structures, and discover and register them on demand at runtime. This allows the tool ecosystem to be reused and significantly reduces integration costs.

    Implementation recommendations: maintain a registry with hot-update support; apply timeouts, rate limiting, and circuit breaking to tools; strictly validate parameters to prevent injection attacks; log all calls for traceability.

    5. Sandboxed Code Execution Environment

    When letting a model generate and execute code, always treat it as “untrusted” by default. The common approach is to confine code to a disposable container with restricted network, file system, and resource quotas, destroyed immediately after execution. Object storage can be combined to save artifacts, and logging services with monitoring alerts can collect execution traces.

    1. # Example: Restricted container execution policy
    2. network: none
    3. readOnlyRoot: true
    4. memLimit: 256m
    5. cpuQuota: 0.5
    6. timeout: 10s

    Implementation recommendations: deny external network access by default; mount only necessary directories; run static checks on generated code first; retain a complete audit trail.

    Conclusion

    The essence of agent engineering is confining uncertainty within controllable boundaries: layered memory solves continuity, scheduling solves timeliness, hot-plugging and protocol integration solve extensibility, and sandboxes solve security. On cloud platforms such as Baidu AI Cloud, the modules above can be hosted using general-purpose capabilities like container platforms, object storage, logging services, and monitoring alerts, enabling faster construction of operable agent systems.