state通常用于保存当前会话中的消息,也可以自定义State用来存储额外的信息字段,state在节点之间传递,可以在节点中访问和修改state,此外LangGraph中的短期记忆通常使用state实现。
一、访问State中的消息
python
from langgraph.graph import StateGraph, MessagesState, START, END
# 定义节点
def node1(state: MessagesState):
print(state)
print(state['messages'])
#定义State类型为MessagesState
graph = StateGraph(MessagesState)
graph.add_node("node1", node1)
graph.add_edge(START, "node1")
graph.add_edge("node1", END)
graph = graph.compile()
graph.invoke({"messages": [{"role": "user", "content": "hi!"}]})
输出结果:
{'messages': [HumanMessage(content='hi!', additional_kwargs={}, response_metadata={}, id='6bcb92b6-d508-4ba4-996c-f05af82c1c2a')]}
HumanMessage(content='hi!', additional_kwargs={}, response_metadata={}, id='6bcb92b6-d508-4ba4-996c-f05af82c1c2a')
-
MessagesState是内置的state类型,默认只有"messages"一个字段,可用于保存图执行过程中产生的消息。
-
在节点中可以访问state中的消息
二、自定义state
python
from typing import TypedDict
from langgraph.graph import StateGraph, MessagesState, START, END
# 自定义State
class State(TypedDict):
# 注意:这里也可以定义message字段来接收上下文消息,大家可以自行尝试
name: str
age: int
def node1(state: State):
print(state['name'])
print(state['age'])
# print(state['name'])
# return state
graph = StateGraph(State)
graph.add_node("node1", node1)
graph.add_edge(START, "node1")
graph.add_edge("node1", END)
graph = graph.compile()
# 调用图时可传入State的内容
result = graph.invoke({"messages": [{"role": "user", "content": "hi!"}], "name": '张三', 'age': 18})
print(result)
输出结果:
张三
18
{'name': '张三', 'age': 18}
- 自定义state可通过继承TypedDict来实现
- 在调用图时,可传入state的内容字段
三、修改State
python
from typing import TypedDict
from langgraph.graph import StateGraph, MessagesState, START, END
class State(TypedDict):
name: str
age: int
def node1(state: State):
print(state['name'])
print(state['age'])
state['name'] = '李四'
state['age'] += 1
return state
graph = StateGraph(State)
graph.add_node("node1", node1)
graph.add_edge(START, "node1")
graph.add_edge("node1", END)
graph = graph.compile()
result = graph.invoke({"messages": [{"role": "user", "content": "hi!"}], "name": '张三', 'age': 18})
print(result)
输出结果:
张三
18
{'name': '李四', 'age': 19}
-
可以在节点中修改state中的字段
-
节点必须返回修改后的state,否则修改无效
四、总结
- state是用于保存当前会话的上下文信息的,不同会话间不能共享,可用于实现短期记忆
- MessageState保存图执行过程中产生的消息;
- 自定义state可以额外增加字段属性,当然也可以接受上下文的消息,上述案例为了简单起见只是定义了两个字段;
- 节点中可修改state,但需要返回修改后的State否则修改无效。