AI Agents Explained: How They Work, Core Architecture, and Engineering Practices

    Learn how AI agents turn user goals into controlled actions through planning, tool execution, state management, and feedback. This article explains their core architecture, walks through a business reporting workflow, and covers design choices, security, reliability, evaluation, and cost control for production systems.

    1. Understanding AI Agents: From Generating Answers to Completing Tasks

    An AI agent is an artificial intelligence system that organizes actions around a goal. It receives user requirements and information about its environment, assesses the current task state, chooses the next action, uses external tools to produce results, and then decides whether to continue, adjust its approach, or stop based on feedback.

    An “action” is not limited to generating text. It can include querying a database, reading business documents, running controlled computations, creating files, or submitting operation requests to business systems.

    Consider a user asking: “Compile this week’s sales data, generate a summary report, and send it to the person responsible.” An application focused on question answering would typically provide instructions. An agent with the appropriate tools and permissions could clarify the reporting definitions, retrieve the data, calculate metrics, generate the report, and send it once approval requirements are met.

    However, the distinction is not simply that ordinary large language models cannot use tools while agents can. LLM applications can also connect to tools through external systems. What matters is whether the application has mechanisms for goal management, state maintenance, action orchestration, and feedback control.

    An agent is therefore neither a particular model nor an unusually complex prompt. It is a task-execution architecture built from a model and the surrounding software system.

    2. How AI Agents Work: Perception, Planning, Execution, and Feedback

    An agent’s operation can be summarized as a loop:

    User goal → Understand state → Plan an action → Execute a tool → Check results → Update state

    This loop does not imply unlimited autonomous execution. Reliable systems must enforce budgets, permissions, and stopping conditions, and return control when necessary.

    2.1 Perception: Turn Requirements into an Actionable Task State

    The perception stage processes two types of information.

    The first is user intent: the goal, scope, timing, output format, and constraints. For a “weekly sales report,” the definition of the week, whether sales figures exclude refunds, and whether results should be grouped by region or product can all affect the outcome.

    The second is environmental state: the current user’s permissions, available tools, existing files, business data freshness, and previous execution records.

    When essential conditions are missing, the agent should ask the user or apply explicitly authorized defaults. Important details such as metric definitions, recipients, and target resources should not be filled in by guessing.

    Ideally, this stage produces a structured task description rather than only a natural-language summary. Structured representations are easier for downstream validation, execution, and auditing components to use.

    2.2 Planning: Break Down the Task and Choose an Execution Path

    Planning turns a goal into verifiable steps and identifies dependencies between them.

    A reporting task might involve:

    • Confirming the reporting period and metric definitions.
    • Querying transaction and refund data.
    • Checking data completeness.
    • Calculating summary metrics.
    • Generating the report file.
    • Verifying recipients and sending permissions.
    • Sending the report and recording confirmation.

    Planning does not always need to be freely generated by a model. For stable business processes, predefined workflows are often more controllable. For open-ended tasks, a model can select the next step from a restricted set of actions.

    Practical systems often use a hybrid approach: rules or a state machine constrain the main workflow, while the model handles local analysis and exceptions. This preserves flexibility without producing a different process on every run.

    2.3 Execution: Change External State Through Controlled Tools

    The model generally proposes an intended action; the tool execution layer performs the actual operation.

    For example, the model may suggest querying data for a particular time range. The execution layer—not the model—must determine whether access is allowed, whether the parameters are valid, and whether the query exceeds resource limits.

    Before execution, the system should verify at least the following:

    • Is the tool permitted?
    • Do the parameters satisfy type and business constraints?
    • Does the user have the required permissions?
    • Does the operation have external side effects?
    • Is human confirmation required?
    • Is there a risk of duplicate execution?

    Tool responses should contain an explicit success status, result data, and error information. Vague text such as “operation completed” makes subsequent assessment difficult and can conceal partial failures.

    2.4 Feedback: Revise Actions Based on Evidence

    Feedback determines whether the result satisfies the task requirements, not merely whether the tool returned an error.

    A successful query does not prove that the data is complete. A generated file does not prove that its metrics are correct. An accepted send request does not prove that the recipient has received the message.

    Validation should therefore cover both technical status and business outcomes. Evidence can include row counts, field validation, financial reconciliation, reporting-period checks, and operation confirmations.

    When problems occur, an agent may correct parameters, retrieve additional data, switch to another permitted execution path, or request human intervention. Maximum retry counts and an overall execution budget are essential to prevent repeated-failure loops.

    3. Core Architecture: Four Component Types and a Control Loop

    Functionally, an agent can be divided into four component types: reasoning and decision-making, tool execution, memory and state, and runtime control. Knowledge retrieval, security governance, and observability typically span these components rather than operating in isolation.

    3.1 Reasoning and Decision Layer: Decide What to Do Next

    This layer usually centers on an LLM. It interprets requirements, breaks down tasks, selects actions, explains results, and may generate the final deliverable.

    Model output should not be treated directly as a trusted instruction. In an engineered system, the model should produce constrained action descriptions that deterministic code validates.

    Tasks that can be implemented explicitly in software—such as monetary calculations, permission checks, and format validation—should generally be handled by code. Models are better suited to semantic understanding, information synthesis, and judgments involving uncertainty. Probabilistic generation should not replace deterministic logic where that logic is available.

    3.2 Tool Execution Layer: Connect to Business Capabilities

    The tool layer packages external capabilities as callable operations, such as:

    • Querying business databases.
    • Searching authorized documents.
    • Running computations in an isolated environment.
    • Generating or reading files.
    • Submitting approval requests.
    • Sending notifications.

    Tools should have narrowly defined responsibilities. A universal tool that can read data, modify records, and send notifications is difficult to govern with fine-grained permissions.

    Read and write operations should also be separated. Read-only queries may qualify for lower-risk automatic execution, while deleting records, changing configurations, or sending external messages usually requires stricter approval and auditing.

    Standardized tool descriptions and calling conventions can reduce integration effort, but they do not replace permission checks, business validation, or error handling.

    3.3 Memory and State Layer: Retain Necessary Context

    Agent “memory” is not a single mechanism. It can be divided into three categories.

    Working memory holds the current task goal, plan, summaries of tool results, and pending work. Its lifetime usually matches the task.

    Persistent state stores task progress, completed steps, artifact locations, and operation records. It supports recovery across processes, resuming interrupted work, and deduplication. It is closer to a reliable software execution record than to model context alone.

    Long-term memory stores authorized preferences, stable business rules, or historical lessons for future tasks. It is not a requirement for every agent, and it needs controls for provenance, retention, deletion, and access.

    Knowledge retrieval is also distinct from long-term memory. Retrieval finds relevant material in an external knowledge collection; memory concerns information retained during interaction and execution. They can work together, but should be managed separately.

    Continuously adding all historical content to the model’s context is not recommended. A better approach is to maintain structured state and retrieve relevant information as needed, while preserving the sources of key facts to reduce distortion from summarization.

    3.4 Runtime Control Layer: Decide When to Execute and Stop

    The runtime control layer drives the loop, maintains task status, limits resource consumption, and handles pausing, cancellation, and recovery.

    Typical states include pending, running, awaiting approval, awaiting an external result, succeeded, failed, and canceled.

    Reliable software logic should implement this layer. The model may recommend the next step, but it must not bypass permissions, increase its own budget, or remove approval requirements.

    The following simplified pseudocode illustrates the architecture, not a specific interface:

    1. Create task state
    2. Set execution budget and permitted actions
    3. Loop until the task reaches a terminal state:
    4. If human approval is required:
    5. Save state and pause the task
    6. If the budget is exhausted:
    7. Save available results and stop the task
    8. Read the current task state
    9. Generate a proposed next action
    10. Validate the action, parameters, and execution permissions
    11. If validation fails:
    12. Record the reason, then replan or escalate to a human
    13. Continue to the next iteration
    14. Execute the controlled tool
    15. Save tool results and operation records
    16. Check technical status and business outcomes
    17. Update task progress
    18. Return results, unfinished work, and supporting evidence

    Production implementations must also handle timeouts, interruptions, concurrency, and state persistence. An in-memory loop alone is insufficient.

    4. End-to-End Practice: Generate and Send a Business Report

    A weekly business performance report can follow the workflow below.

    Step 1: Confirm the Task Boundaries

    Define the reporting period, time zone, metric definitions, data scope, output format, and recipients. Record these conditions as task configuration and verify the requester’s data access permissions.

    For recurring tasks, reuse approved configurations rather than asking the model to infer them again on every run.

    Step 2: Retrieve and Validate the Data

    Use read-only tools to retrieve data, then check required fields, data freshness, and anomalous values. Apply explicit business rules to records that may be ambiguous, such as refunds and canceled orders.

    If data is missing, disclose the limitation in the report or pause the task until the missing information is supplied. Do not produce an apparently complete result from incomplete data.

    Step 3: Calculate Metrics and Assemble the Report

    Deterministic code should calculate metrics. The model can explain trends, summarize anomalies, and organize the narrative.

    The report should distinguish data-backed facts from analytical judgments. For example, calculated results can support “sales declined,” but “sales declined because promotional activity decreased” requires additional evidence. Without that evidence, the explanation should be presented as a possible cause that needs verification.

    Step 4: Approve and Send

    Before sending, verify the file, recipients, and scope of sensitive information. Require human approval for first-time deliveries, external recipients, or reports containing sensitive data.

    The send operation should use idempotency or operation deduplication to prevent duplicate notifications during retries. An idempotency identifier is effective only if the execution endpoint actually enforces deduplication. A task identifier alone does not prevent duplicate actions.

    Step 5: Save Confirmation and Task Records

    Record the report version, data sources, approval outcome, and send confirmation. The final response should state which steps were completed, any limitations, and whether work remains outstanding.

    5. Choosing an Architecture: Define the Workflow Before the Level of Autonomy

    5.1 Fixed Workflow

    Fixed workflows suit tasks with stable steps and clear rules, such as scheduled reports and standardized data processing. They are easier to test and audit, with the model handling only selected steps that require semantic understanding.

    5.2 Single-Agent Control Loop

    A single-agent loop suits tasks that need to adapt their execution path based on intermediate results. It can reduce manual orchestration, but requires tighter action constraints, validation, and budget controls.

    5.3 Multi-Agent Collaboration

    Multi-agent systems can suit complex tasks with clearly separated responsibilities that can run in parallel. Different execution units might handle data analysis, source verification, and content organization.

    Multiple agents are not inherently better than one. They add communication overhead, state synchronization, conflict resolution, and debugging complexity. Introduce them only when responsibilities are clearly bounded and evaluation demonstrates a benefit.

    A practical principle is to start with a verifiable fixed workflow, then gradually allow local autonomous decisions rather than pursuing full autonomy from the outset.

    6. Security and Reliability: Treat the Model as a Partially Trusted Decision Component

    6.1 Defend Against Instructions Embedded in External Content

    Documents, web pages, and emails read by an agent may contain text designed to induce information disclosure, change the task goal, or trigger dangerous tool calls.

    Treat this content as data to process, not as trusted control instructions. The system must distinguish user authorization, system rules, and external material, while restricting data access and external sending permissions at the tool layer.

    A prompt telling the model to “ignore malicious content” is not sufficient. Permission isolation and execution checks are also required.

    6.2 Apply Least Privilege

    Use task-specific permission scopes and, where possible, short-lived, revocable credentials. Sensitive credentials should not be exposed directly to the model or written in full to logs.

    For high-risk operations, use approval, additional confirmation, or restricted execution environments so that a single model error cannot cause irreversible damage.

    6.3 Distinguish Retryable from Non-Retryable Errors

    Temporary network failures may justify limited retries. Insufficient permissions, invalid parameters, and business-rule violations require corrected conditions or a halt.

    Write operations also introduce an uncertain outcome: a request may time out even though the operation succeeded. In that case, check operation records or the target state rather than immediately submitting the request again.

    7. Evaluation and Cost Control: Measure Task Outcomes, Not Just Answer Quality

    Agent evaluation should cover at least four areas:

    • Task effectiveness: Was the goal actually completed, and is the deliverable correct?
    • Execution safety: Did the system exceed its permissions, disclose data, or produce unapproved side effects?
    • Operational reliability: Can it handle exceptions, recover from interruptions, and avoid duplicate operations?
    • Resource efficiency: Are model calls, tool calls, elapsed time, and human intervention reasonable?

    Test cases should include normal workflows, missing information, tool failures, malicious input, duplicate requests, and partial success. Systems that modify external state should first be validated in an isolated environment or a mode that does not perform real writes.

    Costs extend beyond model calls. They also include retrieval, storage, tool execution, monitoring, and human approval. Costs can be reduced by reusing deterministic workflows, trimming irrelevant context, limiting repeated planning, and caching results that are permitted to be reused.

    Industry cost-reduction claims without consistent measurement criteria are not a sound basis for deciding whether a project is viable. A more reliable estimate uses actual task volumes, failure rates, and time saved from manual work.

    8. Conclusion: Reliable AI Agents Depend on a Controlled Feedback Loop

    AI agents connect language understanding with business actions, allowing systems to make sustained progress toward a goal. But greater autonomy also demands stronger state management, permission controls, and result validation.

    A practical architecture lets the model interpret and recommend, tools perform explicit operations, the state layer preserve facts and progress, and runtime control enforce execution boundaries.

    The ultimate test is not how intelligent the system appears. It is whether the system consistently completes verifiable tasks at an acceptable cost and level of risk.