跳至内容

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

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

在本 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 的输出仅包含输出模式。