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
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.
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 automatically retries failed model calls with configurable backoff.
Supports retrying on specific exceptions and exponential backoff.
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
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
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 automatically retries failed model calls with configurable backoff.
Supports retrying on specific exceptions and exponential backoff.
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
Shorthand helper to extract the Tools type from an AgentTypeConfig or ReactAgent.
Shorthand helper to extract the Tools type from an AgentTypeConfig or ReactAgent.
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.