LangChain Agent Workflow
In the previous section, we learned about create_agent() the function's parameters and basic usage.
This chapter further explores the agent's internal execution mechanism: how the model selects tools, how tool results are returned to the model, under what conditions the agent ends, and how to observe the entire execution process through streaming interfaces.
In LangChain 1.x,create_agent() the agent execution graph is built on LangGraph, which automatically manages model calls, tool execution, and state updates.
This tutorial continues to use the DeepSeek Flash model and demonstrates with mock weather, mock time, and course query tools.
**Note:** This chapter uses the version="v2" streaming event format supported by LangGraph 1.1 and above. Older versions of LangGraph may return a different streaming structure.
1. The Agent's Basic Execution Loop
The core mechanism of an agent can be summarized as:
调用模型 → 判断工具调用 → 执行工具 → 再次调用模型
When the model returns a tool-call request, the agent executes the corresponding tool and adds the result to the message history.
The model can then continue processing the task based on the tool result.
The whole process usually continues until the model no longer requests tools, or until other stop, pause, or error conditions occur.
The basic flow of an agent is as follows:

The Model Node and the Tools Node
A typical agent can be abstracted into two core nodes:
| Node | Purpose |
|---|---|
model |
Call the language model to generate a reply or tool-call request |
tools |
Execute the client tools requested by the model and return the tool results |
For example, the user asks:
杭州的模拟天气和模拟时间分别是什么?
The model may generate two tool calls:
get_weather(city="Hangzhou")
get_time(city="Hangzhou")
After the tools finish executing, the results are returned as ToolMessage , and the model then generates the final answer.
**Note:** The model may request multiple tools at once or call tools over several rounds. Therefore, the node order and count in the execution graph are not fixed.
2. Installation and Environment Setup
This tutorial uses LangChain 1.x and adopts the LangGraph v2 streaming format.
Install or update dependencies:
pip install -U langchain langgraph langchain-deepseek python-dotenv
Use version="v2" LangGraph 1.1 or later is required.
In the project directory, .env File:
DEEPSEEK_API_KEY=your_deepseek_api_key
use the following when creating the model:
model = init_chat_model(
"deepseek:deepseek-flash"
)
Before making actual calls, make sure the API Key is correctly configured and that the corresponding model supports tool calling.
3. Tracing the Agent's Complete Execution Process
Next, define two tools:
get_weather(): returns mock weather.get_time(): returns mock time.
For easier observation, both tools use fixed dictionary data and do not call real weather or time APIs.
Example: Tracing Execution Nodes with updates
Example
File: agent_workflow.py
from
dotenv
import
load_dotenv
from
langchain.
tools
import
tool
from
langchain.
agents
import
create_agent
from
langchain.
chat_models
import
init_chat_model
load_dotenv
(
)
Tool 1: Mock Weather
@
tool
def
get_weather
(
city:
str
)
str
:
"""Query mock weather for a given city."""
weather_data
=
{
"Hangzhou"
:
"Sunny, 25°C"
,
"Beijing"
:
"Cloudy, 18°C"
}
return
weather_data.
get
(
city
,
f
"No mock weather data found for {city}"
)
Tool 2: Mock Time
@
tool
def
get_time
(
city:
str
)
str
:
"""Query mock time for a given city."""
time_data
=
{
"Hangzhou"
:
"14:30"
,
"Beijing"
:
"14:30"
,
"New York"
:
"02:30"
}
return
time_data.
get
(
city
,
f
"No mock time data found for {city}"
)
Initialize the model
model
=
init_chat_model
(
"deepseek:deepseek-flash"
)
Creating the Agent
agent
=
create_agent
(
model
=
model
,
tools
=
[
get_weather
,
get_time
]
,
system_prompt
=
(
"You are a Chinese assistant."
"The data in the weather and time tools is mock data."
"When users query this kind of data, you should use the tools."
"Do not treat mock data as real-time information."
)
)
User message
inputs
=
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
(
"Please query the mock weather of Hangzhou"
"and the mock time."
)
}
]
}
Tracing node updates
(
"=== Agent Execution Process ==="
)
event_count
=
0
for
event
in
agent.
stream
(
inputs
,
stream_mode
=
"updates"
,
version
=
"v2"
)
:
if
event
[
"type"
]
!=
"updates"
:
continue
event_count +
=
1
(
f
"\n--- Update event {event_count} ---"
)
v2 event data
updates
=
event
[
"data"
]
for
node_name
,
update
in
updates.
items
(
)
:
(
"Node:"
,
node_name
)
if
not
isinstance
(
update
,
dict
)
:
(
"Node data:"
,
update
)
continue
messages
=
update.
get
(
"messages"
,
[
]
)
for
message
in
messages:
if
message.
type
==
"ai"
and
message.
tool_calls
:
for
call
in
message.
tool_calls
:
(
"[Requesting tools]"
,
call
[
"name"
]
,
call
[
"args"
]
)
elif
message.
type
==
"tool"
:
(
"[Tool result]"
,
message.
name
,
message.
content
)
elif
message.
type
==
"ai"
:
(
"[Model reply]"
,
message.
text
)
Possible execution flow
If the model requests two tools in the same round, the log may look like:
=== Agent 执行过程 ===
--- Update Event 1 ---
节点: model
[请求工具] get_weather {'city': '杭州'}
[请求工具] get_time {'city': '杭州'}
--- Update Event 2 ---
节点: tools
[工具结果] get_weather 晴,25°C
[工具结果] get_time 14:30
--- Update Event 3 ---
节点: model
[模型回复] 杭州的模拟天气为晴天、25°C,
模拟时间为14:30。
This contains three node updates:
- **Model:** The model generates two tool-call requests.
- **Tools:** The tools execute, returning mock weather and time.
- **Model:** The model reads the tool results and generates an answer.
However,three updates are only one possible execution path。
The model may also call the weather tool first and the time tool in the next round, which would produce more node updates.
If multiple tools execute in the same round, the tool results are not necessarily completed in the order the model requested them.
4. Understanding the Agent's Message Changes
Besides observing nodes, you can also view the messages produced during execution.
A typical tool call involves the following messages:
HumanMessage
↓
AIMessage(tool_calls=[...])
↓
ToolMessage
↓
AIMessage(最终回答)
If the model requests two tools at once, the messages may be:
HumanMessage
↓
AIMessage(两个 tool_calls)
↓
ToolMessage(天气)
ToolMessage(时间)
↓
AIMessage(最终回答)
Where:
| Message types | Content |
|---|---|
HumanMessage |
User input |
AIMessage |
Model reply or tool-call request |
ToolMessage |
Tool execution result |
Note that an AIMessage containing a tool call may have empty plain-text content, but tool_calls still contains the tool request.
Therefore, when observing the agent workflow, you should check both:
message.content
message.tool_calls
message.type
Do not simply rely on whether content is empty to determine whether the model called a tool.
5. The stream_mode Parameter in Detail
agent.stream() Different streaming modes are supported to obtain data at different levels of granularity.
| Mode | Returns | Applicable scenarios |
|---|---|---|
updates |
State updates after node execution | Observe the agent's execution steps |
values |
Full state snapshots during graph execution | Inspect message history and state fields |
messages |
Language model message chunks and metadata | Streaming chat output |
custom |
Custom data sent by tools or graph nodes | Progress hints and task status |
debug |
Debug information related to graph execution | In-depth troubleshooting of the execution process |
updates、messages and custom is the mode emphasized in the official LangChain Agent getting-started documentation;values and debug For others, see the LangGraph streaming documentation.
Use version="v2" when streaming, events use a unified structure:
{
"type": "updates",
"ns": [],
"data": {
"model": {
"messages": [...]
}
}
}
Where:
type: the current streaming mode.ns: the graph or subgraph namespace the event belongs to.data: the specific event content.
Different stream_mode data values contain different content.
6. stream_mode="updates": Viewing Node Updates
updates It is used to observe the agent's execution steps.
Whenever a relevant node produces a state update, you receive a corresponding event.
Example
Example
for
event
in
agent.
stream
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please query Hangzhou's mock weather."
}
]
}
,
stream_mode
=
"updates"
,
version
=
"v2"
)
:
if
event
[
"type"
]
!=
"updates"
:
continue
for
node_name
,
update
in
event
[
"data"
]
.
items
(
)
:
(
"Node:"
,
node_name
)
if
isinstance
(
update
,
dict
)
:
for
message
in
update.
get
(
"messages"
,
[
]
)
:
(
message.
type
,
message.
content
)
If the model calls the weather tool, you may observe:
节点: model
ai
节点: tools
tool 晴,25°C
节点: model
ai 杭州的模拟天气为晴天,气温25°C。
This mode is suitable for debugging agent tool calls and for showing in the background which node is currently executing.
**Note:** One node update event does not necessarily equal one tool call. A single Tools node update may contain multiple tool results.
7. stream_mode="values": Viewing the Full State
updates mainly shows the changes produced by nodes, while values is used to observe the full state during execution.
For example, you can check the number of messages after each update.
Example
Example
inputs
=
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Query Hangzhou's mock weather."
}
]
}
snapshot_count
=
0
for
event
in
agent.
stream
(
inputs
,
stream_mode
=
"values"
,
version
=
"v2"
)
:
if
event
[
"type"
]
!=
"values"
:
continue
snapshot_count +
=
1
state
=
event
[
"data"
]
messages
=
state.
get
(
"messages"
,
[
]
)
(
f
"\nState snapshot {snapshot_count}:"
f
"{len(messages)} messages"
)
for
message
in
messages:
(
f
"[{message.type}]"
,
str
(
message.
content
)
[
:
80
]
)
If the tool-calling flow is:
用户 → 模型请求工具 → 工具返回 → 模型回答
then the observed message count may increase sequentially:
状态快照 1:1 条消息
状态快照 2:2 条消息
状态快照 3:3 条消息
状态快照 4:4 条消息
But the specific number of snapshots and messages depends on the actual execution path and should not be treated as a fixed result.
**Note:** Do not, merely to reduce the number of prints, arbitrarily break exit the streaming loop before execution is complete.
Stopping event consumption early may leave execution, resource cleanup, or subsequent result processing incomplete. Teaching examples recommend consuming the entire event stream.
8. stream_mode="messages": Streaming Text Generation
messages It is used to obtain message chunks produced during language model generation.
It is suitable for creating a ChatGPT-like streaming typing effect.
Note that what is streamed back is not necessarily a complete token, nor does it necessarily contain only plain text.
The model may produce:
- Text message chunks.
- Tool-call argument chunks.
- Reasoning content blocks.
- Response metadata.
Example: Outputting Model Text Step by Step
Example
from
langchain.
agents
import
create_agent
No tools are registered, making it easy to observe plain-text output
text_agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
)
(
"=== Streaming Output ==="
)
for
event
in
text_agent.
stream
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
(
"Introduce Runoob Tutorial RUNOOB in one sentence."
)
}
]
}
,
stream_mode
=
"messages"
,
version
=
"v2"
)
:
if
event
[
"type"
]
!=
"messages"
:
continue
message_chunk
,
metadata
=
event
[
"data"
]
Only display text output by the model node
if
metadata.
get
(
"langgraph_node"
)
==
"model"
:
(
message_chunk.
text
,
end
=
""
,
flush
=
True
)
(
)
In the code, the message_chunk is usually AIMessageChunk。
metadata can contain information such as the current node name.
Because different models may use different streaming response formats,message_chunk.text the content may be empty.
If the model returns non-text blocks such as tool calls or thinking content, you need to handle them according to the corresponding data structures.
Streaming Tool Calls
If the agent has registered tools, the model may also gradually return tool-call arguments during streaming output.
For example:
工具名称:get_weather
参数片段:{"city":
参数片段:"杭州"
参数片段:}
These chunks are not necessarily complete JSON.
You need to wait until the necessary message chunks are merged before you can understand the tool call as a complete request.
Therefore, when displaying the agent process, it is usually recommended to:
- Use
messagesShow the text being generated by the model. - Use
updatesShow completed tool calls and tool results.
9. stream_mode="custom": Custom Progress Events
Besides events produced by the model and graph nodes, developers can also send custom progress from within tools.
For example, a tool that processes many files can continuously report the current processed count.
LangChain provides a way to get_stream_writer() obtain a streaming writer.
Example: A Tool Sending Progress Updates
Example
from
langchain.
tools
import
tool
from
langchain.
agents
import
create_agent
from
langgraph.
config
import
get_stream_writer
@
tool
def
process_documents
(
task_name:
str
)
str
:
"""Simulate processing documents and send progress updates."""
writer
=
get_stream_writer
(
)
for
i
in
range
(
1
,
4
)
:
writer
(
{
"task"
: task_name
,
"current"
: i
,
"total"
:
3
,
"message"
: f
"Processed {i}/3 documents"
}
)
return
"Processing of the three mock documents is complete"
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
process_documents
]
,
system_prompt
=
(
"You are a document processing assistant."
"When the user asks to perform mock document processing,"
"call process_documents."
)
)
for
event
in
agent.
stream
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
(
"Please use the tool to simulate processing the test documents."
)
}
]
}
,
stream_mode
=
"custom"
,
version
=
"v2"
)
:
if
event
[
"type"
]
==
"custom"
:
(
event
[
"data"
]
)
If the model calls the tool, you may observe progress like:
{'task': '测试文档', 'current': 1, 'total': 3, 'message': '已处理 1/3 个文档'}
{'task': '测试文档', 'current': 2, 'total': 3, 'message': '已处理 2/3 个文档'}
{'task': '测试文档', 'current': 3, 'total': 3, 'message': '已处理 3/3 个文档'}
No files are actually read here; progress is only simulated through a loop.
Note:get_stream_writer() An appropriate LangGraph execution context is required. When you call the tool function containing it directly, you may not obtain the corresponding streaming writer.
In real projects, custom events can be sent to the frontend to show upload progress, data processing progress, or task stages.
10. Using Multiple stream_mode Values at Once
If you need to observe node updates and model text at the same time, you can pass multiple modes.
For example:
stream_mode=["messages", "updates"]
In the v2 format, all events use the same outer structure and can be event["type"] distinguished by their event type.
Example: Observing Tool Calls and Text Output Together
Example
inputs
=
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Query Hangzhou's mock weather."
}
]
}
for
event
in
agent.
stream
(
inputs
,
stream_mode
=
[
"messages"
,
"updates"
]
,
version
=
"v2"
)
:
mode
=
event
[
"type"
]
if
mode
==
"messages"
:
message_chunk
,
metadata
=
event
[
"data"
]
if
metadata.
get
(
"langgraph_node"
)
==
"model"
:
text
=
message_chunk.
text
if
text:
(
text
,
end
=
""
,
flush
=
True
)
elif
mode
==
"updates"
:
updates
=
event
[
"data"
]
for
node_name
,
update
in
updates.
items
(
)
:
if
not
isinstance
(
update
,
dict
)
:
continue
for
message
in
update.
get
(
"messages"
,
[
]
)
:
if
message.
type
==
"tool"
:
(
f
"\n[Tool {message.name}] "
f
"{message.content}"
)
(
)
This example assumes that the agent in the current program is the weather agent defined earlier.
If you use a different agent that does not include the weather tool, replace it with the corresponding tool and input.
Also, when using multiple streaming modes, do not confuse event data with the full execution state.
messages provides chunks from the model generation process,updates the other provides updates after nodes complete.
11. Under What Conditions Does an Agent Stop?
Normally, when the model no longer returns a tool-call request, the agent ends the current tool-calling loop.
But this is not the only stopping condition.
| Conditional | Behavior |
|---|---|
| No tool calls | The model generates a final answer and ends normally |
return_direct |
Ends after tool execution when the direct-return condition is met |
| Structured output complete | Ends when the completion condition of the structured output strategy is met |
| Middleware ends execution | Middleware can terminate the loop via supported execution-control mechanisms |
| Graph execution limit reached | May trigger corresponding exceptions or limit the processing flow |
| Execution interrupted | Pauses and waits for resume, not equal to normal completion |
| Model or tool error | May throw an exception or enter an error-handling flow |
1. The Model No Longer Calls Tools
This is the most common normal ending condition.
For example, the model receives a question and generates an answer directly:
AIMessage(
content="Python is a general-purpose programming language.",
tool_calls=[]
)
Since there is no tool-call request, the agent does not need to enter the Tools node again.
2、return_direct=True
In agents that support this behavior, when a tool sets return_direct=True , the loop can end once the direct-return condition is met.
Note that the current create_agent() implementation evaluates the direct-return settings of a batch of client tool calls collectively.
You cannot simply assume that if one tool in a batch sets return_direct=Trueit will end immediately.
Also, when returning directly, the last message may be ToolMessage。
3. Structured Output Complete
If both the create_agent() When response_formatis configured, the agent can end when the corresponding structured output strategy is satisfied.
Structured data is usually obtained through:
result["structured_response"]
.
Do not assume that just because a model reply looks like JSON, the agent has completed the structured output flow.
4. Middleware-Controlled Ending
LangChain middleware can control the agent's subsequent flow in the corresponding execution hooks.
For example, middleware can decide to end the current run based on the execution state.
But this requires using middleware state update or routing mechanisms supported by the current LangChain version, not modifying ordinary variables.
5. Execution Limits
If the agent keeps requesting tools, it may cause too many loop iterations.
can be used via recursion_limit Set a limit on the graph's execution steps.
But reaching the limit does not mean the task completed normally; it may raise an exception. GraphRecursionError。
6. Interruption and Pausing
The agent can also pause execution through LangGraph's interruption mechanism.
For example, waiting for user approval before executing a tool.
**Pausing is not the same as ending.** To continue the task, you need to follow the corresponding resume flow.
12. Example: Comparing Execution Flows With and Without Tools
Below, two agents are used to compare changes in message history.
Example
Example
from
langchain.
tools
import
tool
from
langchain.
agents
import
create_agent
Agent Without Tools
agent_without_tools
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
)
@
tool
def
search_course
(
keyword
:
str
)
str
:
"""Query mock courses for a given keyword."""
data
=
{
"python"
:
"Python Basics, Python Data Analysis"
,
"java"
:
"Java Fundamentals, Java Object-Oriented"
}
return
data.
get
(
keyword
.
lower
(
)
,
"No relevant mock courses found"
)
Agent With Tools
agent_with_tools
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
search_course
]
,
system_prompt
=
(
"You are a programming course assistant."
"Use the tool when querying courses."
"Tool results are mock data."
)
)
def
show_messages
(
agent
,
question
)
:
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
: question
}
]
}
)
(
"\nQuestion:"
,
question
)
(
"Total messages:"
,
len
(
result
[
"messages"
]
)
)
for
message
in
result
[
"messages"
]
:
if
message.
type
==
"ai"
and
message.
tool_calls
:
(
"[AI tool call]"
,
[
call
[
"name"
]
for
call
in
message.
tool_calls
]
)
elif
message.
type
==
"tool"
:
(
"[Tool result]"
,
message.
name
,
message.
content
)
else
:
(
f
"[{message.type}]"
,
str
(
message.
content
)
[
:
100
]
)
Without using tools
show_messages
(
agent_without_tools
,
"Introduce Python in one sentence."
)
Using tools
show_messages
(
agent_with_tools
,
"Please use the tool to search for Python courses."
)
The no-tool scenario generally contains a user message and a model reply.
In the tool scenario, if the model makes one tool call, it usually contains:
human
ai(包含 tool_calls)
tool
ai(最终回答)
However, if the model calls multiple tools or chooses no tool, the message count also changes.
Therefore, the total message count should not be the only criterion for judging whether tool execution succeeded.
A more reliable way is to check the corresponding tool_calls、ToolMessage and the final state.
13. Limiting the Agent's Execution Steps
An agent may call multiple tools in succession; if the tool results do not meet the task's needs, it may keep looping.
LangGraph provides recursion_limitfor limiting the number of graph execution steps.
Example
Example
from
langgraph.
errors
import
GraphRecursionError
try
:
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
(
"Please query Hangzhou's mock weather and mock time."
)
}
]
}
,
config
=
{
"recursion_limit"
:
15
}
)
(
result
[
"messages"
]
[
1
]
.
content
)
except
GraphRecursionError:
(
"The agent has reached the execution step limit,"
"the task did not complete normally."
)
Here, recursion_limit=15 It represents a step budget for graph execution, not a strict limit of at most 15 tool calls.
In real applications, you should also limit, based on business needs:
- The number of model calls.
- The number of tool calls.
- Request timeout.
- API token consumption.
- Maximum task execution duration.
If a task reaches a limit, you should clearly tell the user it did not complete, rather than disguising partial results as a success.
14. The Difference Between invoke() and stream()
LangChain agents support both synchronous and asynchronous calls, as well as complete results and streaming output.
| Method | Return method | Main scenario |
|---|---|---|
invoke() |
Wait synchronously for the execution result | Ordinary scripts, simple backend APIs |
ainvoke() |
Wait asynchronously for the execution result | Asynchronous web services |
stream() |
Iterate over streaming events synchronously | Execution tracing, real-time output |
astream() |
Iterate over streaming events asynchronously | SSE, WebSocket, asynchronous services |
Which method to choose depends on whether the application needs to display the execution process in real time and whether the program uses an asynchronous architecture.
Example: Asynchronous Streaming Calls
Example
import
asyncio
from
langchain.
agents
import
create_agent
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
)
async
def
main
(
)
:
async
for
event
in
agent.
astream
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Introduce three advantages of Python."
}
]
}
,
stream_mode
=
"messages"
,
version
=
"v2"
)
:
if
event
[
"type"
]
!=
"messages"
:
continue
message_chunk
,
metadata
=
event
[
"data"
]
if
metadata.
get
(
"langgraph_node"
)
==
"model"
:
(
message_chunk.
text
,
end
=
""
,
flush
=
True
)
(
)
if
name
==
"main"
:
asyncio.
run
(
main
(
)
)
This approach works well with asynchronous web frameworks such as FastAPI to implement streaming chat interfaces.
but astream() It is only an asynchronous event iterator and does not automatically create an SSE or WebSocket service. Event transport must still be handled by the web framework.
15. thread_id: Managing Different Conversation Threads
If you want the agent to retain conversation history across calls, you can use a Checkpointer together with thread_id。
thread_id to distinguish different sessions.
Note thatPassing thread_id alone does not automatically save conversation history; a Checkpointer must also be configured.
Example: Saving the History of the Same Conversation
Example
from
langchain.
agents
import
create_agent
from
langgraph.
checkpoint
.
memory
import
InMemorySaver
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
checkpointer
=
InMemorySaver
(
)
,
system_prompt
=
"You are a programming learning assistant."
)
config
=
{
"configurable"
:
{
"thread_id"
:
"conversation-001"
}
}
First round of conversation
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"I'm learning Python."
}
]
}
,
config
=
config
)
Second round of conversation
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"What did I say I was learning earlier?"
}
]
}
,
config
=
config
)
(
result
[
"messages"
]
[
1
]
.
content
)
Since both calls use the same thread_id, the second round can access the previous state saved by the Checkpointer.
InMemorySaver Data is saved only in the current Python process and is usually lost after the program exits.
If a real project needs to persist conversations long-term, it should use a database-backed Checkpointer.
stream() also supports thread_id
Example
Use the same Agent configured with a Checkpointer
for
event
in
agent.
stream
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Recommend another Python learning direction for me."
}
]
}
,
config
=
config
,
stream_mode
=
"updates"
,
version
=
"v2"
)
:
if
event
[
"type"
]
!=
"updates"
:
continue
(
event
[
"data"
]
)
Use invoke() and stream() can all be passed in config。
If you want to bind the configuration in advance, you can also use:
session_agent = agent.with_config(
configurable={
"thread_id": "conversation-001"
}
)
Then, through session_agent.invoke() or session_agent.stream() execute the call.
**Note:** In web applications, different users or sessions must use thread identifiers managed at the application layer, and permission isolation must be implemented to prevent one user from reading another user's chat history.
16. Complete Example: Tracking Both Tools and the Final Answer
The following integrates the previous material into a complete Agent workflow observation program.
Filename:agent_workflow_demo.py
Complete example
File: agent_workflow_demo.py
from
dotenv
import
load_dotenv
from
langchain.
tools
import
tool
from
langchain.
agents
import
create_agent
from
langchain.
chat_models
import
init_chat_model
load_dotenv
(
)
-------------------------
Simulated tools
-------------------------
@
tool
def
get_weather
(
city:
str
)
str
:
"""Query mock weather for a given city."""
data
=
{
"Hangzhou"
:
"Sunny, 25°C"
,
"Beijing"
:
"Cloudy, 18°C"
}
return
data.
get
(
city
,
"No simulated weather for this city"
)
@
tool
def
get_time
(
city:
str
)
str
:
"""Query mock time for a given city."""
data
=
{
"Hangzhou"
:
"14:30"
,
"Beijing"
:
"14:30"
}
return
data.
get
(
city
,
"No simulated time for this city"
)
-------------------------
Creating the Agent
-------------------------
model
=
init_chat_model
(
"deepseek:deepseek-flash"
,
timeout
=
30
,
max_retries
=
2
)
agent
=
create_agent
(
model
=
model
,
tools
=
[
get_weather
,
get_time
]
,
system_prompt
=
(
"You are a Chinese assistant."
"The data provided by the tools is all simulated."
"Use tools when encountering weather or time queries."
"Do not claim that simulated data is real-time data."
)
)
-------------------------
Track the execution process
-------------------------
def
trace_agent
(
question:
str
)
:
inputs
=
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
: question
}
]
}
final_ai_message
=
None
(
"\nQuestion:"
,
question
)
(
"="
50
)
for
event
in
agent.
stream
(
inputs
,
stream_mode
=
"updates"
,
version
=
"v2"
,
config
=
{
"recursion_limit"
:
15
}
)
:
if
event
[
"type"
]
!=
"updates"
:
continue
for
node_name
,
update
in
event
[
"data"
]
.
items
(
)
:
(
"\nExecution node:"
,
node_name
)
if
not
isinstance
(
update
,
dict
)
:
continue
for
message
in
update.
get
(
"messages"
,
[
]
)
:
if
message.
type
==
"ai"
:
if
message.
tool_calls
:
for
call
in
message.
tool_calls
:
(
"[Tool request]"
,
call
[
"name"
]
,
call
[
"args"
]
)
else
:
final_ai_message
=
message
elif
message.
type
==
"tool"
:
(
"[Tool result]"
,
message.
name
,
message.
content
)
(
"\n=== Final answer ==="
)
if
final_ai_message
is
not
None
:
(
final_ai_message.
content
)
else
:
(
"No complete final AI response was observed,"
"Please check the execution process."
)
if
name
==
"main"
:
trace_agent
(
"Please query Hangzhou's mock weather and mock time."
)
Run:
python agent_workflow_demo.py
If the Agent completes the model tool request, tool execution, and final reply in sequence, you can observe the entire workflow.
This type of tracking method is suitable for:
- Checking whether the Agent selects the correct tool.
- Seeing what parameters the tool actually used.
- Observing whether the tool returns the expected data.
- Determining whether duplicate calls occur.
- Analyzing the Agent's execution path.
Because model behavior is dynamic, the order of tool calls, the number of events, and the final wording may vary.
17. Frequently Asked Questions
1. Does the Agent always call tools?
Not necessarily.
Even if tools are registered, the model may decide that no tool is needed and generate an answer directly.
If the business requires that a tool must be executed, this should be explicitly controlled in the program or workflow.
2. Why does a single Model node request multiple tools?
Because some models that support Tool Calling can produce multiple tool call requests in a single response round.
For example, querying the weather of two cities at the same time.
However, whether multiple tool calls are used still depends on the model and related settings.
3. Does stream_mode="messages" return one Token at a time?
Not necessarily.
It returns message chunks and metadata. A chunk may contain a piece of text, part of a tool argument, or other structured content.
4. Why is the number of events from stream_mode="updates" not fixed?
Because the Agent's execution path is dynamic.
The model may reply directly, call one or more tools, or perform multiple rounds of tool calls.
5. Why is the Agent's last message not an AIMessage?
It may be because the tool used return_direct=True, and the Agent ended directly after the tool execution.
It may also be because the graph is in a paused or error state and has not yet produced a final reply.
You should judge based on the specific execution state.
6. Why isn't the conversation remembered after setting thread_id?
Because thread_id It is only a conversation identifier.
You also need to configure a Checkpointer in order to save and restore conversation state.
7. Is recursion_limit equal to the maximum number of tool calls?
No.
It limits the number of graph execution steps, not strictly the number of model requests or tool calls.
8. How can I view the complete Agent state?
You can use the stream_mode="values" Observe the state snapshots during execution.
If a Checkpointer is configured, you can also use, after execution, get_state(config) to view the saved state.
9. How can I display Agent execution progress on the frontend?
You can use the stream_mode="updates" Display node execution steps, via messages display text being generated, via custom display business progress.
Then use a backend framework such as FastAPI to convert events into SSE or WebSocket messages.
10. What is the new Event Streaming API?
LangChain v1.3 introduced a new Event Streaming API, such as stream_events(), providing separate ways to access different types of events.
For newly developed complex streaming applications, the official recommendation is to consider this approach.
But this tutorial first uses stream() and astream() as the main approach, to make it easier to understand the Agent's execution nodes, message chunks, and basic loop mechanism.
Summary
The core working mechanism of a LangChain Agent is:
模型 → 工具调用 → 工具结果 → 模型
Use create_agent() After that, this process is managed by the LangGraph execution graph.
This chapter introduces:
- The execution relationship between the Model node and the Tools node.
stream_mode="updates": Observe node updates.stream_mode="values": Observe the complete state.stream_mode="messages": Stream model messages.stream_mode="custom": Send custom progress.- Combine multiple streaming modes to observe the Agent.
- The Agent's normal termination, pause, and error conditions.
recursion_limit: Limit the number of graph execution steps.thread_idand Checkpointer: Save multi-turn conversations.
For beginners, it is recommended to first master:
for event in agent.stream(
inputs,
stream_mode="updates",
version="v2"
):
print(event["data"])
By observing the updates of the model node and tool nodes, you can more intuitively understand what happens at each step of the Agent.
**Finally, remember:** The Agent's execution path is not a fixed script. The model is responsible for proposing the next action, the tools are responsible for execution, and LangGraph manages the entire execution flow and its state.