LangChain Reference home pageLangChain ReferenceLangChain Reference
  • GitHub
  • Main Docs
Deep Agents
LangChain
LangGraph
Integrations
LangSmith
LangChain
  • Universal
  • Hub
  • Node
  • Load
  • Serializable
  • Encoder Backed
  • File System
  • In Memory
LangChain Core
  • Agents
  • Caches
  • Base
  • Dispatch
  • Web
  • Manager
  • Promises
  • Chat History
  • Context
  • Base
  • Langsmith
  • Documents
  • Embeddings
  • Errors
  • Example Selectors
  • Indexing
  • Base
  • Chat Models
  • Llms
  • Profile
  • Load
  • Serializable
  • Memory
  • Messages
  • Tool
  • Output Parsers
  • Openai Functions
  • Openai Tools
  • Outputs
  • Prompt Values
  • Prompts
  • Retrievers
  • Document Compressors
  • Runnables
  • Graph
  • Singletons
  • Stores
  • Structured Query
  • Tools
  • Base
  • Console
  • Log Stream
  • Run Collector
  • Tracer Langchain
  • Stream
  • Async Caller
  • Chunk Array
  • Context
  • Env
  • Event Source Parse
  • Format
  • Function Calling
  • Hash
  • Json Patch
  • Json Schema
  • Math
  • Ssrf
  • Stream
  • Testing
  • Tiktoken
  • Types
  • Vectorstores
Text Splitters
MCP Adapters
⌘I

LangChain Assistant

Ask a question to get started

Enter to send•Shift+Enter new line

Menu

LangChain
UniversalHubNodeLoadSerializableEncoder BackedFile SystemIn Memory
LangChain Core
AgentsCachesBaseDispatchWebManagerPromisesChat HistoryContextBaseLangsmithDocumentsEmbeddingsErrorsExample SelectorsIndexingBaseChat ModelsLlmsProfileLoadSerializableMemoryMessagesToolOutput ParsersOpenai FunctionsOpenai ToolsOutputsPrompt ValuesPromptsRetrieversDocument CompressorsRunnablesGraphSingletonsStoresStructured QueryToolsBaseConsoleLog StreamRun CollectorTracer LangchainStreamAsync CallerChunk ArrayContextEnvEvent Source ParseFormatFunction CallingHashJson PatchJson SchemaMathSsrfStreamTestingTiktokenTypesVectorstores
Text Splitters
MCP Adapters
Language
Theme
JavaScriptlangchain

langchain

Description

🦜️🔗 LangChain.js

npm License: MIT Twitter

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.

⚡️ Quick Install

You can use npm, pnpm, or yarn to install LangChain.js

npm install -S langchain
# or
pnpm install langchain
# or
yarn add langchain

🚀 Why use LangChain?

LangChain helps developers build applications powered by LLMs through a standard interface for agents, models, embeddings, vector stores, and more.

Use LangChain for:

  • Real-time data augmentation. Easily connect LLMs to diverse data sources and external/internal systems, drawing from LangChain’s vast library of integrations with model providers, tools, vector stores, retrievers, and more.
  • Model interoperability. Swap models in and out as your engineering team experiments to find the best choice for your application’s needs. As the industry frontier evolves, adapt quickly — LangChain’s abstractions keep you moving without losing momentum.

📦 LangChain's ecosystem

  • LangSmith - Unified developer platform for building, testing, and monitoring LLM applications. With LangSmith, you can debug poor-performing LLM app runs, evaluate agent trajectories, gain visibility in production, and deploy agents with confidence.
  • LangGraph - Build agents that can reliably handle complex tasks with LangGraph, our low-level agent orchestration framework. LangGraph offers customizable architecture, long-term memory, and human-in-the-loop workflows — and is trusted in production by companies like LinkedIn, Uber, Klarna, and GitLab.
  • Deep Agents - Build sophisticated "deep" agents that go beyond simple tool-calling loops. Deep Agents combines planning tools, sub-agent spawning, file system access, and detailed prompts to handle complex, multi-step tasks — inspired by applications like Claude Code and Deep Research.

🌐 Supported Environments

LangChain.js is written in TypeScript and can be used in:

  • Node.js (ESM and CommonJS) - 20.x, 22.x, 24.x
  • Cloudflare Workers
  • Vercel / Next.js (Browser, Serverless and Edge functions)
  • Supabase Edge Functions
  • Browser
  • Deno
  • Bun

📖 Additional Resources

  • Getting started: Installation, setting up the environment, simple examples
  • Learn: Learn about the core concepts of LangChain.
  • LangChain Forum: Connect with the community and share all of your technical questions, ideas, and feedback.
  • Chat LangChain: Ask questions & chat with our documentation.

💁 Contributing

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.

Classes

Class

AIMessage

LangChain Messages

Class

AIMessageChunk

Represents a chunk of an AI message, which can be concatenated with

Class

BaseMessage

Base class for all types of messages in a conversation. It includes

Class

BaseMessageChunk

Represents a chunk of a message, which can be concatenated with other

Class

ClearToolUsesEdit

Strategy for clearing tool outputs when token limits are exceeded.

Class

Document

Interface for interacting with a document.

Class

DynamicStructuredTool

A tool that can be created dynamically from a function, name, and

Class

DynamicTool

A tool that can be created dynamically from a function, name, and description.

Class

FakeToolCallingModel

Fake chat model for testing tool calling functionality

Class

HumanMessage

Represents a human message in a conversation.

Class

HumanMessageChunk

Represents a chunk of a human message, which can be concatenated with

Class

InMemoryStore

In-memory implementation of the BaseStore using a dictionary. Used for

Class

MiddlewareError

Error thrown when a middleware fails.

Class

MultipleStructuredOutputsError

Raised when model returns multiple structured output tool calls when only one is expected.

Class

MultipleToolsBoundError

Class

PIIDetectionError

Error thrown when PII is detected and strategy is 'block'

Class

ProviderStrategy

Class

StructuredOutputParsingError

Raised when structured output tool call arguments fail to parse according to the schema.

Class

StructuredTool

Base class for Tools that accept input of any shape defined by a Zod schema.

Class

SystemMessage

Represents a system message in a conversation.

Class

SystemMessageChunk

Represents a chunk of a system message, which can be concatenated with

Class

Tool

Base class for Tools that accept input as a string.

Class

ToolCallLimitExceededError

Exception raised when tool call limits are exceeded.

Class

ToolInvocationError

Raised when a tool call is throwing an error.

Class

ToolMessage

Represents a tool message in a conversation.

Class

ToolMessageChunk

Represents a chunk of a tool message, which can be concatenated

Class

ToolStrategy

Information for tracking structured output tool metadata.

Class

Serializable

Class

EncoderBackedStore

Class that provides a layer of abstraction over the base storage,

Class

LocalFileStore

File system implementation of the BaseStore using a dictionary. Used for

Class

InMemoryStore

In-memory implementation of the BaseStore using a dictionary. Used for

Functions

Function

_inferModelProvider

Attempts to infer the model provider based on the given model name.

Function

getChatModelByClassName

Helper function to get a chat model class by its class name or model provider.

Function

initChatModel

Initialize a ChatModel from the model name and provider.

Function

pull

Pull a prompt from the hub.

Function

push

Push a prompt to the hub.

Function

inferModelProviderFromNamespace

Infer modelProvider from the id namespace to avoid className collisions.

Function

pull

Pull a prompt from the hub.

Function

push

Push a prompt to the hub.

Function

anthropicPromptCachingMiddleware

Creates a prompt caching middleware for Anthropic models to optimize API usage.

Function

applyStrategy

Apply strategy to content based on matches

Function

context

LangChain utilities

Function

contextEditingMiddleware

Middleware that automatically prunes tool results to manage context size.

Function

countTokensApproximately

Default token counter that approximates based on character count.

Function

createAgent

Creates a production-ready ReAct (Reasoning + Acting) agent that combines language models with tools

Function

createMiddleware

Creates a middleware instance with automatic schema inference.

Function

detectCreditCard

Detect credit card numbers in content (validated with Luhn algorithm)

Function

detectEmail

Detect email addresses in content

Function

detectIP

Detect IP addresses in content (validated)

Function

detectMacAddress

Detect MAC addresses in content

Function

detectUrl

Detect URLs in content

Function

dynamicSystemPromptMiddleware

Dynamic System Prompt Middleware

Function

filterMessages

LangChain Messages

Function

humanInTheLoopMiddleware

Creates a Human-in-the-Loop (HITL) middleware for tool approval and oversight.

Function

llmToolSelectorMiddleware

Middleware for selecting tools using an LLM-based strategy.

Function

modelCallLimitMiddleware

Creates a middleware to limit the number of model calls at both thread and run levels.

Function

modelFallbackMiddleware

Middleware that provides automatic model fallback on errors.

Function

modelRetryMiddleware

Middleware that automatically retries failed model calls with configurable backoff.

Function

openAIModerationMiddleware

Provider specific middleware

Function

piiMiddleware

Creates a middleware that detects and handles personally identifiable information (PII)

Function

providerStrategy

Creates a provider strategy for structured output using native JSON schema support.

Function

resolveRedactionRule

Resolve a redaction rule to a concrete detector function

Function

summarizationMiddleware

Summarization middleware that automatically summarizes conversation history when token limits are approached.

Function

todoListMiddleware

Creates a middleware that provides todo list management capabilities to agents.

Function

tool

LangChain Tools

Function

toolCallLimitMiddleware

Middleware that tracks tool call counts and enforces limits.

Function

toolEmulatorMiddleware

Middleware that emulates specified tools using an LLM instead of executing them.

Function

toolRetryMiddleware

Middleware that automatically retries failed tool calls with configurable backoff.

Function

toolStrategy

Creates a tool strategy for structured output using function calling.

Function

trimMessages

LangChain Messages

Function

initChatModel

Initialize a ChatModel from the model name and provider.

Function

load

Load a LangChain module from a serialized text representation.

Function

get_lc_unique_name

Get a unique name for the module, rather than parent class implementations.

Function

createDocumentStoreFromByteStore

Function

piiRedactionMiddleware

deprecated

Creates a middleware that detects and redacts personally identifiable information (PII)

Exports

Interfaces

Types

Module

chat_models/universal

Module

hub

Module

hub/node

Module

index

Module

load

Module

load/serializable

Module

storage/encoder_backed

Module

storage/file_system

Module

storage/in_memory

Interface

ConfigurableChatModelCallOptions

Interface

InitChatModelFields

Interface

InvalidToolCall

Content block to represent an invalid tool call

Interface

ServerToolCall

Interface

ServerToolCallChunk

Interface

ServerToolCallResult

Interface

ToolCall

Represents a request to call a tool.

Interface

ToolCallChunk

Content block to represent partial data of a tool call

Interface

Citation

Annotation for citing data from a document.

Interface

NonStandard

Provider-specific content block.

Interface

Reasoning

Reasoning output from a LLM.

Interface

Text

Text output from a LLM.

Interface

Action

Represents an action with a name and arguments.

Interface

ActionRequest

Represents an action request with a name, arguments, and description.

Interface

AgentMiddleware

Base middleware interface.

Interface

AgentTypeConfig

Type bag that encapsulates all agent type parameters.

Interface

ApproveDecision

Response when a human approves the action.

Interface

BuiltInState

Interface

ClearToolUsesEditConfig

Configuration for clearing tool outputs when token limits are exceeded.

Interface

ContentBlock

LangChain Messages

Interface

ContextEdit

Protocol describing a context editing strategy.

Interface

ContextEditingMiddlewareConfig

Configuration for the Context Editing Middleware.

Interface

DefaultAgentTypeConfig

Default type configuration for agents.

Interface

DocumentInput

LangChain Documents

Interface

EditDecision

Response when a human edits the action.

Interface

ExecutedToolCall

Information about a tool call that has been executed.

Interface

HITLRequest

Request for human feedback on a sequence of actions requested by a model.

Interface

HITLResponse

Response payload for a HITLRequest.

Interface

Interrupt

Represents information about an interrupt.

Interface

MiddlewareTypeConfig

Type bag that encapsulates all middleware type parameters.

Interface

ModelRequest

Configuration for modifying a model call at runtime.

Interface

OpenAIModerationMiddlewareOptions

Options for configuring the OpenAI Moderation middleware.

Interface

PIIMatch

Represents a detected PII match in content

Interface

ReactAgent

ReactAgent is a production-ready ReAct (Reasoning + Acting) agent that combines

Interface

RedactionRuleConfig

Configuration for a redaction rule

Interface

RejectDecision

Response when a human rejects the action.

Interface

ResolvedRedactionRule

Resolved redaction rule with a concrete detector function

Interface

ReviewConfig

Policy for reviewing a HITL request.

Interface

TodoListMiddlewareOptions

Interface

ToolCall

Information about a tool call that has been executed.

Interface

ToolCallRequest

Represents a tool call request for the wrapToolCall hook.

Interface

ToolEmulatorOptions

Options for configuring the Tool Emulator middleware.

Interface

ToolResult

Information about a tool result from a tool execution.

Interface

TypedToolStrategy

Branded type for ToolStrategy arrays that preserves type information

Interface

BaseSerialized

Interface

SerializableInterface

Interface

SerializableLike

Interface for objects that can be serialized.

Interface

SerializedConstructor

Interface

SerializedNotImplemented

Interface

SerializedSecret

Interface

Base64ContentBlock

deprecated
Interface

BaseDataContentBlock

deprecated
Interface

IDContentBlock

deprecated
Interface

PlainTextContentBlock

deprecated
Interface

URLContentBlock

deprecated
Type

ChatModelProvider

Type

ConfigurableFields

Type

Audio

Content block for audio data

Type

BaseDataRecord

Type

Data

Content block for multimodal data

Type

DataRecord

Type

DataRecordBase64

Type

DataRecordFileId

Type

DataRecordUrl

Type

File

Content block for file data

Type

Image

Content block for image data

Type

PlainText

Content block for plain text data

Type

Standard

Type

Video

Content block for video data

Type

Standard

Type

Data

Type

Multimodal

Type

Standard

Type

Tools

Type

AfterAgentHook

Hook type for the afterAgent lifecycle event.

Type

AfterModelHook

Hook type for the afterModel lifecycle event.

Type

AnyAnnotationRoot

Type

BeforeAgentHook

Hook type for the beforeAgent lifecycle event.

Type

BeforeModelHook

Hook type for the beforeModel lifecycle event.

Type

BuiltInPIIType

Built-in PII types

Type

CombineTools

Helper type to combine agent tools with middleware tools into a single readonly array.

Type

CreateAgentParams

Type

Decision

Union of all possible decision types.

Type

DecisionType

Type

DefaultMiddlewareTypeConfig

Default type configuration for middleware.

Type

DescriptionFactory

Function type that dynamically generates a description for a tool call approval request.

Type

DynamicSystemPromptMiddlewareConfig

Type

ExtractZodArrayTypes

Type helper to extract union type from an array of Zod schemas

Type

HumanInTheLoopMiddlewareConfig

Type

InferAgentContext

Helper type to infer the full merged context from an agent, including:

Type

InferAgentContextSchema

Shorthand helper to extract the raw Context schema type from an AgentTypeConfig or ReactAgent.

Type

InferAgentMiddleware

Shorthand helper to extract the Middleware type from an AgentTypeConfig or ReactAgent.

Type

InferAgentResponse

Shorthand helper to extract the Response type from an AgentTypeConfig or ReactAgent.

Type

InferAgentState

Helper type to infer the full merged state from an agent, including:

Type

InferAgentStateSchema

Shorthand helper to extract the raw State schema type from an AgentTypeConfig or ReactAgent.

Type

InferAgentTools

Shorthand helper to extract the Tools type from an AgentTypeConfig or ReactAgent.

Type

InferAgentType

Helper type to extract any property from an AgentTypeConfig or ReactAgent.

Type

InferChannelType

Type

InferContextInput

Helper type to extract input type from context schema (with optional defaults)

Type

InferMergedInputState

Helper type to infer merged input state from an array of middleware (includes built-in state)

Type

InferMergedState

Helper type to infer merged state from an array of middleware (includes built-in state)

Type

InferMiddlewareContext

Helper type to infer the context schema type from a middleware

Type

InferMiddlewareContextInput

Helper type to infer the input context schema type from a middleware (with optional defaults)

Type

InferMiddlewareContextInputs

Helper type to infer merged input context from an array of middleware (with optional defaults)

Type

InferMiddlewareContexts

Helper type to infer merged context from an array of middleware

Type

InferMiddlewareContextSchema

Shorthand helper to extract the ContextSchema type from a MiddlewareTypeConfig or AgentMiddleware.

Type

InferMiddlewareFullContext

Shorthand helper to extract the FullContext type from a MiddlewareTypeConfig or AgentMiddleware.

Type

InferMiddlewareInputState

Helper type to infer the input state schema type from a middleware (all properties optional)

Type

InferMiddlewareInputStates

Helper type to infer merged input state from an array of middleware (with optional defaults)

Type

InferMiddlewareSchema

Shorthand helper to extract the Schema type from a MiddlewareTypeConfig or AgentMiddleware.

Type

InferMiddlewareState

Helper type to infer the state schema type from a middleware

Type

InferMiddlewareStates

Helper type to infer merged state from an array of middleware (just the middleware states)

Type

InferMiddlewareTools

Helper type to infer tools from a single middleware instance.

Type

InferMiddlewareToolsArray

Helper type to infer and merge tools from an array of middleware.

Type

InferMiddlewareToolsFromConfig

Shorthand helper to extract the Tools type from a MiddlewareTypeConfig or AgentMiddleware.

Type

InferMiddlewareType

Helper type to extract any property from a MiddlewareTypeConfig or AgentMiddleware.

Type

InferSchemaInput

Type

InterruptOnConfig

Type

JumpTo

jump targets (internal)

Type

JumpToTarget

Type

LLMToolSelectorConfig

Type

MiddlewareResult

Result type for middleware functions.

Type

ModelCallLimitMiddlewareConfig

Type

ModelRetryMiddlewareConfig

Type

N

Type

NormalizedSchemaInput

Type

PIIDetector

Custom detector function that takes content and returns matches

Type

PIIMiddlewareConfig

Type

PIIStrategy

Strategy for handling detected PII

Type

PromptCachingMiddlewareConfig

Type

ResolveAgentTypeConfig

Helper type to resolve an AgentTypeConfig from either:

Type

ResolveMiddlewareTypeConfig

Helper type to resolve a MiddlewareTypeConfig from either:

Type

ResponseFormat

Type

ResponseFormatUndefined

Special type to indicate that no response format is provided.

Type

Runtime

Runtime information available to middleware (readonly).

Type

SummarizationMiddlewareConfig

Type

ToAnnotationRoot

Type

TokenCounter

Type

ToolCallHandler

Handler function type for wrapping tool calls.

Type

ToolCallLimitConfig

Type

ToolRetryMiddlewareConfig

Type

ToolRuntime

Runtime context automatically injected into tools.

Type

ToolsToMessageToolSet

Helper type to convert an array of tools (ClientTool | ServerTool)[] to a MessageToolSet.

Type

UserInput

Base input type for .invoke and .stream methods.

Type

WithStateGraphNodes

Type

WrapModelCallHandler

Handler function type for wrapping model calls.

Type

WrapModelCallHook

Wrapper function type for the wrapModelCall hook.

Type

WrapToolCallHook

Wrapper function type for the wrapToolCall hook.

Type

Serialized

Type

DataContentBlock

deprecated
Type

DataContentBlockType

deprecated
Type

StandardAudioBlock

deprecated
Type

StandardFileBlock

deprecated
Type

StandardImageBlock

deprecated
Type

StandardTextBlock

deprecated
Type

PIIRedactionMiddlewareConfig

deprecated