import { ... } from "@langchain/langgraph";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:
The Pregel class is not intended to be instantiated directly by consumers. Instead, use the following higher-level APIs:
PregelPregel instance is returned by the entrypoint functionThe 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:
The Pregel class is not intended to be instantiated directly by consumers. Instead, use the following higher-level APIs:
PregelPregel instance is returned by the entrypoint functionThe root graph paused. Static interrupts can have an empty payload list.
Selects the type of output you'll receive when streaming from the graph. See Streaming for more details.
Special reserved node name denoting the end of a graph.
Special channel reserved for graph interrupts
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:
import { MessagesAnnotation, StateGraph } from "@langchain/langgraph";
const graph = new StateGraph(MessagesAnnotation)
.addNode(...)
...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(...)
...Experimental. A messages state field backed by a DeltaChannel.
A drop-in alternative to MessagesValue that persists only per-step message deltas (plus periodic snapshots) instead of the full accumulated history in every checkpoint blob. Useful for long-running threads where re-serializing the entire message list on each step is costly.
import { StateSchema, MessagesDeltaValue } from "@langchain/langgraph";
const State = new StateSchema({ messages: MessagesDeltaValue });Prebuilt schema meta for Zod state definition.
import { z } from "zod/v4-mini";
import { MessagesZodState, StateGraph } from "@langchain/langgraph";
const AgentState = z.object({
messages: z.custom<BaseMessage[]>().register(registry, MessagesZodMeta),
});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:
import { MessagesZodState, StateGraph } from "@langchain/langgraph";
const graph = new StateGraph(MessagesZodState)
.addNode(...)
...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(...)
...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.
Special reserved node name denoting the start of a graph.
The set of stream modes requested by
streamEvents(..., { version: "v3" }) — every mode the protocol maps
to a channel.
The verbose "debug" mode is intentionally excluded: it was a thin
re-wrap of checkpoints + tasks carrying no new information.
The "checkpoints" mode is likewise excluded from the stream-mode
request because the protocol's checkpoints channel carries only a
lightweight envelope (id, parent_id, step, source) emitted as a
separate [namespace, "checkpoints", envelope] chunk before each paired
values chunk — not the full-state shape from Pregel's checkpoints
stream mode when subscribed via debug.
Helper that instantiates channels within a StateGraph state.
Can be used as a field in an Annotation.Root wrapper in one of two ways:
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();Creates a GraphRunStream with built-in transformers and kicks off the background pump that feeds raw stream chunks through the transformer pipeline.
Built-in transformers are registered in this order:
_discoveries log.lifecycle channel events.run.values / run.output.run.messages / .messagesFrom.Subgraph discovery is registered first so that downstream transformers (notably lifecycle) observe child namespaces with their stream handles already in place. User-supplied transformer factories are registered afterwards.
Create the built-in lifecycle transformer.
Marked as a NativeStreamTransformer so the run stream
factory can expose _lifecycleLog via a dedicated getter
(run.lifecycle) rather than through run.extensions.
Creates a StreamTransformer that groups messages channel events into
per-message ChatModelStream instances.
A new ChatModelStream is created on message-start and closed on
message-finish. Content-block events in between are forwarded to the
active stream. Only events whose namespace exactly matches path
are processed; child namespaces are ignored.
Create the subgraph discovery transformer.
Registering this transformer against a mux replaces the legacy
inline behavior that previously lived in StreamMux.push.
The mux no longer knows about the subgraph factory: instead, this
transformer is the single component that materializes stream
handles and announces them on _discoveries.
Marked as a NativeStreamTransformer so the projection is
treated as internal wiring (not merged into run.extensions and
not auto-forwarded via StreamMux.wireChannels).
Creates a StreamTransformer that captures values channel events
into a local StreamChannel. Only events whose namespace exactly
matches path are recorded; events from child or sibling namespaces
are ignored.
The final snapshot is resolved by StreamMux.close directly; this transformer only accumulates intermediate values.
Define a LangGraph workflow using the entrypoint function.
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.
To write data to the "custom" stream, use the getWriter function, or the LangGraphRunnableConfig.writer property.
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.
Filter a lifecycle StreamChannel to only the entries whose namespace lies within the subtree rooted at path.
Returns an AsyncIterable whose iterator yields every entry whose
namespace either equals path or is a descendant of it.
Iteration begins at startAt, so callers can capture the
log's current size at construction time to skip entries emitted
before the caller existed (e.g. a subgraph stream discovered
mid-run shouldn't replay the root's started).
Filter a SubgraphDiscovery channel to only the direct children of a given namespace.
Returns an AsyncIterable whose iterator yields stream handles for
discoveries whose namespace is exactly one segment deeper than
path and shares it as a prefix. Iteration begins at
startAt (so each caller picks up only discoveries added
after its construction) and terminates when the underlying log
closes or fails.
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.
Note: When called without arguments, this relies on node:async_hooks /
AsyncLocalStorage, which is available in many JavaScript environments
(Node.js, Deno, Cloudflare Workers) but not in web browsers. In environments
without AsyncLocalStorage support, pass the config that your node/tool
function receives directly, e.g. getCurrentTaskInput(config).
Tip: Inside a tool run by a ToolNode, prefer reading graph state from
runtime.state on the second tool argument (typed as ToolRuntime from
@langchain/core/tools). It works in every runtime, including web browsers.
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:
resume value available (from a previous Command), it returns that value.GraphInterrupt with the provided valueCommand with a resume valueBecause 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.
True when payload is a lightweight checkpoint envelope (not a full-state
Pregel checkpoints debug payload).
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 that tests whether a transformer is a NativeStreamTransformer.
Type guard that checks whether a value is a NodeError.
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.
Experimental. Batch reducer for use with DeltaChannel.
Processes all writes in one pass — dedup by ID and RemoveMessage
tombstoning — without calling messagesStateReducer.
This reducer is batching-invariant, as required by DeltaChannel:
reducer(reducer(state, xs), ys) === reducer(state, xs.concat(ys)).
A RemoveMessage carrying the REMOVE_ALL_MESSAGES sentinel id
clears all messages accumulated so far (prior state plus earlier writes in
the same batch) and keeps only the messages that follow it, mirroring
messagesStateReducer. Clearing happens in the same single linear
pass, so the batching-invariant still holds.
Raw object / string inputs are coerced to typed BaseMessage objects so
that HTTP-driven graphs work without a separate coercion step. This is not
full messagesStateReducer parity — unknown-id RemoveMessage
errors and missing-id UUID assignment are not handled here.
Reducer function for combining two sets of messages in LangGraph's state system.
This reducer handles several tasks:
left and right message inputs to arrays.BaseMessage instances.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.left and right messages together following these rules:
right shares an ID with a message in left:
RemoveMessage, that message (by ID) is marked for removal.left.right does not exist in left:
RemoveMessage, this is considered an error (cannot remove non-existent ID).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:
Reducer function for combining two sets of messages in LangGraph's state system.
This reducer handles several tasks:
left and right message inputs to arrays.BaseMessage instances.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.left and right messages together following these rules:
right shares an ID with a message in left:
RemoveMessage, that message (by ID) is marked for removal.left.right does not exist in left:
RemoveMessage, this is considered an error (cannot remove non-existent ID).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:
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:
Stores the result of applying a binary operator to the current value and each new value.
The main stream object returned by chat model streaming.
Implements AsyncIterable<ChatModelStreamEvent> for raw event access
and PromiseLike<AIMessage> for simple await usage.
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.
Reducer channel that stores only a sentinel in checkpoint blobs and reconstructs state by replaying ancestor writes through the reducer.
DeltaChannel avoids re-serializing the full accumulated value at every
step. Instead of writing the value into channel_values, the channel is
omitted entirely and its state is reconstructed on read by walking the
ancestor chain and replaying the per-step writes through the reducer (see
BaseCheckpointSaver.getDeltaChannelHistory).
Snapshot cadence is driven by two counters: a per-channel update count and
the total supersteps since the last snapshot. A full DeltaSnapshot
blob is written when EITHER the update count reaches snapshotFrequency OR
the supersteps count reaches the system-wide
DELTA_MAX_SUPERSTEPS_SINCE_SNAPSHOT bound (default 5000), bounding replay
depth even for channels that stop receiving writes.
Represents a state field backed by a DeltaChannel.
Unlike ReducedValue (which stores the full accumulated value in every
checkpoint blob via BinaryOperatorAggregate), a DeltaValue field persists
only per-step deltas (plus periodic snapshots) and reconstructs its state on
read by replaying ancestor writes through a batch reducer. This avoids
re-serializing large accumulators (e.g. long message histories) at every step.
A projection channel for StreamTransformers.
Implements AsyncIterable<T> so it can be iterated directly by
in-process consumers via run.extensions.<key>. Channels created with
StreamChannel.remote or new StreamChannel(name) are also
auto-forwarded to remote clients.
Extend this class and pass an instance through callbacks to observe graph
interrupts and resumes. Lifecycle methods are always awaited, including when
other callbacks run in the background. Set raiseError to propagate errors.
Raised when a graph run exits early due to a drain request.
This indicates the graph stopped cooperatively at a superstep boundary because RunControl#requestDrain was called (e.g., in response to SIGTERM). The checkpoint is saved and the run can be resumed later.
Primary run stream for a LangGraph execution.
Implements AsyncIterable over ProtocolEvent and exposes ergonomic projections for values, messages, subgraphs, output, and interrupts. Created by createGraphRunStream.
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.
Failure context passed to a node-level error handler.
A node-level error handler is registered via
StateGraph.addNode(name, fn, { errorHandler }). The handler runs ONLY after
the failing node's RetryPolicy is exhausted, so retry and handling
stay decoupled. The handler receives the failed node's name and the thrown
error via a NodeError instance, can return a state update, and can route to
a recovery branch via new Command({ goto }) (saga / compensation flows).
Raised by a node to interrupt execution.
Convenience type for referencing a compiled graph by named type slots.
Infer the Update type from a StateSchemaFields. This is the type for partial updates to state.
Infer the State type from a StateSchemaFields. This is the type of the full state object.
Maps a single StateSchema field definition to its corresponding Channel type.
This utility type inspects the type of the field and returns an appropriate
BaseChannel type, parameterized with the state "value" and "input" types according to the field's shape.
Rules:
F) is a DeltaValue<V, I>, the channel will store values of type V
and accept input of type I (or an Overwrite).F) is a ReducedValue<V, I>, the channel will store values of type V
and accept input of type I.UntrackedValue<V>, the channel will store and accept values of type V.SerializableSchema<I, O>, the channel will store values of type O
(the schema's output/validated value) and accept input of type I.BaseChannel<unknown, unknown> is used as fallback.