LangChain Reference home pageLangChain ReferenceLangChain Reference
  • GitHub
  • Main Docs
Deep Agents
LangChain
LangGraph
Integrations
LangSmith
LangGraph
  • Web
  • Channels
  • Pregel
  • Prebuilt
  • Remote
React SDK
Vue SDK
Svelte SDK
Angular SDK
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
WebChannelsPregelPrebuiltRemote
React SDK
Vue SDK
Svelte SDK
Angular SDK
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 v2.0

stream

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

Functions

function
assembledMessageToBaseMessage→ BaseMessage

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

function
assembledToBaseMessage→ BaseMessage

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.

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
toolCallsProjection→ ProjectionSpec<AssembledToolCall[]>
function
valuesProjection→ ProjectionSpec<T | undefined>
function
videoProjection→ ProjectionSpec<VideoMedia[]>

Classes

class
ChannelRegistry

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.

class
StreamController

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.

class
StreamStore
class
SubagentDiscovery
class
SubgraphDiscovery
class
MediaAssembler
class
MediaAssemblyError

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.

Interfaces

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

Assembled view of a single tool call lifecycle (tool-started → optional tool-output-delta → tool-finished | tool-error).

Mirrors the in-process ToolCallStream interface so that remote consumers get the same ergonomics.

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
StreamControllerOptions
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, transports are bound to a specific thread at construction time — the thread ID is part of the connection URL.

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.

Type Aliases

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[] ? ToolCallFromTool<T[number]> : InferToolCalls<T>

Infer the discriminated union of tool call shapes from an input that may be an agent brand, an array of LangGraph tools, or a direct DefaultToolCall shape.

See InferToolCallsFromUi for the full resolution table.

typeAlias
MessageMetadataMap: ReadonlyMap<string, MessageMetadata>

Read-only map exposed via MessageMetadataTracker.store.

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
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 : never

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.

deprecatedtypeAlias
StateOf: InferStateType<T> extends Record<string, unknown> ? InferStateType<T> : Record<string, unknown>

Legacy alias shared by the framework bindings. Unwraps a compiled graph or agent brand into its state shape.

Variables

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.

View source on GitHub