跳到内容

如何为你的图定义输入/输出模式

前提条件

本指南假设您熟悉以下内容

默认情况下,StateGraph 使用单一模式运行,并且所有节点都应使用该模式进行通信。但是,也可以为图定义不同的输入和输出模式。

当指定不同的模式时,内部模式仍将用于节点之间的通信。输入模式确保提供的输入与预期的结构匹配,而输出模式则过滤内部数据,以仅返回根据定义的输出模式的相关信息。

在此示例中,我们将看到如何定义不同的输入和输出模式。

设置

首先,让我们安装所需的软件包

%%capture --no-stderr
%pip install -U langgraph

设置 LangSmith 以进行 LangGraph 开发

注册 LangSmith 以快速发现问题并提高 LangGraph 项目的性能。 LangSmith 允许您使用跟踪数据来调试、测试和监控使用 LangGraph 构建的 LLM 应用程序 — 在此处阅读有关如何开始使用的更多信息:here

定义和使用图

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"}))

API 参考:StateGraph | START | END

{'answer': 'bye'}
请注意,invoke 的输出仅包含输出模式。

评论