LangChain Agent API Reference
LangChain 1.x provides a unified Agent API that combines large language models, tool calling, Middleware, conversation memory, and structured output into a runnable agent.
The most core function among these is create_agent().
Unlike the older AgentExecutor, LangChain 1.x's create_agent() is implemented on top of LangGraph and returns a compiled CompiledStateGraph, supporting synchronous, asynchronous, and streaming output, state persistence, and human intervention.
This chapter systematically covers the complete parameters of create_agent(), common methods of CompiledStateGraph, the AgentState structure, runtime context, and the practical usage of various configurations.
1. What is create_agent()?
create_agent() It is the core entry point for creating an Agent in LangChain 1.x.
A typical Agent execution flow is as follows:
用户消息
↓
Agent
↓
调用 Chat Model
↓
是否需要工具?
|
├── 否 → 生成最终回复 → 结束
|
└── 是 → 调用 Tool
↓
工具结果
↓
再次调用模型
↓
循环判断
Developers only need to provide the model, tools, and necessary configuration, and LangChain automatically orchestrates the execution loop between the model and tools.
The simplest Agent
Example
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
load_dotenv
(
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
]
,
system_prompt
=
"You are a Python programming assistant."
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"What is Python?"
}
]
}
)
(
result
[
"messages"
]
[
1
]
.
content
)
No tools are registered here, so the Agent mainly performs model calls and does not enter a normal tool-calling loop.
If tools are provided, the model can choose to call the appropriate tool based on the question.
2. Complete function signature of create_agent()
The main function signature of LangChain's current API is as follows:
create_agent(
model,
tools=None,
*,
system_prompt=None,
middleware=(),
response_format=None,
state_schema=None,
context_schema=None,
checkpointer=None,
store=None,
interrupt_before=None,
interrupt_after=None,
debug=False,
name=None,
cache=None,
transformers=None
)
where model is a required parameter; all other parameters have default values.
Parameter quick reference table
| Parameters | Type | Default value | Description |
|---|---|---|---|
model |
str | BaseChatModel | Required | Chat model or model identifier |
tools |
Sequence | None | None | List of available tools |
system_prompt |
str | SystemMessage | None | None | System prompt |
middleware |
Sequence[AgentMiddleware] | () | Agent middleware |
response_format |
ResponseFormat | type | dict | None | None | Structured output configuration |
state_schema |
type[AgentState] | None | None | Custom Agent state structure |
context_schema |
type | None | None | Runtime context type |
checkpointer |
Checkpointer | None | None | Conversation and execution state persistence |
store |
BaseStore | None | None | Cross-session long-term data storage |
interrupt_before |
list[str] | None | None | Pause before a specified node executes |
interrupt_after |
list[str] | None | None | Pause after a specified node executes |
debug |
bool | False | Enable graph execution debug logging |
name |
str | None | None | Name of the Agent graph |
cache |
BaseCache | None | None | Graph execution cache backend |
transformers |
Sequence[TransformerFactory] | None | None | Register additional stream event transformers |
There appear to be many parameters, but in actual development you usually only need model, tools, and system_prompt.
As features grow, you can gradually add configurations such as Middleware, Checkpointer, and Store.
3. model: Language model
model Specifies the large language model used by the Agent.
Two ways are supported:
- A model name string.
- A BaseChatModel instance.
Method 1: Specifying the model with a string
Example
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
]
)
Strings generally take the form:
provider:model_name
You need to install the integration package for the corresponding model provider in advance.
For example, DeepSeek:
pip install -U langchain-deepseek
Method 2: Passing in a model instance
Example
from
langchain_deepseek
import
ChatDeepSeek
model
=
ChatDeepSeek
(
model
=
"deepseek-chat"
,
temperature
=
0
,
timeout
=
30
,
max_retries
=
2
)
agent
=
create_agent
(
model
=
model
,
tools
=
[
]
)
This approach suits scenarios that require configuring timeouts, retries, and other model parameters.
**Note:** The model must have the corresponding capabilities. For example, if the Agent needs to call tools, the underlying model and integration interface must support tool calling.
4. tools: Registering tools
tools Specifies the collection of tools the Agent can use.
Common tool forms include:
- Use
@toolDecorated functions. - BaseTool instances.
- Python Callables that meet the requirements.
- Supported tool definition dictionaries.
Pydantic BaseModel is typically used to define tool parameter Schemas, rather than directly replacing executable Python tool functions.
Example: Registering multiple tools
Example
from
langchain.
agents
import
create_agent
from
langchain.
tools
import
tool
@
tool
def
get_weather
(
city:
str
)
str
:
"""Query simulated city weather."""
return
f
"{city}: Simulated sunny, 25°C"
@
tool
def
calculate_sum
(
a:
float
,
b:
float
)
float
:
"""Calculate the sum of two numbers."""
return
a + b
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
get_weather
,
calculate_sum
]
,
system_prompt
=
"You are a tool assistant. Choose the appropriate tool based on the user's question."
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please use a tool to calculate 25 plus 17."
}
]
}
)
(
result
[
"messages"
]
[
1
]
.
content
)
The model can choose which tool to call based on the tool name, description, and parameter Schema.
**Note:** Registering a tool does not mean the model will necessarily call it. If a business must perform a certain operation, use a deterministic workflow or further constrain the execution flow.
5. system_prompt: System prompt
system_prompt Used to define the Agent's role, goals, and behavior rules.
Supports a plain string or SystemMessage.
Example
Example
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
]
,
system_prompt
=
"""You are the Python learning assistant for Runoob Tutorial RUNOOB.
Answer requirements:
- Prefer Chinese.
- Give concise technical explanations.
- Provide code examples when necessary.
- Do not fabricate information you are unsure about."""
)
system_prompt is used as the system message during model calls.
If you need to dynamically generate prompts based on time, user identity, or other context, you can use @dynamic_prompt Middleware。
**Note:** system_prompt cannot replace authentication, database permissions, or tool execution security checks in your program.
6. middleware: Agent middleware
middleware Used to add custom logic during Agent execution.
For example:
- Inspect messages before a model call.
- Dynamically modify the system prompt.
- Limit the number of tool calls.
- Automatically retry when the model fails.
- Request human approval before executing sensitive tools.
Common Middleware Hooks
| Hook | Execution Timing |
|---|---|
before_agent |
When the Agent starts executing |
before_model |
Before each model call |
after_model |
After each model call |
after_agent |
After the Agent completes normally |
wrap_model_call |
Wraps the model call, allowing modification of requests and handling of responses |
wrap_tool_call |
Wraps tool execution, supporting exception handling and retries |
dynamic_prompt |
Dynamically generate the model's system prompt |
Example: Using a dynamic prompt
Example
from
datetime
import
datetime
from
langchain.
agents
.
middleware
import
dynamic_prompt
,
ModelRequest
@
dynamic_prompt
def
inject_date
(
request: ModelRequest
)
str
:
today
=
datetime
.
now
(
)
.
date
(
)
.
isoformat
(
)
return
f
"You are a Python learning assistant. Current server date: {today}."
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
]
,
middleware
=
[
inject_date
]
)
If you need the user's local date, use a trusted user time zone rather than relying directly on the server's default time.
Multiple Middleware can be combined. For wrapping-style Hooks, the earlier Middleware in the list is usually on the outside.
7. response_format: Structured output
response_format Used to make the Agent return structured data conforming to a specified Schema.
Supports passing in a Pydantic model directly, or explicitly specifying a structured output strategy.
Main strategies
| Strategy | Description |
|---|---|
ToolStrategy |
Use the model's tool-calling capability to generate structured output |
ProviderStrategy |
Use the provider's native structured output capability |
AutoStrategy |
Select an appropriate strategy based on model capabilities |
When passing in a Schema directly, LangChain can try to select an appropriate strategy based on model capabilities.
Example: Pydantic structured output
Example
from
pydantic
import
BaseModel
,
Field
from
langchain.
agents
.
structured_output
import
ToolStrategy
class
CourseInfo
(
BaseModel
)
:
name:
str
=
Field
(
description
=
"Course name"
)
level:
str
=
Field
(
description
=
"Course difficulty"
)
language:
str
=
Field
(
description
=
"Programming Language"
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
]
,
response_format
=
ToolStrategy
(
CourseInfo
)
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Extract: Python3 Fundamentals Tutorial, beginner level, Python language."
}
]
}
)
(
result
[
"structured_response"
]
)
Structured output is usually stored in:
result["structured_response"]
It differs from the ordinary:
result["messages"][-1].content
in how data is read.
**Note:** Not every model supports all structured output strategies. Structured data passing Schema validation does not mean the business facts within it have been verified.
8. state_schema: Custom Agent state
state_schema Used to extend the Agent's state structure.
The default state mainly stores messages, flow control, and an optional structured response.
If you need to add business fields, you can define a TypedDict that inherits from AgentState.
Example: Adding a task category
Example
from
typing
import
NotRequired
from
langchain.
agents
import
AgentState
,
create_agent
class
CustomState
(
AgentState
)
:
task_category: NotRequired
[
str
]
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
]
,
state_schema
=
CustomState
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Hello" (Chinese)
}
]
,
"task_category"
:
"general"
}
)
(
"Task category: "
,
result.
get
(
"task_category"
)
)
Here a normal state field is extended:
task_category
Note that defining a state field does not automatically make the model update it.
If you want to modify the field during execution, you need to explicitly return a state update in the corresponding Middleware, tool, or custom node.
**Recommendation:** If a state field only serves one Middleware, you can place its state Schema within that Middleware to avoid the global AgentState continuously growing.
9. context_schema: Runtime context
context_schema Used to define context information passed in during execution.
For example:
- Current user ID.
- The user's time zone.
- The tenant the application belongs to.
- Business permission information for the current request.
The difference between runtime context and AgentState is:
| compares | Agent State | Runtime Context |
|---|---|---|
| Main Use | Stores state during execution | Provides external context for the current request |
| Whether it's suitable to be updated by nodes | Can be modified through state updates | Usually used as read-only configuration for the current execution |
| Whether it is saved by the Checkpointer | You can | Not automatically persisted as state |
| Typical contents | messages, task progress | user_id、timezone |
Example: Injecting user identity into a tool
Example
from
dataclasses
import
dataclass
from
langchain.
agents
import
create_agent
from
langchain.
tools
import
tool
,
ToolRuntime
@
dataclass
class
UserContext:
user_id:
str
@
tool
def
get_my_profile
(
runtime: ToolRuntime
[
UserContext
]
)
str
:
"""View the current user's simulated account identifier."""
return
f
"Current user ID: {runtime.context.user_id}"
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
get_my_profile
]
,
context_schema
=
UserContext
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please call a tool to view my account identifier."
}
]
}
,
context
=
UserContext
(
user_id
=
"student-001"
)
)
(
result
[
"messages"
]
[
1
]
.
content
)
Here, runtime.context.user_id Tool-call arguments are not generated by the model, but provided by the application caller.
**Security reminder:** In a web service, user_id must be determined by a trusted backend based on login status; you must not allow the browser to pass in arbitrary user IDs.
10. checkpointer: Conversation persistence
checkpointer Used to save the Agent's execution state within the same thread.
Common applications include:
- Multi-turn conversation memory.
- Resuming interrupted execution.
- Viewing historical state.
- Debugging a particular conversation thread.
Example: InMemorySaver
Example
from
langgraph.
checkpoint
.
memory
import
InMemorySaver
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
]
,
checkpointer
=
InMemorySaver
(
)
)
config
=
{
"configurable"
:
{
"thread_id"
:
"conversation-001"
}
}
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"I'm learning Python."
}
]
}
,
config
=
config
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"What did I just say I was learning?"
}
]
}
,
config
=
config
)
(
result
[
"messages"
]
[
1
]
.
content
)
Under the same thread_id, the Agent can continue using the previously saved message history.
InMemorySaver is suitable for testing; the in-memory state is lost after the process exits.
Production systems can choose persistent Checkpointers such as SQLite or PostgreSQL.
**Note:** thread_id is a session identifier, not a security credential. Business systems must verify which user a session belongs to.
11. store: Cross-session long-term storage
store Its purpose differs from that of checkpointer.
Checkpointer mainly saves execution state within a single thread, while Store can save long-term data shared across threads.
For example:
用户 student-001
|
├── 会话 A
├── 会话 B
└── 会话 C
|
↓
共享 Store
|
↓
Python 学习偏好
Example: Configuring InMemoryStore
Example
from
langgraph.
store
.
memory
import
InMemoryStore
store
=
InMemoryStore
(
)
store.
put
(
(
"users"
,
"student-001"
)
,
"learning_preference"
,
{
"language"
:
"Python"
,
"level"
:
"beginner"
}
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
]
,
store
=
store
)
item
=
store.
get
(
(
"users"
,
"student-001"
)
,
"learning_preference"
)
(
item.
value
)
This only demonstrates creating and reading from a Store.
**Note:** Passing a store to the Agent does not automatically inject all data in the Store into the model context.
You need to explicitly read the required data through tools, Middleware, or other business logic.
12. interrupt_before and interrupt_after
These two parameters are used to set static interrupt points.
Common node names include:
model
tools
| Parameters | Pause timing |
|---|---|
interrupt_before=["tools"] |
Before the tool node executes |
interrupt_after=["tools"] |
After the tool node executes |
interrupt_before=["model"] |
Before the model node executes |
interrupt_after=["model"] |
After the model node executes |
Example: Pausing before tool execution
Example
from
langgraph.
checkpoint
.
memory
import
InMemorySaver
from
langchain.
tools
import
tool
@
tool
def
delete_demo_item
(
item_id:
str
)
str
:
"""Simulate deleting a piece of data."""
return
f
"Simulated deletion: {item_id}"
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
delete_demo_item
]
,
checkpointer
=
InMemorySaver
(
)
,
interrupt_before
=
[
"tools"
]
,
system_prompt
=
"You are a management assistant. Use delete_demo_item when the user requests a simulated deletion."
)
config
=
{
"configurable"
:
{
"thread_id"
:
"approval-demo-001"
}
}
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please use a tool to simulate deleting item-001."
}
]
}
,
config
=
config
)
state
=
agent.
get_state
(
config
)
(
"Next node: "
,
state.
next
)
If the model decides to call a tool, the Agent can pause before the tools node executes.
Note:
- Interrupt points need to be used together with a Checkpointer to reliably resume execution.
- Pausing before the tools node does not mean pausing only a specific tool.
- Static interrupts by themselves do not automatically implement full approval and permission checks.
If you need to approve, reject, or modify arguments for an individual tool, it's more appropriate to use interrupt() or HumanInTheLoopMiddleware.
13. debug: Debug mode
debug=True It can output more detailed graph execution information during execution.
Example
Example
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
]
,
debug
=
True
)
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Hello" (Chinese)
}
]
}
)
This approach is suitable for troubleshooting the execution process during local development.
However, you should not rely on a fixed Debug text format, because the actual output may change with LangChain and LangGraph versions.
For production, it's recommended to use structured logging and observability tools such as LangSmith rather than outputting full debug data long-term.
14. name: Agent name
name Used to specify a name for the compiled Agent graph.
For example:
Example
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
]
,
name
=
"python_learning_agent"
)
In multi-Agent projects, you can use:
coordinator
course_expert
math_expert
code_reviewer
These names help with graph composition and tracing.
When an Agent is embedded as a subgraph in other LangGraph graphs, name can also serve as the corresponding graph identifier.
But you cannot assume name will automatically become the name field of all AIMessages.
15. cache: Graph execution caching
cache Used to configure the LangGraph graph execution cache backend.
For example:
Example
from
langgraph.
cache
.
memory
import
InMemoryCache
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
]
,
cache
=
InMemoryCache
(
)
)
Here a cache backend is provided for the Agent graph.
**Note:** Setting cache does not mean all model calls and tool results are automatically cached.
Whether the cache is hit also depends on the corresponding nodes having appropriate caching strategies.
If you want to cache specific model responses or retrieval results, you should design them separately based on the specific cache layer and business needs.
16. transformers: Stream event transformers
transformers Used to register additional StreamTransformer factories.
It belongs to relatively advanced graph streaming capabilities and can be used to adjust or extend how stream events are handled.
General Agent development usually does not need to set it.
If you only want to output model text or tool execution status, prefer using:
agent.stream(..., stream_mode="updates")
agent.stream(..., stream_mode="messages")
Only consider transformers when you genuinely need custom stream event transformation logic.
Therefore, for ordinary tutorials and business Agents, keeping the default value None is fine.
17. Common methods of CompiledStateGraph
create_agent() returns a CompiledStateGraph。
This means the created Agent can not only be invoked, but also supports streaming execution, state queries, and historical checkpoint management.
| Method | Purpose | Typical return values |
|---|---|---|
invoke() |
Execute the Agent synchronously | Final state |
ainvoke() |
Execute the Agent asynchronously | Final state |
stream() |
Synchronous streaming execution | Event iterator |
astream() |
Asynchronous streaming execution | Asynchronous event iterator |
get_state() |
Get a thread state snapshot | StateSnapshot |
aget_state() |
Read state asynchronously | StateSnapshot |
get_state_history() |
Get historical checkpoints | StateSnapshot iterator |
update_state() |
Update thread state | Checkpoint configuration |
get_graph() |
Get a graph structure representation | Graph object |
These methods come from the LangGraph and Runnable interfaces, and in fact support more configuration parameters as well as other asynchronous and batch operations.
18. invoke(): Running the Agent synchronously
invoke() is the most commonly used Agent execution method.
Example
Example
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Introduce Python lists."
}
]
}
)
(
result
[
"messages"
]
[
1
]
.
content
)
The return value is usually the final Agent State containing fields such as messages.
If response_format is configured, it may also contain:
structured_response
If an interrupt occurs during execution, it may return interrupt information instead of a normal final answer.
19. ainvoke(): Asynchronous execution
In FastAPI, asynchronous web services, or asyncio programs, you can use ainvoke().
Example
Example
import
asyncio
from
langchain.
agents
import
create_agent
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
]
)
async
def
main
(
)
:
result
=
await agent.
ainvoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Hello" (Chinese)
}
]
}
)
(
result
[
"messages"
]
[
1
]
.
content
)
asyncio.
run
(
main
(
)
)
If the Agent contains custom tools, you also need to consider whether the tools themselves support asynchronous execution.
20. stream(): Streaming the Agent
Streaming an Agent differs slightly from calling a Chat Model directly.
Because besides generating text, the Agent may also call tools and execute multiple graph nodes.
Common stream_mode values
| Mode | Main Use |
|---|---|
updates |
View state updates after node execution |
values |
View the complete state values during execution |
messages |
Get model message increments and related metadata |
custom |
Get custom stream events |
debug |
Get more detailed graph debug events |
Example: Viewing node updates
Example
for
event
in
agent.
stream
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Hello" (Chinese)
}
]
}
,
stream_mode
=
"updates"
)
:
(
event
)
Example: Streaming model text output
Example
for
chunk
,
metadata
in
agent.
stream
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Introduce the features of Python."
}
]
}
,
stream_mode
=
"messages"
)
:
if
metadata.
get
(
"langgraph_node"
)
==
"model"
:
if
isinstance
(
chunk
.
content
,
str
)
:
(
chunk
.
content
,
end
=
""
,
flush
=
True
)
(
)
Here the model-generated text is output incrementally.
If the model also generates tool calls or intermediate analytical text, you should filter further based on event type and application needs.
**Note:** What is visible in stream events is what the model interface and Agent runtime expose; it does not mean you can read the model's hidden internal reasoning process.
21. get_state(): Reading the current state
If a Checkpointer is configured, you can use get_state() to read the current state snapshot of a specified thread.
Example
Example
from
langgraph.
checkpoint
.
memory
import
InMemorySaver
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
]
,
checkpointer
=
InMemorySaver
(
)
)
config
=
{
"configurable"
:
{
"thread_id"
:
"state-demo-001"
}
}
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Hello" (Chinese)
}
]
}
,
config
=
config
)
state
=
agent.
get_state
(
config
)
(
"State fields: "
,
state.
values
.
keys
(
)
)
(
"Message count: "
,
len
(
state.
values
.
get
(
"messages"
,
[
]
)
)
)
(
"Next node: "
,
state.
next
)
(
"Checkpoint configuration: "
,
state.
config
)
Here state is a StateSnapshot, not an ordinary Agent return dictionary.
Common fields include:
| Field | Description |
|---|---|
values |
Current state data |
next |
Next nodes to be executed |
config |
Current checkpoint configuration |
metadata |
Checkpoint metadata |
tasks |
Current tasks and possible interrupt information |
If state.next is empty, it usually means there are no ordinary follow-up nodes pending.
22. get_state_history(): Viewing historical state
Checkpointer can save multiple historical checkpoints for the same thread.
Use get_state_history() You can view previous state snapshots.
Example
Example
config
=
{
"configurable"
:
{
"thread_id"
:
"state-demo-001"
}
}
for
snapshot
in
agent.
get_state_history
(
config
)
:
(
"Checkpoint:"
,
snapshot.
config
)
(
"Next node: "
,
snapshot.
next
)
This approach is suitable for debugging:
- Which step the Agent has reached.
- What state a particular conversation turn produced.
- Whether there are pending interrupts.
- Previous checkpoint information.
But it does not mean all Checkpointers permanently store unlimited history. Data retention capability and cleanup policies depend on the storage implementation and deployment configuration.
23. update_state(): Manually updating state
update_state() Allows writing a state update to a specified thread.
For example, adding a new user message to the Agent.
Example
Example
from
langchain.
messages
import
HumanMessage
config
=
{
"configurable"
:
{
"thread_id"
:
"state-demo-001"
}
}
new_config
=
agent.
update_state
(
config
,
{
"messages"
:
[
HumanMessage
(
content
=
"Additional note: I'm learning Python."
)
]
}
)
(
"New checkpoint configuration: "
,
new_config
)
state
=
agent.
get_state
(
config
)
(
"Current message count: "
,
len
(
state.
values
[
"messages"
]
)
)
**Note:** update_state() does not directly overwrite a historical Checkpoint.
It merges updates according to the Reducer corresponding to each state field and generates a new checkpoint state.
For messages, the add_messages Reducer is used by default; the same message ID can replace an existing message, while messages with different IDs are appended.
If you truly want to clear old messages, use a deletion method consistent with the message Reducer semantics, rather than simply returning a shorter message list.
24. AgentState: Default state structure
LangChain 1.x's default AgentState is a TypedDict.
It contains message history, an optional routing control field, and a structured response field.
| Field | Type | Required | Description |
|---|---|---|---|
messages |
list[AnyMessage] | Is | Message history, using the add_messages Reducer |
jump_to |
"tools" / "model" / "end" / None | No | Internal temporary routing instructions |
structured_response |
ResponseT | No | Structured output result, not used as a normal input field |
messages
This is the most commonly used state field.
For example:
{
"messages": [
{"role": "user", "content": "你好"}
]
}
After execution completes, the Agent usually returns user messages and model replies.
jump_to
Used by specific Middleware Hooks to control the subsequent execution path.
Allowed targets include:
tools
model
end
This field is temporary internal routing control and is not suitable for saving as ordinary business data.
If a Middleware wants to jump via jump_to, it also needs to declare the allowed jump targets in the corresponding Hook.
structured_response
When response_format is configured and structured output is successfully generated, you can use
result["structured_response"]
to read the result.
If structured output is not configured, this field usually does not appear.
25. The difference between AgentState and ToolRuntime
In actual development, AgentState and ToolRuntime are easy to confuse.
They serve different purposes:
| object | Main Use |
|---|---|
| AgentState | Stores state in the current execution flow |
| ToolRuntime | Provides tools with runtime capabilities such as state, context, and Store |
| Runtime Context | Provides trusted user information and request configuration |
| Checkpointer | Saves and restores thread execution state |
| Store | Saves cross-session long-term data |
For example:
Example
from
langchain.
tools
import
tool
,
ToolRuntime
@
tool
def
inspect_runtime
(
runtime: ToolRuntime
)
str
:
"""View the number of messages in the current session."""
messages
=
runtime.
state
.
get
(
"messages"
,
[
]
)
return
f
"There are {len(messages)} messages in the current state."
When the model calls this tool, Runtime injects it automatically; the model does not need to generate a runtime argument.
This avoids exposing internal state objects directly as model-controllable tool arguments.
26. Complete example: Comprehensive use of the Agent API
Below we combine the model, tools, Middleware, structured output, and Checkpointer.
Filename:agent_api_demo.py
Install dependencies:
pip install -U langchain langchain-deepseek langgraph pydantic python-dotenv
Configure .env:
DEEPSEEK_API_KEY=your_deepseek_api_key
Complete example
from
dotenv
import
load_dotenv
from
pydantic
import
BaseModel
,
Field
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
middleware
import
dynamic_prompt
,
ModelRequest
from
langchain.
agents
.
structured_output
import
ToolStrategy
from
langchain.
tools
import
tool
from
langchain_deepseek
import
ChatDeepSeek
from
langgraph.
checkpoint
.
memory
import
InMemorySaver
load_dotenv
(
)
========== 1. Tools ==========
@
tool
def
search_course
(
keyword
:
str
)
str
:
"""Find courses in the simulated course catalog."""
data
=
{
"Python"
:
"Python Fundamentals, Python Functions"
,
"Java"
:
"Java Fundamentals, Java Object-Oriented"
}
return
data.
get
(
keyword
,
"No matching simulated course found"
)
========== 2. Structured output ==========
class
CourseResult
(
BaseModel
)
:
keyword
:
str
=
Field
(
description
=
"Keywords of the user's query"
)
courses:
list
[
str
]
=
Field
(
description
=
"Retrieved courses"
)
found:
bool
=
Field
(
description
=
"Whether a matching course was found"
)
========== 3. Middleware ==========
@
dynamic_prompt
def
build_prompt
(
request: ModelRequest
)
str
:
return
(
"You are a programming course search assistant."
"You must use the search_course tool first when answering course queries."
"Generate results only based on the simulated course catalog returned by the tool."
"Do not fabricate courses that do not exist."
)
========== 4. Create the Agent ==========
agent
=
create_agent
(
model
=
ChatDeepSeek
(
model
=
"deepseek-chat"
,
temperature
=
0
)
,
tools
=
[
search_course
]
,
middleware
=
[
build_prompt
]
,
response_format
=
ToolStrategy
(
CourseResult
)
,
checkpointer
=
InMemorySaver
(
)
,
name
=
"course_search_agent"
)
========== 5. Execution ==========
config
=
{
"configurable"
:
{
"thread_id"
:
"agent-api-demo"
}
}
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Use a tool to query which courses are available for Python, and return a structured result."
}
]
}
,
config
=
config
)
(
"Structured output: "
,
result.
get
(
"structured_response"
)
)
========== 6. View state ==========
state
=
agent.
get_state
(
config
)
(
"Message count: "
,
len
(
state.
values
.
get
(
"messages"
,
[
]
)
)
)
(
"Next node: "
,
state.
next
)
========== 7. View history ==========
for
snapshot
in
agent.
get_state_history
(
config
)
:
(
"Checkpoint:"
,
snapshot.
config
)
This example demonstrates:
- Creating an Agent via create_agent().
- Registering business tools with @tool.
- Using dynamic_prompt to define model rules.
- Using ToolStrategy to obtain structured output.
- Using InMemorySaver to save thread state.
- Getting the current state via get_state().
- Viewing historical checkpoints via get_state_history().
Note that whether the model calls tools as required and returns valid structured data depends on its actual capabilities and output behavior.
For businesses that must perform real database queries, you cannot rely solely on the Prompt to guarantee call order; you should use deterministic retrieval or tool execution flows.
27. Frequently asked questions
1. What object does create_agent() return?
It returns a CompiledStateGraph, which can be executed via methods such as invoke and stream.
2. Must model be a string?
No, you can also pass in a BaseChatModel instance such as ChatDeepSeek.
3. Can tools be omitted?
Yes. tools defaults to None, in which case no normal tool-calling loop is built.
4. Can a Pydantic BaseModel be used directly as an executable tool?
Usually not. Pydantic is mainly used to define tool input Schemas or structured output; to execute tools, you should use Callable, BaseTool, or a supported tool definition.
5. Can response_format take a Pydantic class directly?
Yes. LangChain selects an appropriate structured output strategy based on support.
6. What's the difference between AgentState and context_schema?
AgentState is for execution state; context_schema is for defining runtime context.
7. Why doesn't the Agent read user preferences even though a Store is configured?
Because Store data is not automatically injected into the model; you need to read it explicitly using a tool or Middleware.
8. Why doesn't multi-turn conversation work?
You need to check whether a Checkpointer is configured and whether multiple calls use the same thread_id.
9. Does interrupt_before=["tools"] pause only sensitive tools?
No. It sets an interrupt point on the specified tools node and does not automatically distinguish sensitive from ordinary tools.
10. How do I approve an individual sensitive tool?
You can use interrupt() or HumanInTheLoopMiddleware.
11. Is debug=True suitable for long-term use in production?
Usually not recommended, as it may output large amounts of messages and state data.
12. Does the name parameter modify the names of all AIMessages?
No. It is mainly used to identify the Agent graph.
13. After configuring cache, are all model responses automatically cached?
No. You also need caching strategies on the actual nodes or separate model caching logic.
14. Does update_state() overwrite the original historical Checkpoint?
Usually not; it creates a new state version and applies updates according to each field's Reducer.
15. Why can't messages be replaced directly with a shorter list?
Because the add_messages Reducer is used by default, an ordinary list update usually merges messages rather than deleting old ones.
16. What's the difference between stream_mode="updates" and "messages"?
updates is for observing node state updates; messages is for getting model-generated message increments.
17. When do you need a custom state_schema?
When the Agent needs to save extra task state, business steps, or other execution data, you can extend AgentState.
18. When do you need transformers?
You can use them when you need to customize the transformation and presentation of graph stream events. Ordinary business usually doesn't need them.
Summary
LangChain 1.x's create_agent() provides a unified, extensible interface for creating Agents.
This chapter introduces:
model: model configuration.tools: tool registration.system_prompt: system prompt.middleware: Agent execution process control.response_format: structured output.state_schema: custom state.context_schema: runtime context.checkpointer: single-thread conversation state persistence.store: cross-session long-term data storage.interrupt_beforeandinterrupt_after: static interrupt points.debug: debug logging.name: Agent name.cache: graph caching.transformers: stream event transformers.CompiledStateGraph: the Agent's execution and state management interfaces.AgentState: the Agent's default state structure.
The most common way to write an Agent:
from langchain.agents import create_agent
agent = create_agent(
model="deepseek:deepseek-chat",
tools=[my_tool],
system_prompt="You are an intelligent assistant."
)
result = agent.invoke({
"messages": [{"role": "user", "content": "你好"}]
})
**Core principle:** create_agent() is responsible for organizing the model, tools, and execution flow; Middleware is responsible for extending behavior; AgentState and Checkpointer handle execution state; Runtime Context and Store provide external context and long-term data capabilities.
Once you master these parameters, you can gradually build Agents with multi-tool collaboration, conversation memory, structured output, human approval, and long-term storage capabilities according to business needs.
Reference Documentation
- create_agent API Reference
- AgentState API Reference
- LangChain Agents official documentation
- LangChain Tools Official Documentation
- LangChain Middleware Official Documentation
- LangChain Structured Output Official Documentation
- LangGraph Persistence
- LangGraph Interrupts
- LangChain Streaming Official Documentation