https://academy.langchain.com/courses/intro-to-langgraphhttps://github.com/shangxiang0907/langchain-academy文章目录State Schema 状态模式Review 回顾Goals 学习目标Schema 模式TypedDictDataclass 数据类DataclassPydanticState Schema 状态模式一句话总结这节课是在比较 LangGraph 状态的三种定义方法TypedDict 最轻量dataclass 更面向对象Pydantic 能进行运行时数据验证。Review 回顾图中所有节点共同读取和修改的数据。每个字段都像一条数据“通道”节点通过返回字典更新对应字段。In module 1, we laid the foundations!在模块 1 中我们打下了基础We built up to an agent that can:我们构建了一个具备以下能力的智能体act- let the model call specific toolsact执行——让模型调用特定工具observe- pass the tool output back to the modelobserve观察——将工具输出传回模型reason- let the model reason about the tool output to decide what to do next (e.g., call another tool or just respond directly)reason推理——让模型基于工具输出进行推理以决定下一步操作例如调用另一个工具或直接响应persist state- use an in memory checkpointer to support long-running conversations with interruptionspersist state持久化状态——使用内存中的检查点器checkpointer支持带有中断的长时间运行对话And, we showed how to serve it locally in LangGraph Studio or deploy it with LangGraph Cloud.此外我们还演示了如何在 LangGraph Studio 中本地运行该智能体或通过 LangGraph Cloud 部署它。Goals 学习目标In this module, we’re going to build a deeper understanding of both state and memory.在本模块中我们将深入理解状态与记忆。First, let’s review a few different ways to define your state schema.首先让我们回顾几种定义状态模式的不同方式。%%capture--no-stderr%pip install--quiet-U langgraphSchema 模式When we define a LangGraphStateGraph, we use a state schema.当我们定义一个 LangGraphStateGraph时需使用 状态模式。The state schema represents the structure and types of data that our graph will use.状态模式表示图将使用的数据结构与类型。All nodes are expected to communicate with that schema.所有节点都应依据该模式进行通信。LangGraph offers flexibility in how you define your state schema, accommodating various Python types and validation approaches!LangGraph 在状态模式的定义方式上提供了灵活性支持多种 Python 类型及验证方法TypedDictAs we mentioned in Module 1, we can use theTypedDictclass from python’stypingmodule.如模块 1 所述我们可以使用 Pythontyping模块中的TypedDict类。It allows you to specify keys and their corresponding value types.它允许你指定键及其对应值的类型。But, note that these are type hints.但请注意这些仅为类型提示。They can be used by static type checkers (like mypy) or IDEs to catch potential type-related errors before the code is run.它们可被静态类型检查器如 mypy或 IDE 用于在代码运行前捕获潜在的类型相关错误。But they are not enforced at runtime!但它们在运行时并不强制执行fromtyping_extensionsimportTypedDictclassTypedDictState(TypedDict):foo:strbar:strFor more specific value constraints, you can use things like theLiteraltype hint.若需更具体的值约束可使用Literal等类型提示。Here,moodcan only be either “happy” or “sad”.此处mood只能是 “happy” 或 “sad”。fromtypingimportLiteralclassTypedDictState(TypedDict):name:strmood:Literal[happy,sad]We can use our defined state class (e.g., hereTypedDictState) in LangGraph by simply passing it toStateGraph.我们可在 LangGraph 中通过将已定义的状态类例如此处的TypedDictState直接传入StateGraph来使用它。And, we can think about each state key as just a “channel” in our graph.同时我们可以将每个状态键视作图中的一个“通道”。As discussed in Module 1, we overwrite the value of a specified key or “channel” in each node.如模块 1 所述我们在每个节点中覆写指定键即“通道”的值。importrandomfromIPython.displayimportImage,displayfromlanggraph.graphimportStateGraph,START,ENDdefnode_1(state):print(---Node 1---)return{name:state[name] is ... }defnode_2(state):print(---Node 2---)return{mood:happy}defnode_3(state):print(---Node 3---)return{mood:sad}defdecide_mood(state)-Literal[node_2,node_3]:# Here, lets just do a 50 / 50 split between nodes 2, 3ifrandom.random()0.5:# 50% of the time, we return Node 2returnnode_2# 50% of the time, we return Node 3returnnode_3# Build graphbuilderStateGraph(TypedDictState)builder.add_node(node_1,node_1)builder.add_node(node_2,node_2)builder.add_node(node_3,node_3)# Logicbuilder.add_edge(START,node_1)builder.add_conditional_edges(node_1,decide_mood)builder.add_edge(node_2,END)builder.add_edge(node_3,END)# Addgraphbuilder.compile()# Viewdisplay(Image(graph.get_graph().draw_mermaid_png()))Because our state is a dict, we simply invoke the graph with a dict to set an initial value of thenamekey in our state.由于我们的状态是一个字典只需传入一个字典即可为状态中的name键设置初始值。graph.invoke({name:Lance})---Node 1--- ---Node 2--- {name: Lance is ... , mood: happy}Dataclass 数据类DataclassPython’s dataclasses provide another way to define structured data.Python 的 dataclasses 提供了 另一种定义结构化数据的方式。Dataclasses offer a concise syntax for creating classes that are primarily used to store data.数据类提供了一种简洁语法用于创建主要用途为存储数据的类。fromdataclassesimportdataclassdataclassclassDataclassState:name:strmood:Literal[happy,sad]To access the keys of adataclass, we just need to modify the subscripting used innode_1:要访问dataclass的键我们只需修改node_1中使用的下标访问方式We usestate.namefor thedataclassstate rather thanstate[name]for theTypedDictabove对于dataclass状态我们使用state.name而对于上方的TypedDict状态则使用state[name]You’ll notice something a bit odd: in each node, we still return a dictionary to perform the state updates.你会注意到一个略显奇怪的现象在每个节点中我们仍返回一个字典来执行状态更新。This is possible because LangGraph stores each key of your state object separately.这是可行的因为 LangGraph 将状态对象的每个键单独存储。The object returned by the node only needs to have keys (attributes) that match those in the state!节点所返回的对象只需包含与状态中匹配的键属性即可In this case, thedataclasshas keynameso we can update it by passing a dict from our node, just as we did when state was aTypedDict.本例中dataclass具有键name因此我们可通过节点返回字典来更新它这与状态为TypedDict时的操作完全一致。defnode_1(state):print(---Node 1---)return{name:state.name is ... }# Build graphbuilderStateGraph(DataclassState)builder.add_node(node_1,node_1)builder.add_node(node_2,node_2)builder.add_node(node_3,node_3)# Logicbuilder.add_edge(START,node_1)builder.add_conditional_edges(node_1,decide_mood)builder.add_edge(node_2,END)builder.add_edge(node_3,END)# Addgraphbuilder.compile()# Viewdisplay(Image(graph.get_graph().draw_mermaid_png()))We invoke with adataclassto set the initial values of each key / channel in our state!我们通过传入一个dataclass实例来为状态中的每个键通道设置初始值graph.invoke(DataclassState(nameLance,moodsad))---Node 1--- ---Node 3--- {name: Lance is ... , mood: sad}PydanticAs mentioned,TypedDictanddataclassesprovide type hints but they don’t enforce types at runtime.如前所述TypedDict和dataclasses仅提供类型提示而不在运行时强制执行类型。This means you could potentially assign invalid values without raising an error!这意味着你可能在不引发错误的情况下赋给变量非法值For example, we can setmoodtomadeven though our type hint specifiesmood: list[Literal[happy,sad]].例如尽管我们的类型提示声明为mood: list[Literal[happy,sad]]我们仍可将mood设为mad。dataclass_instanceDataclassState(nameLance,moodmad)Pydantic is a data validation and settings management library using Python type annotations.Pydantic 是一个利用 Python 类型注解实现数据验证和配置管理的库。It’s particularly well-suited for defining state schemas in LangGraph due to its validation capabilities.得益于其强大的验证能力Pydantic 特别适合 在 LangGraph 中定义状态模式。Pydantic can perform validation to check whether data conforms to the specified types and constraints at runtime.Pydantic 可在运行时执行验证以检查数据是否符合指定的类型与约束条件。frompydanticimportBaseModel,field_validator,ValidationErrorclassPydanticState(BaseModel):name:strmood:str# happy or sadfield_validator(mood)classmethoddefvalidate_mood(cls,value):# Ensure the mood is either happy or sadifvaluenotin[happy,sad]:raiseValueError(Each mood must be either happy or sad)returnvaluetry:statePydanticState(nameJohn Doe,moodmad)exceptValidationErrorase:print(Validation Error:,e)Validation Error: 1 validation error for PydanticState mood Input should be happy or sad [typeliteral_error, input_valuemad, input_typestr] For further information visit https://errors.pydantic.dev/2.8/v/literal_errorWe can usePydanticStatein our graph seamlessly.我们可以无缝地在图中使用PydanticState。# Build graphbuilderStateGraph(PydanticState)builder.add_node(node_1,node_1)builder.add_node(node_2,node_2)builder.add_node(node_3,node_3)# Logicbuilder.add_edge(START,node_1)builder.add_conditional_edges(node_1,decide_mood)builder.add_edge(node_2,END)builder.add_edge(node_3,END)# Addgraphbuilder.compile()# Viewdisplay(Image(graph.get_graph().draw_mermaid_png()))graph.invoke(PydanticState(nameLance,moodsad))---Node 1--- ---Node 3--- {name: Lance is ... , mood: sad}
