跳到内容

如何为您的图定义输入/输出 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' }
请注意,调用的输出仅包含输出 schema。