LangChain AgentState State Management
Agents need to maintain state during execution, such as conversation messages, tool execution results, learning progress, and structured output.
In LangChain 1.x, AgentState defines the agent's state structure, while LangGraph handles state updates, merging, and management.
This chapter covers AgentState's default fields, the Reducer merging mechanism, Middleware flow control, custom state, and how to manage state with Command and Checkpointer.
1. Basic AgentState Structure
AgentState is based on Python's TypedDict, and mainly contains the following three fields:
| Field | Required | Description |
|---|---|---|
messages |
Is | Message history, merged using add_messages |
jump_to |
No | Middleware's transient flow-control field |
structured_response |
No | Structured output result, not used as a normal input field |
You can check the current version's definition in Python:
Example
from
langchain.
agents
import
AgentState
for
name
,
annotation
in
AgentState.annotations.
items
(
)
:
(
name
,
annotation
)
(
"Required fields:"
,
AgentState.required_keys
)
(
"Optional fields:"
,
AgentState.optional_keys
)
The most commonly used is messages, which stores user messages, AI replies, and tool execution results.
**Note:** AgentState is only a state structure definition; it does not mean data has been saved to a database. Whether state can be restored across calls requires configuring a Checkpointer.
2. messages: Message History and Reducer
messages The add_messages Reducer is used to merge new and old messages.
It supports three main operations:
- **Append:** When a new message ID does not exist, add it to the message list.
- **Replace:** When a new message ID matches an existing one, replace the corresponding message.
- **Delete:** Use RemoveMessage to delete a message with a given ID.
1. Appending Messages
Example
from
langchain.
messages
import
HumanMessage
,
AIMessage
from
langgraph.
graph
.
message
import
add_messages
existing
=
[
HumanMessage
(
content
=
"Hello" (Chinese)
,
id
=
"1"
)
,
AIMessage
(
content
=
"Hello!"
,
id
=
"2"
)
]
new
=
[
HumanMessage
(
content
=
"Introduce Python"
,
id
=
"3"
)
]
result
=
add_messages
(
existing
,
new
)
(
"Before merging:"
,
len
(
existing
)
)
(
"After merging:"
,
len
(
result
)
)
for
msg
in
result:
(
msg.
id
,
msg.
type
,
msg.
content
)
Output:
合并前: 2
合并后: 3
1 human 你好
2 ai 你好!
3 human 介绍 Python
2. Replacing Messages with the Same ID
Example
from
langchain.
messages
import
AIMessage
from
langgraph.
graph
.
message
import
add_messages
old
=
[
AIMessage
(
content
=
"The original answer"
,
id
=
"msg_1"
)
]
new
=
[
AIMessage
(
content
=
"The modified answer"
,
id
=
"msg_1"
)
]
result
=
add_messages
(
old
,
new
)
(
len
(
result
)
,
result
[
0
]
.
content
)
Output:
1 修改后的回答
What is compared here is the message id, not the message content or message type.
3. Deleting Messages with RemoveMessage
Example
from
langchain.
messages
import
HumanMessage
,
AIMessage
,
RemoveMessage
from
langgraph.
graph
.
message
import
add_messages
messages
=
[
HumanMessage
(
content
=
"Hello" (Chinese)
,
id
=
"1"
)
,
AIMessage
(
content
=
"Hello!"
,
id
=
"2"
)
,
HumanMessage
(
content
=
"Introduce Python"
,
id
=
"3"
)
]
result
=
add_messages
(
messages
,
[
RemoveMessage
(
id
=
"2"
)
]
)
for
msg
in
result:
(
msg.
id
,
msg.
content
)
Output:
1 你好
3 介绍 Python
**Note:** When deleting tool-calling messages, consider the relationship between AIMessage and ToolMessage to avoid producing a message history that does not meet the model API's requirements.
3. jump_to: Middleware Flow Control
jump_to It lets Middleware control the agent's next execution direction at a specific stage.
| Value | Description |
|---|---|
"model" |
Redirect to the model execution flow |
"tools" |
Redirect to the tool node, requires a valid tool-call context |
"end" |
End the current main loop or enter the corresponding end hook |
jump_to It is transient state used to control execution flow and is not suitable for storing long-term business data.
Example: Ending an Agent Early
Below we use @before_model Intercept a demo keyword to show how to skip the model call.
Example
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
middleware
import
before_model
,
AgentState
from
langchain.
messages
import
AIMessage
from
langgraph.
runtime
import
Runtime
load_dotenv
(
)
@
before_model
(
can_jump_to
=
[
"end"
]
)
def
check_question
(
state: AgentState
,
runtime: Runtime
)
dict
|
None
:
"""Intercept the demo keyword."""
users
=
[
m
for
m
in
state
[
"messages"
]
if
m.
type
==
"human"
]
if
users
and
"BLOCK_DEMO"
in
str
(
users
[
1
]
.
content
)
:
return
{
"messages"
:
[
AIMessage
(
content
=
"The request was intercepted by the demo rule."
)
]
,
"jump_to"
:
"end"
}
return
None
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
middleware
=
[
check_question
]
,
system_prompt
=
"You are a Chinese programming assistant."
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"BLOCK_DEMO"
}
]
}
)
(
result
[
"messages"
]
[
1
]
.
content
)
Output:
请求已被演示规则拦截。
The middleware here checks messages before model execution; if the condition is met, it adds an AIMessage and jumps to the end flow.
Note:jump_to="tools" You cannot execute arbitrary Python functions out of thin air; the tool node still needs a valid tool-calling request.
4. structured_response: Structured Output
If structured output is set via create_agent() 's response_format a parameter, the agent stores the parsed result in structured_response。
This field usually does not need to be provided by the user when inputting the State, but can be obtained from the return value after execution completes.
Example: Recommending a Course
Example
from
pydantic
import
BaseModel
,
Field
from
langchain.
agents
import
create_agent
class
CourseRecommendation
(
BaseModel
)
:
"""Course recommendation."""
course:
str
=
Field
(
description
=
"Course name"
)
reason:
str
=
Field
(
description
=
"Reason for recommendation"
)
level:
str
=
Field
(
description
=
"Learning difficulty"
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
response_format
=
CourseRecommendation
,
system_prompt
=
"You are a programming learning advisor. Recommend a learning direction based on the user's needs."
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"I'm a complete beginner. Recommend a programming learning direction."
}
]
}
)
rec
=
result
[
"structured_response"
]
(
"Course:"
,
rec.
course
)
(
"Reason:"
,
rec.
reason
)
(
"Difficulty:"
,
rec.
level
)
If the model completes structured output correctly, you might get:
课程: Python 基础教程
理由: Python 语法简洁,适合零基础学习
难度: 入门
What is returned is a Pydantic data structure that matches the definition, rather than having to extract fields from natural language yourself.
The specific structured output mechanism is determined by the model and the LangChain integration. When the model does not support it, the Schema is incompatible, or parsing fails, an exception may be thrown.
5. Custom AgentState
Besides the default fields, you can add business state by subclassing AgentState.
For example, a learning assistant can store the learning level, completed topics, and current goal.
Example
from
typing_extensions
import
NotRequired
from
langchain.
agents
import
AgentState
class
LearningAgentState
(
AgentState
)
:
user_level: NotRequired
[
str
]
completed_topics: NotRequired
[
list
[
str
]
]
current_goal: NotRequired
[
str
]
where NotRequired indicating that the initial state may omit this field, but a default value is not set automatically.
When reading, it is recommended to use:
level = state.get("user_level", "入门")
topics = state.get("completed_topics", [])
Specify when creating the agent:
agent = create_agent(
model="deepseek:deepseek-flash",
tools=[],
state_schema=LearningAgentState
)
Note that custom State only describes fields; tools need to use the proper state update mechanism to modify these fields.
6. ToolRuntime: Reading Agent State
In LangChain 1.x, it is recommended to use ToolRuntime to access the current Agent State.
For example, you can read the learning level and completed topics in a tool:
Example
from
langchain.
tools
import
tool
,
ToolRuntime
@
tool
def
view_progress
(
runtime: ToolRuntime
)
str
:
"""View current learning progress."""
level
=
runtime.
state
.
get
(
"user_level"
,
"Beginner"
)
topics
=
runtime.
state
.
get
(
"completed_topics"
,
[
]
)
return
f
"Level: {level}; Completed: {', '.join(topics) if topics else 'none'}"
runtime It is injected by the agent execution framework; the model does not need to provide this parameter.
Therefore, do not assume that directly executing view_progress.invoke({}) will give you the complete Agent State.
If you need to modify the State, you should use the one introduced in the next section, Command。
7. Command: Updating AgentState
Directly modifying runtime.state the dictionaries or lists in it is not a reliable way to update state.
It is recommended to use Command(update=...) to submit changes.
Example: Recording a Learning Topic
Example
from
langchain.
tools
import
tool
,
ToolRuntime
from
langchain.
messages
import
ToolMessage
from
langgraph.
types
import
Command
@
tool
def
complete_topic
(
topic:
str
,
runtime: ToolRuntime
)
Command:
"""Mark the given learning topic as completed."""
topics
=
list
(
runtime.
state
.
get
(
"completed_topics"
,
[
]
)
)
if
topic
not
in
topics:
topics.
append
(
topic
)
return
Command
(
update
=
{
"completed_topics"
: topics
,
"messages"
:
[
ToolMessage
(
content
=
f
"Recorded completed topic: {topic}"
,
tool_call_id
=
runtime.
tool_call_id
)
]
}
)
Here it uses Command to update two fields at the same time:
completed_topics: store the new list of learning topics.messages: append a tool result associated with the current call ID.
In agent tool-calling scenarios, when returning a Command you should keep the corresponding ToolMessage to avoid breaking the message protocol.
**Note:** This uses a whole-list update. If multiple tools modify the same field in parallel, you need to design an additional Reducer or a sequential execution mechanism.
8. Complete Example: Learning Progress Agent
Next, we combine custom State, ToolRuntime, Command, and Checkpointer to create an agent that can record and query learning progress.
Filename:agent_state_demo.py
Install dependencies:
pip install -U langchain langchain-deepseek langgraph python-dotenv
Configure .env:
DEEPSEEK_API_KEY=your_deepseek_api_key
Complete example
from
typing_extensions
import
NotRequired
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
,
AgentState
from
langchain.
tools
import
tool
,
ToolRuntime
from
langchain.
messages
import
ToolMessage
from
langgraph.
types
import
Command
from
langgraph.
checkpoint
.
memory
import
InMemorySaver
load_dotenv
(
)
class
LearningState
(
AgentState
)
:
user_level: NotRequired
[
str
]
completed_topics: NotRequired
[
list
[
str
]
]
@
tool
def
complete_topic
(
topic:
str
,
runtime: ToolRuntime
)
Command:
"""Record a completed learning topic."""
topics
=
list
(
runtime.
state
.
get
(
"completed_topics"
,
[
]
)
)
if
topic
not
in
topics:
topics.
append
(
topic
)
return
Command
(
update
=
{
"completed_topics"
: topics
,
"messages"
:
[
ToolMessage
(
content
=
f
"Recorded: {topic}"
,
tool_call_id
=
runtime.
tool_call_id
)
]
}
)
@
tool
def
view_progress
(
runtime: ToolRuntime
)
str
:
"""Query current learning progress."""
level
=
runtime.
state
.
get
(
"user_level"
,
"Beginner"
)
topics
=
runtime.
state
.
get
(
"completed_topics"
,
[
]
)
return
f
"Level: {level}; Completed: {', '.join(topics) if topics else 'none'}"
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
complete_topic
,
view_progress
]
,
state_schema
=
LearningState
,
checkpointer
=
InMemorySaver
(
)
,
system_prompt
=
"You are a learning assistant. Call complete_topic when the user asks to record a topic, and view_progress when they ask to query progress."
)
config
=
{
"configurable"
:
{
"thread_id"
:
"learning_demo_001"
}
}
Round 1: Recording a Learning Topic
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"I've finished the Python basics. Please record that."
}
]
,
"user_level"
:
"Beginner"
,
"completed_topics"
:
[
"HTML basics"
]
}
,
config
=
config
)
(
"Round 1 state:"
,
result.
get
(
"completed_topics"
)
)
Round 2: Reading the Previously Saved State
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Query the topics I've completed."
}
]
}
,
config
=
config
)
(
"Round 2 state:"
,
result.
get
(
"completed_topics"
)
)
(
"AI:"
,
result
[
"messages"
]
[
1
]
.
content
)
Reading the state saved by the Checkpointer
snapshot
=
agent.
get_state
(
config
)
(
"Saved:"
,
snapshot.
values
.
get
(
"completed_topics"
,
[
]
)
)
If the model calls the tools correctly, the Round 1 state should contain:
['HTML 基础', 'Python 基础']
Round 2 uses the same thread_id, so it can read the previously saved state.
Here, InMemorySaver It only stores data in process memory. After the program exits, the state is usually lost.
**Note:** Whether the model calls a tool is not guaranteed. When business data must be recorded, it should be done by deterministic application logic rather than relying solely on the model to choose a tool.
9. Shopping Cart Agent: State Management in Practice
A shopping cart is another common custom State scenario.
For example, you need to store the list of cart items and calculate the total price from a product catalog.
The following uses mock product data; it does not create real orders or process payments.
To prevent the model from changing prices arbitrarily, product prices are determined by an internal catalog in the program, not passed in by the model.
Example
from
typing_extensions
import
NotRequired
from
langchain.
agents
import
create_agent
,
AgentState
from
langchain.
tools
import
tool
,
ToolRuntime
from
langchain.
messages
import
ToolMessage
from
langgraph.
types
import
Command
PRODUCTS
=
{
"Python Tutorial"
:
49.90
,
"Java Tutorial"
:
39.90
,
"HTML Tutorial"
:
29.90
}
class
ShoppingState
(
AgentState
)
:
cart: NotRequired
[
list
[
str
]
]
@
tool
def
add_to_cart
(
item:
str
,
runtime: ToolRuntime
)
Command:
"""Add a mock product to the cart."""
cart
=
list
(
runtime.
state
.
get
(
"cart"
,
[
]
)
)
if
item
in
PRODUCTS:
cart.
append
(
item
)
message
=
f
"Added: {item}"
else
:
message
=
f
"Item not found: {item}"
return
Command
(
update
=
{
"cart"
: cart
,
"messages"
:
[
ToolMessage
(
content
=
message
,
tool_call_id
=
runtime.
tool_call_id
)
]
}
)
@
tool
def
view_cart
(
runtime: ToolRuntime
)
str
:
"""View the cart and total price."""
cart
=
runtime.
state
.
get
(
"cart"
,
[
]
)
total
=
sum
(
PRODUCTS
[
item
]
for
item
in
cart
)
return
f
"Cart: {', '.join(cart) or 'empty'}; Total: ¥{total:.2f}"
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
add_to_cart
,
view_cart
]
,
state_schema
=
ShoppingState
,
system_prompt
=
"You are a mock shopping cart assistant. Product prices are based on the tool's catalog; do not create real orders."
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Add the Python Tutorial to the mock cart and view the cart."
}
]
,
"cart"
:
[
]
}
)
(
"Cart:"
,
result.
get
(
"cart"
,
[
]
)
)
(
"AI:"
,
result
[
"messages"
]
[
1
]
.
content
)
If the agent successfully executes the relevant tools, the cart state is:
['Python 教程']
The amount calculated by the tool is:
购物车:Python 教程;总价:¥49.90
Here, the model is not asked to provide price the parameter; instead, the program reads a predefined mock product catalog.
**Note:** If the model calls multiple tools that modify the cart in parallel, concurrent state conflicts may occur. A production-grade cart should be managed with database transactions or a dedicated state update mechanism.
10. Custom Reducer
Custom fields in AgentState typically use overwrite-style updates by default.
If multiple updates need to be merged, you can Annotated use a Reducer to do so.
Example: Appending a Learning Log
Example
import
operator
from
typing
import
Annotated
from
typing_extensions
import
NotRequired
from
langchain.
agents
import
AgentState
class
LearningState
(
AgentState
)
:
learning_logs: NotRequired
[
Annotated
[
list
[
str
]
,
operator
.
add
]
]
When the original state is:
["学习 HTML"]
the new update is:
["学习 Python"]
After the Reducer merges them, you get:
["学习 HTML", "学习 Python"]
Note thatoperator.add It is just list concatenation; duplicates are not removed automatically.
If you need unique records, strict ordering, or protection against duplicate execution, you should design a dedicated Reducer or handle it at the business layer.
11. state_schema and Middleware state_schema
Besides using create_agent(state_schema=...) to define global business state, Middleware can also declare its own extension fields.
| Method | Applicable scenarios |
|---|---|
create_agent(state_schema=...) |
Business state shared by the agent |
Middleware state_schema |
Middleware state such as model call counts and internal flow flags |
Do not assume that a field with the same name declared in create_agent will always override the field definition in Middleware. The types and Reducers of the two Schemas must remain compatible.
Example: Middleware Counting Model Calls
Example
from
typing_extensions
import
NotRequired
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
middleware
import
AgentState
,
after_model
from
langgraph.
runtime
import
Runtime
class
TrackingState
(
AgentState
)
:
model_call_count: NotRequired
[
int
]
@
after_model
(
state_schema
=
TrackingState
)
def
count_calls
(
state: TrackingState
,
runtime: Runtime
)
dict
:
"""Accumulate the model call count."""
return
{
"model_call_count"
: state.
get
(
"model_call_count"
,
0
)
1
}
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
middleware
=
[
count_calls
]
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Hello" (Chinese)
}
]
}
)
(
"Model call count:"
,
result.
get
(
"model_call_count"
)
)
For a simple task that calls the model only once, the output is usually:
模型调用次数: 1
If the agent needs multiple rounds of model calls, this count increases accordingly.
12. Checkpointer: Saving AgentState
By default, each agent call does not necessarily retain the previous session state.
If you need to restore messages and custom fields across calls, configure a Checkpointer and use thread_id to distinguish between sessions.
Example: Saving a Multi-turn Conversation
Example
from
langchain.
agents
import
create_agent
from
langgraph.
checkpoint
.
memory
import
InMemorySaver
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
checkpointer
=
InMemorySaver
(
)
)
config
=
{
"configurable"
:
{
"thread_id"
:
"session_001"
}
}
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"I'm learning Python."
}
]
}
,
config
=
config
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"What did I say I was learning earlier?"
}
]
}
,
config
=
config
)
(
result
[
"messages"
]
[
1
]
.
content
)
snapshot
=
agent.
get_state
(
config
)
(
"Message count: "
,
len
(
snapshot.
values
[
"messages"
]
)
)
Here, the same thread_idis used, so the second round can read the previously saved session messages.
but InMemorySaver It is not a disk-persistence solution.
When data must survive a service restart, use a database-backed Checkpointer.
13. The Difference Between AgentState and Store
| Dimension | AgentState | Store |
|---|---|---|
| Main Use | Messages and task state of the current thread | User preferences, long-term memory, and shared records |
| Across calls | Restored via Checkpointer | Read and written via Store |
| Data organization | State fields | Namespace and Key |
| Persistence | Depends on the Checkpointer | Depends on the Store implementation |
For example, a learning assistant can be designed like this:
AgentState:
当前对话历史
当前学习章节
本轮任务进度
Store:
用户已完成的全部课程
长期学习偏好
跨会话学习记录
For real business data that must be stored long-term, you should typically use a persistent Store or database rather than relying only on AgentState.
14. Frequently Asked Questions
1. Is AgentState a plain dictionary?
AgentState uses TypedDict to describe state and is usually passed as a dictionary at runtime, but the actual merge behavior is also controlled by Reducers and LangGraph's execution mechanism.
2. Does add_messages always only append messages?
No. It can also replace messages with the same ID and delete messages using RemoveMessage.
3. Can jump_to="tools" directly execute a Python function?
No. It only handles flow routing; the tool node still needs a valid tool-calling request.
4. Why doesn't structured_response exist?
Usually, response_formatit was not configured, or structured output did not complete successfully.
5. Why does directly modifying runtime.state have no effect?
Because this is not a reliable way to update graph state. Tools should use Command(update=...) to submit state changes.
6. Does Command need a ToolMessage?
In agent tool-calling scenarios, you should provide a ToolMessage corresponding to the current Tool Call ID, keeping the tool request and tool response correctly associated.
7. Can fields be omitted in custom State?
You can use the NotRequired Define optional fields, but you need to handle default values yourself when reading them.
8. How to resolve conflicts when multiple tools update state at the same time?
You can use an appropriate Reducer, limit parallel execution, or handle it through deterministic business logic.
9. Is State automatically saved to a database?
No. You need to configure a Checkpointer and choose a suitable persistence implementation.
10. Can AgentState store a user's long-term learning progress?
It can save thread state together with a Checkpointer. But for learning progress that must be shared across multiple sessions, a Store or business database is more suitable.
Summary
AgentState is the core of state management in LangChain agents.
This chapter mainly introduced:
messages: stores message history.add_messages: appends, replaces, and deletes messages.jump_to: controls Middleware flow jumps.structured_response: stores structured responses.state_schema: extends custom state fields.ToolRuntime: accesses State in tools.Command: submits state updates.Reducer: defines state merge rules.Checkpointer: saves and restores session state.
You can simply remember:
读取状态:runtime.state
更新状态:Command(update={...})
保存会话:checkpointer + thread_id
长期数据:Store