如何将 Pydantic 模型用作图状态¶
StateGraph 在初始化时接受一个 state_schema
参数,用于指定图中节点可以访问和更新的状态的“形状”。
在我们的示例中,我们通常使用 python 原生的 TypedDict
作为 state_schema
(或者在 MessageGraph 的情况下,使用 list),但 state_schema
可以是任何 type。
在本操作指南中,我们将了解如何使用 Pydantic BaseModel。可以将其用作 state_schema
,以在输入上添加运行时验证。
已知限制
- 本笔记本使用 Pydantic v2
BaseModel
,它需要langchain-core >= 0.3
。使用langchain-core < 0.3
将由于混合使用 Pydantic v1 和 v2BaseModels
而导致错误。 - 目前,图的
output
将**不会**是 pydantic 模型的实例。 - 运行时验证仅在节点的**输入**上发生,而不是在输出上发生。
- 来自 pydantic 的验证错误跟踪不会显示错误发生在哪个节点中。
设置¶
首先,我们需要安装所需的软件包
import getpass
import os
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("OPENAI_API_KEY")
设置 LangSmith 以进行 LangGraph 开发
注册 LangSmith 以快速发现问题并提高 LangGraph 项目的性能。LangSmith 允许您使用跟踪数据来调试、测试和监控使用 LangGraph 构建的 LLM 应用程序——阅读 此处 了解更多关于如何开始使用。
输入验证¶
from langgraph.graph import StateGraph, START, END
from typing_extensions import TypedDict
from pydantic import BaseModel
# The overall state of the graph (this is the public state shared across nodes)
class OverallState(BaseModel):
a: str
def node(state: OverallState):
return {"a": "goodbye"}
# Build the state graph
builder = StateGraph(OverallState)
builder.add_node(node) # node_1 is the first node
builder.add_edge(START, "node") # Start the graph with node_1
builder.add_edge("node", END) # End the graph after node_1
graph = builder.compile()
# Test the graph with a valid input
graph.invoke({"a": "hello"})
API 参考:StateGraph | START | END
使用无效输入调用图
try:
graph.invoke({"a": 123}) # Should be a string
except Exception as e:
print("An exception was raised because `a` is an integer rather than a string.")
print(e)
An exception was raised because `a` is an integer rather than a string.
1 validation error for OverallState
a
Input should be a valid string [type=string_type, input_value=123, input_type=int]
For further information visit https://errors.pydantic.dev/2.9/v/string_type
多个节点¶
运行时验证也将在多节点图中工作。在下面的示例中,bad_node
将 a
更新为整数。
由于运行时验证发生在输入上,因此验证错误将在调用 ok_node
时发生(而不是在 bad_node
返回与模式不一致的状态更新时发生)。
from langgraph.graph import StateGraph, START, END
from typing_extensions import TypedDict
from pydantic import BaseModel
# The overall state of the graph (this is the public state shared across nodes)
class OverallState(BaseModel):
a: str
def bad_node(state: OverallState):
return {
"a": 123 # Invalid
}
def ok_node(state: OverallState):
return {"a": "goodbye"}
# Build the state graph
builder = StateGraph(OverallState)
builder.add_node(bad_node)
builder.add_node(ok_node)
builder.add_edge(START, "bad_node")
builder.add_edge("bad_node", "ok_node")
builder.add_edge("ok_node", END)
graph = builder.compile()
# Test the graph with a valid input
try:
graph.invoke({"a": "hello"})
except Exception as e:
print("An exception was raised because bad_node sets `a` to an integer.")
print(e)
API 参考:StateGraph | START | END
An exception was raised because bad_node sets `a` to an integer.
1 validation error for OverallState
a
Input should be a valid string [type=string_type, input_value=123, input_type=int]
For further information visit https://errors.pydantic.dev/2.9/v/string_type