Understanding AI Agents: From Core Principles to Engineering Practices
This article demystifies AI agents by exploring their core architecture, contrasting them with chatbots and workflows, and detailing key engineering practices. It covers state management, common architectural patterns, tool design, control loops, human-in-the-loop mechanisms, and security considerations to help developers build reliable and useful AI agent systems.
1. Understanding Through an Example: From “Providing Advice” to “Completing Tasks”
Suppose you need to process a batch of expense reports, identify missing information, and generate an audit checklist.
A standard chatbot might tell you: “First check the dates, then verify the amounts, and finally confirm the attachments.” It provides operational advice, but you still have to review each document yourself and verify the calculations.
An AI agent with appropriate permissions and tools can execute a different process: reading specified documents, extracting necessary fields, calling calculation tools to verify amounts, flagging missing items, and generating a checklist for review. If a document is unreadable, it can log an anomaly, attempt permitted alternative processing, or request manual information supplementation.
The core difference is not whether the response is longer or more natural, but whether the system possesses the capability to advance a task toward a defined goal.
You can think of the Large Language Model (LLM) as the “brain” responsible for analysis and judgment, tools as the “hands and feet” performing specific operations, and state management as the “work notes” tracking progress. The agent is the complete system that organizes these components to work together.
“Autonomy” here has clear boundaries: it can only act within authorized limits. Receiving a goal does not automatically grant it permission to read all data, modify business records, or send external messages.
2. The Core Formula: Why “Model + Tools” is Not Enough
For beginners, a simplified expression is helpful:
AI Agent ≈ Large Language Model + Tools
This formula captures two key roles:
- The LLM is responsible for understanding goals, analyzing information, and choosing the next action.
- Tools are responsible for executing queries, calculations, file processing, or business operations, and returning results.
From an engineering perspective, however, this formula is incomplete. A more practical understanding is:
AI Agent System = Model Decision + Tool Execution + State Management + Control Loop + Security Constraints
This is not a strict mathematical definition, but an architectural decomposition method.
For example, the model might propose “query a specific business record,” but the actual query is executed by an external program. The program must check access permissions, validate inputs, handle timeouts, and feed the results back to the model. The model can then decide whether to continue based on these results.
Therefore, the model generating the sentence “query completed” does not mean the query actually happened. The system must rely on tool execution logs and verifiable results, rather than treating the model’s natural language descriptions as facts.
Furthermore, general agents do not necessarily use LLMs. This article focuses on the currently common agent applications that use LLMs as their core decision-making engine.
3. The Difference Between Chatbots, Workflows, and Agents
These three types of systems are easily confused because they may all present a conversational interface and utilize models.
1. Chatbots: Driven Primarily by the User
A typical chat process is: the user asks a question, the model answers, the user follows up, and the model answers again.
In this mode, the user handles most of the task management, including supplementing information, judging answer suitability, and deciding what to do next.
However, a chat interface does not mean the system can only chat. Some conversational applications may run tool calls and autonomous loops in the background. Thus, determining whether a system is an agent requires looking at its internal control mechanism, not just its interface.
2. Workflows: Driven Primarily by Preset Rules
Workflows are usually predefined by developers, for example:
“Receive document → Extract fields → Validate format → Call calculation tool → Generate report”.
The model can participate in certain nodes, but the overall path is determined by rules. Even if a model is used, it may not need to plan tasks independently.
The advantage of workflows is a relatively clear execution path, making them easy to test, audit, and control costs. For businesses with stable rules and clear steps, a preset process is often more suitable than a highly autonomous system.
3. Agents: Dynamically Selecting Actions Based on Goals and Feedback
An agent does not face a completely fixed route; instead, it selects the next step within constraints based on the current state.
For example, if an amount discrepancy is found while checking a document, it might first re-extract the relevant fields; if the difference persists, it generates an anomaly report; if essential information is missing, it requests human confirmation.
This dynamic selection does not mean all steps are decided by the model. In actual engineering, a common approach is “deterministic workflows surrounding local autonomous decisions”: critical business segments are controlled by rules, while information analysis and branch exploration are delegated to the model.
4. The Essence of the Autonomous Loop: Decision, Execution, Observation, Adjustment
The key mechanism of an agent can be summarized as:
Receive Goal → Assess Current State → Select Action → Execute Action → Observe Result → Continue or End
“Observing the result” is particularly important. Without feedback, the system merely outputs continuous plans; with feedback, the system can correct its actions based on reality.
Take generating a document audit checklist as an example:
- The system confirms the input document scope and audit requirements.
- The model determines which fields need extraction.
- The tool reads the documents and returns structured results.
- The model finds some fields missing and decides to conduct further checks.
- The tool executes supplementary checks and returns results.
- The system verifies if the checklist covers all documents.
- Upon meeting completion conditions, it outputs the result; otherwise, it continues processing or escalates to a human.
A common misconception needs correcting: a single tool call does not strictly correspond to “two model responses.” While common flows include “the model requests a tool call” and “the model continues processing after the tool returns,” there may also be parallel calls to multiple tools, consecutive execution of multiple actions, or direct termination after tool execution.
Thus, a single reply seen by the user may involve multiple model requests and tool executions behind the scenes, depending on the architectural design.
5. Model “Statelessness” vs. Agent “Memory”
LLM services typically do not automatically remember the entire progress of a current task based solely on the previous request. Each inference relies on the context provided in the current prompt, or relevant information maintained and reorganized by the server.
This is not the same as “the model has no memory at all.”
Model parameters contain knowledge and language patterns formed during training, but this knowledge is not equivalent to the continuous state of a specific user’s current task. Chat applications remember previous conversations usually because the application saves history and provides relevant content in subsequent requests.
The state an agent needs to maintain usually includes:
- Original goals and task constraints;
- Completed steps and pending items;
- Tool call results and anomaly logs;
- User-confirmed information;
- Current permissions, budget, and stop conditions.
State management can be divided into at least two layers.
Intra-task state supports the current task, such as “which files have been checked” or “which items are still pending confirmation.”
Cross-task memory saves authorized, long-term necessary information, such as user preferences or stable business rules. It should not save all conversations by default, nor should it write unverified model inferences into permanent facts.
Since context space is limited, the system must also filter information: retaining key results, compressing redundant records, and retrieving historical materials on demand. Compressed summaries should retain sources and evidence as much as possible to avoid losing key constraints.
6. Three Common Architectures: More Autonomy is Not Always Better
Based on how the task path is determined, common approaches can be categorized into three types. This is an engineering classification method, not the only standard.
1. Preset Workflows
Developers explicitly define steps, branches, and tool usage rules; the model only participates at designated nodes.
This is suitable for tasks with stable formats and clear rules, such as information extraction, fixed template generation, and standard validation.
Its main limitation is inflexibility when facing unknown situations, requiring constant rule updates. However, if the business itself is stable, this limitation actually improves controllability.
2. Dynamic Planning Agents
The model selects subsequent actions based on goals and tool feedback; the execution path forms at runtime.
This is suitable for tasks requiring exploration, with unstable information sources, and many anomalies.
The trade-off is that execution steps and costs are harder to predict, potentially leading to repeated queries, erroneous branches, or premature termination. Therefore, tool permissions, loop budgets, and result verification mechanisms are essential.
3. Hybrid Architecture
The system combines fixed processes with dynamic decision-making. For example, reading scope, permission validation, and result submission are controlled by programs, while document analysis and supplementary checks are decided by the model.
For enterprise applications, hybrid architectures are usually easier to balance flexibility and reliability. In practice, you can first establish a stable workflow and then gradually hand over components that truly require dynamic judgment to the agent.
7. The Tool Layer: Turning Language Intentions into Controllable Operations
Tools do not have to be complex software systems. Query interfaces, calculation functions, document retrieval, file reading, and internal business operations can all be tools.
Good tool design requires clarifying several elements:
Input boundaries. Tools should specify required fields, allowed values, and how to handle missing information. Models should not trigger high-risk operations directly using vague natural language.
Output structure. Tools should distinguish between success, failure, and partial success, returning necessary results, error categories, and source information.
Permission scope. Query and modification should be authorized separately. Being able to view a record does not imply the ability to delete it.
Repeat execution behavior. For operations with business side effects, retries causing duplicate submissions must be prevented. Idempotent processing mechanisms should be used when necessary so that repeated requests for the same operation do not cause additional impact.
Timeout and recovery. After a tool fails, the system should distinguish between retryable faults and issues requiring manual handling, rather than infinitely repeating the call.
The clearer the tools, the easier it is for the model to use them correctly; the blurrier the tool boundaries, the harder it is for the system to run reliably.
8. What a Minimal Control Loop Should Contain
The following pseudocode illustrates the basic structure. The names are for explaining logic only and do not represent actual product interfaces:
Initialize task stateSet execution budget and allowed toolsWhile task is not finished:Check remaining budget and current permissionsIf budget is insufficient:Save progress and endGenerate next decision based on goal, state, and tool resultsIf decision is to request clarification:Pause task, wait for user inputIf decision is to call a tool:Validate tool name, inputs, and permissionsRequest manual confirmation if necessaryExecute tool and record real resultsUpdate task stateIf decision is to submit results:Check completion conditions and evidenceIf validated, return resultsOtherwise, continue processing or escalate to manual
In this loop, the model proposes decisions, and the program executes boundary controls. The model should not decide to bypass permissions on its own, nor should it end a task simply by claiming “I think it’s done.”
The loop should also set maximum execution rounds, time budgets, cost budgets, and repetitive action detection. For long tasks, checkpoints can be set to support pausing, resuming, and canceling, avoiding the need to start from scratch after a failure.
9. Human Participation is Not a Setback, but Risk Control
Humans play at least two roles in the system:
- Human-in-the-loop: Key steps require human input or approval to continue.
- Human-on-the-loop: Humans mainly supervise the running process and can intervene, pause, or terminate at any time.
The latter should not be simply understood as “humans completely outside the loop.” For high-risk operations, even if the system can usually run autonomously, it may still need human approval at specific nodes.
For example, organizing documents can be automated, but modifying formal business records, sending external content, or deleting data usually requires stricter approval.
A reasonable design does not ask humans to review every trivial step, but sets different control levels based on operational risk, allowing low-risk tasks to execute efficiently while keeping high-risk actions under explicit constraints.
10. Security and Reliability: Key Issues to Prevent
1. Untrusted Content Influencing Decisions
Web pages, documents, or messages read by the agent may contain content instructing it to ignore original rules, leak data, or call irrelevant tools.
The system must distinguish between “data to be processed” and “authorized instructions”. Command-like text in external materials should not automatically gain control over the system.
2. Model Hallucinations
The model may provide conclusions that appear complete but lack evidence. For calculations, queries, and business statuses, priority should be given to verifiable tool results, and information sources should be retained.
3. Over-Permissioning
If a tool simultaneously has read, modify, and delete capabilities, the consequences of an erroneous call are amplified. The principle of least privilege should be followed, and data scopes should be limited.
4. Infinite Loops
The system may repeatedly execute the same action without making new progress. Besides setting budgets, it should also detect whether the task state has effectively changed, stopping and explaining the reason if necessary.
5. Sensitive Information Leaks
Data passed to the model and tools should follow the principle of minimum necessity. Logs may also contain sensitive information, requiring desensitization, access control, and reasonable retention periods.
11. How to Judge Whether an Agent is Truly Useful
Evaluating an agent should not solely rely on smooth demos or answer quality. More importantly, it depends on whether the task is actually completed.
An evaluation system can be built from the following dimensions:
- Completion quality: Is the goal achieved, and are key constraints met?
- Result correctness: Can conclusions pass rule-based, data-driven, or manual verification?
- Execution stability: Does it frequently enter anomalous branches during repeated runs?
- Resource consumption: How much time, model requests, and tool calls are needed to complete the task?
- Human intervention level: Which steps still require manual processing, and is the intervention reasonable?
- Security performance: Does it maintain boundaries when facing malicious inputs, unauthorized requests, and tool failures?
Test sets should not only include normal tasks but also cover scenarios like missing data, contradictory information, tool timeouts, insufficient permissions, and users changing goals midway.
It is worth noting that less human intervention is not always better. A necessary approval may be more valuable than an unconfirmed automated operation.
12. Conclusion: The Value of Agents Lies in Constrained Closed-Loop Execution
To understand AI agents, grasp three keywords:
Goal-driven, feedback loop, controlled execution.
The LLM provides understanding and decision-making capabilities, tools provide action capabilities, state management maintains task continuity, and control programs with human supervision ensure the system stays within bounds.
In actual implementation, you don’t have to start with a fully autonomous system. A more prudent path is: choose tasks with clear boundaries, establish verifiable completion conditions, provide a few reliable tools, first achieve a stable process, and then gradually add dynamic decision-making capabilities.
The maturity of an agent is not determined by how much it resembles a human, but by whether it can stably complete tasks within explicit authorization and resource budgets, ensuring that every action and the final result can be inspected, traced, and explained.
