Runoob Tutorial ArchiveEnglish

AI Agent

AI Agent

You might be used to this kind of interaction: you ask a question, and the AI gives an answer.

In this mode, the AI is more like a consultant—it gives you advice but doesn't do the work directly.

But what if the task is a bit more complex? For example: check the weather in Beijing for tomorrow, if the temperature exceeds 25 degrees, recommend a short-sleeved shirt within a budget of 300 RMB, and then compile the results into an email to send to my boss.

With a regular conversational AI, you have to break it down into several steps:

You need to manually advance each step.

The idea behind an AI Agent is: you just tell it to do something, and it will complete the rest by itself.

It automatically determines what needs to be done, which tools to call, the execution order, and how to adjust when encountering problems until the task is finished.

75e97117 6 6 41cb a 44 bb38a4858735

Simply put: a regular LLM is a strategist that helps you plan; an AI Agent is an executor that handles the task itself after receiving the goal.


What is an AI Agent

An AI Agent is an autonomous system that can perceive its environment, make decisions, and take actions.

A more academic definition is: An Agent is an entity in an environment that can perceive the environment through sensors and act upon the environment through actuators to achieve a series of goals.

This definition sounds a bit abstract, so let's break it down in plain language.

Agent vs. Standard LLM

First, let's look at a comparison table:

Feature Standard LLM AI Agent
Interaction Mode Question-and-Answer, User-Driven Autonomous Execution, Goal-Driven
Capability Boundaries Only Model Built-in Capabilities Capabilities can be extended through tools
Memory Session Context (Limited) Short-term + long-term memory
Planning None (or requires user guidance) Autonomous task decomposition and planning
Feedback loop None (single generation) Observe-think-act loop

A specific example: "Help me book a flight from Shanghai to Beijing for tomorrow, within 1500 RMB."

A standard LLM might respond like this: "Okay, I can help you write code to query flights, or tell you which website to use to check." But it won't actually check flights or help you place an order.

However, a qualified Agent will:

Do you see the difference? A regular LLM gives you an answer, an Agent gives you a result.

Core capabilities of an Agent

A complete Agent usually possesses the following three core capabilities:

Capability Description Analogy
Perception Obtain environment information and feedback Eyes, ears
Decision Thinking about what to do and how to do it Brain
Action Execute specific operations Hands, feet

Basic Agent Architecture

Now let's look at the standard "four pieces" of an Agent: brain, tools, memory, and planning.

First, look at an architecture diagram:

Agent basic architecture diagram: LLM brain + Tools + Memory + Planning four modules

Brain: LLM as the reasoning core

The brain of an Agent is usually a large language model, such as GPT-4, Claude, Llama, etc.

This LLM is responsible for:

LLM is the core of an Agent, but not everything—just as the human brain is important, hands and feet are also needed to get things done.

Tools: Expanding the boundaries of AI capabilities

Native LLMs have two obvious limitations:

Tools are used to solve these problems.

Common tool types:

Tool types Function Example
Search tool Get the latest information Google Search, Bing Search
Calculation tool Perform mathematical operations Calculator, Wolfram Alpha
File Operations Reading and writing local files Reading PDF, writing CSV
API Calls Interacting with external systems Booking flights, sending emails, checking weather
Database Queries Accessing structured data SQL queries, vector retrieval
Code execution Running code to solve problems Python REPL, Jupyter

Giving the Agent tools is like giving a person a computer—instantly turning it from only being able to think to being able to act.

Memory: short-term vs. long-term memory

LLMs are inherently amnesiac—every conversation is new unless you feed it the context.

But Agents need to remember a lot:

Common implementations of memory systems:

Memory types Stored content Implementation methods
Short-term memory Conversation history and intermediate steps of the current session Directly put into the LLM context window
Long-term memory User preferences, historical tasks, knowledge documents Vector database + similarity search
Summarization memory Compressed historical summaries Have the LLM periodically generate summaries

A good memory system makes the Agent seem like it remembers you, rather than acting like it's the first time meeting you every time.

Planning: Task Decomposition

Complex tasks cannot be completed in one step; the Agent needs to be able to break down large goals into small steps.

For example: Help me plan a birthday party for 10 people.

The Agent might plan as follows:

Common planning strategies:


Tool Use: Tool Use / Function Calling

Tool Use is the most fundamental and important capability of an Agent.

Let's start by discussing what it is.

What is Function Calling

Simply put: Function Calling means the LLM outputs a structured JSON telling you which function it wants to call and what parameters to pass.

The LLM does not actually execute the function—it only tells you it wants to call it; you are responsible for the execution.

The entire process is usually like this:

See? The LLM is responsible for thinking, and you are responsible for executing.

Define the JSON Schema for the tool

To make the LLM call a tool, you must first tell it which tools are available.

This telling process is describing the function using a JSON Schema.

Here is a standard function definition format:

Example

This is a typical tool definition (represented by a Python dictionary, which will finally be converted to JSON)

tool_definition

=

{

   

"type"

:

"function"

,

   

"function"

:

{

       

"name"

:

"get_weather"

,

 

Function name

       

"description"

:

"Query the weather for a specified city and date"

,

 

Function usage description, LLM will look at this

       

"parameters"

:

{

           

"type"

:

"object"

,

           

"properties"

:

{

               

"city"

:

{

                   

"type"

:

"string"

,

                   

"description"

:

"City name, such as 'Beijing', 'Shanghai', or 'Shenzhen'"

,

               

}

,

               

"date"

:

{

                   

"type"

:

"string"

,

                   

"description"

:

"Date, format is YYYY-MM-DD, for example '2024-06-18'"

,

               

}

,

               

"unit"

:

{

                   

"type"

:

"string"

,

                   

"enum"

:

[

"celsius"

,

"fahrenheit"

]

,

                   

"description"

:

"Temperature unit, Celsius or Fahrenheit, default is Celsius"

,

               

}

,

           

}

,

           

"required"

:

[

"city"

,

"date"

]

,

 

Required parameters

       

}

,

   

}

,

}

Another tool: search

search_tool

=

{

   

"type"

:

"function"

,

   

"function"

:

{

       

"name"

:

"web_search"

,

       

"description"

:

"Search for the latest information on the internet, suitable for checking news, real-time data, or unknown knowledge"

,

       

"parameters"

:

{

           

"type"

:

"object"

,

           

"properties"

:

{

               

"query"

:

{

                   

"type"

:

"string"

,

"description"

"description"

:

"Search keywords or questions"

,

               

}

,

               

"num_results"

:

{

                   

"type"

:

"integer"

,

                   

"description"

:

"The number of results to return, default is 5"

,

                   

"default"

:

5

,

               

}

,

           

}

,

           

"required"

:

[

"query"

]

,

       

}

,

   

}

,

}

Another tool: calculator

calculator_tool

=

{

   

"type"

:

"function"

,

   

"function"

:

{

       

"name"

:

"calculate"

,

       

"description"

:

"Executes mathematical calculations, supporting addition, subtraction, multiplication, division, power operations, etc."

,

       

"parameters"

:

{

           

"type"

:

"object"

,

           

"properties"

:

{

               

"expression"

:

{

                   

"type"

:

"string"

,

                   

"description"

:

"A mathematical expression, such as '25 * 4 + 10' or 'sqrt(16)'"

,

               

}

,

           

}

,

           

"required"

:

[

"expression"

]

,

       

}

,

   

}

,

}

print

(

f

"Defined {len([tool_definition, search_tool, calculator_tool])} tools: get_weather, web_search, calculate"

)

Output: 3 tools have been defined: get_weather, web_search, calculate

Key points:

Practical coding: Adding search and calculation tools to AI

Now let's write a complete, runnable example.

For demonstration, we will simulate the complete Function Calling process using Python.

Instance

============================================

A simplified demonstration of Agent tool calling

No real API Key is needed, demonstration uses mock data

============================================

import

json

import

random

from

typing

import

Dict

,

Any

,

List

,

Optional

class

SimpleAgent:

   

"""A simple Agent demonstration class"""

   

def

init

(

self

)

:

       

Register available tools

       

self

.

tools

=

self

._define_tools

(

)

       

Conversation history (memory)

       

self

.

messages

: List

[

Dict

]

=

[

]

   

def

_define_tools

(

self

)

List

[

Dict

]

:

       

"""Define all available tools"""

       

return

[

           

{

               

"name"

:

"web_search"

,

               

"description"

:

"Search the internet for the latest information"

,

               

"parameters"

:

{

                   

"query"

:

{

"type"

:

"string"

,

"description"

:

"Search keywords"

}

,

               

}

,

               

"required"

:

[

"query"

]

,

           

}

,

           

{

               

"name"

:

"calculate"

,

               

"description"

:

"Perform mathematical calculations"

,

               

"parameters"

:

{

                   

"expression"

:

{

"type"

:

"string"

,

"description"

:

"Mathematical expression"

}

,

               

}

,

               

"required"

:

[

"expression"

]

,

           

}

,

           

{

               

"name"

:

"get_weather"

,

               

"description"

:

"Query weather"

,

               

"parameters"

:

{

                   

"city"

:

{

"type"

:

"string"

,

"description"

:

"City name"

}

,

                   

"date"

:

{

"type"

:

"string"

,

"description"

:

"Date"

}

,

               

}

,

               

"required"

:

[

"city"

,

"date"

]

,

           

}

,

       

]

   

def

_call_tool

(

self

,

tool_name:

str

,

parameters: Dict

[

str

,

Any

]

)

str

:

       

"""(Simulated) call tool and return result"""

       

print

(

f

" [Tool Call] {tool_name}({parameters})"

)

       

if

tool_name

==

"web_search"

:

            query

=

parameters

[

"query"

]

           

Simulate search results

results

=

{

               

"runoob"

:

"runoob is a programming learning website that provides a large number of programming tutorials and examples."

,

               

"Beijing weather on June 18, 2024"

:

Beijing 2024-06-18: Sunny, 25°C, humidity 45%.

,

               

Shanghai Population

:

Shanghai's permanent resident population in 2024 is approximately 24.89 million.

,

           

}

           

return

results.

get

(

query

,

f

"Search results: No exact information found for '{query}', this is a simulated result."

)

       

elif

tool_name

==

"calculate"

:

expr

=

parameters

[

"expression"

]

           

try

:

               

Note: Do not use eval in production environments, this is just for demonstration

result

=

eval

(

expr

,

{

"builtins"

:

None

}

,

{

                   

"sqrt"

:

lambda

x: x**

0.5

,

                   

"pow"

:

pow

,

               

}

)

               

return

f

"Calculation result: {expr} = {result}"

           

except

Exception

as

e:

               

return

f

"Calculation error: {e}"

       

elif

tool_name

==

"get_weather"

:

            city

=

parameters

[

"city"

]

date

=

parameters

[

"date"

]

           

Simulate weather data

weathers

=

[

"Sunny"

,

"Cloudy"

,

"Light rain"

,

"Overcast"

]

temp

=

random

.

randint

(

15

,

35

)

           

return

f

"{city} {date}: {random.choice(weathers)}, {temp}°C"

       

else

:

           

return

f

"Unknown tool: {tool_name}"

   

def

_decide_action

(

self

,

user_input:

str

)

Dict

[

str

,

Any

]

:

       

"""
(Simulation) LLM decision process
In a real project, this will call the actual LLM API
"""

       

This uses simple rules for simulation; real scenarios should use LLM

       

if

"search"

in

user_input

or

"Check"

in

user_input

or

"What is"

in

user_input:

           

Extract search terms (simple simulation)

query

=

user_input.

replace

(

"Search"

,

""

)

.

replace

(

"Check"

,

""

)

.

replace

(

"What is"

,

""

)

.

strip

(

)

           

if

not

query:

query

=

"runoob"

           

return

{

               

"action"

:

"call_tool"

,

               

"tool"

:

"web_search"

,

               

"parameters"

:

{

"query"

: query

}

,

           

}

       

elif

"calculate"

in

user_input

or

"equals"

in

user_input:

           

Extract expression (simple simulation)

           

return

{

               

"action"

:

"call_tool"

,

               

"tool"

:

"calculate"

,

               

"parameters"

:

{

"expression"

:

"25 * 4 + 10"

}

,

 

Example fixed values

           

}

       

elif

"weather"

in

user_input:

           

return

{

               

"action"

:

"call_tool"

,

               

"tool"

:

"get_weather"

,

               

"parameters"

:

{

"city"

:

"Beijing"

,

"date"

:

"2024-06-18"

}

,

           

}

       

else

:

           

return

{

               

"action"

:

"respond"

,

               

"content"

:

"Okay, I will help you handle this issue."

,

           

}

   

def

run

(

self

,

user_input:

str

)

str

:

       

"""Run Agent to process user input"""

       

print

(

f

"[User input] {user_input}"

)

       

self

.

messages

.

append

(

{

"role"

:

"user"

,

"content"

: user_input

}

)

       

Step one: decide what to do

decision

=

self

._decide_action

(

user_input

)

       

if

decision

[

"action"

]

==

"call_tool"

:

           

Step 2: Call tool

tool_result

=

self

._call_tool

(

decision

[

"tool"

]

,

decision

[

"parameters"

]

)

           

self

.

messages

.

append

(

{

"role"

:

"tool"

,

"content"

: tool_result

}

)

           

Step 3: Generate final answer based on tool results

           

(Simple concatenation here, LLM should actually generate it)

final_response

=

f

"According to my query: {tool_result}\n\nHope this information is helpful to you!"

           

self

.

messages

.

append

(

{

"role"

:

"assistant"

,

"content"

: final_response

}

)

           

return

final_response

       

else

:

           

Direct answer

           

self

.

messages

.

append

(

{

"role"

:

"assistant"

,

"content"

: decision

[

"content"

]

}

)

           

return

decision

[

"content"

]

============================================

Test this Agent

============================================

agent

=

SimpleAgent

(

)

print

(

"="

60

)

response1

=

agent.

run

(

"Search what runoob is"

)

print

(

f

"[Agent Response]\n{response1}"

)

print

(

"\n"

"="

60

)

response2

=

agent.

run

(

"Help me check the weather in Beijing on 2024-06-18"

)

print

(

f

"[Agent Response]\n{response2}"

)

print

(

"\n"

"="

60

)

response3

=

agent.

run

(

"Calculate 25 * 4 + 10"

)

print

(

f

"[Agent Response]\n{response3}"

)

Although this example is simple, it demonstrates the complete closed loop of Function Calling:

Understand → Decide → Call Tool → Observe Results → Generate Answer.

In a real project,_decide_actionthis step will be replaced with a real LLM call, allowing the model to decide which tool to use and what parameters to pass.


ReAct planning loop

After gaining tool-calling capability, the next question is: when to stop?

Simple tasks might be completed in one step, but complex tasks often require multiple iterations.

This is the problem that the ReAct framework aims to solve.

Thought → Action → Observation

The name ReAct comes from the combination of Reasoning and Acting.

Its core idea is simple: let the Agent think step-by-step, act step-by-step, observe, and then repeat this cycle until the task is complete.

Here is a flowchart:

ReAct loop flowchart: Thought-Action-Observation loop

Each cycle includes three steps:

Step English What to do
Think Thought What do I need to do now? Why?
Action Action Call a tool to perform a specific operation
Observation Observation Record the result of the action

Then return to thinking—decide what to do next based on the observed results.

This loop will continue until the Agent determines the task is complete, at which point it will exit the loop and provide the final answer.

Let's look at how ReAct works with a specific example:

Loop termination condition

The ReAct loop cannot run infinitely; it requires a termination condition.

Common termination conditions:

Termination condition Description Example
Task completed Agent determines that enough information has been collected to answer the user's question "I found the answer, and I can answer now"
Maximum steps reached Set a maximum number of rounds (e.g., 10 steps) to prevent infinite loops "Iterated 10 times, forcing stop"
User interruption User actively says "stop" or "enough" "No need to search, I know it"
Determination failed Agent determines that this task cannot be completed "Searched multiple times but could not find relevant information"

When designing an Agent, there must be a "maximum step count" safety valve—otherwise, it might loop endlessly and never stop.


Memory system design

When an Agent works for a long time, it encounters a problem: the context window cannot hold all the conversation history.

This is when a good memory system is needed.

Conversation history: Short-term memory

The simplest form of memory is to save the entire conversation history.

By feeding all previous messages to the LLM every time, it can remember what happened.

However, this method has a clear drawback: the LLM's context window is limited.

For example, GPT-4 is 8K or 32K, and Claude is 200K—while large, it is not infinite.

It works fine for short conversations, but once the conversation gets very long, or the content returned by tool calls in each turn is extensive, it quickly runs out of space.

Vector Database: Long-term Memory

When the memory is too large and cannot fit in the context, a common solution is to store the memory in a vector database and "retrieve" relevant information when needed.

This approach is called RAG (Retrieval-Augmented Generation) and is also applicable in Agents.

Workflow:

This way, even with ten thousand historical memories, only the most relevant ones need to be retrieved and used.

Summarize compressed memories

Another memory optimization scheme: not storing the full conversation text, but having the large model periodically generate concise summaries of historical sessions, only persisting the summary content.

Original long conversation:

Compressed Summary:

Original prompt (Chinese, left untranslated)

用户需要查询北京明日天气,Agent 先后确认城市与日期,用户明确查询时间为明天。

This method can significantly reduce Token overhead: a full conversation that originally occupied 500 Tokens only requires a 50 Token summary to retain core information.

Implemented projects usually use multiple solutions in combination, managing session memory in layers:


Mainstream Agent Frameworks

After understanding the principle, you can write your own Agent or use an existing framework.

The most popular ones right now are these:

LangChain Agents

LangChain is currently the most popular LLM application development framework, and it has a built-in Agent system.

Core concepts:

Agent: The brain, decides what to do.

Tools: A list of tools.

Toolkits: A set of tools (for example, bundling several database-related tools together).

AgentExecutor: The executor, responsible for running the ReAct loop.

The advantage of LangChain is its rich ecosystem—it integrates many ready-made tools and is ready to use out of the box.

The disadvantage is that it can sometimes feel a bit heavy, with many layers of abstraction, making debugging difficult when issues arise.

LlamaIndex Agents

LlamaIndex (formerly GPT Index) focuses more on data connection—connecting your private data (documents, databases, APIs) to the LLM.

Its Agent strengths are:

If your Agent needs to deal with a lot of "your data", LlamaIndex is a good choice.

AutoGPT Principle

AutoGPT is a project that gained popularity in early 2023, characterized by: complete autonomy.

You give it a big goal (e.g., "help me build a website"), and it will automatically:

AutoGPT first showed many people the power of "autonomous Agents," but it also exposed many problems with Agents:

It often runs in the wrong direction until it hits a dead end and fails to stop losses in time.

It is prone to getting stuck in infinite loops, repeating the same tasks.

The cost is high—a single run can cost tens of dollars in API fees.

However, AutoGPT is very inspiring as a proof of concept.

CrewAI Multi-Agent

What I just mentioned were single Agents, but the idea behind CrewAI is: to let multiple Agents team up and collaborate.

For example, you can define:

Product Manager Agent: Responsible for understanding requirements and writing PRDs.

Engineer Agent: Responsible for writing code.

Review Agent: Responsible for Code Review and providing feedback.

Then let them collaborate like a real team—discussing with each other, assigning tasks, and delivering results.

Multi-agent is a very promising direction: a single Agent might make mistakes, but multiple Agents can correct each other and complement each other.


Practical application: Building an automatic information collection Agent

Now let's connect the knowledge points discussed earlier to write a truly usable Agent.

The Agent we are making is calledrunoob-researcher— give it a topic, and it will automatically search, organize, and generate a research report.

Example

============================================

Practical Application: Automatic Information Collection Agent

============================================

import

json

import

time

from

typing

import

Dict

,

Any

,

List

class

ResearchAgent:

   

"""
A simple research agent:
Given a topic, automatically search for related information and organize it into a report
"""

   

def

init

(

self

,

max_steps:

int

=

5

)

:

       

self

.

max_steps

=

max_steps

       

self

.

memory

: List

[

Dict

]

=

[

]

 

Memory

       

self

.

known_facts

: List

[

str

]

=

[

]

 

Collected facts

       

self

.

queries_used

: List

[

str

]

=

[

]

 

Used search terms

   

def

_search_web

(

self

,

query:

str

)

str

:

       

"""(Simulated) web search"""

       

print

(

f

" Search: {query}"

)

       

time

.

sleep

(

0.5

)

 

Simulate delay

       

Simulated knowledge base

knowledge_base

=

{

           

"Artificial Intelligence"

:

"Artificial Intelligence (AI) is a branch of computer science dedicated to creating systems that can perform tasks that usually require human intelligence."

,

           

"Machine Learning"

:

"Machine learning is a subset of artificial intelligence that enables computers to learn from data without being explicitly programmed."

,

           

"Deep Learning"

:

Deep learning is a subset of machine learning, based on multi-layer neural networks, and is particularly good at processing unstructured data such as images and text.

,

           

"Large Language Model"

:

A Large Language Model (LLM) is an AI model based on the Transformer architecture, trained on massive amounts of text, and capable of understanding and generating human language.

,

           

"Agent"

:

"An AI Agent is a system that can autonomously perceive its environment, make decisions, and take actions, usually composed of four parts: LLM, tools, memory, and planning."

,

           

"Transformer"

:

Transformer is a neural network architecture proposed by Google in 2017, which is the foundation of modern LLMs, with the attention mechanism at its core.

,

           

"runoob"

:

"runoob" was created in 2013 and is a website focused on programming tutorials, providing learning resources for various programming languages.

,

       

}

       

Find the most relevant knowledge

       

for

key

,

value

in

knowledge_base.

items

(

)

:

           

if

key

in

query:

               

return

value

       

return

f

Search results for '{query}': This is a very interesting topic involving multiple technical fields. (Simulated result)

   

def

_think

(

self

,

step:

int

,

user_topic:

str

)

Dict

[

str

,

Any

]

:

       

"""
Think about what to do next
(In a real project, this should call the LLM)
"""

       

Simple heuristic rules simulate the thinking process

       

if

step

==

1

:

           

Step one: first search for the topic itself

           

return

{

               

"thought"

: f

"I need to first understand the basic definition and background of '{user_topic}'."

,

               

"action"

:

"search"

,

               

"query"

: user_topic

,

           

}

       

elif

step

==

2

:

           

Step two: Search for related technologies

           

return

{

               

"thought"

:

"The basic definition is in place, now I need to search for related technologies and concepts."

,

               

"action"

:

"search"

,

               

"query"

: f

"{user_topic} related technologies"

,

           

}

       

elif

step

<

self

.

max_steps

:

           

Intermediate step: continue in-depth

           

return

{

               

"thought"

:

"Let me search for more dimensional information to make the report richer."

,

               

"action"

:

"search"

,

               

"query"

: f

"{user_topic} application scenarios"

,

           

}

       

else

:

           

Final step: organize the report

           

return

{

               

"thought"

:

"I have collected enough information and can now compile the final report."

,

               

"action"

:

"finish"

,

           

}

   

def

_observe

(

self

,

action_result:

str

)

:

       

"Observe results and record to memory"

       

self

.

known_facts

.

append

(

action_result

)

       

self

.

memory

.

append

(

{

           

"role"

:

"observation"

,

           

"content"

: action_result

,

       

}

)

   

def

_generate_report

(

self

,

topic:

str

)

str

:

       

"""Generate a report based on the collected information"""

report

=

f

"# {topic} Research Report\n\n"

report +

=

f

"> This report was automatically generated by runoob-researcher\n\n"

        report +

=

"---\n\n"

        report +

=

"## Key Points\n\n"

       

for

i

,

fact

in

enumerate

(

self

.

known_facts

,

1

)

:

report +

=

f

"{i}. {fact}\n\n"

report +

=

"---\n\n"

report +

=

"## Summary\n\n"

        report +

=

f

"This is a summary of the main information regarding '{topic}'."

        report +

=

For more in-depth research, you can further search for related academic papers or technical documents.

       

return

report

   

def

run

(

self

,

topic:

str

)

str

:

       

"Run research Agent"

       

print

(

f

" runoob-researcher started!"

)

       

print

(

f

" Research topic: {topic}"

)

       

print

(

"-"

50

)

       

for

step

in

range

(

1

,

self

.

max_steps

1

)

:

           

print

(

f

"\n Step {step} / Total {self.max_steps} steps"

)

           

1. Think

decision

=

self

._think

(

step

,

topic

)

           

print

(

f

" Thinking: {decision['thought']}"

)

           

if

decision

[

"action"

]

==

"finish"

:

               

print

(

" Collection complete, starting report generation..."

)

               

break

           

2. Action

           

if

decision

[

"action"

]

==

"search"

:

result

=

self

._search_web

(

decision

[

"query"

]

)

               

print

(

f

" Result: {result[:60]}..."

)

               

3. Observation

               

self

._observe

(

result

)

       

Generate final report

       

print

(

"\n"

"-"

50

)

       

print

(

" Generating research report..."

)

final_report

=

self

._generate_report

(

topic

)

       

return

final_report

============================================

Try to see the effect

============================================

agent

=

ResearchAgent

(

max_steps

=

4

)

report

=

agent.

run

(

"Agent"

)

print

(

"\n"

"="

50

)

print

(

report

)

print

(

=

50

)

Although this Agent simplifies LLM calls (by simulating with rules), the entire process is practically usable.

You just need to replace_thinkthe method with a real LLM API call, and replace_search_webit with a real search API, and it can truly help you with research.


Limitations and failure modes of Agents

AI Agents are very powerful, but they are not omnipotent.

Understanding its limitations can help you use it in appropriate scenarios and avoid pitfalls.

Common failure modes

1. Incorrect tool selection

User asks for the weather, Agent calls search; user wants to search, Agent calls calculator.

This error is very common, especially when tool definitions are not clear enough.

2. Parameter passing errors

Incorrect date format, missing required parameters, or incorrect parameter types will all cause tool invocation to fail.

3. Infinite loop

The Agent gets stuck in a dead loop of "Search A -> Not found -> Search A again -> Still not found -> Search A again...".

4. Premature stopping

The Agent decides it's "enough" and provides an incomplete answer before gathering sufficient information.

5. Hallucination

The Agent may fabricate tools that do not exist, parameters that do not exist, or fake search results.

6. Lack of common sense

Sometimes Agents do things that seem silly to humans—for example, if the user says "Help me book a flight for tomorrow," the Agent checks which day "tomorrow" is, but it should actually use today's date plus one day.

How to make Agents more reliable

Facing these issues, the industry has some common mitigation strategies:

Strategy What problem it solves How to do it
Human-in-the-loop Prevent the Agent from going astray Key steps require human confirmation, not full autonomy
Clearer tool definitions Incorrect tool selection The more detailed the description, the better; provide examples
Retry + fault tolerance Tool invocation failure Automatic retry upon failure, or provide clear error feedback to the LLM
Enforced output format Parameter parsing failed Use JSON Schema constraints, or use Output Parser
Reflection mechanism Infinite loop Have the Agent periodically review: "Am I doing useless work?"

A practical suggestion: Don't aim for complete autonomy from the start. Start with a human-machine collaboration mode—the Agent proposes what to do, and the human confirms before execution. Once you have confidence in it, gradually delegate authority.