类 StateGraph<SD, S, U, N, I, O, C>

一个图,其节点通过读取和写入共享状态进行通信。每个节点接受定义的 State 作为输入,并返回 Partial<State>

每个状态键都可以选择使用 reducer 函数进行注释,该函数将用于聚合从多个节点接收到的该键的值。reducer 函数的签名是 (left: Value, right: UpdateValue) => Value。

请参阅 Annotation 以了解有关定义状态的更多信息。

在向图中添加节点和边之后,您必须先对其调用 .compile(),然后才能使用它。

示例

import {
type BaseMessage,
AIMessage,
HumanMessage,
} 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 StateAnnotation = Annotation.Root({
sentiment: Annotation<string>,
messages: Annotation<BaseMessage[]>({
reducer: (left: BaseMessage[], right: BaseMessage | BaseMessage[]) => {
if (Array.isArray(right)) {
return left.concat(right);
}
return left.concat([right]);
},
default: () => [],
}),
});

const graphBuilder = new StateGraph(StateAnnotation);

// 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 StateAnnotation.State) => {
return {
messages: [new AIMessage("Some new response")],
sentiment: "positive",
};
};

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

await graph.invoke({ messages: [new HumanMessage("how are you?")] });

// {
// messages: [HumanMessage("how are you?"), AIMessage("Some new response")],
// sentiment: "positive",
// }

类型参数

继承关系 (查看完整)

构造函数

属性

branches: Record<string, Record<string, Branch<S, N, any>>>
channels: Record<string, BaseChannel<unknown, unknown, unknown> | ManagedValueSpec>
compiled: boolean
edges: Set<["__start__" | N, "__end__" | N]>
entryPoint?: string
nodes: Record<N, StateGraphNodeSpec<S, U>>
waitingEdges: Set<[N[], N]>

访问器

  • get allEdges(): Set<[string, string]>
  • 返回 Set<[string, string]>

方法

  • 参数

    返回 void

  • 参数

    • startKey: "__start__" | N | N[]
    • endKey: "__end__" | N

    返回 this

  • 参数

    • key: N

    返回 this

    已弃用

    请使用 addEdge(START, key) 代替

  • 参数

    • key: N

    返回 this

    已弃用

    请使用 addEdge(key, END) 代替

  • 参数

    • Optional interrupt: string[]

    返回 void

  • 参数

    • message: string

    返回 void