The First LangChain Agent
To complete a task, we sometimes need to query external data, perform calculations, or execute multiple operations in succession; relying solely on the model to generate text is not enough.
In this case, you can use Agent (intelligent agent)。
An Agent can decide whether to call a tool based on the user's question, call the model again after obtaining the tool execution result, and repeat this process until a final answer is generated or a stopping condition is reached.
This section will use LangChain's create_agent() to create the first Agent, and through two tools—weather query and mathematical calculation—understand the complete execution process of an Agent.
I. What is an Agent?
An Agent is a program that can combine a language model with external tools to complete tasks.
An Agent does not only generate answers; it can also select tools according to task needs and use the results returned by tools to continue processing the problem.
Differences between a regular model and an Agent
| Comparison item | Regular model call | Agent |
|---|---|---|
| Basic flow | Input question → Generate answer | Input question → Decide whether to call a tool → Execute tool → Continue processing |
| Tool use | Requires extra orchestration | Can execute automatically based on the model's tool call requests |
| External Data | Cannot guarantee access to real-time data based on model parameters alone | Can access external data sources such as databases and APIs through tools |
| Number of executions | Usually completes one model call | May perform multiple rounds of model calls and tool executions |
| Applicable scenarios | Chat, rewriting, summarization, translation | Data query, task automation, multi-step operations |
The Agent's work loop
The Agent's working process can usually be summarized as:
用户输入
↓
调用语言模型
↓
模型是否请求调用工具?
├── 否 → 生成最终回答
│
└── 是
↓
执行工具
↓
获得工具结果
↓
再次调用模型
↓
继续判断是否需要工具
This loop is often summarized asReasoning, action, observation(Reasoning、Action、Observation)。
For example, the user asks:
杭州今天的天气怎么样?
An Agent may first call a weather query tool, provide the returned weather data to the model, and then have the model organize it into a natural language answer.
**Note:** Whether the Agent can obtain real-time weather depends on whether a real weather API is connected. This section first uses simulated data, with the aim of learning the Agent's operating mechanism rather than querying real weather.
2. Installation and Environment Setup
This tutorial uses LangChain 1.x style create_agent() API。
First install the required dependencies:
pip install -U langchain langchain-deepseek python-dotenv
Where:
langchain: Provides Agents, tools, and a unified model call interface.langchain-deepseek: Provides DeepSeek model integration.python-dotenv: Reads environment variable configuration in the project.
Configure DeepSeek API Key
Create in the project directory .env File:
DEEPSEEK_API_KEY=your_deepseek_api_key
data to the child component via your_deepseek_api_key Replace with the actual API Key.

Then load in Python:
from dotenv import load_dotenv
load_dotenv()
This tutorial uses the model officially recommended by DeepSeek deepseek-flash model.
The corresponding LangChain initialization method is:
from langchain.chat_models import init_chat_model
model = init_chat_model(
"deepseek:deepseek-flash"
)
Before use, please confirm that the model service is accessible and that the model used supports tool calls.
DeepSeek officially also provides deepseek-v4-pro, if needed, you can change the model name to:
model = init_chat_model(
"deepseek:deepseek-v4-pro"
)
III. Creating the First Agent
Creating an Agent mainly involves three steps:
- Define the tools the Agent can call.
- Use
create_agent()Create an agent. - called
agent.invoke()Execute the task.
Step 1: Define tool functions
LangChain provides @tool decorator can convert a regular Python function into a tool that the Agent can use.
Two tools are created here:
get_weather(): Query simulated weather for a specified city.calculate(): Calculate simple mathematical expressions.
Tool one: Weather query
Example
from
langchain.
tools
import
tool
@
tool
def
get_weather
(
city:
str
)
str
:
"""Query simulated weather data for a specified city.
Args:
city: City name, such as Hangzhou, Beijing, Shanghai.
"""
weather_data
=
{
"Hangzhou"
:
"Sunny, 25°C, humidity 60%"
,
"Beijing"
:
"Cloudy, 18°C, humidity 45%"
,
"Shanghai"
:
"Light rain, 22°C, humidity 80%"
,
}
return
weather_data.
get
(
city
,
f
"No simulated weather data found for {city}"
)
Predefined dictionary data is used here.
If the user queries Hangzhou, the tool returns:
晴,25°C,湿度60%
If a city that is not included is queried, a "data not found" message is returned.
**Note:** These values are teaching samples and do not represent real weather. In a real project, the dictionary can be replaced with a weather API request.
The role of the @tool decorator
@tool It converts a Python function into a LangChain tool object and establishes a tool definition based on the function signature and description information.
For example:
@tool
def get_weather(city: str) -> str:
"""查询指定城市的模拟天气数据。"""
...
Where:
get_weather: Tool name.city: str: Parameters and types the tool receives.- Docstring: Describes the purpose of the tool.
- Return value: The result provided to the Agent after tool execution.
The model uses this information to determine when to call the tool and what parameters to pass in.
Therefore, tool descriptions should be as clear as possible and explain the meaning of the parameters.
Tool two: Safe calculator
The second tool is used to perform simple mathematical calculations.
Previously used eval() to directly evaluate expressions generated by the model is not safe. Even if built-in functions are removed, it is not recommended to pass untrusted expressions directly to eval()。
Here we use Python's ast module instead, which only allows numbers, parentheses, addition, subtraction, multiplication, division, and unary plus/minus signs.
Example
import
ast
import
operator
from
langchain.
tools
import
tool
Allowed mathematical operators
OPERATORS
=
{
ast.
Add
:
operator
.
add
,
ast.
Sub
:
operator
.
sub
,
ast.
Mult
:
operator
.
mul
,
ast.
Div
:
operator
.
truediv
,
ast.
UAdd
:
operator
.
pos
,
ast.
USub
:
operator
.
neg
,
}
def
safe_calculate
(
expression:
str
)
:
"""Only calculate simple mathematical expressions."""
Limit expression length to prevent oversized input
if
len
(
expression
)
100
:
raise
ValueError
(
"Expression too long"
)
tree
=
ast.
parse
(
expression
,
mode
=
"eval"
)
def
evaluate
(
node
)
:
Numeric constants
if
isinstance
(
node
,
ast.
Constant
)
:
if
type
(
node.
value
)
in
(
int
,
float
)
:
if
abs
(
node.
value
)
1
_000_000_000:
raise
ValueError
(
"Number too large"
)
return
node.
value
Binary operations
if
isinstance
(
node
,
ast.
BinOp
)
:
op_type
=
type
(
node.
op
)
if
op_type
not
in
OPERATORS:
raise
ValueError
(
"Unsupported operator"
)
left
=
evaluate
(
node.
left
)
right
=
evaluate
(
node.
right
)
if
op_type
is
ast.
Div
and
right
==
0
:
raise
ValueError
(
"Divisor cannot be zero"
)
result
=
OPERATORS
[
op_type
]
(
left
,
right
)
if
abs
(
result
)
1
_000_000_000:
raise
ValueError
(
"Calculation result too large"
)
return
result
Unary plus and minus signs
if
isinstance
(
node
,
ast.
UnaryOp
)
:
op_type
=
type
(
node.
op
)
if
op_type
not
in
(
ast.
UAdd
,
ast.
USub
)
:
raise
ValueError
(
"Unsupported operator"
)
return
OPERATORS
[
op_type
]
(
evaluate
(
node.
operand
)
)
raise
ValueError
(
"Unsupported expression"
)
return
evaluate
(
tree.
body
)
@
tool
def
calculate
(
expression:
str
)
str
:
"""Compute simple mathematical expressions, supporting addition, subtraction, multiplication, division, and parentheses.
Args:
expression: for example "3 * 7 + 2" or "(25 - 18)".
"""
try
:
result
=
safe_calculate
(
expression
)
return
f
"Calculation result: {expression} = {result}"
except
(
ValueError
,
SyntaxError
,
ZeroDivisionError
,
OverflowError
)
as
error:
return
f
"Calculation failed: {error}"
For example, calculate:
3 * 7 + 2
Tool returns:
计算结果:3 * 7 + 2 = 23
This calculator only supports limited mathematical syntax; it does not allow calling functions, accessing object attributes, or executing arbitrary Python code.
It is suitable for teaching demonstrations. In production applications, you should still limit input length, computation complexity, and execution resources according to business requirements.
Step 2: Create the Agent
After defining the tools, use create_agent() to combine the language model with the tools.
Example
from
langchain.
agents
import
create_agent
from
langchain.
chat_models
import
init_chat_model
Initialize the DeepSeek model
model
=
init_chat_model
(
"deepseek:deepseek-flash"
)
Creating the Agent
agent
=
create_agent
(
model
=
model
,
tools
=
[
get_weather
,
calculate
]
,
system_prompt
=
(
"You are a Chinese AI assistant."
"When answering weather questions, you must call get_weather first."
"get_weather returns mock data, not real-time weather."
"For arithmetic problems that require precise calculation, prefer calculate."
"If the tool has no relevant data, do not fabricate results."
)
,
)
Here, create_agent() creates an Agent execution graph powered by LangGraph.
The Agent executes the corresponding tools based on the tool-call requests returned by the model, and adds the tool results to the message history.
Common create_agent() parameters
| Parameters | Description | Required |
|---|---|---|
model |
Chat model instance or a supported model identifier string | Is |
tools |
List of tools available to the Agent | No |
system_prompt |
System prompt that defines the Agent's role and behavior | No |
middleware |
Used to extend the Agent's runtime behavior, such as logging, retries, model selection, etc. | No |
response_format |
Used to configure structured output | No |
checkpointer |
Configure state persistence and conversation checkpoints | No |
debug |
Enable debug information | No |
For beginners, you usually only need to focus on model、tools and system_prompt three parameters.
**Note:** When the tool list is empty, the Agent will not run a tool-calling loop, but can still use the language model to complete replies.
Step 3: Run the Agent
After the Agent is created, you can use invoke() Execute the task.
The input format is:
{
"messages": [
{
"role": "user",
"content": "杭州天气怎么样?"
}
]
}
where messages represents the list of messages sent to the Agent.
Example
Execute Agent
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"What's the mock weather like in Hangzhou?"
}
]
}
)
Output the final answer
(
result
[
"messages"
]
[
1
]
.
content
)
A sample answer might be:
杭州的模拟天气为晴天,气温25°C,湿度60%。
The answer here is based on get_weather() the mock data in it.
Because the Agent's tool selection and model output have a certain dynamism, actual answers may vary.
If you want to see the complete execution process, you can print the message history.
View the complete message history
Example
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"What's the mock weather like in Hangzhou?"
}
]
}
)
for
message
in
result
[
"messages"
]
:
(
"Message type:"
,
message.
type
)
View the tool calls requested by the model
if
message.
type
==
"ai"
and
message.
tool_calls
:
for
call
in
message.
tool_calls
:
(
"Tool name:"
,
call
[
"name"
]
)
(
"Tool arguments:"
,
call
[
"args"
]
)
View the tool return results
if
message.
type
==
"tool"
:
(
"Tool name:"
,
message.
name
)
(
"Tool results:"
,
message.
content
)
View the model's answer
if
message.
type
==
"ai"
and
not
message.
tool_calls
:
(
"AI reply:"
,
message.
content
)
(
"-"
40
)
A typical execution might look like:
消息类型: human
----------------------------------------
消息类型: ai
工具名称: get_weather
工具参数: {'city': '杭州'}
----------------------------------------
消息类型: tool
工具名称: get_weather
工具结果: 晴,25°C,湿度60%
----------------------------------------
消息类型: ai
AI 回复: 杭州的模拟天气是晴天,气温25°C,湿度60%。
----------------------------------------
Here you can see four messages:
- User message
HumanMessage。 - the one where the model initiates the tool call
AIMessage。 - Tool execution result
ToolMessage。 - the one where the model generates the final answer
AIMessage。
**Note:** For the AI message that requests a tool call, its content may be empty, but tool_calls still contains information such as the tool name and arguments.
IV. Agent Execution Flow Analysis
Below, using the weather query example, we explain the Agent's internal execution flow.

Step 1: Receive the user's question
User input:
杭州的模拟天气怎么样?
The Agent sends the user's message to the language model, while providing the currently available tool definitions.
Step 2: The model decides whether to call a tool
Based on the question, system prompt, and tool descriptions, the model may decide to use get_weather。
At this point, the message returned by the model may contain:
{
"name": "get_weather",
"args": {
"city": "杭州"
}
}
This is called a tool call request (Tool Call).
Note here:The model is responsible for making tool call requests, but this does not mean the model directly executes Python functions itself.
Step 3: The Agent executes the tool
LangChain finds the corresponding tool based on the tool call request and passes in the arguments.
For example:
get_weather(city="Hangzhou")
After execution, the tool returns:
晴,25°C,湿度60%
This result serves as a ToolMessage and is added to the message history.
Step 4: Call the model again
The model reads the tool execution result and decides whether other tools still need to be called.
If no further tool execution is needed, it generates the final answer.
If more data is needed, it can initiate another tool call.
Therefore, the core mechanism of the Agent can be summarized as:
Model → Tool Call → Tool Result → Model
This loop usually continues until the model no longer requests tools, or a stop condition such as an execution limit or error is reached.
V. Having the Agent Call Multiple Tools
The Agent can call not just one tool, but can combine multiple tools as needed by the task.
For example:
杭州和北京的模拟气温相差多少度?
For this question, the Agent may need to:
- Query the mock weather in Hangzhou.
- Query the mock weather in Beijing.
- Calculate the temperature difference between the two cities.
- Generate the final answer.
Example
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
(
"Please query the mock weather in Hangzhou and Beijing separately,"
"then use the calculate tool to compute the temperature difference between the two."
)
}
]
}
)
for
message
in
result
[
"messages"
]
:
if
message.
type
==
"ai"
and
message.
tool_calls
:
for
call
in
message.
tool_calls
:
(
f
"[Calling tool] {call['name']} "
f
"Arguments: {call['args']}"
)
elif
message.
type
==
"tool"
:
(
f
"[Tool result] {message.name}: "
f
"{message.content}"
)
(
"\nFinal answer:"
)
(
result
[
"messages"
]
[
1
]
.
content
)
One possible execution process is as follows:
[调用工具] get_weather 参数:{'city': '杭州'}
[调用工具] get_weather 参数:{'city': '北京'}
[工具结果] get_weather: 晴,25°C,湿度60%
[工具结果] get_weather: 多云,18°C,湿度45%
[调用工具] calculate 参数:{'expression': '25 - 18'}
[工具结果] calculate: 计算结果:25 - 18 = 7
Final Answer:
根据模拟数据,杭州为25°C,北京为18°C,
两地气温相差7°C。
The key point here is: the user does not need to write a fixed sequence of tool calls; the model can continue to choose tools based on the current task and the results already returned.
Are tools always executed in order?
Not necessarily.
If the model returns multiple tool call requests at once, LangChain's tool execution node can handle these calls, and independent calls may execute concurrently.
But the following situations may also occur:
- The model queries Hangzhou first, then Beijing.
- The model requests to query both cities at once.
- After obtaining the weather data, the model performs the simple subtraction itself without calling the calculator.
- The model calls the calculator according to the user's request, then generates the final answer.
Therefore,You cannot assume the Agent will definitely call three tools, nor can you guarantee that the two weather tool calls will run in parallel.
If a step must be executed, or must be completed in a specific order, it should be controlled through explicit program flow, tool orchestration, or a LangGraph workflow, rather than relying solely on prompts.
VI. Tool Calls and Message Types
During LangChain Agent execution, the following message types are mainly involved:
| Message types | Purpose |
|---|---|
HumanMessage |
Represents user input |
SystemMessage |
Provides system-level instructions to the model |
AIMessage |
Represents model output, which may contain tool call requests |
ToolMessage |
Represents the result returned after tool execution |
AIMessage.tool_calls
When the model needs to call a tool, it usually provides in its AIMessage the tool_calls。
For example:
[
{
"name": "get_weather",
"args": {"city": "杭州"},
"id": "call_example_001",
"type": "tool_call"
}
]
Where:
name: Tool name.args: the arguments passed to the tool.id: tool call identifier, used to associate the request with the tool result.type: the type of the message content.
The actual id is generated by the model provider or interface and should not be hard-coded in business code.
ToolMessage
After tool execution completes, LangChain uses ToolMessage to save the tool result.
A tool result usually contains:
name: get_weather
content: 晴,25°C,湿度60%
tool_call_id: call_example_001
tool_call_id Used to associate with the earlier tool call request.
This lets the model know which call each tool result corresponds to.
VII. Complete Runnable Example
Below, we integrate the previous tool definitions, model initialization, and Agent running code into a single Python file.
Filename:04_first_agent.py
Before running, make sure you have installed:
pip install -U langchain langchain-deepseek python-dotenv
and, in your project directory's .env file, configure DEEPSEEK_API_KEY。
Complete example
File: 04_first_agent.py
import
ast
import
operator
from
dotenv
import
load_dotenv
from
langchain.
tools
import
tool
from
langchain.
agents
import
create_agent
from
langchain.
chat_models
import
init_chat_model
Read environment variables
load_dotenv
(
)
-------------------------
Tool 1: Mock weather query
-------------------------
@
tool
def
get_weather
(
city:
str
)
str
:
"""Query simulated weather data for a specified city.
Args:
city: City name, such as Hangzhou, Beijing, Shanghai.
"""
weather_data
=
{
"Hangzhou"
:
"Sunny, 25°C, humidity 60%"
,
"Beijing"
:
"Cloudy, 18°C, humidity 45%"
,
"Shanghai"
:
"Light rain, 22°C, humidity 80%"
,
}
return
weather_data.
get
(
city
,
f
"No simulated weather data found for {city}"
)
-------------------------
Tool 2: Safe mathematical calculation
-------------------------
OPERATORS
=
{
ast.
Add
:
operator
.
add
,
ast.
Sub
:
operator
.
sub
,
ast.
Mult
:
operator
.
mul
,
ast.
Div
:
operator
.
truediv
,
ast.
UAdd
:
operator
.
pos
,
ast.
USub
:
operator
.
neg
,
}
def
safe_calculate
(
expression:
str
)
:
"""Only compute limited simple arithmetic expressions."""
if
len
(
expression
)
100
:
raise
ValueError
(
"Expression too long"
)
tree
=
ast.
parse
(
expression
,
mode
=
"eval"
)
def
evaluate
(
node
)
:
if
isinstance
(
node
,
ast.
Constant
)
:
if
type
(
node.
value
)
in
(
int
,
float
)
:
if
abs
(
node.
value
)
1
_000_000_000:
raise
ValueError
(
"Number too large"
)
return
node.
value
if
isinstance
(
node
,
ast.
BinOp
)
:
op_type
=
type
(
node.
op
)
if
op_type
not
in
OPERATORS:
raise
ValueError
(
"Unsupported operator"
)
a
=
evaluate
(
node.
left
)
b
=
evaluate
(
node.
right
)
if
op_type
is
ast.
Div
and
b
==
0
:
raise
ValueError
(
"Divisor cannot be zero"
)
result
=
OPERATORS
[
op_type
]
(
a
,
b
)
if
abs
(
result
)
1
_000_000_000:
raise
ValueError
(
"Calculation result too large"
)
return
result
if
isinstance
(
node
,
ast.
UnaryOp
)
:
op_type
=
type
(
node.
op
)
if
op_type
not
in
(
ast.
UAdd
,
ast.
USub
)
:
raise
ValueError
(
"Unsupported operator"
)
return
OPERATORS
[
op_type
]
(
evaluate
(
node.
operand
)
)
raise
ValueError
(
"Unsupported expression"
)
return
evaluate
(
tree.
body
)
@
tool
def
calculate
(
expression:
str
)
str
:
"""Compute simple arithmetic expressions, supporting addition, subtraction, multiplication, division, and parentheses.
Args:
expression: for example "3 * 7 + 2".
"""
try
:
result
=
safe_calculate
(
expression
)
return
f
"Calculation result: {expression} = {result}"
except
(
ValueError
,
SyntaxError
,
ZeroDivisionError
,
OverflowError
)
as
error:
return
f
"Calculation failed: {error}"
-------------------------
Creating the Agent
-------------------------
model
=
init_chat_model
(
"deepseek:deepseek-flash"
)
agent
=
create_agent
(
model
=
model
,
tools
=
[
get_weather
,
calculate
]
,
system_prompt
=
(
"You are a Chinese AI assistant."
"All data in the weather tool is mock data,"
"and must not be treated as real weather."
"Use get_weather first when answering weather questions."
"For arithmetic tasks that require precise calculation,"
"prefer the calculate tool."
"If a tool returns an error or has no data,"
"state this clearly and do not fabricate."
)
)
-------------------------
Execute Agent
-------------------------
def
ask
(
question:
str
)
:
(
"\n"
"="
50
)
(
"Question:"
,
question
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
: question
}
]
}
,
config
=
{
"recursion_limit"
:
15
}
)
Print the tool call process
for
message
in
result
[
"messages"
]
:
if
message.
type
==
"ai"
and
message.
tool_calls
:
for
call
in
message.
tool_calls
:
(
f
"[Tool call] {call['name']} "
f
"{call['args']}"
)
elif
message.
type
==
"tool"
:
(
f
"[Tool result] {message.name}: "
f
"{message.content}"
)
(
"Final answer: "
)
(
result
[
"messages"
]
[
1
]
.
content
)
return
result
-------------------------
Testing
-------------------------
if
name
==
"main"
:
Test the weather query
ask
(
"What's the mock weather like in Hangzhou?"
)
Test multiple tools
ask
(
"Query the mock weather in Hangzhou and Beijing,"
"then use calculate to compute the temperature difference between the two."
)
Test mathematical calculation
ask
(
"Please use the calculate tool to compute "
"the result of (3 + 2) * 7."
)
Run the Code
Execute in the terminal:
python 04_first_agent.py
The program sends three questions to the Agent in sequence and prints:
- The user's question.
- The tool calls initiated by the model and their arguments.
- The tool execution results.
- The Agent's final answer.
Because the way the model decides on tool calls may differ, the actual output order and text may not be exactly the same as the example.
However, if the Agent calls the tools correctly, you should be able to see something like the following in the output:
[工具调用] get_weather {'city': '杭州'}
[工具结果] get_weather: 晴,25°C,湿度60%
and:
[工具调用] calculate {'expression': '(3 + 2) * 7'}
[工具结果] calculate: 计算结果:(3 + 2) * 7 = 35
If the expected tool calls do not appear, check whether the model supports Tool Calling, whether the tool descriptions are clear, and whether the relevant system prompts are appropriate.
VIII. Synchronous and Asynchronous Calls
LangChain Agents support both synchronous and asynchronous calls.
Synchronous call: invoke()
The synchronous approach waits for the Agent to finish executing before returning a result.
result = agent.invoke({
"messages": [
{
"role": "user",
"content": "查询杭州的模拟天气"
}
]
})
Asynchronous call: ainvoke()
In an asynchronous program, you can use ainvoke()。
Example
import
asyncio
async
def
main
(
)
:
result
=
await agent.
ainvoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"What's the mock weather like in Hangzhou?"
}
]
}
)
(
result
[
"messages"
]
[
1
]
.
content
)
if
name
==
"main"
:
asyncio.
run
(
main
(
)
)
This code needs to run in a program where agent has already been defined.
Asynchronous calls are suitable for web services, chat systems, and other programs that use asyncio .
Note that if a tool contains time-consuming synchronous I/O internally, it may still affect concurrency performance. In real projects, you should use asynchronous tool implementations as needed.
IX. Agent Streaming Output
In addition to waiting for the Agent to complete its task, LangChain also supports streaming observation of the execution process.
You can use the agent.stream() together with stream_mode="updates", to view the state updates of each execution node of the Agent.
Example
inputs
=
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Query Hangzhou's mock weather."
}
]
}
for
update
in
agent.
stream
(
inputs
,
stream_mode
=
"updates"
)
:
for
node_name
,
state
in
update.
items
(
)
:
(
"Executing node:"
,
node_name
)
messages
=
state.
get
(
"messages"
,
[
]
)
for
message
in
messages:
if
message.
type
==
"ai"
and
message.
tool_calls
:
(
"Tool calls:"
,
message.
tool_calls
)
elif
message.
type
==
"tool"
:
(
"Tool results:"
,
message.
content
)
elif
message.
type
==
"ai"
:
(
"Model answer:"
,
message.
content
)
Use stream_mode="updates" , you can observe the updates after the model node and tool node execute.
This is suitable for debugging the Agent's runtime flow.
If you need to display the model's generated content token by token, you can further use the message stream mode supported by LangChain, but different models may differ in their support for streaming tool calls and output content.
X. Limiting Agent Execution Count
Since the Agent may loop between multiple tools, you need to consider the execution count and cost.
If the model repeatedly requests tools, it may produce:
- Unnecessary API call costs.
- Excessively long response times.
- Repeated external tool requests.
- Unexpected task execution.
You can set during execution recursion_limit, to limit the number of execution steps of LangGraph.
result = agent.invoke(
{
"messages": [
{
"role": "user",
"content": "查询杭州的模拟天气。"
}
]
},
config={
"recursion_limit": 15
}
)
Note:recursion_limit What is limited is the graph execution steps; it is not equivalent to precisely limiting the number of tool calls, nor is it a Token or cost cap.
Real applications should also set API timeouts, call budgets, concurrency limits, and necessary tool permissions.
XI. Common Questions
1. Why didn't the Agent call a tool?
Tool calls are decided by the model based on the question and tool definitions; not every question automatically triggers a tool.
Common reasons include:
- The question itself does not need external tools.
- The tool description is unclear.
- The model lacks reliable tool-calling capability.
- The model thinks it can answer directly.
You can improve the accuracy of tool calls by refining tool descriptions and system prompts.
But if a tool execution is a mandatory business step, it should be explicitly controlled by program logic rather than relying solely on prompts.
2. Why is AIMessage's content empty?
When the model requests a tool call, it may not generate ordinary text, but directly returns tool_calls。
For example:
message.content == ""
message.tool_calls != []
Therefore, you need to view both content and tool_calls, and cannot judge based only on content whether the model has output.
3. Why is the tool call order different from the example?
The Agent's tool selection and execution path are dynamic.
The same question may produce one tool call or multiple tool calls.
If multiple tool calls are independent of each other, the model may return multiple tool call requests in the same turn.
Therefore, the order of tool execution logs should not be treated as a fixed interface specification.
4. Why does the Agent call the model again after the tool returns a result?
Because the tool is only responsible for performing specific operations, such as querying data or computing expressions.
The model also needs to read the tool result and determine whether the task is complete.
If the task is not yet complete, the model can continue requesting tool calls; if it is complete, it generates the final answer.
5. Why might the Agent keep calling tools?
Repeated calls may occur when the information returned by the tool cannot satisfy the task, or the model keeps choosing the wrong tool.
This should be reduced through clear tool descriptions, error feedback, and execution limits.
For real applications, you can also use Agent middleware to control tool calls and model behavior.
6. How to integrate a real weather API?
You can think of get_weather() Replace the mock dictionary lookup in it with a real HTTP request.
When actually integrating, you need to handle:
- Conversion between city names and location codes.
- API Key and request authentication.
- Request timeouts and error responses.
- Data time, temperature units, and time zones.
- API call quotas and exception retries.
The tool should return weather data with clearly marked query times, to avoid the model mistaking historical or cached information for real-time results.
7. What is the difference between create_agent() and the older initialize_agent()?
LangChain 1.x recommends using create_agent() Create an agent.
It is based on LangGraph's execution mechanism and supports tool loops, state management, and extension capabilities such as middleware.
Some older tutorials use initialize_agent()、AgentExecutor or the older ReAct Agent API, which belong to previous versions and should not be mixed with this tutorial.
8. How to remember multi-turn conversations?
In this tutorial, each call to ask() passes in a new message list, so the examples treat each request as an independent task by default.
If you need to save conversation state across multiple requests, you can use LangGraph's checkpointer and other mechanisms, and assign corresponding thread identifiers to different conversations.
Conversation persistence is an advanced topic for later; this chapter first focuses on the basic workflow of the Agent.
Summary
This chapter uses LangChain to create a simple Agent that can call a weather tool and a calculation tool.
The whole process is divided into three main steps:
- Use
@toolDefine tools with decorators. - Use
create_agent()Combine the model and tools. - Use
agent.invoke()Execute the Agent and read the result.
To understand the Agent, you need to remember several key concepts:
- **The model is responsible for decisions:** it chooses whether to call a tool based on the messages and tool definitions.
- **The tool is responsible for execution:** it actually accesses data, performs calculations, or completes other operations.
- **The Agent is responsible for the loop:** it feeds tool results back to the model until a stop condition is met.
- **Tool calls are not a fixed flow:** the model may call a tool once, multiple times, or not at all.
- **Tool output is not necessarily trustworthy:** production environments need proper permission control, data validation, and error handling.
For beginners, it is recommended to first master @tool、create_agent() and invoke(), and then further study multi-turn conversation memory, streaming output, Agent middleware, and LangGraph workflows.