How AI Agents Work: Core Architecture and Engineering Practices

    This article explores the working principles, core architecture, and engineering practices of AI agents. It details the closed-loop process of perception, planning, execution, and feedback, alongside key components like model decision, tool execution, memory, and orchestration control. Through practical examples and reliability strategies, it provides a roadmap for building robust, production-ready AI agent systems from controlled task execution to broader autonomy.

    1. Understanding AI Agents: From Answer Generation to Task Completion

    An AI agent can be understood as an artificial intelligence system designed around a clear goal. Within its authorized scope, it perceives the environment, selects actions, calls tools, and continuously adjusts based on execution feedback. Its value lies not merely in generating content, but in translating user intent into verifiable business results.

    For example, if a user requests to “compile this month’s operating data and send the report to the relevant managers,” a standalone language model might explain how to create the report or generate text analysis based on existing data. An agent, equipped with tool access and task orchestration capabilities, can go further: querying data, checking calculation metrics, performing computations, generating files, and, upon receiving necessary authorization, completing the delivery.

    However, a common misconception must be corrected: language models are not limited to merely answering questions, nor are agents inherently equipped with reliable autonomy as a special type of model. They typically do not exist on the same technical level.

    Large language models primarily provide language understanding, content generation, and action decision suggestions. An agent, on the other hand, is an application system built around a model, combined with tools, state management, control logic, and security policies. The same model can be used for Q&A and serve as the decision component within an agent system.

    Therefore, an agent’s capability cannot be judged solely by whether the model is “smart.” It also depends on whether the system has clear goals, reliable interfaces, execution feedback, and controlled action boundaries.

    2. Working Principles: The Perception, Planning, Execution, and Feedback Loop

    The operational process of an agent can be abstracted into the following loop:

    User Goal -> Environment Understanding -> Action Planning -> Tool Execution -> Result Verification -> Adjustment or Completion

    This process does not mean that the four stages must be implemented as four separate model calls. Simple tasks can be merged, while complex tasks might repeat certain stages multiple times.

    2.1 Perception: Defining the Task and Current Environment

    The perception phase first converts natural language requests into actionable task descriptions, including:

    • What the final deliverable is;
    • What data and tools can be accessed;
    • What time, cost, and permission constraints must be observed;
    • What information is still missing;
    • How to determine when the task is complete.

    For a reporting task, details like which time zone “this month” refers to, the statistics cutoff time, the business metrics used, and the recipient list can all affect the outcome.

    If key conditions are unclear, the agent should ask for clarification rather than guess. For low-risk items where default values are acceptable, preset rules can be applied, but related assumptions should be stated in the results.

    Environmental information also comes not only from user input but includes tool return results, task states, historical records, and permission configurations. The model can only make judgments based on the information actually provided by the system, not treat unverified speculations as established facts.

    2.2 Planning: Breaking Down Goals into Executable Steps

    The focus of planning is to establish task dependencies, not to generate lengthy reasoning texts.

    An operating report usually requires defining statistical metrics first, then querying data, performing calculations, validating results, generating files, and finally entering the sending process. Calculations depend on query results, and sending depends on successful file generation. These relationships should be reflected in the execution plan.

    Planning also requires identifying risk differences. Reading public materials carries different risks than modifying business records; drafting an email should not share the same approval requirements as actually sending it.

    In engineering, the plan can be represented as structured steps, each containing the goal, input, tool category, expected output, and failure handling method. The plan can be dynamically adjusted, but adjustments must be constrained by permissions, budgets, and task scope.

    2.3 Execution: Influencing the External Environment via Tools

    A language model itself outputs text or structured content. Operations like querying databases, performing calculations, and writing files are typically handled by external tools or services.

    A typical execution process is:

    1. The model proposes a tool call request;
    2. The system checks if the tool is allowed;
    3. It validates parameter formats, business scope, and permissions;
    4. It executes the tool operation;
    5. It writes the result or error information to the task state;
    6. It determines the next step based on the new state.

    What actually issues external requests is the execution layer, not the model’s text description. Therefore, conclusions like “sent” or “saved” must be backed by successful tool returns or verifiable states.

    2.4 Feedback: Checking Results and Deciding Whether to Continue

    Feedback is not just about discovering anomalies; it also involves judging whether the task deliverables meet acceptance criteria.

    For instance, successful report file generation does not mean the report content is correct; a successful send API response does not necessarily mean the recipient has received or read it. The system should clearly distinguish between states like “request accepted,” “file generated,” and “sending completed,” avoiding overstating the meaning of tool returns.

    Different issues require different handling methods:

    • Temporary network anomaly: Retry a limited number of times;
    • Parameter error: Correct input and re-execute;
    • Insufficient permissions: Request authorization or hand over to human;
    • Missing data: Explain the limitation, do not fabricate results;
    • Metrics conflict: Pause and request confirmation;
    • Persistent inability to complete: Terminate the task and provide the failure reason.

    Reliable iteration must include stopping conditions; otherwise, it easily leads to repetitive calls and cost overruns.

    3. Core Architecture: Four Capabilities and One Execution Loop

    From a functional perspective, an agent can be broken down into four component types: model decision, tool execution, memory state, and orchestration control. Security, auditing, and evaluation permeate all components. This is an easy-to-understand division, not the only standard.

    3.1 Model Decision Layer: Understanding Goals and Proposing Actions

    The model decision layer is responsible for understanding requests, generating candidate plans, selecting tools, analyzing return results, and organizing final responses.

    It can participate in generating final answers, but it should not unilaterally decide permissions, budgets, and compliance boundaries. The model might make incorrect judgments or be interfered with by external text, so deterministic rules must be executed in the system control layer.

    For tasks like amount calculation, quantity aggregation, and format validation, repeatable and testable program logic should be prioritized. The model is suitable for explaining calculation requirements and summarizing results, not replacing precise calculation components.

    3.2 Tool Execution Layer: Translating Actions into Real Operations

    Tools can be database query interfaces, file services, code execution environments, messaging interfaces, or business system APIs. Design should aim to provide operations with clear boundaries rather than exposing unlimited execution capabilities.

    A reliable tool description should at least specify:

    • Tool purpose and applicable conditions;
    • Input parameters and constraints;
    • Output structure;
    • Whether it causes external side effects;
    • Timeouts and error types;
    • Required permissions.

    For example, query tools should restrict data scope, file tools should restrict accessible directories, and sending tools should restrict recipient lists and attachment types. Scenarios executing arbitrary code should also use isolated environments with restricted network, file, and resource access.

    Universal tool connection protocols can reduce integration differences but cannot replace business authentication, data validation, and risk control. A successful interface connection only means interaction is possible, not that the operation is necessarily safe or correct.

    3.3 Memory and State Layer: Preserving Information for Execution

    An agent’s “memory” is typically implemented via external storage and retrieval mechanisms, not equivalent to the model permanently remembering all conversations.

    Three types of information can be distinguished:

    Task State: Current step, tool execution results, remaining budget, approval status, and failure reasons. This information is the foundation for task recovery and auditing.

    Conversation Context: Requirements, supplementary instructions, and recent operations in the current interaction. Its length needs control to prevent irrelevant information from crowding the model’s processable context.

    Long-term Information: Authorized retained preferences, knowledge, and historical experience. Cross-session saving is not a mandatory capability for all agents and should not be enabled by default.

    Long-term information also needs to record its source, time, and applicability scope. Expired preferences, outdated business metrics, or unverified historical conclusions can lead to incorrect decisions. When sensitive information is involved, the principle of minimal retention should be observed, supported by deletion and access controls.

    3.4 Orchestration Control Layer: Determining How the System Runs and Stops

    The orchestration control layer is the operational backbone of the agent, responsible for driving task state changes, not just forwarding model outputs.

    Its responsibilities usually include:

    • Managing step dependencies and execution order;
    • Controlling timeouts, retries, and concurrency;
    • Limiting call counts and resource budgets;
    • Initiating approvals before high-risk operations;
    • Persisting key checkpoints;
    • Supporting pause, resume, and cancel;
    • Judging whether the task succeeded or should exit.

    For tasks with stable paths and clear rules, fixed workflows are usually more reliable. For tasks with large input variances requiring path selection based on feedback, model decision-making can be introduced locally.

    In actual projects, “deterministic workflows handle the main trunk, while agents handle flexible decisions” is often easier to test and govern than a completely free autonomous loop.

    4. Practical Example: Automatically Generating and Sending a Business Report

    Assume the task goal is: “Generate last month’s business report, including revenue, order volume, and refund rate, and send it to the designated manager after confirmation.”

    Step 1: Form a Clear Task Contract

    The system needs to determine the time range, statistical time zone, metric definitions, data sources, recipient scope, and whether manual confirmation is mandatory.

    The refund rate, for instance, might have multiple definitions: calculated by the number of refunded orders or by the refund amount. The system should not infer definitions solely from the metric name; it should use confirmed business rules.

    Step 2: Query and Validate Data

    Queries use read-only permissions. After returning data, check:

    • Whether the time range is complete;
    • Whether duplicate records exist;
    • Whether key fields are missing;
    • Whether the metric definitions across data sources are consistent;
    • Whether anomalous variations requiring verification have occurred.

    If data anomalies are detected, the system can append queries or pause and prompt the user. Anomaly detection results are merely clues for verification and should not be automatically interpreted as business facts.

    Step 3: Calculate and Generate the Report

    Metrics are calculated by deterministic programs, and the model writes summaries and explanations based on the calculation results. The report should distinguish between data facts and analytical speculations, clearly labeling the statistical scope, metrics, and known limitations.

    If analyzing the cause of revenue changes is required, corresponding evidence must exist. Merely observing a revenue drop does not justify directly asserting that a specific business action caused it.

    Step 4: Execute Sending After Confirmation

    The system displays the recipients, subject, attachments, and key data, waiting for manual confirmation. Once confirmed, the execution layer issues the send request and records verifiable results.

    If the send request times out, it should not immediately assume sending failed and resend. The system should prioritize querying the existing operation status or use business operation identifiers to recognize duplicate requests, reducing the risk of duplicate sending.

    5. Execution Loop Illustration: Placing Model Suggestions Within Rules

    The following is general pseudocode, only used to illustrate control logic, and does not represent any actual product interface:

    1. state = initialize_task(goal, permissions, budget)
    2. while not state.finished:
    3. if budget_exceeded(state) or deadline_reached(state):
    4. stop_with_reason(state, "Resource or time limit reached")
    5. break
    6. proposal = propose_next_action(state)
    7. if proposal.requires_missing_information:
    8. request_clarification(state, proposal)
    9. pause_task(state)
    10. break
    11. if not action_allowed(proposal, state.permissions):
    12. stop_with_reason(state, "Action exceeds authorization scope")
    13. break
    14. validate_action_parameters(proposal)
    15. if requires_approval(proposal):
    16. save_pending_action(state, proposal)
    17. request_approval(state)
    18. break
    19. result = execute_action(proposal)
    20. persist_observation(state, result)
    21. if result.is_uncertain:
    22. schedule_status_check(state, proposal)
    23. elif result.failed:
    24. apply_bounded_recovery(state, result)
    25. if acceptance_checks_pass(state):
    26. mark_finished(state)

    This logic embodies three principles: a model proposing an action does not mean the action is approved; tool returns must enter the state record; and task completion should be determined by acceptance rules and evidence together, not just by the model’s self-declaration.

    6. Reliability and Security: Must-Solve Issues Before Launch

    6.1 Preventing External Content from Affecting Decisions Unauthorized

    Web pages, documents, emails, and tool return contents may all contain inducing instructions. The system should treat these contents as data to be analyzed, not as control commands with permissions.

    Security boundaries cannot be maintained solely by prompts; they must be enforced through tool whitelists, parameter constraints, sensitive operation approvals, and data access controls. Text like “ignore original rules” from external documents should not change the system’s authorization scope.

    6.2 Limiting Impact Scope with Least Privilege

    Read, write, delete, and external send operations should be authorized separately. Access credentials should be managed by the execution layer wherever possible, not exposed to the model as plain text.

    For high-risk operations, independent controls such as manual confirmation, amount or quantity thresholds, and operation object restrictions should be retained. The degree of autonomy should decrease as risk increases, rather than blindly pursuing zero human intervention.

    6.3 Designing Idempotency and Recovery Mechanisms for Retries

    Execution failure does not necessarily mean the operation did not occur. A network interruption might happen after the business operation completes but before the response returns.

    Therefore, operations involving creation, payment, sending, or modification should support duplicate request identification, status queries, and audit logs wherever possible. If a safe retry is impossible, it should be handed over to human processing.

    Multi-step tasks might also result in partial success. The system needs to record which steps have completed and execute compensatory actions if necessary, but it cannot assume all external operations can be rolled back.

    6.4 Establishing Comprehensive Observability

    Logs should be able to answer: Why did the task call this tool? What parameters were used? What result was obtained? What approvals were passed? How was completion ultimately judged?

    Records should revolve around auditable action summaries, tool events, and state changes; there is no need to save the model’s internal reasoning process. Sensitive fields should also be masked and subject to reasonable retention periods.

    7. Cost and Effectiveness: Evaluating Agent Investment

    Agents might call models and tools multiple times, so it is not enough to compare the price of a single model call. It is more meaningful to evaluate the total cost required to complete a qualified task.

    Total costs include model inference, data retrieval, tool execution, manual approvals, failure retries, and operational costs. Cost variances across different models, task lengths, and execution paths are significant, so it is inadvisable to derive project benefits using industry price drops that lack a unified measurement standard.

    Optimization can start from the following directions:

    • Use rule-based programs to handle stable, repetitive steps;
    • Only provide the model with information needed for the current decision;
    • Cache reusable results with clear time validity;
    • Execute independent read-only tasks in parallel;
    • Set call budgets for complex tasks;
    • Exit promptly during continuous failures or insufficient returns.

    Effectiveness metrics should cover task success rate, result accuracy, tool call success rate, manual takeover rate, duplicate side-effect occurrences, average time consumed, and cost per successful task. Whether the reply is fluent is merely one experience metric and cannot replace business acceptance.

    8. Implementation Path: Start with Controlled Tasks, Then Expand Autonomy

    It is recommended to start with high-frequency, clearly bounded, and verifiable tasks, such as read-only data queries, fixed-metric report generation, and document organization.

    In the first phase, only generate suggestions or drafts to validate understanding and result quality; in the second phase, open read-only tools to check data access and action selection; in the third phase, integrate limited write operations, adding approvals, duplicate request identification, and exception handling; finally, expand the authorization scope based on actual operational evidence.

    Multi-agent collaboration should also not be the default choice. Introducing multiple execution entities is only worthwhile when the task truly requires role division, parallel processing, or permission isolation. Otherwise, it will increase the costs of communication, state synchronization, and problem diagnosis.

    Ultimately, the working principle of an AI agent is a controlled execution loop with model participation in decision-making. The focus of its architectural design is not to let the model act with unlimited freedom, but to connect goals, permissions, tools, states, and acceptance criteria. Only when every action can be verified, constrained, and recovered can an agent transition from a demo system to a reliable production application.