如何为你的图定义输入/输出模式¶
默认情况下,StateGraph
使用单一模式运行,并且期望所有节点都使用该模式进行通信。不过,也可以为图定义不同的输入和输出模式。
当指定了不同的模式时,节点之间的通信仍将使用内部模式。输入模式确保提供的输入与预期结构相匹配,而输出模式则根据定义的输出模式过滤内部数据,仅返回相关信息。
在这个示例中,我们将了解如何定义不同的输入和输出模式。
安装设置¶
首先,让我们安装所需的包
为 LangGraph 开发设置 LangSmith
注册 LangSmith 以快速发现问题并提升你的 LangGraph 项目的性能。LangSmith 允许你使用跟踪数据来调试、测试和监控使用 LangGraph 构建的大语言模型应用程序 — 点击 此处 了解更多关于如何开始使用的信息。
定义并使用图¶
from langgraph.graph import StateGraph, START, END
from typing_extensions import TypedDict
# Define the schema for the input
class InputState(TypedDict):
question: str
# Define the schema for the output
class OutputState(TypedDict):
answer: str
# Define the overall schema, combining both input and output
class OverallState(InputState, OutputState):
pass
# Define the node that processes the input and generates an answer
def answer_node(state: InputState):
# Example answer and an extra key
return {"answer": "bye", "question": state["question"]}
# Build the graph with input and output schemas specified
builder = StateGraph(OverallState, input=InputState, output=OutputState)
builder.add_node(answer_node) # Add the answer node
builder.add_edge(START, "answer_node") # Define the starting edge
builder.add_edge("answer_node", END) # Define the ending edge
graph = builder.compile() # Compile the graph
# Invoke the graph with an input and print the result
print(graph.invoke({"question": "hi"}))
invoke
的输出仅包含输出架构。