LangChain Reference home pageLangChain ReferenceLangChain Reference
  • GitHub
  • Main Docs
Deep Agents
LangChain
LangGraph
Integrations
LangSmith
LangGraph
  • Web
  • Channels
  • Pregel
  • Prebuilt
  • Remote
LangGraph SDK
  • Client
  • Auth
  • React
  • Logging
  • React Ui
  • Server
LangGraph Checkpoint
LangGraph Checkpoint MongoDB
LangGraph Checkpoint Postgres
  • Store
LangGraph Checkpoint Redis
  • Shallow
  • Store
LangGraph Checkpoint SQLite
LangGraph Checkpoint Validation
  • Cli
LangGraph API
LangGraph CLI
LangGraph CUA
  • Utils
LangGraph Supervisor
LangGraph Swarm
⌘I

LangChain Assistant

Ask a question to get started

Enter to send•Shift+Enter new line

Menu

LangGraph
WebChannelsPregelPrebuiltRemote
LangGraph SDK
ClientAuthReactLoggingReact UiServer
LangGraph Checkpoint
LangGraph Checkpoint MongoDB
LangGraph Checkpoint Postgres
Store
LangGraph Checkpoint Redis
ShallowStore
LangGraph Checkpoint SQLite
LangGraph Checkpoint Validation
Cli
LangGraph API
LangGraph CLI
LangGraph CUA
Utils
LangGraph Supervisor
LangGraph Swarm
Language
Theme
JavaScript@langchain/langgraphindex
Module●Since v0.3

index

Copy
import { ... } from "@langchain/langgraph";

Functions

function
entrypoint→ Pregel<Record<string, PregelNode<InputT, EntrypointReturnT<OutputT>>>, __type, Record<string, unknown>, InputT, EntrypointReturnT<OutputT>, any, Awaited<EntrypointReturnT<OutputT>>>
function
getConfig→ LangGraphRunnableConfig
function
getCurrentTaskInput→ T
function
getJsonSchemaFromSchema→ Record<string, unknown> | undefined
function
getPreviousState→ StateT
function
getSchemaDefaultGetter→ () => unknown | undefined
function
getStore→ BaseStore | undefined
function
getSubgraphsSeenSet→ any
function
getWriter→ (chunk: unknown) => void | undefined
function
interrupt→ R
function
isCommand→ x is Command<unknown, Record<string, unknown>, string>
function
isGraphBubbleUp→ e is GraphBubbleUp
function
isGraphInterrupt→ e is GraphInterrupt
function
isInterrupted→ values is __type
function
isParentCommand→ e is ParentCommand
function
isSerializableSchema→ schema is SerializableSchema<Input, Output>
function
isStandardSchema→ schema is StandardSchemaV1<Input, Output>
function
messagesStateReducer→ BaseMessage<MessageStructure<MessageToolSet>, MessageType>[]
function
pushMessage→ BaseMessage<MessageStructure<MessageToolSet>, MessageType>
function
task→ (args: ArgsT) => Promise<OutputT>
function
writer
function
addMessages→ BaseMessage<MessageStructure<MessageToolSet>, MessageType>[]

Classes

class
AsyncBatchedStore
class
BaseCheckpointSaver
class
BaseLangGraphError
class
BaseStore
class
BinaryOperatorAggregate
class
Command
class
CompiledStateGraph
class
EmptyChannelError
class
EmptyInputError
class
Graph
class
GraphBubbleUp
class
GraphInterrupt
class
GraphRecursionError
class
GraphValueError
class
InMemoryStore
class
InvalidUpdateError
class
MemorySaver
class
NodeInterrupt
class
ParentCommand
class
ReducedValue
class
RemoteException
class
Send
class
StateGraph
class
StateGraphInputError
class
StateSchema
class
UnreachableNodeError
class
UntrackedValue
class
Pregel
deprecatedclass
MultipleSubgraphsError

Interfaces

Type Aliases

Variables

Namespaces

View source on GitHub
interface
AnnotationRoot

Should not be instantiated directly. See Annotation.

interface
AnyValue

Stores the last value received, assumes that if multiple values are received, they are all equal.

Note: Unlike 'LastValue' if multiple nodes write to this channel in a single step, the values will be continuously overwritten.

interface
Checkpoint
interface
CheckpointTuple
interface
CompiledGraph

The Pregel class is the core runtime engine of LangGraph, implementing a message-passing graph computation model inspired by Google's Pregel system. It provides the foundation for building reliable, controllable agent workflows that can evolve state over time.

Key features:

  • Message passing between nodes in discrete "supersteps"
  • Built-in persistence layer through checkpointers
  • First-class streaming support for values, updates, and events
  • Human-in-the-loop capabilities via interrupts
  • Support for parallel node execution within supersteps

The Pregel class is not intended to be instantiated directly by consumers. Instead, use the following higher-level APIs:

  • StateGraph: The main graph class for building agent workflows
    • Compiling a StateGraph will return a CompiledGraph instance, which extends Pregel
  • Functional API: A declarative approach using tasks and entrypoints
    • A Pregel instance is returned by the entrypoint function
interface
ConditionalEdgeRouterTypes

Type bag for ConditionalEdgeRouter that accepts schema types. Unlike GraphNodeTypes, conditional edges don't have separate input/output - they just read state and return routing decisions.

interface
DynamicBarrierValue

A channel that switches between two states

  • in the "priming" state it can't be read from.
    • if it receives a WaitForNames update, it switches to the "waiting" state.
  • in the "waiting" state it collects named values until all are received.
    • once all named values are received, it can be read once, and it switches back to the "priming" state.
interface
EphemeralValue

Stores the value received in the step immediately preceding, clears after.

interface
GetOperation

Operation to retrieve an item by namespace and ID.

interface
GraphNodeTypes

Type bag for GraphNode that accepts schema types. All fields are optional - unspecified fields use defaults.

This enables separate input/output schemas for nodes, which is useful when a node receives a subset of state fields and returns different fields.

interface
Item

Represents a stored item with metadata.

interface
LangGraphRunnableConfig
interface
ListNamespacesOperation

Operation to list and filter namespaces in the store.

interface
MatchCondition
interface
NamedBarrierValue

A channel that waits until all named values are received before making the value available.

This ensures that if node N and node M both write to channel C, the value of C will not be updated until N and M have completed updating.

interface
PregelNode
interface
PregelOptions

Configuration options for executing a Pregel graph. These options control how the graph executes, what data is streamed, and how interrupts are handled.

interface
PutOperation

Operation to store, update, or delete an item.

interface
Runtime
interface
SearchOperation

Operation to search for items within a namespace prefix.

interface
StateDefinition
interface
StateGraphArgs
interface
StateSnapshot
interface
TaskOptions

Options for the task function

interface
Topic

A configurable PubSub Topic.

interface
UntrackedValueInit

Initialization options for UntrackedValue.

interface
WaitForNames
typeAlias
BaseLangGraphErrorFields
typeAlias
BinaryOperator: (a: ValueType, b: UpdateType)
typeAlias
CheckpointMetadata: __type & ExtraProperties

Additional details about the checkpoint, including the source, step, writes, and parents.

typeAlias
CommandParams
typeAlias
ConditionalEdgeRouter: IsConditionalEdgeRouterTypeBag<Schema> extends true ? (state: ExtractBagInput<Schema, unknown>, config: LangGraphRunnableConfig<ExtractBagContext<Schema, Record<string, unknown>>>)

Type for conditional edge routing functions.

Use this to type functions passed to addConditionalEdges for full type safety on state, runtime context, and return values.

Supports two patterns:

  1. Single schema pattern - Single schema: ConditionalEdgeRouter<Schema, Context, Nodes>

  2. Type bag pattern - Separate schemas for state, context: ConditionalEdgeRouter<{ Schema; ContextSchema; Nodes }>

typeAlias
EntrypointOptions

Options for the entrypoint function

typeAlias
ExtractStateType: Schema extends AnnotationRoot<SD> ? StateType<SD> : StateType<ToStateDefinition<Schema>> extends S ? [S] extends [never] ? Fallback : S : Fallback

Extract the State type from any supported schema type.

Supports:

  • StateSchema
  • AnnotationRoot
  • StateDefinition (internal channel definitions)
  • InteropZodObject (Zod v3/v4 object schemas)
typeAlias
ExtractUpdateType: Schema extends AnnotationRoot<SD> ? UpdateType<SD> : UpdateType<ToStateDefinition<Schema>> extends U ? [U] extends [never] ? Partial<FallbackBase> : U : Partial<FallbackBase>

Extract the Update type from any supported schema type.

The Update type represents what a node can return to update the state. All fields are optional since nodes only need to return the fields they modify.

Supports:

  • StateSchema
  • AnnotationRoot
  • StateDefinition (internal channel definitions)
  • InteropZodObject (Zod v3/v4 object schemas)
typeAlias
GetStateOptions

Options for getting the state of the graph.

typeAlias
GraphNode: IsGraphNodeTypeBag<Schema> extends true ? (state: ExtractBagInput<Schema, unknown>, config: LangGraphRunnableConfig<ExtractBagContext<Schema, Record<string, unknown>>>)

Strongly-typed utility for authoring graph nodes outside of the StateGraph builder, supporting inference for both state (from Schema) and config context (from Context type).

This type enables you to define graph node functions with full type safety—both for the evolving state and for additional context that may be passed in at runtime. Typing the context parameter allows for better code organization and precise editor support.

Works with StateSchema, AnnotationRoot, and Zod object schemas for state, and with a user-defined object shape for context.

Supports two patterns:

  1. Single schema usage - Single schema for both input and output: GraphNode<Schema, Context, Nodes>

  2. Type bag pattern - Separate schemas for input, output, context: GraphNode<{ InputSchema; OutputSchema; ContextSchema; Nodes }>

typeAlias
GraphNodeReturnValue: Update | CommandInstance<unknown, Update, Nodes> | Promise<Update | CommandInstance<unknown, Update, Nodes>>

Return value type for GraphNode functions. Nodes can return an update object, a Command, or a Promise of either.

typeAlias
InferStateSchemaUpdate: { [K in keyof TFields]: TFields[K] extends ReducedValue<any, any> ? TFields[K]["InputType"] : TFields[K] extends UntrackedValue<any> ? TFields[K]["ValueType"] : TFields[K] extends SerializableSchema<TInput, any> ? TInput : never }

Infer the Update type from a StateSchemaFields. This is the type for partial updates to state.

  • ReducedValue<Value, Input> → Input (the reducer input type)
  • UntrackedValue → Value
  • SerializableSchema<Input, Output> → Input (what you provide)
typeAlias
InferStateSchemaValue: { [K in keyof TFields]: TFields[K] extends ReducedValue<any, any> ? TFields[K]["ValueType"] : TFields[K] extends UntrackedValue<any> ? TFields[K]["ValueType"] : TFields[K] extends SerializableSchema<any, TOutput> ? TOutput : never }

Infer the State type from a StateSchemaFields. This is the type of the full state object.

  • ReducedValue<Value, Input> → Value (the stored type)
  • UntrackedValue → Value
  • SerializableSchema<Input, Output> → Output (the validated type)
typeAlias
Interrupt
typeAlias
Messages: BaseMessage | BaseMessageLike[] | BaseMessage | BaseMessageLike

Type that represents an acceptable input for the messages state reducer.

  • Can be a single BaseMessage or BaseMessageLike.
  • Can be an array of BaseMessage or BaseMessageLike.
typeAlias
MultipleChannelSubscriptionOptions

Options for subscribing to multiple channels.

typeAlias
NamespaceMatchType: "prefix" | "suffix"
typeAlias
NameSpacePath: string | "*"[]
typeAlias
NodeType: RunnableLike<StateType<SD>, UpdateType<SD> | Partial<StateType<SD>>>
typeAlias
Operation: GetOperation | SearchOperation | PutOperation | ListNamespacesOperation
typeAlias
OperationResults: { [K in keyof Tuple]: Tuple[K] extends PutOperation ? void : Tuple[K] extends SearchOperation ? SearchItem[] : Tuple[K] extends GetOperation ? Item | null : Tuple[K] extends ListNamespacesOperation ? string[][] : never }
typeAlias
ReducedValueInit: ReducedValueInitWithSchema<Value, Input> | ReducedValueInitBase<Value>

Initialization options for ReducedValue.

Two forms are supported:

  1. Provide only a reducer (and optionally jsonSchemaExtra)—in this case, the reducer's inputs are validated using the output value schema.
  2. Provide an explicit inputSchema field to distinguish the reducer's input type from the stored/output type.
typeAlias
RetryPolicy
typeAlias
SingleChannelSubscriptionOptions

Options for subscribing to a single channel.

typeAlias
SingleReducer: __type | __type | null
typeAlias
StateGraphInit

Initialization options for StateGraph. Accepts any combination of schema types for state/input/output.

Supports both state and stateSchema as aliases for backward compatibility. If only input is provided (no state/stateSchema), input is used as the state schema.

typeAlias
StateSchemaField: ReducedValue<Input, Output> | UntrackedValue<Output> | SerializableSchema<Input, Output>

Valid field types for StateSchema. Either a LangGraph state value type or a raw schema (e.g., Zod schema).

typeAlias
StateSchemaFields: __type

Init object for StateSchema constructor. Uses any to allow variance in generic types (e.g., ReducedValue<string, string[]>).

typeAlias
StateType: { [key in keyof SD]: ExtractValueType<SD[key]> }
typeAlias
StreamMode: "values" | "updates" | "debug" | "messages" | "checkpoints" | "tasks" | "custom"

Selects the type of output you'll receive when streaming from the graph. See Streaming for more details.

typeAlias
StreamOutputMap: IsEventStream<TEncoding> extends true ? Uint8Array : undefined extends TStreamMode ? [] : StreamMode | StreamMode[] extends TStreamMode ? TStreamMode extends StreamMode[] ? TStreamMode[number] : TStreamMode : TStreamMode extends StreamMode[] ? TStreamMode[number] : [] extends Multiple ? [TStreamSubgraphs] extends [true] ? __type[Multiple] : __type[Multiple] : undefined extends TStreamMode ? DefaultStreamMode : TStreamMode extends Single ? [TStreamSubgraphs] extends [true] ? __type[Single] : __type[Single] : never
typeAlias
UpdateType: { [key in keyof SD]: ExtractUpdateType<SD[key]> }
variable
END: "__end__"

Special reserved node name denoting the end of a graph.

variable
INTERRUPT: "__interrupt__"

Special channel reserved for graph interrupts

variable
MessagesAnnotation: AnnotationRoot<__type>

Prebuilt state annotation that combines returned messages. Can handle standard messages and special modifiers like RemoveMessage instances.

Specifically, importing and using the prebuilt MessagesAnnotation like this:

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

const graph = new StateGraph(MessagesAnnotation)
  .addNode(...)
  ...
Copy
import { BaseMessage } from "@langchain/core/messages";
import { Annotation, StateGraph, messagesStateReducer } from "@langchain/langgraph";

export const StateAnnotation = Annotation.Root({
  messages: Annotation<BaseMessage[]>({
    reducer: messagesStateReducer,
    default: () => [],
  }),
});

const graph = new StateGraph(StateAnnotation)
  .addNode(...)
  ...
variable
MessagesValue: ReducedValue<BaseMessage<MessageStructure<MessageToolSet>, MessageType>[], Messages>
variable
MessagesZodMeta: SchemaMeta<BaseMessage[], Messages>

Prebuilt schema meta for Zod state definition.

Copy
import { z } from "zod/v4-mini";
import { MessagesZodState, StateGraph } from "@langchain/langgraph";

const AgentState = z.object({
  messages: z.custom<BaseMessage[]>().register(registry, MessagesZodMeta),
});
variable
MessagesZodState: ZodObject<__type, "strip", ZodTypeAny, __type, __type>

Prebuilt state object that uses Zod to combine returned messages. This utility is synonymous with the MessagesAnnotation annotation, but uses Zod as the way to express messages state.

You can use import and use this prebuilt schema like this:

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

const graph = new StateGraph(MessagesZodState)
  .addNode(...)
  ...
Copy
import { z } from "zod";
import type { BaseMessage, BaseMessageLike } from "@langchain/core/messages";
import { StateGraph, messagesStateReducer } from "@langchain/langgraph";
import "@langchain/langgraph/zod";

const AgentState = z.object({
  messages: z
    .custom<BaseMessage[]>()
    .default(() => [])
    .langgraph.reducer(
       messagesStateReducer,
       z.custom<BaseMessageLike | BaseMessageLike[]>()
    ),
});
const graph = new StateGraph(AgentState)
  .addNode(...)
  ...
variable
REMOVE_ALL_MESSAGES: "__remove_all__"

Special value that signifies the intent to remove all previous messages in the state reducer. Used as the unique identifier for a RemoveMessage instance which, when encountered, causes all prior messages to be discarded, leaving only those following this marker.

variable
START: "__start__"

Special reserved node name denoting the start of a graph.

namespace
Annotation

Helper that instantiates channels within a StateGraph state.

Can be used as a field in an Annotation.Root wrapper in one of two ways:

  1. Directly: Creates a channel that stores the most recent value returned from a node.
  2. With a reducer: Creates a channel that applies the reducer on a node's return value.
Copy
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();
Copy
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();

Define a LangGraph workflow using the entrypoint function.

Function signature

The wrapped function must accept at most two parameters. The first parameter is the input to the function. The second (optional) parameter is a LangGraphRunnableConfig object. If you wish to pass multiple parameters to the function, you can pass them as an object.

Helper functions

Streaming

To write data to the "custom" stream, use the getWriter function, or the LangGraphRunnableConfig.writer property.

State management

The getPreviousState function can be used to access the previous state that was returned from the last invocation of the entrypoint on the same thread id.

If you wish to save state other than the return value, you can use the entrypoint.final function.

A helper utility function that returns the LangGraphRunnableConfig that was set when the graph was initialized.

Note: This only works when running in an environment that supports node:async_hooks and AsyncLocalStorage. If you're running this in a web environment, access the LangGraphRunnableConfig from the node function directly.

A helper utility function that returns the input for the currently executing task

Get the JSON schema from a SerializableSchema.

A helper utility function for use with the functional API that returns the previous state from the checkpoint from the last invocation of the current thread.

This function allows workflows to access state that was saved in previous runs using entrypoint.final.

Detect if a schema has a default value by validating undefined.

Uses the Standard Schema ~standard.validate API to detect defaults. If the schema accepts undefined and returns a value, that value is the default.

This approach is library-agnostic and works with any Standard Schema compliant library (Zod, Valibot, ArkType, etc.) without needing to introspect internals.

A helper utility function that returns the BaseStore that was set when the graph was initialized

Used for subgraph detection.

A helper utility function that returns the LangGraphRunnableConfig#writer if "custom" stream mode is enabled, otherwise undefined.

Interrupts the execution of a graph node. This function can be used to pause execution of a node, and return the value of the resume input when the graph is re-invoked using Command. Multiple interrupts can be called within a single node, and each will be handled sequentially.

When an interrupt is called:

  1. If there's a resume value available (from a previous Command), it returns that value.
  2. Otherwise, it throws a GraphInterrupt with the provided value
  3. The graph can be resumed by passing a Command with a resume value

Because the interrupt function propagates by throwing a special GraphInterrupt error, you should avoid using try/catch blocks around the interrupt function, or if you do, ensure that the GraphInterrupt error is thrown again within your catch block.

A type guard to check if the given value is a Command.

Useful for type narrowing when working with the Command object.

Checks if the given graph invoke / stream chunk contains interrupt.

Type guard to check if a given value is a SerializableSchema, i.e. both a Standard Schema and a Standard JSON Schema object.

Type guard to check if a given value is a Standard Schema V1 object.

Reducer function for combining two sets of messages in LangGraph's state system.

This reducer handles several tasks:

  1. Normalizes both left and right message inputs to arrays.
  2. Coerces any message-like objects into real BaseMessage instances.
  3. Ensures all messages have unique, stable IDs by generating missing ones.
  4. If a RemoveMessage instance is encountered in right with the ID REMOVE_ALL_MESSAGES, all previous messages are discarded and only the subsequent messages in right are returned.
  5. Otherwise, merges left and right messages together following these rules:
    • If a message in right shares an ID with a message in left:
      • If it is a RemoveMessage, that message (by ID) is marked for removal.
      • If it is a normal message, it replaces the message with the same ID from left.
    • If a message in right does not exist in left:
      • If it is a RemoveMessage, this is considered an error (cannot remove non-existent ID).
      • Otherwise, the message is appended.
    • Messages flagged for removal are omitted from the final output.

Manually push a message to a message stream.

This is useful when you need to push a manually created message before the node has finished executing.

When a message is pushed, it will be automatically persisted to the state after the node has finished executing. To disable persisting, set options.stateKey to null.

Define a LangGraph task using the task function.

Tasks can only be called from within an entrypoint or from within a StateGraph. A task can be called like a regular function with the following differences:

  • When a checkpointer is enabled, the function inputs and outputs must be serializable.
  • The wrapped function can only be called from within an entrypoint or StateGraph.
  • Calling the function produces a promise. This makes it easy to parallelize tasks.

Reducer function for combining two sets of messages in LangGraph's state system.

This reducer handles several tasks:

  1. Normalizes both left and right message inputs to arrays.
  2. Coerces any message-like objects into real BaseMessage instances.
  3. Ensures all messages have unique, stable IDs by generating missing ones.
  4. If a RemoveMessage instance is encountered in right with the ID REMOVE_ALL_MESSAGES, all previous messages are discarded and only the subsequent messages in right are returned.
  5. Otherwise, merges left and right messages together following these rules:
    • If a message in right shares an ID with a message in left:
      • If it is a RemoveMessage, that message (by ID) is marked for removal.
      • If it is a normal message, it replaces the message with the same ID from left.
    • If a message in right does not exist in left:
      • If it is a RemoveMessage, this is considered an error (cannot remove non-existent ID).
      • Otherwise, the message is appended.
    • Messages flagged for removal are omitted from the final output.

Abstract base class for persistent key-value stores.

Stores enable persistence and memory that can be shared across threads, scoped to user IDs, assistant IDs, or other arbitrary namespaces.

Features:

  • Hierarchical namespaces for organization
  • Key-value storage with metadata
  • Vector similarity search (if configured)
  • Filtering and pagination

Abstract base class for persistent key-value stores.

Stores enable persistence and memory that can be shared across threads, scoped to user IDs, assistant IDs, or other arbitrary namespaces.

Features:

  • Hierarchical namespaces for organization
  • Key-value storage with metadata
  • Vector similarity search (if configured)
  • Filtering and pagination

Stores the result of applying a binary operator to the current value and each new value.

One or more commands to update the graph's state and send messages to nodes. Can be used to combine routing logic with state updates in lieu of conditional edges

Final result from building and compiling a StateGraph. Should not be instantiated directly, only using the StateGraph .compile() instance method.

In-memory key-value store with optional vector search.

A lightweight store implementation using JavaScript Maps. Supports basic key-value operations and vector search when configured with embeddings.

Raised by a node to interrupt execution.

Represents a state field whose value is computed and updated using a reducer function.

ReducedValue allows you to define accumulators, counters, aggregators, or other fields whose value is determined incrementally by applying a reducer to incoming updates.

Each time a new input is provided, the reducer function is called with the current output and the new input, producing an updated value. Input validation can be controlled separately from output validation by providing an explicit input schema.

Exception raised when an error occurs in the remote graph.

A message or packet to send to a specific node in the graph.

The Send class is used within a StateGraph's conditional edges to dynamically invoke a node with a custom state at the next step.

Importantly, the sent state can differ from the core graph's state, allowing for flexible and dynamic workflow management.

One such example is a "map-reduce" workflow where your graph invokes the same node multiple times in parallel with different states, before aggregating the results back into the main graph's state.

A graph whose nodes communicate by reading and writing to a shared state. Each node takes a defined State as input and returns a Partial<State>.

Each state key can optionally be annotated with a reducer function that will be used to aggregate the values of that key received from multiple nodes. The signature of a reducer function is (left: Value, right: UpdateValue) => Value.

See Annotation for more on defining state.

After adding nodes and edges to your graph, you must call .compile() on it before you can use it.

Error thrown when invalid input is provided to a StateGraph.

This typically means that the input to the StateGraph constructor or builder did not match the required types. A valid input should be a StateDefinition, an Annotation.Root, or a Zod schema.

StateSchema provides a unified API for defining LangGraph state schemas.

Represents a state field whose value is transient and never checkpointed.

Use UntrackedValue for state fields that should be tracked for the lifetime of the process, but should not participate in durable checkpoints or recovery.

The Pregel class is the core runtime engine of LangGraph, implementing a message-passing graph computation model inspired by Google's Pregel system. It provides the foundation for building reliable, controllable agent workflows that can evolve state over time.

Key features:

  • Message passing between nodes in discrete "supersteps"
  • Built-in persistence layer through checkpointers
  • First-class streaming support for values, updates, and events
  • Human-in-the-loop capabilities via interrupts
  • Support for parallel node execution within supersteps

The Pregel class is not intended to be instantiated directly by consumers. Instead, use the following higher-level APIs:

  • StateGraph: The main graph class for building agent workflows
    • Compiling a StateGraph will return a CompiledGraph instance, which extends Pregel
  • Functional API: A declarative approach using tasks and entrypoints
    • A Pregel instance is returned by the entrypoint function