新闻详情

新闻详情

首页 / 资讯中心 / 详情

(LangGraph教程)2. State and Memory——Lesson 1: State Schema(状态模式、状态结构、TypedDict、dataclass、Pydantic)

发布时间:2026/11/15 12:57:42来源:尧图网络
(LangGraph教程)2. State and Memory——Lesson 1: State Schema(状态模式、状态结构、TypedDict、dataclass、Pydantic)
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}
网站建设高端定制企业官网
RELATED

相关资讯

更多精彩内容,欢迎继续阅读

较早相关资讯

最新相关资讯

【外设】之大彩串口显示屏 2026/11/15 4:54:16

【外设】之大彩串口显示屏

大彩串口屏初步使用 1 .官网下载 STM32 屏幕 GUI 设计资料 http://www.gz-dc.com/category/typeid/4112 找到 STM32 Keil 工程,移植相关代码因项目而异进行移植,由于项目简单,本人只对用到的指令接口进行修改。 比如:注意事项&…

阅读更多 →
无法下载Windows系统iso文件 2026/11/15 2:04:12

无法下载Windows系统iso文件

当我遇到这个问题的时候,我打开了一个网站: 登录 然后我打算下载的时候: 突然那个官方的连接就可以下载了:

阅读更多 →
【清华代码熊】DeepSeek V4.1 Flash 后训练详解 2026/11/14 10:11:15

【清华代码熊】DeepSeek V4.1 Flash 后训练详解

📌 上期解析了 DeepSeek V4.1 Flash 模型架构改进,本期解析 DeepSeek V4.1 Flash 预训练/后训练技术: 🌟 预训练:45T 文本 多模态混合语料、直接训练 sparse attention(取消 DeepSeek V4 的 dense 冷启动&…

阅读更多 →
Shuffle-R1: Efficient RL framework for Multimodal Large Language Models via Data-centric Dynamic ... 2026/11/14 17:14:38

Shuffle-R1: Efficient RL framework for Multimodal Large Language Models via Data-centric Dynamic ...

文章主要内容和创新点 主要内容 本文聚焦于多模态大语言模型(MLLM)强化学习(RL)训练中的效率问题,提出了一个名为Shuffle-R1的框架。研究发现,当前RL训练存在两个关键缺陷: 优势值坍缩(Advantage Collapsing):批次中大多数优势值集中在零附近,导致有效梯度信号被淹…

阅读更多 →
PRvL: Quantifying the Capabilities and Risks of Large Language Models for PII Redaction 2026/11/14 16:35:50

PRvL: Quantifying the Capabilities and Risks of Large Language Models for PII Redaction

一、文章主要内容总结 本文聚焦于利用大型语言模型(LLMs)实现个人身份信息(PII)脱敏的研究,旨在解决传统脱敏方法(如基于规则的系统、领域特定命名实体识别(NER)模型)泛化能力差、跨格式/跨语境适应性弱的问题。 研究通过全面评估多种LLM架构(包括密集型LLM(D-LLM…

阅读更多 →
LLaVA-RE: Binary Image-Text Relevancy Evaluation with Multimodal Large Language Model 2026/11/15 4:06:36

LLaVA-RE: Binary Image-Text Relevancy Evaluation with Multimodal Large Language Model

文章主要内容和创新点 主要内容 本文聚焦于二进制图像-文本相关性评估任务(判断图像与文本“相关”或“不相关”),针对该任务中文本格式多样、相关性定义随场景变化等挑战,提出了基于多模态大语言模型(MLLM)的解决方案LLaVA-RE。 模型设计:LLaVA-RE基于LLaVA 1.5架构,…

阅读更多 →

今日资讯

本周资讯

本月资讯

看完文章仍有疑问?

联系尧图顾问,获取一对一建站咨询

立即免费咨询 📞 400-888-8888
📞 ✉