Architecture and Engineering Practices for Deploying General AI Agents in Production

    This article explores the architecture and engineering practices required to transition general AI agents from experimental demos to reliable production systems. It covers establishing a controllable execution loop across six core modules—task entry, context management, planning, tool execution, state management, and result verification. Additionally, it details security design, reliability engineering, evaluation metrics, and a phased deployment strategy to ensure agents operate within defined boundaries while delivering verifiable business value.

    1. From Answering Questions to Executing Tasks: The Value Boundary of General AI Agents

    The core reason general AI agents have garnered attention is not merely a change in the conversational format, but the combination of large language models (LLMs) with external execution capabilities. Traditional Q&A systems primarily generate explanations, suggestions, or text. Agents, however, can read necessary information, decompose tasks, call tools based on user goals, and adjust subsequent steps based on execution results.

    For example, if a user requests to “summarize this week’s project progress and generate a list of pending items,” a Q&A system typically only provides a method for organization. An agent with appropriate authorization can read project records within a specified scope, extract task statuses, identify missing information, and generate a summary along with a pending checklist. However, whether it can truly complete the task depends on data accessibility, tool reliability, sufficient permissions, and clear completion criteria, rather than just model capability.

    Therefore, a general agent is better understood as a system architecture: the model handles semantic understanding and strategy selection, while deterministic software handles permission validation, tool execution, state storage, and result verification. “General” means it can adapt to various tasks, not that it has unrestricted resource access or can autonomously handle all anomalies.

    For enterprises, the key question in evaluating an agent’s value is: Can it continuously reduce the manual effort required to complete tasks within clear boundaries while maintaining result quality and controlling risks?

    2. Core Architecture: Establishing a Controllable Execution Loop

    An agent system designed for production environments can be divided into six collaborative modules.

    1. Task Entry and Goal Constraints

    Users’ natural language requirements are often imprecise. For instance, “clean up historical files” does not specify the directory scope, retention period, file types, or whether permanent deletion is allowed. Direct execution could lead to irreversible losses.

    The task entry module needs to convert the request into a structured task, clarifying at least the following:

    • Goal: What needs to be ultimately accomplished.
    • Input scope: What data is allowed to be read.
    • Operation boundaries: What actions are allowed.
    • Completion criteria: How to determine task success.
    • Budget limits: Maximum time, API calls, or computing resources allowed.
    • Approval conditions: Which operations require manual confirmation.

    For information critical to execution safety, the system should proactively clarify rather than let the model guess. Goal constraints should not only prompt the model but also serve as rules verifiable by the execution layer.

    2. Context Management and Information Retrieval

    The model needs to understand the task background, but placing all historical information into the context at once is unreliable. Irrelevant information increases processing costs, outdated records may mislead decisions, and sensitive content may expand the exposure surface.

    A more robust approach is on-demand information retrieval: first identify the evidence needed for the current step, then retrieve relevant content from authorized data sources. Retrieval results should be accompanied by their source, timestamp, and access scope for subsequent verification.

    It is crucial to distinguish three types of information: goals and constraints explicitly provided by the user, factual materials from external data, and inferences formed by the model based on these materials. These must not be conflated. In particular, operational requirements found in external documents should be treated as data to be analyzed, not as instructions that can change system permissions.

    3. Task Planning and Step Orchestration

    The planning module is responsible for decomposing the goal into executable and verifiable steps. An effective plan must not only describe “what to do” but also specify dependencies, expected outputs, and failure handling.

    Taking weekly project report generation as an example: first read authorized records, then aggregate statuses by project, next flag conflicts and missing information, and finally generate a draft and wait for confirmation. If a data source is unavailable, the system should clearly state the report’s coverage scope rather than using speculation to fill in missing facts.

    Planning granularity must be appropriate. Coarse steps make it hard to detect errors, while overly fine steps increase call costs and coordination overhead. For stable, high-frequency, and high-risk processes, predefined workflows should be prioritized, introducing the model only in steps that genuinely require semantic judgment.

    4. Tool Execution and Result Return

    The model should not directly receive unrestricted access to underlying resources. The tool layer should provide scoped capabilities, such as reading specific records, creating drafts, or querying task statuses, rather than exposing generic entry points that can execute arbitrary commands.

    Each tool should define input constraints, permission requirements, output structures, and error types. Validate parameters before execution and return structured results afterward, avoiding vague natural language descriptions.

    For operations with external impacts—such as writing, deleting, publishing, or sending—additional controls are necessary. You can use previews, manual approvals, execution receipts, and necessary compensation mechanisms to separate “model-recommended execution” from “system formal submission.”

    5. State Management and Recovery Mechanism

    Real-world tasks may run for extended periods or be interrupted due to timeouts, permission changes, or external service failures. Relying solely on conversation history to save state makes the recovery process fragile.

    The system should persist task states, step states, tool call records, and key outputs. Upon recovery, it should proceed based on confirmed execution records rather than letting the model guess what has already been completed.

    For calls with side effects, the issue of repeated execution must be considered. For example, a network timeout does not necessarily mean a submission failed. Before retrying, the system should query the execution status or use idempotency mechanisms to prevent duplicate creations, sends, or deductions.

    6. Result Verification and Delivery

    The model generating a text stating “task completed” does not mean the task is actually done. The completion status must be supported by verifiable evidence.

    Document generation tasks can check if required sections are present and if key data has sources; record update tasks should read the updated state; notification tasks must distinguish between “request accepted” and “message delivered.” Different tasks require different acceptance rules.

    If evidence is insufficient, the system should deliver partial results and explain the limitations, rather than packaging an uncertain state as a success.

    3. Security Design: Giving the Model Capabilities, Not Unlimited Permissions

    The risk in agent systems stems from connecting model judgments with real-world operations. Erroneous suggestions might merely be a text issue, but erroneous execution can affect data, funds, customer communications, and business continuity.

    1. Least Privilege and Identity Binding

    Permissions should be constrained simultaneously by user identity, task scope, and tool capability. Data that a user is unauthorized to access should not be read simply because the agent holds a certain backend credential. The system must execute authorization checks when actually accessing resources, not just rely on prompt constraints.

    Credentials should be managed by a controlled execution environment, preventing them from entering the model’s context. Temporary authorizations must have clear validity periods and resource scopes, expiring promptly after the task ends.

    2. Defending Against Malicious Instructions in External Content

    External documents, web page text, and message logs may contain inducive content, such as requests to ignore existing rules or export sensitive data. When an agent reads these materials, it must maintain the boundary between instructions and data.

    Protection cannot rely solely on model recognition. It also requires system-level restrictions on tool sets, parameter validation, network access destination control, and inspection of sensitive outputs. Even if the model is misled, it should not easily breach execution boundaries.

    3. Risk Tiering and Manual Approval

    Risk levels can be tiered based on the impact scope and reversibility of operations. Read-only queries typically carry low risk; creating internal drafts can have limited automation; operations like external publishing, batch deletion, or modifying access permissions should employ stricter approvals and auditing.

    The approval interface should display the specific operation object, key parameters, and expected impact, rather than just asking the user to confirm a vague “Do you want to continue?” If the plan or parameters change materially after approval, re-confirmation should be required.

    4. Reliability Engineering: Avoiding “Smart but Unstable”

    1. Constraining Task Progression with Explicit States

    Tasks can utilize states such as Pending Clarification, Pending Execution, Executing, Pending Approval, Completed, Partially Completed, Failed, and Canceled. State transitions should be driven by checkable conditions, not entirely dependent on model judgment.

    The following is pseudocode illustrating the control flow, not a real product interface:

    1. Receive task and define constraints
    2. Validate user permissions
    3. While task is not finished and budget is not exhausted:
    4. Select next step
    5. Check if step complies with task boundaries
    6. If approval is required:
    7. Save plan and wait for confirmation
    8. Validate tool parameters
    9. Execute tool and record result
    10. Check if result meets step acceptance criteria
    11. If a recoverable error occurs:
    12. Retry or adjust plan based on strategy
    13. Else if unable to continue:
    14. Save partial results and terminate
    15. Generate deliverable based on evidence

    Here, permission checks, approval requirements, and budget limits must be enforced by deterministic logic, not left to the model’s free discretion.

    2. Setting Different Handling Strategies for Exceptions

    Temporary network faults can have limited retries, insufficient permissions require applying for authorization or termination, parameter errors need re-validation, and business rule conflicts may require human intervention. Treating all failures uniformly as “retry” can easily cause recursive calls and repeated side effects.

    Retries must have an upper limit on attempts and a wait strategy. For tasks that cannot be completed over a long period, they should enter an explicit failure or manual handling state to avoid continuously consuming resources.

    3. Controlling Time and Resource Costs

    Agents can easily inflate costs through repeated planning, redundant retrieval, or tool loops. The system should separately limit total execution time, model call count, tool call count, and single input size.

    Upon budget exhaustion, the system should retain completed work and explain the uncompleted parts and the conditions required to continue execution. Cost management is not just about reducing expenses; it is also a critical safeguard against runaway execution.

    5. Evaluation and Monitoring: Measuring System Capability by Task Results

    Evaluating an agent should not only look at whether the response is fluent, nor merely count whether tool calls were successful. More meaningful metrics include end-to-end task completion rate, result correctness, manual correction workload, unauthorized attempt count, repeated execution instances, completion time, and cost per task.

    Evaluation samples should cover scenarios such as normal tasks, missing information, data conflicts, insufficient permissions, tool timeouts, and malicious inputs. High-risk businesses should also establish dedicated regression test sets to re-verify after changes to models, prompt strategies, or tool logic.

    Online observation needs to be able to reconstruct the task execution process, including task constraints, planning versions, call parameters, execution results, approval records, and acceptance conclusions. However, logs should not indiscriminately save all content; sensitive fields must be desensitized, with reasonable retention and access policies set in place.

    The purpose of monitoring is not just to locate faults, but also to discover unreasonable task boundary designs, frequently failing tool categories, and whether automation benefits are being offset by approval and correction costs.

    6. Deployment Path: Gradually Expanding Automation Scope from Narrow Scenarios

    Enterprises should not initially pursue a “universal assistant” capable of operating all systems. A more feasible approach is to select scenarios with clear goals, distinct data boundaries, and easily verifiable results, such as internal document summarization, task status querying, or report draft generation.

    Phase One focuses primarily on read-only capabilities to validate information retrieval and result quality. Phase Two allows generating drafts and proposing operational suggestions while retaining manual confirmation. Phase Three opens automated execution for low-risk, stable actions, continuously monitoring for anomalies.

    The infrastructure can consist of general components like object storage, message queues, task execution environments, logging services, and monitoring alerts. Component selection should revolve around data sensitivity, task concurrency, recovery requirements, and team maintenance capabilities, avoiding unnecessary dependencies just for the sake of a complex architecture.

    Ultimately, the production value of a general agent stems from a verifiable engineering loop: goals can be clarified, permissions can be constrained, steps can be traced, exceptions can be recovered, and results can be verified. Only by combining the flexibility of language models with the reliability of deterministic systems can agents transition from impressive demos into business capabilities worthy of continuous use.