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}
企业数字化 ERP 产品动态
相关推荐
大模型四大行业应用实践详解(小白/程序员入门必备) 本文详细拆解大模型技术在汽车、金融、能源和电商四大核心行业的落地实践,结合具体应用场景补充实操逻辑,适合小白入门了解大模型行业价值,也方便程序员参考技术落地思路。在汽车领域,大模型实现智能座舱与自动驾驶的双重升级&… · 2026/9/26 11:10:09
6个月平滑转型大模型应用开发,从CRUD到AI工程化实战路线 本文为有一定经验的Java后端开发者提供了一条清晰、可落地的转型大模型应用开发的技术路线。文章强调了Java开发者在大模型应用开发中的优势,并指出转型关键在于将AI能力作为服务组件集成到现有系统架构中。内容涵盖了从API调用、RAG系统构建到Agent设计及生产级架构… · 2026/9/26 11:10:09
Cursor 四种交互模式配 TaoToken:settings.json 骨架与验证动作 /* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views … · 2026/9/26 11:42:06
基于C++的游戏引擎开发实战:从ECS架构到渲染循环 聊点实在的。这个“基于C的游戏引擎开发”项目,我前前后后折腾了快一年。起因很简单,玩过的游戏多了,不服气,想自己搞明白屏幕上那些角色移动、碰撞反馈、特效闪烁,到底是怎么被“驱动”起来的。结果一路从C基础语法写… · 2026/9/26 11:42:00
SpringBoot+Vue音乐网站实战:数据库设计到前后端联调全解析 每年这个时候,计算机专业的朋友们就开始为毕业设计发愁了。音乐网站系统算是Java Web方向最经典的题目之一,乍一看到处都是,但真正能跑通、能讲清楚原理、能过答辩的项目其实不多。我前阵子刚帮人完整梳理过一套基于SpringBoot Vue的音乐网站… · 2026/9/26 11:42:00
阿里云盘变本地磁盘:RaiDrive+AList的WebDAV桥接避坑指南 简介:资源面向需要将阿里云盘映射为本地磁盘、实现开机自动挂载的Windows用户,解决频繁手动连接云盘的痛点,适合日常办公、大文件临时存取与多设备文件同步场景。压缩包共4个文件,包含RaiDrive安装程序、阿里云盘WebDAV适配工具及… · 2026/9/26 11:42:00
数据库课后习题答案别硬背:当测试用例集刷,效率翻倍 简介:万常选版《数据库原理与设计》课后习题答案资源,覆盖第2至6章及第9章,适合正在学习关系模型、数据库建模、关系数据理论与模式求精的本科生、自学者作为复习与自测材料。压缩包共7个文件,含3个doc参考答案、2个sql示例脚本、… · 2026/9/26 0:00:21
OpenClaw 替代品?Hermes Agent 踩坑实录:macOS 飞书接入 TaoToken 配置 /* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views … · 2026/9/26 0:00:40
向下兼容与向上兼容:接口设计中的兼容性策略与工程实践 一次版本升级事故,是很多团队绕不过去的坎。线上环境里,服务端明明已经上线了新版接口,老的移动端还在照着旧文档传参数。请求一到网关,校验直接拒绝,用户操作失败,客服群炸了锅,开发群里开始互… · 2026/9/26 0:00:46