Runoob Tutorial ArchiveEnglish

AI Agent Working Principle

AI Agent Working Principle

Previously, we introduced the basic concepts and core components of AI Agents. Next, let's look at how these components work together and how to implement a simple Agent using Python.

Traditional Large Language Models (LLMs) primarily generate responses based on the input context. Without connecting external tools, they usually cannot directly read local files, query real-time data, or operate other software.

AI Agents, on the other hand, combine tool calling, task state management, and execution control on top of the model, enabling the program to execute multiple steps based on the goal and decide the next action using the execution results.

For example, if a user requests "read an Excel file, calculate sales, and generate a chart," the Agent can read the file, call Python to process the data, generate the chart, and finally save the results to a specified directory.

The key to an AI Agent is: the model is responsible for decision-making, the tools are responsible for execution, and the program continuously advances the task based on execution feedback.

Basic Components of an AI Agent

A typical LLM Agent usually includes components such as the model, tools, and task state management.

Components Main functions
Model (LLM) Understands tasks, analyzes context, and decides the next action.
Tools (Tools) Executes file operations, search, computation, and API calls.
State and Memory (State / Memory) Records task progress, conversation history, and tool execution results.
Executes control (Agent Runtime) Schedules tools, handles errors, controls the loop, and terminates tasks.

In this, the model is usually responsible for generating decisions, tools are responsible for interacting with the external environment, and the execution program is responsible for organizing the entire task flow.

For simple tasks, the Agent may not require a complex planning system or long-term memory; for multi-step tasks, task state needs to be saved to continue working based on execution results.

Basic components of an AI Agent


Types of AI Agent

Not all Agents are implemented through Large Language Models. In AI research, agents can be divided into different types based on their decision-making mechanisms and system architecture.

Agent Types Main Features Application Scenarios
Reactive Agent Responds based on current input or environment state Rule-based control, simple game AI
Goal-based Agent Selects actions that can advance the task based on goals Task planning, automated workflows
Utility-based Agent Comparing the expected outcomes of different actions through utility functions Path planning, resource optimization
Learning Agent Improving decision-making strategies through learning mechanisms Reinforcement learning, intelligent control
Multi-Agent System Tasks completed through the collaboration of multiple Agents Software development, complex task collaboration

The types mentioned above are not entirely mutually exclusive. For example, a goal-oriented Agent can also have learning capabilities, and each Agent in a multi-agent system can adopt different decision-making mechanisms.

Currently common LLM Agents are usually centered around user goals, utilizing large language models to select tools, process feedback, and execute tasks.

The execution flow of an AI Agent

To understand how an Agent works, the most important thing is to understand its execution loop (Agent Loop).

A common implementation method is ReAct (Reasoning and Acting), which combines reasoning and action.

An Agent does not necessarily complete all decisions in one go, but can continuously judge what to do next based on the results of tool execution.

The basic process is as follows:

Original prompt (Chinese, left untranslated)

用户输入任务

    ↓

模型分析当前任务

    ↓

选择工具并生成参数

    ↓

执行程序调用工具

    ↓

获取工具返回结果

    ↓

模型判断任务是否完成

    ├── 未完成:继续调用工具

    └── 已完成:输出最终结果

For example, the user requests "find the latest version of a Python library and generate the installation command".

  1. The Agent determines that it needs to query the package version.
  2. It calls the package information query tool.
  3. It obtains the version number and related information.
  4. It generates the installation command based on the query results.
  5. It checks if the result meets the requirements and then returns it to the user.

If the query fails, the Agent can retry based on the error message or choose to stop the task and report the reason for failure.

It should be noted that ReAct is just one execution mode for the Agent. Actual systems can also use predefined workflows, task planners, or other orchestration mechanisms.

A complete tool invocation process

Assume the user submits the following task:

Help me calculate the total price of the goods, unit price 89 yuan, purchase 6 items, and then subtract a 30 yuan coupon.

The Agent can process it as follows:

Step 1: Understand the task

The model identifies the unit price, quantity, and discount amount, and determines that a numerical calculation needs to be performed.

Step 2: Select the tool

Assume the system provides a tool namedcalculate_totalcalculation tool, the model can generate the following parameters:

{

    "price": 89,

    "quantity": 6,

    "discount": 30

}

Step 3: Execute tool

The Agent's execution program receives parameters and calls the actual Python function:

def calculate_total(price, quantity, discount):

    return price * quantity - discount

Step 4: Get results

Tool returns:

504

Step 5: Generate answer

The model informs the user based on the tool's returned results:

The total price of the goods is 89 × 6 = 534 yuan, and after deducting the 30 yuan coupon, the actual amount to pay is 504 yuan.

This process demonstrates the division of labor between the model and tools in an Agent: the model is responsible for understanding the task and selecting operations, executing the function call, the tool calculates the result, and finally, the model organizes the answer.


Implementing an AI Agent in Python

Below, we implement a simple Agent workflow using Python.

To make it easier for beginners to understand, we first simulate the perception, decision, action, and memory modules using ordinary Python functions, and then combine them into a runnable program.

**Note:** The basic example below uses keyword matching for decision-making and is not connected to a real large language model, so it is a pedagogical simulation of the Agent workflow, not a complete LLM Agent.

Python Agent program architecture

1. Perception Module

The perception module is responsible for obtaining external input.

In a command-line program, the simplest way to perceive is to use Python'sinput()The function reads user input.

Instance

Perception module: reads user input

def

perceive

(

)

:

user_input

=

input

(

"Please enter a command:"

)

   

return

user_input.

strip

(

)

Get user input

message

=

perceive

(

)

print

(

"Received instruction:"

,

message

)

After executing the program, assume the input:

Original prompt (Chinese, left untranslated)

请输入指令:计算 10 + 5

收到指令: 计算 10 + 5

The perception module here only processes text input. For other Agents, data can also be obtained via API, files can be read, or multimodal models can be used to process images and audio.

2. Decision Module

The decision module is responsible for analyzing the input and deciding what operation to perform.

Real LLM Agents usually utilize the model for task understanding and tool selection. Here, this process is simulated by judging keywords first.

Example

Decision Module: Select operation based on keywords

def

make_decision

(

message

)

:

    message

=

message.

strip

(

)

   

if

message.

lower

(

)

in

(

"Exit"

,

"exit"

,

"quit"

)

:

       

return

"exit"

   

if

"Weather"

in

message:

       

return

"weather"

   

if

"calculate"

in

message:

       

return

"calculator"

   

return

"chat"

Decision module test

message

=

"Help me calculate 10 + 5"

decision

=

make_decision

(

message

)

print

(

"Decision result:"

,

decision

)

Execution result:

Original prompt (Chinese, left untranslated)

决策结果: calculator

This example is only responsible for identifying the task type and does not understand the complete mathematical expression.

In an actual Agent system, the model can generate more specific operation parameters based on tool descriptions and user instructions.

3. Tool and Action Module

The Action Module is responsible for executing the operations selected by the Decision Module.

Tools can be ordinary Python functions, external APIs, database interfaces, or code execution environments.

Below is a definition of a simple calculator tool that supports addition, subtraction, multiplication, and division.

Example

Calculator tool

def

calculator

(

a

,

b

,

operator

)

:

   

if

operator

==

"+"

:

       

return

a + b

   

if

operator

==

"-"

:

       

return

a - b

   

if

operator

==

"*"

:

       

return

a * b

   

if

operator

==

"/"

:

       

if

b

==

0

:

           

raise

ValueError

(

"Divisor cannot be 0"

)

       

return

a / b

   

raise

ValueError

(

"Unsupported operator"

)

Call tool

result

=

calculator

(

3

,

5

,

"*"

)

print

(

"Calculation result:"

,

result

)

Execution result:

Original prompt (Chinese, left untranslated)

计算结果: 15

In this example,calculator()is a tool. The Agent can call it according to the task requirements and use its returned result.

Compared to directly usingeval(), this explicit way of specifying the operator makes it easier to restrict the allowed operations.

For more complex calculators, you can use Python'sastThe module parses restricted mathematical expressions, but should not be used directly.eval()Execute untrusted user input.

4. Memory Module

The memory module is used to save conversation history, task status, and tool call results.

For simple command-line Agents, a Python list can be used to save the current session content.

Instance

Use a list to save conversation history

history

=

[

]

def

save_message

(

role

,

content

)

:

history.

append

(

{

       

"role"

: role

,

       

"content"

: content

   

}

)

Simulate conversation between user and Agent

save_message

(

"user"

,

"Calculate 3 + 5"

)

save_message

(

"assistant"

,

"Calculation result: 8"

)

save_message

(

"user"

,

"multiply by 2"

)

save_message

(

"assistant"

,

Calculation result: 16

)

View history

for

item

in

history:

   

print

(

item

[

"role"

]

,

":"

,

item

[

"content"

]

)

Execution result:

Original prompt (Chinese, left untranslated)

user : 计算 3 + 5

assistant : 计算结果:8

user : 再乘以 2

assistant : 计算结果:16

The history here is pre-written sample data, only used to demonstrate the saving method, and does not mean that the program can already understand contextual instructions like "multiply by 2".

If you need the Agent to make decisions based on the conversation history, you can pass the relevant history information to the model or maintain an explicit task state in the program execution.

For data that needs to be saved across sessions, you can further use SQLite, Redis, or other databases.


Practical Exercise: Create a simple command-line Agent

Previously, input reading, task judgment, tool execution, and history recording were implemented separately. Next, these functions will be combined into a continuously running command-line program.

This program includes the following features:

For testing convenience, weather queries use fixed mock data and will not call a real weather API.

The calculator uses regular expressions to parse simple arithmetic expressions and does not execute arbitrary Python code.

Instance

import

re

Mock weather data

WEATHER_DATA

=

{

   

"Beijing"

:

"Sunny, 25℃"

,

   

"Shanghai"

:

"Cloudy, 23℃"

,

   

"Guangzhou"

:

"Little rain, 28℃"

,

   

"Shenzhen"

:

"Sunny, 29℃"

}

Short-term memory: save conversation history

history

=

[

]

Perception module: read input

def

perceive

(

)

:

   

return

input

(

"You:"

)

.

strip

(

)

Decision module: Identify task type

def

make_decision

(

message

)

:

   

if

message.

lower

(

)

in

(

"Exit"

,

"exit"

,

"quit"

)

:

       

return

"exit"

   

if

"Weather"

in

message:

       

return

"weather"

   

if

"calculate"

in

message

or

re

.

search

(

r

"\d\s*[+-*/]\s*\d"

,

message

   

)

:

       

return

"calculator"

   

return

"chat"

Weather tool: return simulated data

def

get_weather

(

message

)

:

   

for

city

,

weather

in

WEATHER_DATA.

items

(

)

:

       

if

city

in

message:

           

return

f

"{city} weather: {weather} (simulated data)"

   

return

"Please enter Beijing, Shanghai, Guangzhou, or Shenzhen to query."

Calculator tool

def

calculator

(

message

)

:

   

Only recognizes simple arithmetic expressions consisting of two numbers

pattern

=

(

r

"(-?\d+(?:.\d+)?)"

r

"\s*([+-*/])\s*"

r

"(-?\d+(?:.\d+)?)"

   

)

match

=

re

.

search

(

pattern

,

message

)

   

if

not

match:

       

return

"Please enter an equation, for example: calculate 10 + 5"

a

=

float

(

match.

group

(

1

)

)

op

=

match.

group

(

2

)

b

=

float

(

match.

group

(

3

)

)

   

if

op

==

"+"

:

result

=

a + b

   

elif

op

==

"-"

:

result

=

a - b

   

elif

op

==

"*"

:

result

=

a * b

   

elif

op

==

"/"

:

       

if

b

==

0

:

           

return

"Calculation error: divisor cannot be 0"

result

=

a / b

   

else

:

       

return

"Unsupported operator"

   

return

f

Calculation result: {result:g}

Action module: Call corresponding tool

def

execute_action

(

decision

,

message

)

:

   

if

decision

==

"weather"

:

       

return

get_weather

(

message

)

   

if

decision

==

"calculator"

:

       

return

calculator

(

message

)

   

return

"Currently unable to process this command, please try weather query or calculation."

Save conversation history

def

save_history

(

role

,

content

)

:

history.

append

(

{

       

"role"

: role

,

       

"content"

: content

   

}

)

Agent main loop

def

run_agent

(

)

:

   

print

(

"Simple Agent started"

)

   

print

(

"Supports weather query and arithmetic calculation"

)

   

print

(

"Enter" to exit "End program\n"

)

   

while

True

:

       

try

:

message

=

perceive

(

)

       

except

(

EOFError

,

KeyboardInterrupt

)

:

           

print

(

"Program has finished"

)

           

break

       

if

not

message:

           

continue

       

Recognition task

decision

=

make_decision

(

message

)

       

if

decision

==

"exit"

:

           

print

(

"Agent: Goodbye!"

)

           

break

       

Save user input

save_history

(

"user"

,

message

)

       

Execute action

response

=

execute_action

(

decision

,

message

)

       

Output result

       

print

(

"Agent:"

,

response

)

       

Save Agent response

save_history

(

"assistant"

,

response

)

   

Display this conversation history

   

print

(

"\nThis conversation history:"

)

   

for

item

in

history:

       

print

(

f

"{item['role']}:{item['content']}"

)

if

name

==

"main"

:

    run_agent

(

)

Save the above code assimple_agent.py, and then execute in the terminal:

python simple_agent.py

Also can use:

python3 simple_agent.py

Program execution example:

Original prompt (Chinese, left untranslated)

简单 Agent 已启动

支持天气查询、算术计算

输入“退出”结束程序



您:北京天气

Agent: 北京天气:晴,25℃(模拟数据)



您:计算 10 + 5

Agent: 计算结果:15



您:计算 20 / 4

Agent: 计算结果:5



您:退出

Agent:再见!



This conversation history:

user:北京天气

assistant:北京天气:晴,25℃(模拟数据)

user:计算 10 + 5

assistant:计算结果:15

user:计算 20 / 4

assistant:计算结果:5

Program description:

This program does not depend on third-party Python libraries and can run with Python 3.

It should be noted that the program's decision logic is still fixed keyword matching, so it cannot understand complex semantics like a true large language model, nor can it perform multi-step reasoning based on conversation history.

Its main purpose is to demonstrate the relationship between input, decision-making, tool calling, state saving, and the execution loop in an Agent.

How to upgrade it to a true LLM Agent?

The program above already has a basic execution framework, but the most important decision module is still implemented with fixed rules.

To enable the program to have large language model-driven task understanding and tool selection capabilities, the keyword matching can be replaced with the LLM's tool calling mechanism.

The basic steps are as follows:

  1. Select a large language model that supports tool calling.
  2. Define the callable tools and their parameters.
  3. Send the user task and tool definitions to the model.
  4. Read the tool call request returned by the model.
  5. Validate the parameters and execute the corresponding Python function.
  6. Return the tool result to the model to continue the next round of processing.
  7. After the task is complete, output the final result.

For example, in the basic example, tool selection is done with the following code:

Original prompt (Chinese, left untranslated)

if "天气" in message:

    return "weather"

If you integrate a large language model that supports Function Calling, the model can determine whether to callget_weatherand generate relevant parameters based on user instructions and tool descriptions.

This eliminates the need to write separate keyword judgment rules for every natural language expression.

However, actual development still requires restricting tool permissions, validating parameters, handling call errors, and setting execution count and runtime limits.

Common Development Methods

When developing an LLM Agent, you can choose to call the model API directly or use an Agent development framework.

Development Methods Features Applicable Scenarios
Native Python + LLM API Implementing tool calling and execution loop yourself Learning principles, simple Agent
LangChain / LangGraph Provides tool integration, state management, and workflow orchestration capabilities Multi-step Agent, complex business processes
LlamaIndex Provides data connection, retrieval, and Agent related components Knowledge base, document processing, data retrieval
Microsoft Agent Framework Provides capabilities for developing Agents and multi-Agent workflows Enterprise applications, Agent collaboration

For beginners, it is recommended to first understand Python function calling, JSON data, API requests, and task loops before gradually learning the framework.

This makes it easier to understand the actual execution process of an Agent and facilitates troubleshooting issues such as tool call failures and state management errors.


Summary

The working principle of an AI Agent can be summarized as: receiving a task, analyzing the task, selecting tools, executing operations, reading feedback, and deciding whether to continue based on the results.

A typical LLM Agent usually includes the following key components:

This article implements a simple command-line Agent process simulation using Python to demonstrate how these modules work together.

Next, you can try connecting to a real large language model API, allowing the model to autonomously select tools, and gradually incorporate capabilities such as file processing, database querying, and multi-step task planning.

When developing an Agent, you should not only focus on whether the model can correctly understand the task, but also consider whether tool execution is reliable, whether permissions are reasonable, and how to determine if the task is complete.

For more information, please refer to:

  • ReAct: Language model research combining reasoning and action
  • LangChain official documentation
  • Microsoft Agent Framework documentation