跳到内容

如何定义图状态

本操作指南将介绍定义图状态的不同方法。

先决条件

  • 状态概念指南 - 关于定义图状态的概念指南。
  • 构建图 - 本操作指南假设你对如何构建图有基本的了解。

设置

本指南需要安装 @langchain/langgraph@langchain/core

npm install @langchain/langgraph @langchain/core

开始入门

对于新的 StateGraph 图,建议使用 Annotation 函数来定义你的图状态。Annotation.Root 函数用于创建顶层状态对象,其中每个字段代表图中的一个通道。

以下是如何定义一个包含一个名为 messages 通道的简单图状态的示例

import { BaseMessage } from "@langchain/core/messages";
import { Annotation } from "@langchain/langgraph";

const GraphAnnotation = Annotation.Root({
  // Define a 'messages' channel to store an array of BaseMessage objects
  messages: Annotation<BaseMessage[]>({
    // Reducer function: Combines the current state with new messages
    reducer: (currentState, updateValue) => currentState.concat(updateValue),
    // Default function: Initialize the channel with an empty array
    default: () => [],
  })
});

每个通道都可以选择性地具有 reducerdefault 函数:- reducer 函数定义了新值如何与现有状态组合。 - default 函数为通道提供初始值。

有关 reducer 的更多信息,请参阅 reducer 概念指南

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

在上面,我们所做的只是定义通道,然后将未实例化的 Annotation 函数作为值传递。请务必注意,我们始终将每个通道的 TypeScript 类型作为第一个泛型参数传递给 Annotation。这样做确保了我们的图状态是类型安全的,并且我们可以在定义节点时获得正确的类型。下面展示了如何从 Annotation 函数中提取类型

type QuestionAnswerAnnotationType = typeof QuestionAnswerAnnotation.State;

这等效于以下类型

type QuestionAnswerAnnotationType = {
  question: string;
  answer: string;
}

合并状态

如果你有两个图状态注解,你可以使用 spec 值将两者合并为一个注解

const MergedAnnotation = Annotation.Root({
  ...QuestionAnswerAnnotation.spec,
  ...GraphAnnotation.spec,
})

合并后的注解类型是两个注解的交集

type MergedAnnotation = {
  messages: BaseMessage[];
  question: string;
  answer: string;
}

最后,使用注解实例化你的图就像将注解传递给 StateGraph 构造函数一样简单

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

const workflow = new StateGraph(MergedAnnotation);

状态通道

Annotation 函数是围绕 LangGraph 中状态定义方式的底层实现的便捷包装器。仍然可以使用 channels 对象(Annotation 是其包装器)定义状态,尽管不建议在大多数情况下使用。以下示例展示了如何使用此模式实现图

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

interface WorkflowChannelsState {
  messages: BaseMessage[];
  question: string;
  answer: string;
}

const workflowWithChannels = new StateGraph<WorkflowChannelsState>({
  channels: {
    messages: {
      reducer: (currentState, updateValue) => currentState.concat(updateValue),
      default: () => [],
    },
    question: null,
    answer: null,
  }
});

在上面,我们将 questionanswer 的值设置为 null,因为它不包含默认值。要设置默认值,通道应按照 messages 键的方式实现,其中 default 工厂返回默认值。reducer 函数是可选的,如果需要,可以添加到通道对象中。