LangChain is a framework for building LLM-powered applications. It helps you chain together interoperable components and third-party integrations to simplify AI application development — all while future-proofing decisions as the underlying technology evolves.
Documentation: To learn more about LangChain, check out the docs.
If you're looking for more advanced customization or agent orchestration, check out LangGraph.js. our framework for building agents and controllable workflows.
[!NOTE] Looking for the Python version? Check out LangChain.
To help you ship LangChain apps to production faster, check out LangSmith. LangSmith is a unified developer platform for building, testing, and monitoring LLM applications.
You can use npm, pnpm, or yarn to install LangChain.js
npm install -S langchain
# or
pnpm install langchain
# or
yarn add langchain
LangChain helps developers build applications powered by LLMs through a standard interface for agents, models, embeddings, vector stores, and more.
Use LangChain for:
LangChain.js is written in TypeScript and can be used in:
As an open-source project in a rapidly developing field, we are extremely open to contributions, whether it be in the form of a new feature, improved infrastructure, or better documentation.
For detailed information on how to contribute, see here.
Please report any security issues or concerns following our security guidelines.
LangChain Messages
Represents a chunk of an AI message, which can be concatenated with other AI message chunks.
Base class for all types of messages in a conversation. It includes
properties like content, name, and additional_kwargs. It also
includes methods like toDict() and _getType().
Represents a chunk of a message, which can be concatenated with other
message chunks. It includes a method _merge_kwargs_dict() for merging
additional keyword arguments from another `BaseMessageChun
Strategy for clearing tool outputs when token limits are exceeded.
This strategy mirrors Anthropic's clear_tool_uses_20250919 behavior by
replacing older tool results with a placeholder text when t
Interface for interacting with a document.
A tool that can be created dynamically from a function, name, and description, designed to work with structured data. It extends the StructuredTool class and overrides the _call method to execute the
A tool that can be created dynamically from a function, name, and description.
Fake chat model for testing tool calling functionality
Represents a human message in a conversation.
Represents a chunk of a human message, which can be concatenated with other human message chunks.
In-memory implementation of the BaseStore using a dictionary. Used for storing key-value pairs in memory.
Error thrown when a middleware fails.
Use MiddlewareError.wrap() to create instances. The constructor is private
to ensure that GraphBubbleUp errors (like GraphInterrupt) are never wrapped.
Raised when model returns multiple structured output tool calls when only one is expected.
Error thrown when PII is detected and strategy is 'block'
Raised when structured output tool call arguments fail to parse according to the schema.
Base class for Tools that accept input of any shape defined by a Zod schema.
Represents a system message in a conversation.
Represents a chunk of a system message, which can be concatenated with other system message chunks.
Base class for Tools that accept input as a string.
Exception raised when tool call limits are exceeded.
This exception is raised when the configured exit behavior is 'error' and either the thread or run tool call limit has been exceeded.
Raised when a tool call is throwing an error.
Represents a tool message in a conversation.
Represents a chunk of a tool message, which can be concatenated with other tool message chunks.
Information for tracking structured output tool metadata. This contains all necessary information to handle structured responses generated via tool calls, including the original schema, its type class
LangChain Messages
Represents a chunk of an AI message, which can be concatenated with other AI message chunks.
Base class for all types of messages in a conversation. It includes
properties like content, name, and additional_kwargs. It also
includes methods like toDict() and _getType().
Represents a chunk of a message, which can be concatenated with other
message chunks. It includes a method _merge_kwargs_dict() for merging
additional keyword arguments from another `BaseMessageChun
Strategy for clearing tool outputs when token limits are exceeded.
This strategy mirrors Anthropic's clear_tool_uses_20250919 behavior by
replacing older tool results with a placeholder text when t
Interface for interacting with a document.
A tool that can be created dynamically from a function, name, and description, designed to work with structured data. It extends the StructuredTool class and overrides the _call method to execute the
A tool that can be created dynamically from a function, name, and description.
Fake chat model for testing tool calling functionality
Represents a human message in a conversation.
Represents a chunk of a human message, which can be concatenated with other human message chunks.
In-memory implementation of the BaseStore using a dictionary. Used for storing key-value pairs in memory.
Error thrown when a middleware fails.
Use MiddlewareError.wrap() to create instances. The constructor is private
to ensure that GraphBubbleUp errors (like GraphInterrupt) are never wrapped.
Raised when model returns multiple structured output tool calls when only one is expected.
Error thrown when PII is detected and strategy is 'block'
Raised when structured output tool call arguments fail to parse according to the schema.
Base class for Tools that accept input of any shape defined by a Zod schema.
Represents a system message in a conversation.
Represents a chunk of a system message, which can be concatenated with other system message chunks.
Base class for Tools that accept input as a string.
Exception raised when tool call limits are exceeded.
This exception is raised when the configured exit behavior is 'error' and either the thread or run tool call limit has been exceeded.
Raised when a tool call is throwing an error.
Represents a tool message in a conversation.
Represents a chunk of a tool message, which can be concatenated with other tool message chunks.
Information for tracking structured output tool metadata. This contains all necessary information to handle structured responses generated via tool calls, including the original schema, its type class
Class that provides a layer of abstraction over the base storage, allowing for the encoding and decoding of keys and values. It extends the BaseStore class.
File system implementation of the BaseStore using a dictionary. Used for storing key-value pairs in the file system.
In-memory implementation of the BaseStore using a dictionary. Used for storing key-value pairs in memory.
Creates a prompt caching middleware for Anthropic models to optimize API usage.
This middleware automatically adds cache control headers to the last messages when using Anthropic models, enabling the
Apply strategy to content based on matches
Allow low-risk tool calls and block risky calls using a decision model (beta).
The middleware intercepts explicitly configured tools immediately before
execution and asks a Noul question for the pr
Creates a prompt caching middleware for AWS Bedrock Converse models to optimize API usage.
This middleware automatically enables Bedrock's prompt caching when using AWS Bedrock Converse models. This
LangChain utilities
Middleware that automatically prunes tool results to manage context size.
This middleware applies a sequence of edits when the total input token count exceeds configured thresholds. By default, it us
Default token counter that approximates based on character count.
If tools are provided, the token count also includes stringified tool schemas.
Creates a production-ready ReAct (Reasoning + Acting) agent that combines language models with tools and middleware to create systems that can reason about tasks, decide which tools to use, and iterat
Creates a middleware instance with automatic schema inference.
Creates a native transformer that surfaces nested named agents on
run.subagents.
It watches tasks events to record each namespace's lc_agent_name (set by
createAgent({ name })) and the trigge
Creates a native transformer that correlates tools channel events
into per-call ToolCallStream objects.
Marked __native: true — projection keys land directly on the
GraphRunStream instance as `
Detect credit card numbers in content (validated with Luhn algorithm)
Detect email addresses in content
Detect IP addresses in content (validated)
Detect MAC addresses in content
Detect URLs in content
Dynamic System Prompt Middleware
Allows setting the system prompt dynamically right before each model invocation. Useful when the prompt depends on the current agent state or per-invocation context.
LangChain Testing Utilities
LangChain Messages
Creates a Human-in-the-Loop (HITL) middleware for tool approval and oversight.
This middleware intercepts tool calls made by an AI agent and provides human oversight capabilities before execution. It
Initialize a ChatModel from the model name and provider. Must have the integration package corresponding to the model provider installed.
Whether an interrupt is a "per_call" tool approval, e.g.
result.__interrupt__?.filter(isToolApprovalInterrupt).
Middleware for selecting tools using an LLM-based strategy.
When an agent has many tools available, this middleware filters them down to only the most relevant ones for the user's query. This reduces
Creates a middleware to limit the number of model calls at both thread and run levels.
This middleware helps prevent excessive model API calls by enforcing limits on how many times the model can be i
Middleware that provides automatic model fallback on errors.
This middleware attempts to retry failed model calls with alternative models in sequence. When a model call fails, it tries the next model
Middleware that throws ModelRefusalError when the model refuses.
Providers report a refusal, such as a safety-policy refusal, as a successful response, so without this middleware the agent run ends a
Middleware that automatically retries failed model calls with configurable backoff.
Supports retrying on specific exceptions and exponential backoff.
Select an agent's model with a decision model's Choice answer (beta).
The middleware classifies the latest human message once before an agent
run, stores the complete ChoiceAnswer in agent state
Blocks listed tool calls that the OpenAI Decisions API judges risky (beta).
A call runs only when the probability that it is risky is below 0.5. Risky calls
and refusals return an error ToolMessage
Routes each agent run to one of several models with the OpenAI Decisions API (beta).
Classifies the latest human message once per run and stores the answer in
modelRoute, then uses the chosen model
Provider specific middleware
Creates a middleware that detects and handles personally identifiable information (PII) in conversations.
This middleware detects common PII types and applies configurable strategies to handle them.
Creates a provider strategy for structured output using native JSON schema support.
This function is used to configure structured output for agents when the underlying model supports native JSON sche
Provider-side tool search middleware.
Leverages server-side tool search: the full client tool catalog is forwarded
to the provider, with deferred tools marked defer_loading so the provider
disclose
Resolve a redaction rule to a concrete detector function
Summarization middleware that automatically summarizes conversation history when token limits are approached.
This middleware monitors message token counts and automatically summarizes older messages
Creates a middleware that provides todo list management capabilities to agents.
This middleware adds a write_todos tool that allows agents to create and manage
structured task lists for complex mul
Middleware that tracks tool call counts and enforces limits.
This middleware monitors the number of tool calls made during agent execution and can terminate the agent when specified limits are reache
Middleware that emulates specified tools using an LLM instead of executing them.
This middleware allows selective emulation of tools for testing purposes.
By default (when tools is undefined), all
Converts selected tool execution errors into error ToolMessages.
Handling is opt-in: ToolErrorMiddlewareConfig.onError must return content for an error to be sent to the model. Returning nothing pr
Middleware that automatically retries failed tool calls with configurable backoff.
Supports retrying on specific exceptions and exponential backoff.
Creates a tool strategy for structured output using function calling.
This function configures structured output by converting schemas into function tools that the model calls. Unlike `providerStrate
LangChain Messages
Attempts to infer the model provider based on the given model name.
Helper function to get a chat model class by its class name or model provider.
Initialize a ChatModel from the model name and provider. Must have the integration package corresponding to the model provider installed.
Pull a prompt from the hub.
Push a prompt to the hub. If the specified repo doesn't already exist, it will be created.
Infer modelProvider from the id namespace to avoid className collisions. For non-langchain packages, extracts the provider name from the namespace. e.g., ["langchain", "chat_models", "vertexai", "Chat
Pull a prompt from the hub.
Push a prompt to the hub. If the specified repo doesn't already exist, it will be created.
Creates a prompt caching middleware for Anthropic models to optimize API usage.
This middleware automatically adds cache control headers to the last messages when using Anthropic models, enabling the
Apply strategy to content based on matches
Allow low-risk tool calls and block risky calls using a decision model (beta).
The middleware intercepts explicitly configured tools immediately before
execution and asks a Noul question for the pr
Creates a prompt caching middleware for AWS Bedrock Converse models to optimize API usage.
This middleware automatically enables Bedrock's prompt caching when using AWS Bedrock Converse models. This
LangChain utilities
Middleware that automatically prunes tool results to manage context size.
This middleware applies a sequence of edits when the total input token count exceeds configured thresholds. By default, it us
Default token counter that approximates based on character count.
If tools are provided, the token count also includes stringified tool schemas.
Creates a production-ready ReAct (Reasoning + Acting) agent that combines language models with tools and middleware to create systems that can reason about tasks, decide which tools to use, and iterat
Creates a middleware instance with automatic schema inference.
Creates a native transformer that surfaces nested named agents on
run.subagents.
It watches tasks events to record each namespace's lc_agent_name (set by
createAgent({ name })) and the trigge
Creates a native transformer that correlates tools channel events
into per-call ToolCallStream objects.
Marked __native: true — projection keys land directly on the
GraphRunStream instance as `
Detect credit card numbers in content (validated with Luhn algorithm)
Detect email addresses in content
Detect IP addresses in content (validated)
Detect MAC addresses in content
Detect URLs in content
Dynamic System Prompt Middleware
Allows setting the system prompt dynamically right before each model invocation. Useful when the prompt depends on the current agent state or per-invocation context.
LangChain Testing Utilities
LangChain Messages
Creates a Human-in-the-Loop (HITL) middleware for tool approval and oversight.
This middleware intercepts tool calls made by an AI agent and provides human oversight capabilities before execution. It
Whether an interrupt is a "per_call" tool approval, e.g.
result.__interrupt__?.filter(isToolApprovalInterrupt).
Middleware for selecting tools using an LLM-based strategy.
When an agent has many tools available, this middleware filters them down to only the most relevant ones for the user's query. This reduces
Creates a middleware to limit the number of model calls at both thread and run levels.
This middleware helps prevent excessive model API calls by enforcing limits on how many times the model can be i
Middleware that provides automatic model fallback on errors.
This middleware attempts to retry failed model calls with alternative models in sequence. When a model call fails, it tries the next model
Middleware that throws ModelRefusalError when the model refuses.
Providers report a refusal, such as a safety-policy refusal, as a successful response, so without this middleware the agent run ends a
Middleware that automatically retries failed model calls with configurable backoff.
Supports retrying on specific exceptions and exponential backoff.
Select an agent's model with a decision model's Choice answer (beta).
The middleware classifies the latest human message once before an agent
run, stores the complete ChoiceAnswer in agent state
Blocks listed tool calls that the OpenAI Decisions API judges risky (beta).
A call runs only when the probability that it is risky is below 0.5. Risky calls
and refusals return an error ToolMessage
Routes each agent run to one of several models with the OpenAI Decisions API (beta).
Classifies the latest human message once per run and stores the answer in
modelRoute, then uses the chosen model
Provider specific middleware
Creates a middleware that detects and handles personally identifiable information (PII) in conversations.
This middleware detects common PII types and applies configurable strategies to handle them.
Creates a provider strategy for structured output using native JSON schema support.
This function is used to configure structured output for agents when the underlying model supports native JSON sche
Provider-side tool search middleware.
Leverages server-side tool search: the full client tool catalog is forwarded
to the provider, with deferred tools marked defer_loading so the provider
disclose
Resolve a redaction rule to a concrete detector function
Summarization middleware that automatically summarizes conversation history when token limits are approached.
This middleware monitors message token counts and automatically summarizes older messages
Creates a middleware that provides todo list management capabilities to agents.
This middleware adds a write_todos tool that allows agents to create and manage
structured task lists for complex mul
Middleware that tracks tool call counts and enforces limits.
This middleware monitors the number of tool calls made during agent execution and can terminate the agent when specified limits are reache
Middleware that emulates specified tools using an LLM instead of executing them.
This middleware allows selective emulation of tools for testing purposes.
By default (when tools is undefined), all
Converts selected tool execution errors into error ToolMessages.
Handling is opt-in: ToolErrorMiddlewareConfig.onError must return content for an error to be sent to the model. Returning nothing pr
Middleware that automatically retries failed tool calls with configurable backoff.
Supports retrying on specific exceptions and exponential backoff.
Creates a tool strategy for structured output using function calling.
This function configures structured output by converting schemas into function tools that the model calls. Unlike `providerStrate
LangChain Messages
Initialize a ChatModel from the model name and provider. Must have the integration package corresponding to the model provider installed.
Load a LangChain module from a serialized text representation. NOTE: This functionality is currently in beta. Loaded classes may change independently of semver.
**WARNING — insecure deserialization r
Get a unique name for the module, rather than parent class implementations. Should not be subclassed, subclass lc_name above instead.
Creates a middleware that detects and redacts personally identifiable information (PII) from messages before they are sent to model providers, and restores original values in model responses for tool
Creates a middleware that detects and redacts personally identifiable information (PII) from messages before they are sent to model providers, and restores original values in model responses for tool
Represents an action with a name and arguments.
Represents an action request with a name, arguments, and description.
Base middleware interface.
Type bag that encapsulates all agent type parameters.
This interface bundles all the generic type parameters used throughout the agent system into a single configuration object. This pattern simplifi
Response when a human approves the action.
Configuration for clearing tool outputs when token limits are exceeded.
LangChain Messages
Protocol describing a context editing strategy.
Implement this interface to create custom strategies for managing
conversation context size. The apply method should modify the
messages array in-pla
Configuration for the Context Editing Middleware.
Default type configuration for agents. Used when no explicit type parameters are provided.
LangChain Documents
Response when a human edits the action.
Information about a tool call that has been executed.
Request for human feedback on a sequence of actions requested by a model.
Response payload for a HITLRequest.
Represents information about an interrupt.
LangChain Testing Utilities
Type bag that encapsulates all middleware type parameters.
This interface bundles all the generic type parameters used throughout the middleware system into a single configuration object. This patter
A model available to the router and the criterion for selecting it.
Configuration for modifying a model call at runtime. All fields are optional and only provided fields will override defaults.
The part of OpenAIDecisions from @langchain/openai these middleware use.
Options for configuring the OpenAI Moderation middleware.
Represents a detected PII match in content
ReactAgent is a production-ready ReAct (Reasoning + Acting) agent that combines language models with tools and middleware.
The agent is parameterized by a single type bag Types that encapsulates al
Configuration for a redaction rule
Response when a human rejects the action.
Resolved redaction rule with a concrete detector function
Response when a human answers on behalf of the tool.
Policy for reviewing a HITL request.
A nested named-agent execution surfaced on run.subagents.
A subagent is a nested createAgent run whose lc_agent_name differs from
its parent's — e.g. a createAgent({ name }) invoked inside a
Information about a tool call that has been executed.
Represents a tool call request for the wrapToolCall hook. Contains the tool call information along with the agent's current state and runtime.
Options for configuring the Tool Emulator middleware.
Configuration for toolErrorMiddleware.
Information about a tool result from a tool execution.
Branded type for ToolStrategy arrays that preserves type information
Content block to represent an invalid tool call
Represents a request to call a tool.
Content block to represent partial data of a tool call
Annotation for citing data from a document.
Provider-specific content block.
This is used to represent content blocks that are not part of the standard LangChain content model. If a provider's non-standard output includes reasoning and tool ca
Reasoning output from a LLM.
An explicit refusal reported by the model provider.
Providers report refusals, such as safety-policy refusals, as successful responses. This block marks them so callers can tell a refusal apart from
Text output from a LLM.
This typically represents the main text content of a message, such as the response from a language model or the text of a user message.
Represents an action with a name and arguments.
Represents an action request with a name, arguments, and description.
Base middleware interface.
Type bag that encapsulates all agent type parameters.
This interface bundles all the generic type parameters used throughout the agent system into a single configuration object. This pattern simplifi
Response when a human approves the action.
Configuration for clearing tool outputs when token limits are exceeded.
LangChain Messages
Protocol describing a context editing strategy.
Implement this interface to create custom strategies for managing
conversation context size. The apply method should modify the
messages array in-pla
Configuration for the Context Editing Middleware.
Default type configuration for agents. Used when no explicit type parameters are provided.
LangChain Documents
Response when a human edits the action.
Information about a tool call that has been executed.
Request for human feedback on a sequence of actions requested by a model.
Response payload for a HITLRequest.
Represents information about an interrupt.
LangChain Testing Utilities
Type bag that encapsulates all middleware type parameters.
This interface bundles all the generic type parameters used throughout the middleware system into a single configuration object. This patter
A model available to the router and the criterion for selecting it.
Configuration for modifying a model call at runtime. All fields are optional and only provided fields will override defaults.
The part of OpenAIDecisions from @langchain/openai these middleware use.
Options for configuring the OpenAI Moderation middleware.
Represents a detected PII match in content
ReactAgent is a production-ready ReAct (Reasoning + Acting) agent that combines language models with tools and middleware.
The agent is parameterized by a single type bag Types that encapsulates al
Configuration for a redaction rule
Response when a human rejects the action.
Resolved redaction rule with a concrete detector function
Response when a human answers on behalf of the tool.
Policy for reviewing a HITL request.
A nested named-agent execution surfaced on run.subagents.
A subagent is a nested createAgent run whose lc_agent_name differs from
its parent's — e.g. a createAgent({ name }) invoked inside a
Information about a tool call that has been executed.
Represents a tool call request for the wrapToolCall hook. Contains the tool call information along with the agent's current state and runtime.
Options for configuring the Tool Emulator middleware.
Configuration for toolErrorMiddleware.
Information about a tool result from a tool execution.
Branded type for ToolStrategy arrays that preserves type information
Interface for objects that can be serialized. This is a duck-typed interface to avoid circular imports.
Hook type for the afterAgent lifecycle event. Can be either a handler function or an object with a handler and optional jump targets. This hook is called once at the end of the agent invocation.
Hook type for the afterModel lifecycle event. Can be either a handler function or an object with a handler and optional jump targets. This hook is called after each model invocation.
A GraphRunStream with native agent-level projections assigned
directly on the instance by createGraphRunStream (via __native
transformers).
This is a pure type overlay — no runtime subclass exist
Widened middleware type for agent configuration arrays. Accepts middleware instances with any registered tools or stream transformers while preserving precise inference when middleware arrays are pass
Hook type for the beforeAgent lifecycle event. Can be either a handler function or an object with a handler and optional jump targets. This hook is called once at the start of the agent invocation.
Hook type for the beforeModel lifecycle event. Can be either a handler function or an object with a handler and optional jump targets. This hook is called before each model invocation.
Built-in PII types
Helper type to combine agent stream transformers with middleware stream transformers.
Helper type to combine agent tools with middleware tools into a single readonly array.
Union of all possible decision types.
Default type configuration for middleware. Used when no explicit type parameters are provided.
Function type that dynamically generates a description for a tool call approval request.
Type helper to extract union type from an array of Zod schemas
A headless tool that always interrupts agent execution on the server.
The implementation is provided separately on the client via
useStream({ tools: [...] }) using .implement().
Configuration fields for creating a headless tool.
A tool implementation that pairs a headless tool with its execution function.
Created by calling .implement() on a HeadlessTool.
Pass to useStream({ tools: [...] }) on the client side.
Helper type to infer the full merged context from an agent, including:
contextSchema)This matches the context typ
Shorthand helper to extract the raw Context schema type from an AgentTypeConfig or ReactAgent.
This returns just the contextSchema type passed to createAgent, not merged with middleware.
For the
Shorthand helper to extract the Middleware type from an AgentTypeConfig or ReactAgent.
Shorthand helper to extract the Response type from an AgentTypeConfig or ReactAgent.
Helper type to infer the full merged state from an agent, including:
stateSchema)This matches the state type returned by `in
Shorthand helper to extract the raw State schema type from an AgentTypeConfig or ReactAgent.
This returns just the stateSchema type passed to createAgent, not merged with middleware.
For the comp
Shorthand helper to extract the StreamTransformers type (the tuple of transformer factories) from an AgentTypeConfig or ReactAgent.
Shorthand helper to extract the Tools type from an AgentTypeConfig or ReactAgent.
Helper type to extract any property from an AgentTypeConfig or ReactAgent.
Helper type to extract input type from context schema (with optional defaults)
Helper type to infer merged input state from an array of middleware (includes built-in state)
Helper type to infer merged state from an array of middleware (includes built-in state)
Helper type to infer the context schema type from a middleware
Helper type to infer the input context schema type from a middleware (with optional defaults)
Helper type to infer merged input context from an array of middleware (with optional defaults)
Helper type to infer merged context from an array of middleware
Shorthand helper to extract the ContextSchema type from a MiddlewareTypeConfig or AgentMiddleware.
Shorthand helper to extract the FullContext type from a MiddlewareTypeConfig or AgentMiddleware.
Helper type to infer the input state schema type from a middleware (all properties optional) This filters out private properties (those starting with underscore) Supports both Zod schemas (InteropZodO
Helper type to infer merged input state from an array of middleware (with optional defaults)
Shorthand helper to extract the Schema type from a MiddlewareTypeConfig or AgentMiddleware.
Helper type to infer the state schema type from a middleware This filters out private properties (those starting with underscore) Supports both Zod schemas (InteropZodObject) and StateSchema from Lang
Helper type to infer merged state from an array of middleware (just the middleware states)
Helper type to infer stream transformers from a single middleware instance.
Helper type to infer and merge stream transformers from an array of middleware.
Shorthand helper to extract the StreamTransformers type from a MiddlewareTypeConfig or AgentMiddleware.
Helper type to infer tools from a single middleware instance. Extracts the TTools type parameter from AgentMiddleware.
Helper type to infer and merge tools from an array of middleware. Recursively extracts tools from each middleware and combines them into a single tuple.
Shorthand helper to extract the Tools type from a MiddlewareTypeConfig or AgentMiddleware.
Helper type to extract any property from a MiddlewareTypeConfig or AgentMiddleware.
jump targets (internal)
Result type for middleware functions.
Custom detector function that takes content and returns matches
Strategy for handling detected PII
Helper type to resolve an AgentTypeConfig from either:
typeof agent)Helper type to resolve a MiddlewareTypeConfig from either:
typeof middleware)Special type to indicate that no response format is provided. When this type is used, the structuredResponse property should not be present in the result.
Runtime information available to middleware (readonly).
A reviewer's answer to a "per_call" tool approval.
Interrupt value raised once per gated tool call in "per_call" mode. Keys are
snake_case, as in Python.
Handler function type for wrapping tool calls. Takes a tool call request and returns the tool result or a command.
Discriminated union of ToolCallStream variants, one per tool
in TTools. Enables TypeScript to narrow .input and .output
when the consumer checks call.name === "someToolName".
Falls back to `
Handler called when tool execution throws.
Return content to surface the error to the model as an error ToolMessage.
Return nothing to propagate the original error.
Runtime context automatically injected into tools.
When a tool function has a parameter named tool_runtime with type hint
ToolRuntime, the tool execution system will automatically inject an insta
Helper type to convert an array of tools (ClientTool | ServerTool)[] to a MessageToolSet. This maps each tool's name (as a literal type) to its MessageToolDefinition containing the input and output ty
Base input type for .invoke and .stream methods.
Predicate controlling whether a given tool call triggers an interrupt.
Receives a ToolCallRequest and returns true to interrupt or false
to auto-approve the tool call.
The request is constructed
Handler function type for wrapping model calls. Takes a model request and returns the AI message response.
Wrapper function type for the wrapModelCall hook. Allows middleware to intercept and modify model execution. This enables you to:
Wrapper function type for the wrapToolCall hook. Allows middleware to intercept and modify tool execution.
Content block for audio data
Content block for multimodal data
Content block for file data
Content block for image data
Content block for plain text data
Content block for video data
Hook type for the afterAgent lifecycle event. Can be either a handler function or an object with a handler and optional jump targets. This hook is called once at the end of the agent invocation.
Hook type for the afterModel lifecycle event. Can be either a handler function or an object with a handler and optional jump targets. This hook is called after each model invocation.
A GraphRunStream with native agent-level projections assigned
directly on the instance by createGraphRunStream (via __native
transformers).
This is a pure type overlay — no runtime subclass exist
Widened middleware type for agent configuration arrays. Accepts middleware instances with any registered tools or stream transformers while preserving precise inference when middleware arrays are pass
Hook type for the beforeAgent lifecycle event. Can be either a handler function or an object with a handler and optional jump targets. This hook is called once at the start of the agent invocation.
Hook type for the beforeModel lifecycle event. Can be either a handler function or an object with a handler and optional jump targets. This hook is called before each model invocation.
Built-in PII types
Helper type to combine agent stream transformers with middleware stream transformers.
Helper type to combine agent tools with middleware tools into a single readonly array.
Union of all possible decision types.
Default type configuration for middleware. Used when no explicit type parameters are provided.
Function type that dynamically generates a description for a tool call approval request.
Type helper to extract union type from an array of Zod schemas
A headless tool that always interrupts agent execution on the server.
The implementation is provided separately on the client via
useStream({ tools: [...] }) using .implement().
Configuration fields for creating a headless tool.
A tool implementation that pairs a headless tool with its execution function.
Created by calling .implement() on a HeadlessTool.
Pass to useStream({ tools: [...] }) on the client side.
Helper type to infer the full merged context from an agent, including:
contextSchema)This matches the context typ
Shorthand helper to extract the raw Context schema type from an AgentTypeConfig or ReactAgent.
This returns just the contextSchema type passed to createAgent, not merged with middleware.
For the
Shorthand helper to extract the Middleware type from an AgentTypeConfig or ReactAgent.
Shorthand helper to extract the Response type from an AgentTypeConfig or ReactAgent.
Helper type to infer the full merged state from an agent, including:
stateSchema)This matches the state type returned by `in
Shorthand helper to extract the raw State schema type from an AgentTypeConfig or ReactAgent.
This returns just the stateSchema type passed to createAgent, not merged with middleware.
For the comp
Shorthand helper to extract the StreamTransformers type (the tuple of transformer factories) from an AgentTypeConfig or ReactAgent.
Shorthand helper to extract the Tools type from an AgentTypeConfig or ReactAgent.
Helper type to extract any property from an AgentTypeConfig or ReactAgent.
Helper type to extract input type from context schema (with optional defaults)
Helper type to infer merged input state from an array of middleware (includes built-in state)
Helper type to infer merged state from an array of middleware (includes built-in state)
Helper type to infer the context schema type from a middleware
Helper type to infer the input context schema type from a middleware (with optional defaults)
Helper type to infer merged input context from an array of middleware (with optional defaults)
Helper type to infer merged context from an array of middleware
Shorthand helper to extract the ContextSchema type from a MiddlewareTypeConfig or AgentMiddleware.
Shorthand helper to extract the FullContext type from a MiddlewareTypeConfig or AgentMiddleware.
Helper type to infer the input state schema type from a middleware (all properties optional) This filters out private properties (those starting with underscore) Supports both Zod schemas (InteropZodO
Helper type to infer merged input state from an array of middleware (with optional defaults)
Shorthand helper to extract the Schema type from a MiddlewareTypeConfig or AgentMiddleware.
Helper type to infer the state schema type from a middleware This filters out private properties (those starting with underscore) Supports both Zod schemas (InteropZodObject) and StateSchema from Lang
Helper type to infer merged state from an array of middleware (just the middleware states)
Helper type to infer stream transformers from a single middleware instance.
Helper type to infer and merge stream transformers from an array of middleware.
Shorthand helper to extract the StreamTransformers type from a MiddlewareTypeConfig or AgentMiddleware.
Helper type to infer tools from a single middleware instance. Extracts the TTools type parameter from AgentMiddleware.
Helper type to infer and merge tools from an array of middleware. Recursively extracts tools from each middleware and combines them into a single tuple.
Shorthand helper to extract the Tools type from a MiddlewareTypeConfig or AgentMiddleware.
Helper type to extract any property from a MiddlewareTypeConfig or AgentMiddleware.
jump targets (internal)
Result type for middleware functions.
Custom detector function that takes content and returns matches
Strategy for handling detected PII
Helper type to resolve an AgentTypeConfig from either:
typeof agent)Helper type to resolve a MiddlewareTypeConfig from either:
typeof middleware)Special type to indicate that no response format is provided. When this type is used, the structuredResponse property should not be present in the result.
Runtime information available to middleware (readonly).
A reviewer's answer to a "per_call" tool approval.
Interrupt value raised once per gated tool call in "per_call" mode. Keys are
snake_case, as in Python.
Handler function type for wrapping tool calls. Takes a tool call request and returns the tool result or a command.
Discriminated union of ToolCallStream variants, one per tool
in TTools. Enables TypeScript to narrow .input and .output
when the consumer checks call.name === "someToolName".
Falls back to `
Handler called when tool execution throws.
Return content to surface the error to the model as an error ToolMessage.
Return nothing to propagate the original error.
Runtime context automatically injected into tools.
When a tool function has a parameter named tool_runtime with type hint
ToolRuntime, the tool execution system will automatically inject an insta
Helper type to convert an array of tools (ClientTool | ServerTool)[] to a MessageToolSet. This maps each tool's name (as a literal type) to its MessageToolDefinition containing the input and output ty
Base input type for .invoke and .stream methods.
Predicate controlling whether a given tool call triggers an interrupt.
Receives a ToolCallRequest and returns true to interrupt or false
to auto-approve the tool call.
The request is constructed
Handler function type for wrapping model calls. Takes a model request and returns the AI message response.
Wrapper function type for the wrapModelCall hook. Allows middleware to intercept and modify model execution. This enables you to:
Wrapper function type for the wrapToolCall hook. Allows middleware to intercept and modify tool execution.
A headless tool that always interrupts agent execution on the server.
The implementation is provided separately on the client via
useStream({ tools: [...] }) using .implement().
Configuration fields for creating a headless tool.
A tool implementation that pairs a headless tool with its execution function.
Created by calling .implement() on a HeadlessTool.
Pass to useStream({ tools: [...] }) on the client side.