1103
from typing import Annotated, get_type_hints, get_origin, get_args
from typing_extensions import TypedDict
from operator import add # 用于列表拼接的操作符函数
from langgraph.graph import StateGraph, START, END
# # 定义状态类型,使用TypedDict明确字段类型
# class StateWithoutAdd(TypedDict):
# # foo字段为整数类型,更新时直接替换
# foo: int
# # bar字段为字符串列表
# bar: list[str]
# def example_node(state: StateWithoutAdd):
# return {"bar": ["done"]}
# graph_builder = StateGraph(StateWithoutAdd)
# 定义状态类型,使用TypedDict明确字段类型
class State(TypedDict):
# foo字段为整数类型,更新时直接替换
foo: int
# bar字段为字符串列表,使用Annotated标注合并策略为add(列表拼接)
bar: Annotated[list[str], add] # map高阶函数
graph_builder = StateGraph(State)
# def example_node(state: State):
# return {"bar": ["done"]}
def example_node(state: State):
print(state)
print(state["bar"] + ["OK"])
return {"bar":state["bar"] + ["OK"]}
graph_builder.add_node("example_node", example_node)
graph_builder.add_edge(START, "example_node")
graph_builder.add_edge("example_node", END)
graph = graph_builder.compile()
print(graph.invoke({"bar": ["My", "name"], "foo": 1}))
# def get_reducers() -> dict[str, callable]:
# """获取状态字段的合并策略映射表
# 通过解析State的类型注解,提取字段的合并函数(如add)
# 返回形如 {'foo': None, 'bar': operator.add} 的字典
# """
# reducers = {}
# # 获取State的类型提示,包含元数据(Annotated信息)
# type_hints = get_type_hints(State, include_extras=True)
# print(type_hints)
# for key, hint in type_hints.items():
# origin = get_origin(hint) # 获取类型注解的原始类型(如Annotated)
# if origin is Annotated:
# args = get_args(hint) # 分解Annotated的参数
# # 取第一个参数为实际类型,第二个为合并函数(如add)
# if len(args) >= 2:
# reducers[key] = args[1]
# else:
# reducers[key] = None
# else:
# reducers[key] = None # 无合并策略则设为None
# return reducers
#
# def update_state(current_state: State, update: dict) -> State:
# """更新状态字典,支持字段级合并策略
# 根据get_reducers()中的策略:
# - 若字段有合并函数(如add),则用该函数合并新旧值
# - 否则直接替换为新值
# 注意:直接修改并返回current_state(需传入拷贝以避免副作用)
# """
# reducers = get_reducers()
# for key, new_value in update.items():
# if key in current_state:
# current_value = current_state[key]
# reducer = reducers.get(key)
# if callable(reducer):
# # 使用合并函数(如add(current_value, new_value))
# current_state[key] = reducer(current_value, new_value)
# else:
# current_state[key] = new_value # 直接替换
# else:
# current_state[key] = new_value # 新增字段
# return current_state
#
#
# # 测试示例
# if __name__ == "__main__":
# # 初始化状态(注意TypedDict只是类型提示,实际仍为普通字典)
# initial_state: State = {"foo": 1, "bar": ["hi"]}
# print("初始状态:", initial_state) # {'foo': 1, 'bar': ['hi']}
#
# # 第一次更新:直接替换foo字段
# update1 = {"foo": 2}
# # 传入拷贝以避免修改原始状态
# new_state = update_state(initial_state.copy(), update1)
# print("第一次更新后:", new_state) # {'foo': 2, 'bar': ['hi']}
#
# # 第二次更新:使用add合并bar字段(列表拼接)
# update2 = {"bar": ["bye"]}
# new_state = update_state(new_state.copy(), update2)
# print("第二次更新后:", new_state) # {'foo': 2, 'bar': ['hi', 'bye']}好的,我已经读取了文件的完整内容。下面是对 未被注释 的代码部分的详细解释:
一、导入部分(第 1–4 行)
python
from typing import Annotated, get_type_hints, get_origin, get_args
from typing_extensions import TypedDict
from operator import add
from langgraph.graph import StateGraph, START, END| 导入 | 作用 |
|---|---|
Annotated |
给类型注解附加元数据(这里用来标注字段的合并策略) |
TypedDict |
定义带类型约束的字典结构,相当于给 dict 加上字段类型提示 |
add |
来自 operator 模块,等价于 lambda x, y: x + y,这里用作列表拼接的 reducer 函数 |
StateGraph, START, END |
LangGraph 的核心类,用于构建有状态的图,以及图的起点和终点常量 |
二、状态定义(第 18–26 行)
python
class State(TypedDict):
foo: int
bar: Annotated[list[str], add]
graph_builder = StateGraph(State)这是整个文件的核心概念展示——字段级别的合并策略(Reducer):
foo: int— 普通字段。LangGraph 更新状态时会直接覆盖,即新值替换旧值。bar: Annotated[list[str], add]— 带合并策略的字段。Annotated的第一个参数是实际类型list[str],第二个参数add是reducer 函数。LangGraph 在更新时会调用add(旧值, 新值),也就是旧列表 + 新列表,实现列表拼接而非覆盖。
💡 这就是 LangGraph 的 Channels / Reducers 机制:不同字段可以有不同的更新行为,非常适合多节点协作场景(比如多个节点都往同一个消息列表里追加内容)。
StateGraph(State) 用这个状态类型初始化一个图构建器。
三、节点定义与图构建(第 31–40 行)
python
def example_node(state: State):
print(state)
print(state["bar"] + ["OK"])
return {"bar": state["bar"] + ["OK"]}
graph_builder.add_node("example_node", example_node)
graph_builder.add_edge(START, "example_node")
graph_builder.add_edge("example_node", END)
graph = graph_builder.compile()
print(graph.invoke({"bar": ["My", "name"], "foo": 1}))逐步拆解:
example_node— 一个普通的 LangGraph 节点函数,接收当前state,返回一个状态更新字典。它把state["bar"]后面追加了["OK"]。
add_node/add_edge— 构建最简单的线性图:START → example_node → END。
graph.compile()— 将构建好的图编译成可执行对象。
graph.invoke(...)— 传入初始状态{"bar": ["My", "name"], "foo": 1}执行图。
执行流程推演
| 步骤 | 状态变化 |
|---|---|
| 初始输入 | {"foo": 1, "bar": ["My", "name"]} |
example_node 返回 |
{"bar": ["My", "name", "OK"]} |
| LangGraph 应用 reducer | foo 未被更新 → 保留 1;bar 用 add 合并 → ["My", "name"] + ["My", "name", "OK"] = ["My", "name", "My", "name", "OK"] |
最终输出
text
{'foo': 1, 'bar': ['My', 'name', 'My', 'name', 'OK']}⚠️ 注意:因为
example_node返回的是完整列表["My", "name"] + ["OK"],而 LangGraph 又用add把旧值和这个新值拼接了一遍,所以bar里的["My", "name"]出现了两次。这演示了 reducer 的实际行为——它不会替换,而是合并。
总结
这个文件演示了 LangGraph 的一个关键特性:通过 Annotated[类型, reducer函数] 为状态字段指定合并策略。在多节点场景下,不同节点可以安全地向同一个列表/集合字段追加内容,而不会互相覆盖,这是 LangChain/LangGraph Agent 中消息历史累积的底层原理。