命名空间注释

在 StateGraph 状态中实例化通道的助手。

可以在 Annotation.Root 包装器中以两种方式之一用作字段

  1. 直接:创建一个通道,用于存储从节点返回的最新值。
  2. 使用 reducer:创建一个通道,在节点的返回值上应用 reducer。

示例

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

// Define a state with a single string key named "currentOutput"
const SimpleAnnotation = Annotation.Root({
currentOutput: Annotation<string>,
});

const graphBuilder = new StateGraph(SimpleAnnotation);

// A node in the graph that returns an object with a "currentOutput" key
// replaces the value in the state. You can get the state type as shown below:
const myNode = (state: typeof SimpleAnnotation.State) => {
return {
currentOutput: "some_new_value",
};
}

const graph = graphBuilder
.addNode("myNode", myNode)
...
.compile();

示例

import { type BaseMessage, AIMessage } from "@langchain/core/messages";
import { StateGraph, Annotation } from "@langchain/langgraph";

// Define a state with a single key named "messages" that will
// combine a returned BaseMessage or arrays of BaseMessages
const AnnotationWithReducer = Annotation.Root({
messages: Annotation<BaseMessage[]>({
// Different types are allowed for updates
reducer: (left: BaseMessage[], right: BaseMessage | BaseMessage[]) => {
if (Array.isArray(right)) {
return left.concat(right);
}
return left.concat([right]);
},
default: () => [],
}),
});

const graphBuilder = new StateGraph(AnnotationWithReducer);

// A node in the graph that returns an object with a "messages" key
// will update the state by combining the existing value with the returned one.
const myNode = (state: typeof AnnotationWithReducer.State) => {
return {
messages: [new AIMessage("Some new response")],
};
};

const graph = graphBuilder
.addNode("myNode", myNode)
...
.compile();

索引

函数