LangChain Configuration and Error Classes API Reference
In the previous tutorials, we have learned about LangChain's Chat Model, Agent, Tools, Messages, Middleware, and RAG.
This chapter continues with RunnableConfig, Checkpointer, Store, and common exception classes that are frequently used in real development.
These interfaces do not directly determine the content of the AI's answers, but they affect how the Agent runs, concurrent execution, conversation memory, data persistence, log tracing, and error handling.
For example:
- Use RunnableConfig to control execution parameters.
- Use thread_id to identify conversation threads.
- Use Checkpointer to save and restore Agent state.
- Use Store to save long-term user preferences.
- Use exception types to determine whether to retry, terminate, or prompt the user.
This chapter is based on LangChain 1.x and LangGraph 1.x, providing quick reference tables of commonly used APIs, Python examples, exception handling methods, and a runtime environment troubleshooting checklist.
1. What is RunnableConfig?
RunnableConfig is a data structure used by LangChain to configure the execution behavior of Runnables.
Chat Models, Agents, Chains, and other Runnables typically support passing runtime configuration via the config parameter.
For example:
result = agent.invoke(
{"messages": [{"role": "user", "content": "你好"}]},
config={
"tags": ["demo"],
"metadata": {"source": "web"}
}
)
RunnableConfig allows you to set different execution tags, tracing information, and other parameters for different requests without modifying the Agent definition.
The main functions include:
- Control runtime configuration.
- Set concurrency limits.
- Limit graph execution steps.
- Add tracing tags and metadata.
- Configure callback handlers.
- Specify thread and run identifiers.
2. Complete fields of RunnableConfig
RunnableConfig is a TypedDict, and its configuration fields are usually optional.
| Field | Type | Description |
|---|---|---|
tags |
list[str] | Execution tags, used for filtering and tracing |
metadata |
dict[str, Any] | Additional metadata, usually required to be JSON-serializable |
callbacks |
Callbacks | Callback handlers or CallbackManager |
run_name |
str | The tracing name for this run |
max_concurrency |
int | None | The maximum number of concurrent parallel calls |
recursion_limit |
int | Maximum recursion or graph execution step limit, default 25 |
configurable |
dict[str, Any] | Dynamic configuration and thread-related parameters |
run_id |
UUID | None | The identifier of this traced run |
The most frequently used among them are:
configurable
tags
metadata
recursion_limit
max_concurrency
**Note:** The recursion_limit in RunnableConfig and the Python interpreter's sys.setrecursionlimit() are not the same thing.
3. configurable: Dynamic configuration at runtime
configurable is used to pass in runtime configuration.
In LangGraph Agents, the most common use is to set:
thread_id
For example:
Example: Configuring a conversation thread
config
=
{
"configurable"
:
{
"thread_id"
:
"conversation-001"
}
}
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Hello" (Chinese)
}
]
}
,
config
=
config
)
When the Agent is configured with a Checkpointer, the same thread_id can be used to read and continue previously saved conversation state.
For example:
thread_id = conversation-001
第一轮:你好
第二轮:我正在学习 Python
第三轮:我刚才说在学什么?
These calls can share the same thread history.
If you switch to a new thread_id, another thread will be used.
**Note:** thread_id is only a thread identifier, not a user authentication credential. Multi-user systems must verify whether the current user has permission to access the specified thread.
4. configurable is not only for thread_id
Besides the Checkpointer, configurable can also modify Runnable parameters that have been explicitly declared as configurable.
For example:
Example: Dynamically modifying model parameters
from
dotenv
import
load_dotenv
from
langchain.
chat_models
import
init_chat_model
load_dotenv
(
)
model
=
init_chat_model
(
"deepseek:deepseek-chat"
,
temperature
=
0
,
configurable_fields
=
(
"temperature"
,
)
)
result
=
model.
invoke
(
"Introduce the Python language."
,
config
=
{
"configurable"
:
{
"temperature"
:
0.5
}
}
)
(
result.
content
)
This example allows modifying temperature at call time.
If a parameter has not been declared via configurable_fields or another configurable mechanism, you cannot assume that adding a field with the same name in configurable will modify the model's behavior.
**Security reminder:** Do not directly allow ordinary users to modify sensitive configuration such as api_key and base_url via configurable.
5. recursion_limit: Execution step limit
LangChain Agents execute based on LangGraph.
The Agent may loop multiple times between the model and tools:
模型
↓
工具
↓
模型
↓
工具
↓
模型
...
If the flow never ends, it may exceed the maximum execution step limit.
The default recursion limit of RunnableConfig is:
recursion_limit = 25
It can be adjusted at runtime:
Example
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please query Python courses."
}
]
}
,
config
=
{
"recursion_limit"
:
20
}
)
Here, the limit for this run is set to 20.
One thing to note in particular:recursion_limit does not mean calling the model at most 20 times.
Because one Agent tool-call loop typically contains multiple graph execution steps.
What happens if the limit is exceeded?
If the execution steps exceed the limit, the following is typically raised:
GraphRecursionError
For example:
Example: Catching a recursion limit exception
from
langgraph.
errors
import
GraphRecursionError
try
:
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Query Python courses"
}
]
}
,
config
=
{
"recursion_limit"
:
10
}
)
except
GraphRecursionError:
(
"The Agent has exceeded the execution step limit. Please check whether tools are being called repeatedly."
)
**Recommendation:** When encountering GraphRecursionError, first check whether the Agent is calling tools repeatedly, whether the tool return content is complete, and whether the model can determine that the task is finished.
Do not mask an infinite loop problem simply by continuously increasing recursion_limit.
6. max_concurrency: Concurrency control
RunnableConfig can use max_concurrency to control the number of parallel calls of a Runnable.
For example, using batch() to send questions to the model in bulk:
Example: Batch calls
from
langchain.
chat_models
import
init_chat_model
model
=
init_chat_model
(
"deepseek:deepseek-chat"
)
questions
=
[
"What is Python?"
,
"What is Java?"
,
"What is Go?"
,
"What is Rust?"
]
results
=
model.
batch
(
questions
,
config
=
{
"max_concurrency"
:
2
}
)
for
question
,
response
in
zip
(
questions
,
results
)
:
(
question
)
(
response.
content
)
Here, at most two concurrent call tasks are allowed.
Note that max_concurrency controls the concurrent execution of the relevant Runnables, and is not equal to the provider API's requests-per-second limit.
If you need to control the request rate, you should also use a Rate Limiter or a server-side rate-limiting mechanism.
7. tags: Tracing tags
tags is used to add tags to this run.
For example:
development
production
rag
customer-service
course-search
These tags can be used for filtering and grouping in tracing systems such as LangSmith.
Example
Example
config
=
{
"tags"
:
[
"development"
,
"course-search"
]
}
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Query Python courses"
}
]
}
,
config
=
config
)
tags can propagate along with the parent Runnable's configuration to some child calls, making it easier to correlate the entire execution flow.
8. metadata: Additional metadata
metadata is suitable for storing runtime environment and business classification information.
For example:
Example
config
=
{
"metadata"
:
{
"environment"
:
"development"
,
"source"
:
"web"
,
"app_version"
:
"1.0.0"
,
"feature"
:
"course_search"
}
}
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Query Java courses"
}
]
}
,
config
=
config
)
Difference from tags:
| Field | Applicable Situations |
|---|---|
tags |
Simple classification tags |
metadata |
Structured data with field names |
**Note:** metadata should use JSON-serializable data as much as possible, and should not store sensitive information such as API Keys, passwords, or identity credentials.
9. callbacks: Callback handlers
callbacks You can specify the callback handlers to use when the Runnable executes.
For example, custom callbacks can log:
- Model call start.
- Model call end.
- Model errors.
- Tool calls.
You can inherit from BaseCallbackHandler to create a handler.
Example: Logging model execution
Example
from
langchain_core.
callbacks
import
BaseCallbackHandler
class
DebugCallback
(
BaseCallbackHandler
)
:
def
on_llm_start
(
self
,
serialized
,
prompts
,
**kwargs
)
:
(
"[Callback] Model execution started"
)
def
on_llm_end
(
self
,
response
,
**kwargs
)
:
(
"[Callback] Model execution completed"
)
def
on_llm_error
(
self
,
error
,
**kwargs
)
:
(
"[Callback] Model error:"
,
type
(
error
)
.name
)
config
=
{
"callbacks"
:
[
DebugCallback
(
)
]
}
This example defines a model callback handler.
The specific callback events triggered depend on the model integration and execution method. Chat Models often also use a dedicated Chat Model start event, so do not assume that all models trigger only through on_llm_start.
For Agent execution control based on LangChain 1.x, Middleware is recommended; for runtime tracing of models and tools, you can combine callbacks with LangSmith.
10. run_name and run_id
These two fields are mainly used for execution tracing.
| Field | Purpose |
|---|---|
run_name |
Specify the name of this run |
run_id |
Specify the UUID of this traced run |
Example
Example
import
uuid
config
=
{
"run_name"
:
"python_course_query"
,
"run_id"
: uuid.
uuid4
(
)
,
"tags"
:
[
"course-search"
]
}
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Search Python courses"
}
]
}
,
config
=
config
)
Here, run_id is the identifier of a traced run and should not be confused with the Checkpointer's thread_id.
The same thread_id can contain multiple different runs, and each run can have an independent run_id.
11. Complete usage example of RunnableConfig
Combining the commonly used fields:
Example
import
uuid
config
=
{
"configurable"
:
{
"thread_id"
:
"conversation-001"
}
,
"recursion_limit"
:
20
,
"max_concurrency"
:
2
,
"tags"
:
[
"development"
,
"chat"
]
,
"metadata"
:
{
"source"
:
"web"
,
"app_version"
:
"1.0.0"
}
,
"run_name"
:
"runoob_agent_request"
,
"run_id"
: uuid.
uuid4
(
)
}
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Hello" (Chinese)
}
]
}
,
config
=
config
)
**Note:** If the Agent is not configured with a Checkpointer, then thread_id itself does not automatically provide persistent conversation memory.
12. What is a Checkpointer?
A Checkpointer is used to save the execution state of LangGraph.
It can support:
- Multi-turn conversations.
- Restoring execution state.
- Human-in-the-Loop manual interruption.
- Historical checkpoint viewing.
- Debugging the execution process.
Typical flow:
Agent.invoke()
↓
执行节点
↓
保存 Checkpoint
↓
继续执行
↓
保存 Checkpoint
A Checkpointer saves the Agent's state, not just the chat text.
13. Quick reference of Checkpointer implementation classes
| Implementation class | Install packages | Persistence | Applicable scenarios |
|---|---|---|---|
InMemorySaver |
langgraph-checkpoint | No | Local testing |
SqliteSaver |
langgraph-checkpoint-sqlite | Is | Local lightweight applications |
AsyncSqliteSaver |
langgraph-checkpoint-sqlite | Is | Asynchronous SQLite applications |
PostgresSaver |
langgraph-checkpoint-postgres | Is | Server-side persistence |
AsyncPostgresSaver |
langgraph-checkpoint-postgres | Is | Asynchronous server applications |
Common import methods:
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.checkpoint.postgres import PostgresSaver
Synchronous and asynchronous implementations cannot be mixed arbitrarily. When using an asynchronous Checkpointer, it should typically be paired with asynchronous execution methods such as ainvoke() and astream().
14. InMemorySaver: In-memory checkpoints
InMemorySaver Suitable for local development and functional testing.
It stores state in the memory of the current Python process.
Example: Multi-turn conversation
Example
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langgraph.
checkpoint
.
memory
import
InMemorySaver
load_dotenv
(
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
]
,
checkpointer
=
InMemorySaver
(
)
)
config
=
{
"configurable"
:
{
"thread_id"
:
"memory-demo-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
)
With the same thread_id, the second round can access the previous message history.
**Note:** After the program exits, the data in InMemorySaver is lost, making it unsuitable as a persistence solution for production environments.
15. SqliteSaver: SQLite persistence
If you want to retain conversation history after restarting the program, you can use SQLite.
Installation
pip install -U langgraph-checkpoint-sqlite
The correct way to use it
Note thatSqliteSaver.from_conn_string() returns a context manager.
Therefore, you should use with to use:
Example
from
langchain.
agents
import
create_agent
from
langgraph.
checkpoint
.
sqlite
import
SqliteSaver
with
SqliteSaver.
from_conn_string
(
"checkpoints.db"
)
as
checkpointer:
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
]
,
checkpointer
=
checkpointer
)
config
=
{
"configurable"
:
{
"thread_id"
:
"sqlite-demo-001"
}
}
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Hello" (Chinese)
}
]
}
,
config
=
config
)
(
result
[
"messages"
]
[
1
]
.
content
)
After the program runs, it will create in the current directory:
checkpoints.db
Afterwards, you can use the same database and thread_id to restore the historical state.
**Important:** Do not write it like this:
checkpointer = SqliteSaver.from_conn_string("checkpoints.db")
and then pass the checkpointer directly to the Agent, because what you get at that point is not a Saver instance that has entered the connection context.
SQLite is suitable for lightweight local applications and is not recommended for direct use in multi-instance Agent services with heavy concurrent writes.
16. PostgresSaver: PostgreSQL persistence
For multi-user Agents that need to run long-term, you can consider using PostgreSQL.
Install dependencies
pip install -U langgraph-checkpoint-postgres "psycopg[binary,pool]"
The PostgreSQL Checkpointer supports more reliable database persistence management.
Example: PostgresSaver
Example
import
os
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langgraph.
checkpoint
.
postgres
import
PostgresSaver
load_dotenv
(
)
DB_URI
=
os
.
environ
[
"POSTGRES_URI"
]
with
PostgresSaver.
from_conn_string
(
DB_URI
)
as
checkpointer:
Initialize the required database schema on first use
checkpointer.
setup
(
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
]
,
checkpointer
=
checkpointer
)
config
=
{
"configurable"
:
{
"thread_id"
:
"postgres-demo-001"
}
}
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Hello" (Chinese)
}
]
}
,
config
=
config
)
(
result
[
"messages"
]
[
1
]
.
content
)
in .env Configure in :
POSTGRES_URI=postgresql://db_user:db_password@localhost:5432/langchain_db
The connection string above is only for format demonstration.
setup() is used to create or migrate the relevant database schema, usually executed during initial deployment or a controlled migration phase, and does not need to be called in every user request.
**Recommendation:** In production environments, use a dedicated account for the database and store the password via environment variables or a secret management service.
17. Common Checkpointer methods
The Checkpointer itself is responsible for low-level state saving, while the Agent provides a more convenient state access interface through CompiledStateGraph.
For Agents that use a Checkpointer, common methods include:
| Method | Description |
|---|---|
agent.get_state(config) |
Read the current state snapshot |
agent.get_state_history(config) |
View historical checkpoints |
agent.update_state(config, values) |
Write new state updates |
agent.aget_state(config) |
Read state asynchronously |
Example: Reading the current state
Example
config
=
{
"configurable"
:
{
"thread_id"
:
"memory-demo-001"
}
}
state
=
agent.
get_state
(
config
)
(
"Message count: "
,
len
(
state.
values
.
get
(
"messages"
,
[
]
)
)
)
(
"Next node: "
,
state.
next
)
(
"Checkpoint configuration: "
,
state.
config
)
What is read here is a StateSnapshot, not an ordinary conversation message dictionary.
You need to ensure that the agent is one created with a Checkpointer and that the current thread_id has the relevant state.
18. Store: Long-term data storage
The Checkpointer mainly saves the execution state within a single thread.
If you need to save data shared across threads, you can use the Store.
For example, a user has three sessions:
用户 user-001
|
├── thread-a
├── thread-b
└── thread-c
|
↓
共享 Store
|
↓
Python 学习偏好
The Store can save:
- User learning preferences.
- Application configuration.
- Long-term user profiles.
- Business data shared across sessions.
However, the Store does not automatically read and summarize the user's chat content; the extraction and update of long-term memory still need to be implemented by business code.
19. Quick reference of Store implementation classes
| class | Import path | Persistence |
|---|---|---|
InMemoryStore |
langgraph.store.memory | No |
PostgresStore |
langgraph.store.postgres | Is |
AsyncPostgresStore |
langgraph.store.postgres | Is |
Similar to the Checkpointer, the Store also has in-memory and persistent implementations.
Multi-user systems should choose an appropriate storage solution based on concurrency requirements, access permissions, and backup policies.
20. Common APIs of InMemoryStore
InMemoryStore is suitable for demonstrating the basic operations of the Store.
// 2022-01-01 00:00:00 GMT
| Method | Purpose |
|---|---|
put(namespace, key, value) |
Save data |
get(namespace, key) |
Get the data |
search(namespace_prefix) |
Search data under a namespace |
delete(namespace, key) |
Delete data |
Complete example: Store CRUD
Example
from
langgraph.
store
.
memory
import
InMemoryStore
store
=
InMemoryStore
(
)
namespace
=
(
"users"
,
"user-001"
)
1. Save
store.
put
(
namespace
,
"learning_preference"
,
{
"language"
:
"Python"
,
"level"
:
"beginner"
}
)
2. Get
item
=
store.
get
(
namespace
,
"learning_preference"
)
if
item:
(
"User preferences:"
,
item.
value
)
3. Search
items
=
store.
search
(
namespace
)
for
item
in
items:
(
"Key:"
,
item.
key
)
(
"Value:"
,
item.
value
)
4. Delete
store.
delete
(
namespace
,
"learning_preference"
)
(
"After deletion:"
,
store.
get
(
namespace
,
"learning_preference"
)
)
Sample output:
用户偏好: {'language': 'Python', 'level': 'beginner'}
键: learning_preference
值: {'language': 'Python', 'level': 'beginner'}
删除后: None
InMemoryStore data is not persisted across process restarts.
21. PostgresStore: Long-Term Persistent Storage
If you need to persist Store data to PostgreSQL, you can use PostgresStore.
Installation
pip install -U langgraph-checkpoint-postgres "psycopg[binary,pool]"
Example
Example
import
os
from
dotenv
import
load_dotenv
from
langgraph.
store
.
postgres
import
PostgresStore
load_dotenv
(
)
DB_URI
=
os
.
environ
[
"POSTGRES_URI"
]
with
PostgresStore.
from_conn_string
(
DB_URI
)
as
store:
Execute when using for the first time or when migrating the database schema
store.
setup
(
)
namespace
=
(
"users"
,
"user-001"
)
store.
put
(
namespace
,
"language"
,
{
"value"
:
"Python"
}
)
item
=
store.
get
(
namespace
,
"language"
)
(
item.
value
if
item
else
"No data found"
)
PostgresStore is suitable for storing long-term data.
It differs from PostgresSaver:
| object | Content Saved |
|---|---|
PostgresSaver |
The agent's thread execution state and checkpoints |
PostgresStore |
User preferences and other cross-session data |
**Note:** Even if both use the same PostgreSQL service, you should define data lifecycle, permissions, and backup strategies according to your application's needs.
22. Store and Agent Integration
When creating an agent, you can pass long-term storage through the store parameter.
Example
from
langchain.
agents
import
create_agent
from
langgraph.
store
.
memory
import
InMemoryStore
store
=
InMemoryStore
(
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
]
,
store
=
store
)
But there is a very important distinction here:
Passing a Store into an agent does not mean the model automatically reads data from the Store.
You need to read it explicitly via ToolRuntime, Middleware, or other business logic.
For example, when a user asks about their learning preferences, a tool retrieves data from the Store based on the trusted user identity and then provides the result to the model.
23. Common LangChain Exception Classes
LangChain and LangGraph can produce exceptions during model calls, tool execution, structured output, and graph state management.
In actual development, it's best to handle them by category based on the exception source.
| exception | Source | Description |
|---|---|---|
ImportError |
Python | Missing dependencies or import errors |
ValueError |
Python | Invalid parameter values |
TypeError |
Python | Incorrect parameter types or calling methods |
NotImplementedError |
Python | The current interface or implementation does not support the specified operation |
TimeoutError |
Python / SDK | Some request timeout scenarios |
ToolException |
langchain_core.tools | A tool proactively reports an execution error |
StructuredOutputError |
langchain.agents.structured_output | Base class for structured output-related errors |
StructuredOutputValidationError |
langchain.agents.structured_output | Structured tool arguments cannot be parsed according to the schema |
MultipleStructuredOutputsError |
langchain.agents.structured_output | The model returns multiple structured output calls |
GraphRecursionError |
langgraph.errors | Graph execution exceeds the step limit |
InvalidUpdateError |
langgraph.errors | Invalid graph state update |
EmptyInputError |
langgraph.errors | Graph receives empty input |
GraphInterrupt |
langgraph.errors | Internal interrupt signal during graph execution |
**Note:** Model provider SDKs also define their own error types, such as authentication failures, rate limiting, and API connection errors, which are not all converted to Python's built-in TimeoutError.
24. ToolException: Tool Execution Errors
ToolException is used to indicate tool execution errors.
For example, an invalid course ID queried by the user:
Example
from
langchain.
tools
import
tool
,
ToolException
@
tool
def
get_course
(
course_id:
int
)
str
:
"""Query a mock course by ID."""
if
course_id
<=
0
:
raise
ToolException
(
"Course ID must be greater than 0"
)
return
f
"Mock course {course_id}: Python Basics"
get_course.
handle_tool_error
=
True
(
get_course.
invoke
(
{
"course_id"
: -
1
}
)
)
When handle_tool_error=True is configured, a tool can convert a ToolException into an error result.
But note:
- ToolException does not retry automatically.
- It does not mean any exception will be converted into a ToolMessage.
- Real network and database failures should use the appropriate exception categories.
In an agent, you can also use mechanisms like ToolErrorMiddleware to handle tool exceptions uniformly.
25. StructuredOutputError: Structured Output Errors
LangChain agents can return structured results via response_format.
For example:
response_format=ToolStrategy(MySchema)
If the result generated by the model does not meet the requirements, structured output-related errors may occur.
Exception hierarchy
StructuredOutputError
|
├── StructuredOutputValidationError
|
└── MultipleStructuredOutputsError
Where:
| exception | Trigger conditions |
|---|---|
StructuredOutputValidationError |
Structured tool call arguments cannot be parsed by the schema |
MultipleStructuredOutputsError |
Expected a single structured output but received multiple related tool calls |
Example: Catching Structured Output Errors
Example
from
langchain.
agents
.
structured_output
import
(
StructuredOutputError
,
StructuredOutputValidationError
,
MultipleStructuredOutputsError
)
try
:
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Extract structured course information."
}
]
}
)
except
StructuredOutputValidationError
as
e:
(
"Structured output validation failed: "
,
type
(
e
)
.name
)
except
MultipleStructuredOutputsError:
(
"The model generated multiple structured outputs."
)
except
StructuredOutputError:
(
"Structured output processing failed."
)
Here we assume the agent has been configured with an appropriate response_format.
**Note:** When using ToolStrategy, LangChain may feed some exceptions back to the model and request regeneration based on the handle_errors configuration, so not every validation failure directly raises an exception to the application.
In addition, these structured output exceptions do not cover all provider-native JSON output or Pydantic errors.
26. ToolStrategy.handle_errors
If you want the model to attempt a correction when a structured output error occurs, you can configure:
ToolStrategy(
MySchema,
handle_errors=True
)
Main configurations:
| Configure | Description |
|---|---|
True |
Use the default error feedback mechanism |
False |
Do not automatically handle errors through this strategy |
str |
Use a specified error prompt text |
异常类型 |
Only handle specified types of exceptions |
Callable |
Custom error feedback function |
Example: Strict Structured Output
Example
from
typing
import
Literal
from
pydantic
import
BaseModel
,
Field
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
structured_output
import
ToolStrategy
class
CourseInfo
(
BaseModel
)
:
name:
str
=
Field
(
description
=
"Course name"
)
level: Literal
[
"beginner"
,
"intermediate"
,
"advanced"
]
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
]
,
response_format
=
ToolStrategy
(
CourseInfo
,
handle_errors
=
True
)
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Return course information: Python introductory course, beginner level."
}
]
}
)
(
result
[
"structured_response"
]
)
Using a Pydantic schema allows field validation when parsing results.
Note that if you use a raw JSON Schema dictionary directly, the relevant ToolStrategy path does not necessarily perform equivalent schema validation. When reliable field validation is needed, it is recommended to use Pydantic models.
27. GraphRecursionError: Graph Execution Loop
GraphRecursionError indicates that graph execution has exceeded the set step limit.
Common causes:
- The agent repeatedly calls tools.
- The tool results did not allow the model to determine that the task was complete.
- The custom graph has a circular routing error.
- The execution step budget is too small.
You can catch it:
from langgraph.errors import GraphRecursionError
But it is not recommended to solve the problem only by increasing recursion_limit.
For ordinary agents, you can also consider ModelCallLimitMiddleware and ToolCallLimitMiddleware to further limit the number of model and tool calls.
28. InvalidUpdateError: State Update Errors
LangGraph uses State and Reducers to manage state.
This can occur if a node returns an update that does not meet the state requirements, or if multiple parallel nodes write values to a field that does not support concurrent writes:
InvalidUpdateError
For example:
节点 A ──→ 写入 status
节点 B ──→ 写入 status
同一执行步骤中发生冲突
Solutions typically include:
- Check the types of state fields.
- Check whether node return values conform to the State schema.
- Define a Reducer for fields that genuinely need to be merged.
- Adjust the parallel execution or state update design.
**Note:** Do not simply use try/except to ignore InvalidUpdateError; it usually indicates a problem with the program's state design.
29. Timeouts and Network Exceptions
Model calls can produce various network exceptions.
For example:
- Connection timeout.
- Read timeout.
- Connection interrupted.
- Server-side rate limiting.
- Model service unavailable.
You can set a request timeout for the model:
Example
from
langchain_deepseek
import
ChatDeepSeek
model
=
ChatDeepSeek
(
model
=
"deepseek-chat"
,
timeout
=
30
,
max_retries
=
2
)
Here we set a 30-second request timeout and model client retry configuration.
But different provider SDKs may throw different exceptions; you cannot assume all timeouts inherit from Python's built-in TimeoutError.
**Recommendation:** In a production environment, handle authentication, rate limiting, connection errors, and timeouts separately based on the current model SDK's exception classes.
30. Comprehensive Exception Handling Example
Below we create a simple agent and add basic exception handling to the execution process.
Filename:agent_error_demo.py
Complete example
import
logging
import
os
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langchain_deepseek
import
ChatDeepSeek
from
langgraph.
errors
import
(
GraphRecursionError
,
InvalidUpdateError
)
from
langchain.
agents
.
structured_output
import
StructuredOutputError
load_dotenv
(
)
logging
.
basicConfig
(
level
=
logging
.
INFO
)
logger
=
logging
.
getLogger
(
"runoob.agent"
)
if
not
os
.
getenv
(
"DEEPSEEK_API_KEY"
)
:
raise
RuntimeError
(
"DEEPSEEK_API_KEY not configured"
)
agent
=
create_agent
(
model
=
ChatDeepSeek
(
model
=
"deepseek-chat"
,
timeout
=
30
,
max_retries
=
1
)
,
tools
=
[
]
,
system_prompt
=
"You are a Python programming assistant."
)
def
ask
(
question:
str
)
:
try
:
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
: question
}
]
}
,
config
=
{
"recursion_limit"
:
20
,
"tags"
:
[
"error-demo"
]
}
)
(
result
[
"messages"
]
[
1
]
.
content
)
except
GraphRecursionError:
logger.
error
(
"Graph execution steps exceeded the limit"
)
(
"Request not completed: too many execution steps."
)
except
InvalidUpdateError:
logger.
exception
(
"Agent state update failed"
)
(
"Request processing failed: state update error."
)
except
StructuredOutputError:
logger.
exception
(
"Structured output failed"
)
(
"Request processing failed: model output format is incorrect."
)
except
Exception
:
logger.
exception
(
"Unknown error occurred during agent execution"
)
(
"Request processing failed; please check the program logs."
)
if
name
==
"main"
:
ask
(
"Introduce the main features of Python."
)
The exception handling here is mainly for demonstrating the classification approach.
In production, you should also add handling for authentication, connection, rate limiting, and timeout exceptions based on the model SDK used.
Do not return the full exception stack trace to the user, and do not output the API Key in logs.
31. LangChain Environment Configuration Checklist
If the program cannot run, you can check in the following order.
| Check item | Command or Method |
|---|---|
| Python version | python --version |
| Python Environment Path | python -c "import sys; print(sys.executable)" |
| LangChain Version | python -m pip show langchain |
| LangGraph Version | python -m pip show langgraph |
| DeepSeek Integration | python -m pip show langchain-deepseek |
| SQLite Checkpointer | python -m pip show langgraph-checkpoint-sqlite |
| PostgreSQL Checkpointer | python -m pip show langgraph-checkpoint-postgres |
| Dependency Compatibility | python -m pip check |
| Whether API Key Is Configured | Check whether an environment variable exists via Python |
| Model Connectivity | Send a simple request and check the actual error |
| Checkpointer | Check thread_id, database permissions, and connection lifecycle |
For LangChain 1.x, it is recommended to use Python 3.10 or a newer compatible version, and confirm the runtime environment requirements with the metadata of the actually installed packages.
Securely Check the API Key
Example
import
os
from
dotenv
import
load_dotenv
load_dotenv
(
)
key
=
os
.
getenv
(
"DEEPSEEK_API_KEY"
)
(
"DEEPSEEK_API_KEY configured: "
,
bool
(
key
)
)
It is not recommended to print the first few characters or full content of the API Key.
Check dependency versions
Example
from
importlib.
metadata
import
version
,
PackageNotFoundError
packages
=
[
"langchain"
,
"langchain-core"
,
"langgraph"
,
"langchain-deepseek"
,
"langgraph-checkpoint-sqlite"
]
for
package
in
packages:
try
:
(
package
,
version
(
package
)
)
except
PackageNotFoundError:
(
package
,
"Not installed"
)
This example does not connect to a model and does not require an API Key.
32. Complete Example: Configuration and Persistence Demo
Finally, combine RunnableConfig, Checkpointer, Store, and state queries.
This example includes:
- Create an agent.
- Save multi-turn conversations.
- Use RunnableConfig.
- Create a long-term Store.
- Read historical state.
Filename:config_api_demo.py
Install dependencies
pip install -U langchain langchain-deepseek langgraph python-dotenv
Complete example
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langgraph.
checkpoint
.
memory
import
InMemorySaver
from
langgraph.
store
.
memory
import
InMemoryStore
load_dotenv
(
)
========== 1. Checkpointer ==========
checkpointer
=
InMemorySaver
(
)
========== 2. Store ==========
store
=
InMemoryStore
(
)
store.
put
(
(
"users"
,
"student-001"
)
,
"preference"
,
{
"language"
:
"Python"
,
"level"
:
"beginner"
}
)
========== 3. Create Agent ==========
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
]
,
system_prompt
=
"You are a Python programming learning assistant."
,
checkpointer
=
checkpointer
,
store
=
store
)
========== 4. RunnableConfig ==========
config
=
{
"configurable"
:
{
"thread_id"
:
"config-demo-001"
}
,
"recursion_limit"
:
20
,
"tags"
:
[
"tutorial"
,
"memory"
]
,
"metadata"
:
{
"source"
:
"runoob"
,
"environment"
:
"development"
}
}
========== 5. First Round of Conversation ==========
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"I'm learning Python."
}
]
}
,
config
=
config
)
========== 6. Second Round of Conversation ==========
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"What did I just say I was learning?"
}
]
}
,
config
=
config
)
(
"Agent answer: "
,
result
[
"messages"
]
[
1
]
.
content
)
========== 7. Read Checkpointer State ==========
state
=
agent.
get_state
(
config
)
(
"Message count: "
,
len
(
state.
values
.
get
(
"messages"
,
[
]
)
)
)
(
"Next node: "
,
state.
next
)
========== 8. Read Store Data ==========
item
=
store.
get
(
(
"users"
,
"student-001"
)
,
"preference"
)
(
"Long-term preferences: "
,
item.
value
if
item
else
None
)
This example demonstrates how to use Checkpointer and Store together.
One thing to note in particular:
- Checkpointer saves the execution state corresponding to thread_id.
- Store saves long-term data corresponding to the specified namespace and key.
- The agent does not automatically read preferences saved in the Store.
- Neither InMemorySaver nor InMemoryStore persists across process restarts.
33. Frequently Asked Questions
1. Is RunnableConfig a required parameter?
No. Most Runnables can execute without passing config. However, if the agent uses a Checkpointer that requires a thread identifier, you need to provide an appropriate thread_id.
2. What is the default value of recursion_limit?
The default value in the current Python RunnableConfig documentation is 25, not 9999.
3. Does recursion_limit=20 mean the model is called at most 20 times?
No, it limits the number of execution steps of the underlying graph.
4. Can max_concurrency prevent all API rate limiting?
No. It controls the number of concurrent executions; the request rate and quotas of the model provider still need to be managed separately.
5. What is the difference between run_id and thread_id?
run_id identifies a single run trace; thread_id identifies a conversation thread whose state can be persistently saved.
6. What is the difference between Checkpointer and Store?
Checkpointer saves thread execution state; Store saves long-term data across threads.
7. Can InMemorySaver save history across program restarts?
No. It only saves state within the current process.
8. Can SqliteSaver.from_conn_string() be assigned and used directly?
It returns a context manager; it is recommended to use it within a with block to ensure the connection is properly opened and closed.
9. Why does PostgresSaver need setup()?
Because the relevant database structures need to be initialized on first use. It is generally executed during deployment or migration.
10. Does content saved in the Store automatically enter the model context?
No, it needs to be read via tools, Middleware, or other business logic.
11. Does ToolException automatically make the agent re-call a tool?
Not necessarily. It depends on the tool error handling configuration and the agent's strategy.
12. When does StructuredOutputValidationError occur?
Usually when the structured output arguments produced by the tool strategy cannot be parsed by the specified schema.
13. What is MultipleStructuredOutputsError?
The model returned multiple structured tool calls in a scenario where only one structured result should have been generated.
14. How should GraphRecursionError be handled?
First investigate circular calls and flow design, then adjust the execution step limit according to actual needs.
15. Can InvalidUpdateError be ignored?
It is not recommended. It usually indicates a problem with the state update or Reducer configuration.
16. Can Python TimeoutError catch all model timeouts?
No. Different model providers, HTTP clients, and LangGraph nodes may use different exception classes.
17. Can RunnableConfig.metadata store an API Key?
It is not recommended. metadata may be passed to tracing systems or callback handlers and should not store sensitive credentials.
18. Which Python version should be used for the LangChain runtime?
It is recommended to use Python 3.10 or a newer compatible version, and also check the Python version requirements declared by the actually installed packages.
Summary
This section summarizes common configuration, storage, and exception handling APIs in LangChain agent development.
Main contents include:
RunnableConfig: Unified execution configuration.configurable: Dynamic configuration and thread_id.recursion_limit: Graph execution step limit.max_concurrency: Concurrency control.tags、metadata: Tracing information.callbacks: Execution callbacks.run_name、run_id: Run identifier.InMemorySaver: In-memory checkpointer.SqliteSaver: SQLite persistence.PostgresSaver: PostgreSQL state persistence.InMemoryStore: In-memory long-term data storage.PostgresStore: PostgreSQL long-term storage.ToolException: Tool execution errors.StructuredOutputError: Structured output errors.GraphRecursionError: Graph execution exceeding the step limit.InvalidUpdateError: State update errors.
The most common way to write RunnableConfig:
config = {
"configurable": {
"thread_id": "conversation-001"
},
"recursion_limit": 20,
"tags": ["production"],
"metadata": {
"source": "web"
}
}
Then execute:
result = agent.invoke(
{"messages": [{"role": "user", "content": "你好"}]},
config=config
)
**Core principle:** RunnableConfig controls how execution is performed, Checkpointer saves thread state, Store saves cross-session data, and exception classes help the program identify failure reasons. Only by combining these capabilities appropriately can you build LangChain agents that are recoverable, observable, and easy to maintain.