类 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",
// }

类型参数

继承关系 (查看完整)

  • Graph<N, S, U, StateGraphNodeSpec<S, U>, ToStateDefinition<C>>
    • StateGraph

构造函数

属性

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]>

方法

  • 参数

    • stateDefinition: SDZod

    返回 void

  • 参数

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

    返回 this

  • 参数

    • 可选 __namedParameters: {
          可选 checkpointer?: false | BaseCheckpointSaver<number>;
          可选 interruptAfter?: "*" | N[];
          可选 interruptBefore?: "*" | N[];
          可选 name?: string;
          可选 store?: BaseStore;
      }
      • 可选 checkpointer?: false | BaseCheckpointSaver<number>
      • 可选 interruptAfter?: "*" | N[]
      • 可选 interruptBefore?: "*" | N[]
      • 可选 name?: string
      • 可选 store?: BaseStore

    返回 CompiledStateGraph<S, U, N, I, O, C>

  • 参数

    • key: N

    返回 this

    已弃用

    请改用 addEdge(START, key)

  • 参数

    • key: N

    返回 this

    已弃用

    请改用 addEdge(key, END)

  • 参数

    • 可选 interrupt: string[]

    返回 void

  • 参数

    • message: string

    返回 void