LangGraph Multiple Schemas Detailed interpretation
📚 Overview
This document explains in detail the concept of Multiple Schemas (multi-state schema) in LangGraph. This is an advanced state management technique that allows us to use different state structures in different parts of the graph, resulting in more flexible, safer, and clearer state management.
🎯 Core Concept
What are Multiple Schemas?
In previous studies, we usually used the single state mode: all nodes in the entire graph share the same state structure (Schema). But in actual development, this approach sometimes causes problems:
Single state problem:
- State Pollution: Internal nodes may generate intermediate data, but these data should not be exposed to users
- Inflexible input and output: Users may only need to provide part of the input, or only need part of the output
- Node coupling: All nodes rely on the same huge state structure, increasing complexity
Solution for Multiple Schemas:
- Private State: Private data can be passed between nodes and is not exposed to the outside.
- Input Schema: Limit user input fields
- Output Schema: Limit the fields returned to the user
- Internal State: The complete state used internally in the graph
🎭 Practical Case 1: Private State
Demand scenario
Suppose we have a calculation process:
node_1receives user inputfooand calculates the intermediate resultbaznode_2usesbazfor further calculations to obtain the final resultfoo- Key:
bazis an intermediate calculated value and should not be exposed to users
System architecture diagram
用户输入: {foo: 1}
↓
[node_1]
输入: OverallState {foo: 1}
计算: baz = foo + 1 = 2
输出: PrivateState {baz: 2}
↓
[node_2]
输入: PrivateState {baz: 2}
计算: foo = baz + 1 = 3
输出: OverallState {foo: 3}
↓
用户输出: {foo: 3} ← baz 被隐藏了!🔧 Detailed explanation of code implementation: private state
1. Define status
from typing_extensions import TypedDict
# 全局状态(对外可见)
class OverallState(TypedDict):
foo: int
# 私有状态(内部使用)
class PrivateState(TypedDict):
baz: intDesign ideas:
OverallState: The input and output status of the graph, visible to the userPrivateState: Private data passed between internal nodes- The two are completely independent and do not interfere with each other
2. Define nodes
def node_1(state: OverallState) -> PrivateState:
print("---Node 1---")
return {"baz": state['foo'] + 1}
def node_2(state: PrivateState) -> OverallState:
print("---Node 2---")
return {"foo": state['baz'] + 1}Key point analysis:
Type signature of node_1
def node_1(state: OverallState) -> PrivateState:
# ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^
# 输入类型 输出类型- Input:
OverallState- Readfoofrom user input or graph state - Output:
PrivateState- Returns private fieldbaz - Important: Although the return type is
PrivateState, the returned data will be merged into the overall state of the graph
Type signature of node_2
def node_2(state: PrivateState) -> OverallState:
# ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^
# 从私有状态读取 写回全局状态- Input:
PrivateState- Read the private fieldbazgenerated bynode_1 - Output:
OverallState- Update public fieldfoo
Python knowledge points: Type Hints
Python’s type annotations are used for:
- Static Type Checking: Helps IDEs and tools detect type errors
- Document Function: Clearly express the input and output of the function
- LangGraph usage: Tell LangGraph node which state structure to use
# 类型注解语法
def function(param: InputType) -> OutputType:
return value
# LangGraph 中的特殊用途
# LangGraph 会根据类型注解自动进行状态过滤和映射
def node(state: PrivateState) -> OverallState:
# LangGraph 自动:
# 1. 从总状态中提取 PrivateState 字段传给 node
# 2. 将 node 返回的 OverallState 字段合并回总状态
pass3. Build the graph
from langgraph.graph import StateGraph, START, END
# 使用 OverallState 作为图的主状态
builder = StateGraph(OverallState)
# 添加节点
builder.add_node("node_1", node_1)
builder.add_node("node_2", node_2)
# 添加边
builder.add_edge(START, "node_1")
builder.add_edge("node_1", "node_2")
builder.add_edge("node_2", END)
# 编译
graph = builder.compile()LangGraph knowledge point: state chart initialization
StateGraph(OverallState)
# ^^^^^^^^^^^^^
# 图的主状态类型- Although nodes may use different state types (such as
PrivateState), the graph itself has a main state type - This main state type defines the input and output interfaces of the graph
- The input and output types of nodes can be a subset or superset of the main state
4. Execution and Observation
result = graph.invoke({"foo": 1})
print(result)
# 输出: {'foo': 3}Detailed explanation of execution process:
| step | current state | node | input | output | after state update |
|---|---|---|---|---|---|
| 1 | {foo: 1} | node_1 | {foo: 1} | {baz: 2} | {foo: 1, baz: 2} |
| 2 | {foo: 1, baz: 2} | node_2 | {baz: 2} | {foo: 3} | {foo: 3, baz: 2} |
| 3 | Final output filtering | - | - | - | {foo: 3} ← baz is filtered out |
Key Observations:
bazexists in the internal state of the graph (step 1-2)- But in the final output, only the fields defined in
OverallState(foo) are returned. bazis successfully hidden and achieves the effect of private status
🎭 Practical Case 2: Input/Output Schema
Demand scenario
Build a question and answer system:
- User input: Only need to provide
question - Internal processing: Generate
answerandnotes(internal thinking process) - User Output: Only return
answer, hidenotes
System architecture diagram
用户输入: {question: "hi"} ← 符合 InputState
↓
[thinking_node]
生成: answer="bye", notes="... his name is Lance"
↓
[answer_node]
生成: answer="bye Lance"
↓
用户输出: {answer: "bye Lance"} ← 符合 OutputState,notes 被隐藏🔧 Detailed explanation of code implementation: input/output mode
1. Define three states
from typing_extensions import TypedDict
# 输入状态:用户必须提供的字段
class InputState(TypedDict):
question: str
# 输出状态:返回给用户的字段
class OutputState(TypedDict):
answer: str
# 内部状态:图内部使用的完整状态
class OverallState(TypedDict):
question: str
answer: str
notes: strDesign Pattern: State Hierarchy
InputState (最小输入)
↓ 包含于
OverallState (完整内部状态)
↓ 过滤为
OutputState (最小输出)Python knowledge point: TypedDict inheritance relationship
Although inheritance is not used here, TypedDict supports inheritance:
# 方式 1:独立定义(如上面代码)
class InputState(TypedDict):
question: str
# 方式 2:继承扩展
class OverallState(InputState): # 继承 InputState
answer: str
notes: str
# 两种方式效果类似,但继承方式确保字段一致性2. Define nodes (version 1: do not use input/output mode)
Let’s look at the version without Input/Output Schema first:
class OverallState(TypedDict):
question: str
answer: str
notes: str
def thinking_node(state: OverallState):
return {"answer": "bye", "notes": "... his name is Lance"}
def answer_node(state: OverallState):
return {"answer": "bye Lance"}
# 构建图
graph = StateGraph(OverallState)
graph.add_node("answer_node", answer_node)
graph.add_node("thinking_node", thinking_node)
graph.add_edge(START, "thinking_node")
graph.add_edge("thinking_node", "answer_node")
graph.add_edge(answer_node, END)
graph = graph.compile()
# 执行
result = graph.invoke({"question": "hi"})
print(result)
# 输出: {'question': 'hi', 'answer': 'bye Lance', 'notes': '... his name is Lance'}Issue: All internal fields (including notes) are exposed to the user!
3. Define nodes (version 2: using input/output mode)✅
class InputState(TypedDict):
question: str
class OutputState(TypedDict):
answer: str
class OverallState(TypedDict):
question: str
answer: str
notes: str
# 节点 1:只需要 InputState
def thinking_node(state: InputState):
return {"answer": "bye", "notes": "... his name is Lance"}
# 节点 2:使用 OverallState,但声明输出为 OutputState
def answer_node(state: OverallState) -> OutputState:
return {"answer": "bye Lance"}
# 构建图:指定输入和输出模式
graph = StateGraph(
OverallState,
input_schema=InputState, # 限定输入
output_schema=OutputState # 限定输出
)
graph.add_node("answer_node", answer_node)
graph.add_node("thinking_node", thinking_node)
graph.add_edge(START, "thinking_node")
graph.add_edge("thinking_node", "answer_node")
graph.add_edge(answer_node, END)
graph = graph.compile()
# 执行
result = graph.invoke({"question": "hi"})
print(result)
# 输出: {'answer': 'bye Lance'} ← notes 被过滤掉了!Key improvements:
- Specify
input_schemaandoutput_schemawhen constructingStateGraph - The input type of
thinking_nodeis annotated asInputState - The output type of
answer_nodeis annotated asOutputState
4. The role of type annotations
Type annotation for thinking_node
def thinking_node(state: InputState):
# ^^^^^^^^^^
# 只能访问 question 字段
return {"answer": "bye", "notes": "... his name is Lance"}Function:
- Input filtering: LangGraph only passes fields defined in
InputState(question) - Security: Nodes cannot accidentally access other fields
- Clarity: Clearly express a node’s input dependencies
Type annotation for answer_node
def answer_node(state: OverallState) -> OutputState:
# ^^^^^^^^^^^^^ ^^^^^^^^^^^
# 可以访问所有字段 输出会被过滤
return {"answer": "bye Lance"}Function:
- INPUT: gives access to the complete
OverallState(includingnotes) - Output: The return value will be filtered and only the fields defined by
OutputStatewill be retained.
Note: Even if answer_node returns notes, it will be filtered out:
def answer_node(state: OverallState) -> OutputState:
return {
"answer": "bye Lance",
"notes": "some internal note" # 这个会被过滤掉
}🎓 Summary of core knowledge points
LangGraph-specific concepts
1. Private State
Definition: The state passed between nodes but not exposed to the outside world
Implementation method:
# 定义私有状态
class PrivateState(TypedDict):
internal_data: str
# 节点输出私有状态
def node1(state: PublicState) -> PrivateState:
return {"internal_data": "secret"}
# 节点消费私有状态
def node2(state: PrivateState) -> PublicState:
# 使用 state["internal_data"]
return {"result": "processed"}Key Points:
- Private fields will not appear in the final output of the plot
- Exists only in the internal state of the graph
- Control visibility through type annotations
2. Input/Output Schema
Definition: Define the input and output interfaces of the graph
Implementation method:
graph = StateGraph(
InternalState, # 图内部的完整状态
input_schema=InputState, # 用户输入的状态结构
output_schema=OutputState # 返回给用户的状态结构
)Relationship between three states:
| Status type | Purpose | Number of fields | Scope |
|---|---|---|---|
| InputState | User input | Minimum (required fields) | Figure entry |
| InternalState | Internal Processing | Up to (all fields) | Figure Internal |
| OutputState | User Output | Moderate (useful fields) | Figure Export |
Typical mode:
InputState ⊆ InternalState ⊇ OutputState3. Status filtering mechanism
LangGraph automatically performs status filtering:
Input filtering:
# 用户调用
graph.invoke({"question": "hi", "extra": "ignored"})
# ^^^^^^^^^^^^^^^^
# 不在 InputState 中,被忽略
# 如果 InputState 只定义了 question,
# 则只有 question 会被传入图Output filtering:
# 图的内部状态
internal_state = {
"question": "hi",
"answer": "bye",
"notes": "internal"
}
# 返回给用户(只保留 OutputState 定义的字段)
output = {"answer": "bye"} # question 和 notes 被过滤4. Complete syntax of node type annotation
def node(state: InputType) -> OutputType:
# ^^^^^^^^^^^^^ ^^^^^^^^^^
# 从图状态读取 写回图状态
# (过滤输入) (过滤输出)
passType annotation combination:
| Input type | Output type | Meaning |
|---|---|---|
InputState | OutputState | Read minimum input, write specific output |
OverallState | PrivateState | Read all fields, write private fields |
PrivateState | OverallState | Read private fields and write public fields |
OverallState | OverallState | Read and write complete status (default) |
Python-specific knowledge points
1. TypedDict detailed explanation
Basic usage:
from typing_extensions import TypedDict
class Person(TypedDict):
name: str
age: int
# 使用
person: Person = {"name": "Alice", "age": 30}Features:
- Type Check: IDE will prompt a type error
- Dictionary Essence: Still an ordinary dictionary, just with added type information
- Runtime: no strict validation (unlike Pydantic)
Optional fields:
from typing import NotRequired
class OptionalState(TypedDict):
required: str
optional: NotRequired[int] # 可选字段
# 合法
state1: OptionalState = {"required": "value"}
state2: OptionalState = {"required": "value", "optional": 42}2. Type Hints
Function annotation:
def greet(name: str) -> str:
# ^^^ ^^^
# 参数类型 返回类型
return f"Hello, {name}"Variable annotations:
count: int = 0
names: list[str] = ["Alice", "Bob"]
data: dict[str, int] = {"a": 1, "b": 2}Generic annotation:
from typing import List, Dict, Optional, Union
# 旧式(Python 3.8)
names: List[str] = ["Alice"]
mapping: Dict[str, int] = {"a": 1}
optional_value: Optional[int] = None # int 或 None
union_value: Union[int, str] = 42 # int 或 str
# 新式(Python 3.9+)
names: list[str] = ["Alice"]
mapping: dict[str, int] = {"a": 1}
optional_value: int | None = None
union_value: int | str = 423. Annotated type
Common usage of Annotated in LangGraph:
from typing import Annotated
import operator
class State(TypedDict):
# 基础类型
name: str
# 带 reducer 的类型
messages: Annotated[list, operator.add]
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# 类型: list, 合并策略: operator.addAnnotated structure:
Annotated[Type, metadata1, metadata2, ...]
# ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^
# 实际类型 元数据(附加信息)Usage in LangGraph:
- First parameter: actual data type
- Second parameter: Reducer function (how to merge multiple updates)
# 例子:列表追加
messages: Annotated[list, operator.add]
# node1 返回 {"messages": ["a"]}
# node2 返回 {"messages": ["b"]}
# 最终状态: {"messages": ["a", "b"]} ← operator.add 自动合并💡 Best Practices
1. When to use private state?
✅ Applicable scenarios:
- Intermediate results of internal calculations (such as temporary variables, cache)
- Debugging information (such as execution logs, performance indicators)
- Sensitive information (do not want to be exposed to end users)
- Coordination data between nodes (such as counters, flags)
❌ Not applicable scenarios:
- Core data needed by users
- Information that needs to be persisted
- Data that needs to be shared among multiple public nodes
Example:
# ✅ 好的私有状态使用
class PrivateState(TypedDict):
processing_time: float # 性能统计
api_call_count: int # 调试信息
intermediate_result: str # 中间计算
# ❌ 不应该私有的数据
class PrivateState(TypedDict):
user_id: str # 用户需要知道的
final_result: str # 核心输出数据2. When to use input/output mode?
✅ Applicable scenarios:
- API service (requires clear input and output interface)
- Multi-tenant system (different users see different fields)
- Security sensitive applications (hide internal implementation details)
- Large projects (mandatory interface specifications)
❌ Not applicable scenarios:
- Simple internal tools
- Prototype development stage
- When all fields require input and output
Example:
# ✅ 好的输入/输出设计
class InputState(TypedDict):
user_query: str # 用户只需输入查询
class OutputState(TypedDict):
answer: str # 用户只需要答案
confidence: float # 和置信度
class InternalState(TypedDict):
user_query: str
answer: str
confidence: float
api_calls: int # 内部统计
cached: bool # 内部标志
raw_response: dict # 原始数据3. State design principles
Principle 1: Minimization principle
Each status contains only the required fields:
# ✅ 好的设计
class InputState(TypedDict):
question: str # 只要必需字段
# ❌ 过度设计
class InputState(TypedDict):
question: str
answer: str # 输入不需要 answer
notes: str # 输入不需要 notes
metadata: dict # 输入不需要 metadataPrinciple 2: Single Responsibility
Each state serves a specific purpose:
# ✅ 好的分离
class InputState(TypedDict): # 职责:接收用户输入
question: str
class ProcessingState(TypedDict): # 职责:内部处理
question: str
intermediate: str
class OutputState(TypedDict): # 职责:返回结果
answer: str
# ❌ 混淆职责
class MixedState(TypedDict): # 混合了所有职责
question: str # 输入
intermediate: str # 处理
answer: str # 输出Principle 3: Clear type annotations
Always specify the input and output types of a node explicitly:
# ✅ 清晰的类型注解
def process(state: InputState) -> OutputState:
# 一眼就知道输入输出
pass
# ❌ 不清晰的注解
def process(state): # 无法知道使用哪个状态
pass🚀 Advanced skills
1. Partial status update
Nodes can update only some fields of the state:
class State(TypedDict):
a: str
b: str
c: str
def node(state: State) -> State:
# 只更新 a,不影响 b 和 c
return {"a": "new_value"}
# 执行前: {a: "old", b: "b", c: "c"}
# 执行后: {a: "new_value", b: "b", c: "c"}2. Status verification
Runtime verification using Pydantic:
from pydantic import BaseModel, validator
class ValidatedInput(BaseModel):
question: str
@validator('question')
def question_not_empty(cls, v):
if not v.strip():
raise ValueError('Question cannot be empty')
return v
# 在节点中使用
def node(state):
# 验证输入
validated = ValidatedInput(**state)
# 使用 validated.question3. Dynamic status selection
Choose different status structures based on conditions:
def conditional_node(state: OverallState):
if state.get("use_detailed"):
# 返回详细状态
return DetailedState(...)
else:
# 返回简单状态
return SimpleState(...)4. State inheritance
Reuse status definition:
class BaseState(TypedDict):
timestamp: float
user_id: str
class ProcessingState(BaseState): # 继承 BaseState
data: str
status: str
# ProcessingState 自动包含 timestamp 和 user_id📊 Status mode comparison
| Features | Single State | Private State | Input/Output Mode |
|---|---|---|---|
| Complexity | Low | Medium | High |
| Flexibility | Low | Medium | High |
| Packaging | Poor | Good | Best |
| Applicable scenarios | Simple diagram | Internal calculation | API, service |
| Learning Curve | Flat | Moderate | Steep |
Selection suggestions:
# 简单原型 → 单一状态
graph = StateGraph(SimpleState)
# 需要隐藏中间数据 → 私有状态
def node1(state: PublicState) -> PrivateState: ...
def node2(state: PrivateState) -> PublicState: ...
# 对外服务 → 输入/输出模式
graph = StateGraph(
InternalState,
input_schema=InputState,
output_schema=OutputState
)🎯 Practical application cases
Case 1: Intelligent customer service system
# 输入:用户只需提供问题
class InputState(TypedDict):
user_question: str
# 输出:返回答案和置信度
class OutputState(TypedDict):
answer: str
confidence: float
# 内部:包含所有处理信息
class InternalState(TypedDict):
user_question: str
answer: str
confidence: float
retrieved_docs: list # 检索的文档(私有)
api_response: dict # API 原始响应(私有)
processing_time: float # 处理时间(私有)
def retrieve_docs(state: InputState) -> InternalState:
# 检索相关文档
docs = vector_db.search(state["user_question"])
return {"retrieved_docs": docs}
def generate_answer(state: InternalState) -> OutputState:
# 生成答案
response = llm.invoke({
"question": state["user_question"],
"context": state["retrieved_docs"]
})
return {
"answer": response.answer,
"confidence": response.confidence
}
graph = StateGraph(
InternalState,
input_schema=InputState,
output_schema=OutputState
)Case 2: Data processing pipeline
# 私有状态:中间处理步骤
class PrivateState(TypedDict):
cleaned_data: str
validation_result: bool
# 公开状态:输入和输出
class PublicState(TypedDict):
raw_data: str
processed_data: str
def clean_data(state: PublicState) -> PrivateState:
cleaned = state["raw_data"].strip().lower()
is_valid = len(cleaned) > 0
return {
"cleaned_data": cleaned,
"validation_result": is_valid
}
def process_data(state: PrivateState) -> PublicState:
if state["validation_result"]:
processed = state["cleaned_data"].upper()
return {"processed_data": processed}
else:
return {"processed_data": "ERROR"}
# cleaned_data 和 validation_result 不会出现在最终输出Case 3: Multi-stage authentication system
class LoginInput(TypedDict):
username: str
password: str
class SessionState(TypedDict): # 私有
user_id: int
permissions: list[str]
session_token: str
class LoginOutput(TypedDict):
success: bool
session_id: str # 不暴露完整 token
class InternalState(TypedDict):
username: str
password: str
user_id: int
permissions: list[str]
session_token: str
success: bool
session_id: str
def authenticate(state: LoginInput) -> SessionState:
# 验证用户并创建会话
user = db.authenticate(state["username"], state["password"])
return {
"user_id": user.id,
"permissions": user.permissions,
"session_token": generate_token(user.id)
}
def create_response(state: InternalState) -> LoginOutput:
# 创建安全的响应(隐藏敏感信息)
return {
"success": True,
"session_id": hash(state["session_token"])[:16]
}
# session_token 和 user_id 不会暴露给客户端🔍 Frequently Asked Questions
Q1: Will private state data be completely deleted?
Answer: No. The data in the private state still exists in the internal state of the graph, but is just filtered out on final output.
# 内部状态(执行过程中)
internal = {
"foo": 3,
"baz": 2 # ← 仍然存在
}
# 输出状态(返回给用户)
output = {
"foo": 3 # ← baz 被过滤
}Access internal state:
# 使用 stream 查看完整状态
for state in graph.stream({"foo": 1}):
print(state) # 可以看到 baz
# 使用 invoke 只能看到过滤后的状态
result = graph.invoke({"foo": 1})
print(result) # 看不到 bazQ2: Will the return value of the node overwrite or merge the status?
Answer: The default is merge (merge), not overwrite (replace).
# 初始状态
state = {"a": 1, "b": 2, "c": 3}
# 节点返回
def node(state):
return {"a": 99} # 只更新 a
# 执行后的状态
state = {"a": 99, "b": 2, "c": 3} # b 和 c 保持不变Unless using Reducer:
# 使用自定义 reducer
class State(TypedDict):
data: Annotated[list, my_custom_reducer]
# 可以实现覆盖、追加、合并等任何逻辑Q3: Can the status type be switched between different nodes?
Answer: Yes! This is the core functionality of Multiple Schemas.
def node1(state: StateA) -> StateB:
# 输入 StateA,输出 StateB
pass
def node2(state: StateB) -> StateC:
# 输入 StateB,输出 StateC
pass
def node3(state: StateC) -> StateA:
# 输入 StateC,输出 StateA(回到起点)
passRestrictions: Fields from all state types must be able to be merged into the diagram's main state type.
Q4: Can InputState contain fields that OverallState does not have?
Answer: This is not recommended as these fields cannot be stored into the graph state.
# ❌ 不推荐
class InputState(TypedDict):
question: str
extra_field: str # OverallState 没有这个字段
class OverallState(TypedDict):
question: str
answer: str
# 缺少 extra_field
# 当用户输入 {"question": "hi", "extra_field": "value"}
# extra_field 会被忽略或导致错误Correct approach: InputState should be a subset of OverallState.
📖 Further reading
- LangGraph Private State official document
- LangGraph Input/Output Schema official document
- Python TypedDict Documentation
- Python Type Hints PEP 484
🎁 Summary
Multiple Schemas is an advanced feature in LangGraph that provides three powerful capabilities:
Private State
- Pass private data between nodes
- Hide internal implementation details
- Keep output concise
Input Schema
- Limit user input
- Improve security
- Mandatory interface specifications
Output Schema
- Filter output fields
- Protect sensitive information
- Provide clear API
Core Value:
- Better Encapsulation: Hide internal details
- Clearer interface: clear input and output
- Greater Security: Prevent data leaks
- Better maintainability: clear code structure
By mastering Multiple Schemas, you can build more professional, secure, and easy-to-use LangGraph applications!