LangChain Reference home pageLangChain ReferenceLangChain Reference
  • GitHub
  • Main Docs
Deep Agents
LangChain
LangGraph
Integrations
LangSmith
LangGraph
  • Web
  • Channels
  • Pregel
  • Prebuilt
  • Remote
  • Stream
LangGraph SDK
  • Ui
  • Client
  • Auth
  • React
  • Logging
  • React Ui
  • Utils
  • Server
  • Stream
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
WebChannelsPregelPrebuiltRemoteStream
LangGraph SDK
UiClientAuthReactLoggingReact UiUtilsServerStream
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/langgraph-sdkstream
Module●Since v1.9

stream

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

Functions

function
acquireChannelEffect→ () => void
function
assembledMessageToBaseMessage→ BaseMessage
function
assembledToBaseMessage→ BaseMessage
function
audioProjection→ ProjectionSpec<AudioMedia[]>
function
channelProjection→ ProjectionSpec<Event[]>
function
extensionProjection→ ProjectionSpec<T | undefined>
function
filesProjection→ ProjectionSpec<FileMedia[]>
function
imagesProjection→ ProjectionSpec<ImageMedia[]>
function
messagesProjection→ ProjectionSpec<BaseMessage<MessageStructure<MessageToolSet>, MessageType>[]>
function
parseToolOutput→ unknown
function
parseToolPayload→ unknown
function
toolCallsProjection→ ProjectionSpec<AssembledToolCall<string, unknown, unknown>[]>
function
valuesProjection→ ProjectionSpec<T | undefined>
function
videoProjection→ ProjectionSpec<VideoMedia[]>

Classes

class
ChannelRegistry
class
StreamController
class
StreamStore
class
SubagentDiscovery
class
SubgraphDiscovery
class
MediaAssembler
class
MediaAssemblyError

Interfaces

Type Aliases

Variables

View source on GitHub
interface
AcquiredProjection

Handle returned by ChannelRegistry.acquire. Framework bindings use store as the reactivity source and must call release() when the consumer tears down.

interface
AgentServerOptions

Agent-server branch: caller points useStream at an assistant on a LangGraph-Platform-compatible server. Discriminated against CustomAdapterOptions by transport being absent or a string.

interface
AssembledToMessageInput
interface
AssembledToolCall

Reactive tool handle for framework bindings (stream.toolCalls, useToolCalls, injectToolCalls).

status, error, and output are plain values that the assembler updates in place as tool events arrive. That lets React, Vue, Svelte, and Angular re-render from a snapshot on each store tick without await, effects, or Suspense boundaries around a promise. ClientAssembledToolCall keeps a promise-based output instead for script consumers that read tool results sequentially.

output is null while the call is running or after it fails; successful completion sets it to the parsed tool return value (objects and strings are unwrapped from ToolMessage wire envelopes when needed).

interface
ChannelEffectOptions

Options for acquireChannelEffect. Extends ChannelProjectionOptions (bufferSize, replay) with the per-event callback and an optional error sink.

interface
ChannelProjectionOptions
interface
CustomAdapterOptions

Custom-adapter branch: caller brings their own AgentServerAdapter. Discriminated against AgentServerOptions by transport being an adapter instance.

interface
MediaProjectionOptions
interface
MessageMetadata

Metadata tracked per message id. Surfaced to applications via useMessageMetadata(stream, messageId).

interface
ProjectionRuntime
interface
ProjectionSpec

A projection spec describes a single logical subscription managed by the ChannelRegistry. Framework bindings don't construct these directly — the per-kind factory functions in stream/projections/ emit them.

interface
RootEventBus

Read-only fan-out of the StreamController's always-on root subscription. Projections that only need a subset of the root pump's channels at the root namespace can attach here instead of opening a second server subscription.

interface
RootSnapshot

Always-on root snapshot surfaced by StreamController.rootStore.

Populated by a single multi-channel subscription at the thread root (values, lifecycle, input, messages, tools). Every app pays for this — selector hooks for scoped projections layer on top.

interface
RunCompletedInfo

Payload for run-end callbacks.

interface
RunExecutionInfo

Payload for run-start callbacks.

interface
StreamControllerOptions
interface
StreamRespondAllOptions

Options for StreamController.respondAll / framework respondAll().

Carries run-level config / metadata onto the single run that services the batched resume — the same fields as StreamRespondOptions, minus the per-interrupt target (each response in the map carries its own interruptId as the key).

interface
StreamRespondOptions

Options for StreamController.respond / framework respond().

Targets a single pending interrupt (interruptId / namespace) and carries run-level config and metadata onto the resume so the resumed run applies the same configurable values (model, user context, timezone, …) and metadata (trigger source, test flags, …) a fresh StreamSubmitOptions would. The server folds these into the run it starts to service the input.respond command.

To resume several interrupts pending at the same checkpoint, use StreamController.respondAll instead.

interface
StreamStopOptions

Options for StreamController.stop / framework stop().

interface
StreamSubmitOptions
interface
SubagentDiscoverySnapshot

Lightweight discovery record for a subagent running inside the thread.

Populated eagerly from the root subscription (tools + lifecycle channels). Content projections (messages, toolCalls, custom extensions) are opened lazily via selector hooks, keyed on namespace.

interface
SubgraphDiscoverySnapshot

Lightweight discovery record for a subgraph running inside the thread.

interface
SubmissionQueueEntry

Queued submission entry mirrored from the server-side run queue.

Surfaces the deferred submission to UI consumers via StreamController.queueStore.

interface
UseStreamCommonOptions

Options common to both transport branches of framework useStream APIs.

interface
AgentServerAdapter

Public v1 name for TransportAdapter plus optional high-level capabilities. Renamed to reflect that this interface now denotes the full agent-server protocol contract (not merely wire transport): any object that satisfies it can back a useStream call. See plan-custom-transport.md §4 for the rollout.

The extra optional methods let adapters surface thread state and history without the framework needing to issue a parallel HTTP request — useStream.hydrate() calls getState?() when present and falls back to client.threads.getState otherwise. Adapters that don't know how to produce these values can simply omit them.

The legacy TransportAdapter export is retained for back-compat and resolves to the same structural type; new code should prefer AgentServerAdapter.

interface
AgentTypeConfigLike

Minimal interface matching the structure of AgentTypeConfig from @langchain/langgraph. This allows type inference from ReactAgent without requiring the langchain dependency.

interface
AudioMedia

Shared surface across every media handle returned by MediaAssembler.

The handle is live while its parent message is active:

  • partialBytes is a snapshot of all bytes received so far.
  • stream is a lazy, single-consumer byte stream (see accessor docstring).
  • blob / objectURL settle on message-finish.
  • error becomes set if the handle terminates in any of the MediaAssemblyErrorKind failure modes.
interface
CompiledSubAgentLike

Minimal interface matching the structure of a CompiledSubAgent from deepagents. Used for structural type matching without importing deepagents.

interface
DeepAgentTypeConfigLike

Minimal interface matching the structure of DeepAgentTypeConfig from deepagents. Extends AgentTypeConfigLike to include subagent type information.

interface
FileMedia

Shared surface across every media handle returned by MediaAssembler.

The handle is live while its parent message is active:

  • partialBytes is a snapshot of all bytes received so far.
  • stream is a lazy, single-consumer byte stream (see accessor docstring).
  • blob / objectURL settle on message-finish.
  • error becomes set if the handle terminates in any of the MediaAssemblyErrorKind failure modes.
interface
ImageMedia

Shared surface across every media handle returned by MediaAssembler.

The handle is live while its parent message is active:

  • partialBytes is a snapshot of all bytes received so far.
  • stream is a lazy, single-consumer byte stream (see accessor docstring).
  • blob / objectURL settle on message-finish.
  • error becomes set if the handle terminates in any of the MediaAssemblyErrorKind failure modes.
interface
MediaAssemblerCallbacks

Dispatch callbacks receive a freshly-started handle on its first matching content-block-start. Exactly one callback fires per (messageId, blockType) pair.

interface
MediaAssemblerOptions

Dispatch callbacks receive a freshly-started handle on its first matching content-block-start. Exactly one callback fires per (messageId, blockType) pair.

interface
MediaBase

Shared surface across every media handle returned by MediaAssembler.

The handle is live while its parent message is active:

  • partialBytes is a snapshot of all bytes received so far.
  • stream is a lazy, single-consumer byte stream (see accessor docstring).
  • blob / objectURL settle on message-finish.
  • error becomes set if the handle terminates in any of the MediaAssemblyErrorKind failure modes.
interface
SubAgentLike

Minimal interface matching the structure of a SubAgent from deepagents. Used for structural type matching without importing deepagents.

interface
SubagentToolCall

Represents a tool call that initiated a subagent.

interface
TransportAdapter

Transport abstraction implemented by concrete client transports such as WebSocket or SSE adapters.

In the thread-centric protocol the thread ID is part of the request URLs. Transports may be bound at construction time, or left unbound and bound later via setThreadId (see that method) — which lets a single instance follow a lazily-created thread.

interface
VideoMedia

Shared surface across every media handle returned by MediaAssembler.

The handle is live while its parent message is active:

  • partialBytes is a snapshot of all bytes received so far.
  • stream is a lazy, single-consumer byte stream (see accessor docstring).
  • blob / objectURL settle on message-finish.
  • error becomes set if the handle terminates in any of the MediaAssemblyErrorKind failure modes.
typeAlias
AssembledToolCallFromTool: AssembledToolCallFromToolCall<ToolCallFromTool<T>, InferToolOutput<T>>

Infer the streaming AssembledToolCall handle for a single LangChain tool.

Parallel to ToolCallFromTool for message-level tool calls — use this when a component receives one entry from stream.toolCalls and you know which tool definition it came from.

typeAlias
Channel
typeAlias
Event
typeAlias
ExtendedMessageRole: MessageRole | "tool"
typeAlias
InferStateType: InferStateType<T>

Unwrap the state shape from a compiled graph, a create-agent brand, or a plain type. Used by useStream<T>() to resolve T = typeof agent into the state the values/messages projections observe.

Structurally identical to the legacy @langchain/langgraph-sdk/ui helper of the same name; kept here as a framework-facing re-export so bindings can import from the stream subpath without needing the UI module.

typeAlias
InferSubagentStates: InferSubagentStates<T>

Infer the subagent → state map from a DeepAgent brand. Non-brands collapse to DefaultSubagentStates.

typeAlias
InferToolCalls: T extends readonly unknown[] ? AssembledToolCallFromTool<T[number]> : ExtractAgentConfig<T>["Tools"] extends Tools ? InferToolCalls<T> extends TC ? TC extends __type ? AssembledFromMessageToolCall<TC, Tools> : AssembledToolCall : AssembledToolCall : AssembledToolCall

Infer the discriminated union of AssembledToolCall handles from an agent brand, an array of LangChain tools, or fall back to the untyped default handle.

Pass typeof agent or typeof tools and narrow on name / args (aliases for input) in tool-call UI components.

typeAlias
MessageMetadataMap: ReadonlyMap<string, MessageMetadata>

Read-only map exposed via MessageMetadataTracker.store.

typeAlias
RunExecutionReason: "success" | "error" | "interrupt" | "stopped"

Why a run's active streaming phase ended.

typeAlias
StoreListener: ()

Minimal observable store backing every framework binding.

The shape is intentionally tiny:

  • subscribe(listener) → unsubscribe lines up with React's useSyncExternalStore.
  • getSnapshot() returns a referentially-stable value for unchanged state so React can bail out of renders.
  • Vue/Svelte/Angular bindings wrap subscribe + getSnapshot in their own reactivity primitive (shallowRef / writable / signal) in ~10 lines.

Snapshot identity matters: a listener is only useful if getSnapshot() returns a different reference when state changes. Callers MUST pass a freshly-constructed value to setState; mutating the previous snapshot in place will break React's bail-out and cause infinite re-renders.

typeAlias
SubagentMap: ReadonlyMap<string, SubagentDiscoverySnapshot>
typeAlias
SubgraphByNodeMap: ReadonlyMap<string, readonly SubgraphDiscoverySnapshot[]>
typeAlias
SubgraphMap: ReadonlyMap<string, SubgraphDiscoverySnapshot>
typeAlias
SubmissionQueueSnapshot: ReadonlyArray<SubmissionQueueEntry<StateType>>

Read-only snapshot of the queue. The queue store hands this out directly; consumers must not mutate the array.

typeAlias
Target: undefined | __type

Anything with a namespace can be passed to selector hooks as a scope target. Both SubagentDiscoverySnapshot and SubgraphDiscoverySnapshot satisfy this; callers can also hand-build { namespace: [...] } objects.

typeAlias
ToolCallStatus: "running" | "finished" | "error"

High-level outcome of a single tool call.

typeAlias
UseStreamOptions: AgentServerOptions<StateType, ThreadIdType, ApiUrlType, ApiKeyType> | CustomAdapterOptions<StateType, ThreadIdType, CustomAssistantIdType>

Options accepted by framework useStream APIs. Discriminated on the shape of transport:

  • omitted or a string ("sse" / "websocket") -> agent-server branch (AgentServerOptions); supply assistantId + apiUrl.
  • an AgentServerAdapter instance -> custom-adapter branch (CustomAdapterOptions); bring your own transport.
typeAlias
WidenUpdateMessages: T extends Record<string, unknown> ? { [K in keyof T]: K extends "messages" ? T[K] | BaseMessage | BaseMessage[] : T[K] } : T

Widen an update type so its messages field also accepts @langchain/core BaseMessage class instances (single or array). Framework bindings apply this to submit() so callers can write stream.submit({ messages: [new HumanMessage("hi")] }).

Port of the legacy AcceptBaseMessages<T> helper; the public name matches the v1 spec in plan-types.md §8.

typeAlias
AnyMediaHandle: AudioMedia | ImageMedia | VideoMedia | FileMedia
typeAlias
DefaultSubagentStates: Record<string, Record<string, unknown>>

Default subagent state map used when no specific subagent types are provided. Maps any string key to Record<string, unknown>.

typeAlias
DefaultToolCall

Default tool call type when no specific tool definitions are provided.

typeAlias
ExtractAgentConfig: T extends __type ? Config extends AgentTypeConfigLike ? Config : never : never

Extract the AgentTypeConfig from an agent-like type.

typeAlias
ExtractDeepAgentConfig: T extends __type ? Config extends DeepAgentTypeConfigLike ? Config : never : never

Extract the DeepAgentTypeConfig from a DeepAgent-like type.

typeAlias
ExtractSubAgentMiddleware: T extends __type ? M extends readonly AgentMiddlewareLike[] ? M : M extends AgentMiddlewareLike[] ? M : readonly [] : readonly []

Helper type to extract middleware from a SubAgent definition. Handles both mutable and readonly middleware arrays.

typeAlias
InferAgentToolCalls: ExtractAgentConfig<T>["Tools"] extends readonly Tool[] ? ToolCallFromAgentTool<Tool> extends never ? DefaultToolCall : ToolCallFromAgentTool<Tool> : DefaultToolCall

Extract tool calls type from an agent's tools. Converts the tools array to a discriminated union of tool calls.

This handles both tuple types (e.g., readonly [Tool1, Tool2]) and array-of-union types (e.g., readonly (Tool1 | Tool2)[]) which is how createAgent captures tool types.

typeAlias
InferBag: T extends __type ? BagTemplate : B

Infer the Bag type from an agent, defaulting to the provided Bag.

Currently returns the provided Bag for all types. Can be extended in the future to extract Bag from agent types.

typeAlias
InferDeepAgentSubagents: ExtractDeepAgentConfig<T> extends never ? never : ExtractDeepAgentConfig<T>["Subagents"]

Extract the Subagents array type from a DeepAgent.

typeAlias
InferNodeNames: T extends __type ? N extends string ? Exclude<N, "__start__"> : string : string

Infer the node names from a compiled graph.

Extracts the ~NodeType phantom property from CompiledGraph instances, providing a union of all node names defined in the graph.

typeAlias
InferSubagentByName: InferDeepAgentSubagents<T> extends readonly SA[] ? SA extends __type ? SA : never : never

Helper type to extract a subagent by name from a DeepAgent.

typeAlias
InferSubagentNames: InferDeepAgentSubagents<T> extends readonly SA[] ? SA extends __type ? N extends string ? N : never : never : never

Extract all subagent names as a string union from a DeepAgent.

typeAlias
InferSubagentState: InferSubagentByName<T, TName> extends never ? Record<string, unknown> : InferSubagentByName<T, TName> extends SA ? BaseSubagentState<ToolCall> & InferMiddlewareStatesFromArray<ExtractSubAgentMiddleware<SA>> : Record<string, unknown>

Infer the state type for a specific subagent by extracting and merging its middleware state schemas, plus the base agent state (messages).

typeAlias
InferToolOutput: T extends __type ? Out : T extends __type ? UnwrapToolFuncOutput<R> : T extends __type ? Out : T extends __type ? UnwrapToolFuncOutput<R> : unknown

Infer the successful return type of a LangChain tool.

Resolution order mirrors InferToolInput: func, then invoke, then _call, so inference survives cross-package boundaries where _call is protected.

typeAlias
IsAgentLike: T extends __type ? true : false

Check if a type is agent-like (has ~agentTypes phantom property). This property is present on ReactAgent instances created with createAgent.

typeAlias
IsDeepAgentLike: T extends __type ? true : false

Check if a type is a DeepAgent (has ~deepAgentTypes phantom property). This property is present on DeepAgent instances created with createDeepAgent.

typeAlias
MediaAssemblyErrorKind: "message-error" | "stream-closed" | "fetch-failed"

Kinds of failure that can terminate a media handle prematurely.

  • "message-error" — the upstream message emitted an error event before completion.
  • "stream-closed" — the transport stream closed before message-finish arrived (thread closed, transport dropped, etc.).
  • "fetch-failed" — the block was url-sourced and the lazy fetch() rejected (CORS, 404, 5xx, network).
typeAlias
MediaBlockType: "audio" | "image" | "video" | "file"

Block types this assembler knows how to reassemble into media handles.

typeAlias
SubagentStateMap: { [K in InferSubagentNames<T>]: InferSubagentState<T, K, ToolCall> }

Create a map of subagent names to their state types. This is useful for type-safe getSubagentsByType calls.

typeAlias
ToolCallFromTool: T extends __type ? InferToolInput<T> extends Args ? Args extends never ? never : Args extends Record<string, any> ? __type : never : never : T extends __type ? InferToolInput<T> extends Args ? Args extends never ? never : Args extends Record<string, any> ? __type : never : never : never
variable
ROOT_PUMP_CHANNELS: readonly Channel[]

Channel set covered by the always-on root subscription. Exported so projections (and transports) can reason about what the root pump already delivers before opening additional server subscriptions.

variable
NAMESPACE_SEPARATOR: ""

Separator used to create stable string keys from namespace tuples. The null character cannot collide with protocol namespace segments, which are printable identifiers.

Acquire a side-effect subscription over one or more channels.

Convenience: given the raw assembled message + the role captured from message-start, produce a BaseMessage with the same id.

Produce a BaseMessage class instance from an in-progress or finished assembled message. Safe to call repeatedly across deltas — each call returns a new instance whose content reflects the currently-observed blocks.

Parse a tool-finished output payload into the tool's return value.

Wire events often wrap structured tool results in a ToolMessage-shaped object ({ type: "tool", content: "..." }) or a LangGraph Command whose update.messages carries the ToolMessage. This unwraps those envelopes, JSON-decodes string content when possible, and leaves plain strings as-is. Returns null when a ToolMessage envelope is present but its content cannot be normalised.

Parse wire-format tool payloads into structured values.

Tool events may carry JSON-encoded object strings on the wire; this helper normalises them to plain objects for consumers. Non-JSON strings are returned unchanged.

Ref-counted, thread-aware projection registry.

Owns the spec.key → (store, runtime) mapping for one StreamController. Lifecycle:

  • acquire(spec) → +1 ref, returns { store, release }. The first acquire opens the projection's runtime; subsequent acquires for the same key share both the store and the runtime.
  • release() → -1 ref. When the last consumer releases, the entry is removed and its runtime disposed.
  • bind(thread) → swap or detach the underlying thread; every live entry's runtime is recreated against the new thread, keeping the same store identity.
  • dispose() → tear everything down (idempotent). Safe to call multiple times.

The registry is intentionally not generic over a state shape — different consumers can hold projections producing different snapshot types, so the registry keys everything as unknown and lets acquire reapply the caller's T at the boundary.

Coordinates one thread's protocol-v2 stream and exposes stable observable projections for framework bindings.

The controller owns the root subscription, lazily binds scoped projections through ChannelRegistry, and normalizes protocol events into class-message, tool-call, discovery, interrupt, and queue stores.

Typed error thrown through media.stream / rejected from media.blob / media.objectURL when a handle fails before its message completes. Carries the bytes accumulated up to the failure point on partialBytes for callers that want to salvage or diagnose.

Infer a tool call type from a single tool. Works with tools created via tool() from @langchain/core/tools.

For DynamicStructuredTool, this extracts the input type from the _call method, which is the most reliable source as it's the pre-computed input type.