跳到内容

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

前提条件

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

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

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

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

设置

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

pip install -U langgraph

为 LangGraph 开发设置 LangSmith

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

定义和使用图

API 参考:StateGraph | START | END

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"}))
{'answer': 'bye'}
请注意,invoke 的输出仅包含输出模式。

评论