默认情况下,StateGraph使用单一schema进行操作,并且所有节点都应使用该schema进行通信。但是,也可以为图形定义不同的输入和输出schema。当指定不同的schema时,内部schema仍将用于节点之间的通信。输入schema确保提供的输入与预期的结构相匹配,而输出模式则过滤内部数据以根据定义的输出schema仅返回相关信息。在这个例子中,我们将看到如何定义不同的输入和输出schema。from langgraph.graph import StateGraph, START, END
from typing_extensions import TypedDict
# 定义输入的模式
class InputState(TypedDict):
question: str
# 定义输出的模式
class OutputState(TypedDict):
answer: str
# 定义整体模式,结合输入和输出
class OverallState(InputState, OutputState):
pass
# 定义处理输入并生成答案的节点
def answer_node(state: InputState):
# 示例答案和一个额外的键
return {"answer": "bye", "question": state["question"]}
# 构建指定输入和输出模式的图
builder = StateGraph(OverallState, input=InputState, output=OutputState)
builder.add_node(answer_node) # 添加答案节点
builder.add_edge(START, "answer_node") # 定义起始边
builder.add_edge("answer_node", END) # 定义结束边
graph = builder.compile() # 编译图
# 使用输入调用图并打印结果
print(graph.invoke({"question": "hi"}))
StateGraph(OverallState, input=InputState, output=OutputState)