跳到内容

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

默认情况下,StateGraph 接受单个 schema,并且所有节点都应与该 schema 通信。但是,也可以为图定义明确的输入和输出 schema。如果您想区分输入和输出键,这将很有帮助。

在本 notebook 中,我们将通过一个示例来介绍这一点。从高层次上讲,要做到这一点,您只需在定义图时传入单独的 Annotation.Root({}) 对象作为 ` { input: Annotation.Root({}), output: Annotation.Root({}) }`。让我们看下面的示例!

import { Annotation, StateGraph } from "@langchain/langgraph";

const InputAnnotation = Annotation.Root({
  question: Annotation<string>,
});

const OutputAnnotation = Annotation.Root({
  answer: Annotation<string>,
});

const answerNode = (_state: typeof InputAnnotation.State) => {
  return { answer: "bye" };
};

const graph = new StateGraph({
  input: InputAnnotation,
  output: OutputAnnotation,
})
  .addNode("answerNode", answerNode)
  .addEdge("__start__", "answerNode")
  .compile();

await graph.invoke({
  question: "hi",
});
{ answer: 'bye' }
请注意,invoke 的输出只包含输出 schema。