Skip to content

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

先决条件

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

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

当指定不同的模式时,节点之间仍然会使用内部模式进行通信。输入模式确保提供的输入与预期结构匹配,而输出模式则过滤内部数据,只返回与定义的输出模式相关的数据。

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

设置

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

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

为LangGraph开发设置LangSmith

注册LangSmith,可以快速发现并解决项目中的问题,提高LangGraph项目的性能。LangSmith允许您使用跟踪数据来调试、测试和监控使用LangGraph构建的LLM应用程序——更多关于如何开始的内容,请参阅这里

定义和使用图

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 Reference: StateGraph | START | END

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

Comments