@langchain/core contains the core abstractions and schemas of LangChain.js, including base classes for language models,
chat models, vectorstores, retrievers, and runnables.
pnpm install @langchain/core
@langchain/core contains the base abstractions that power the rest of the LangChain ecosystem.
These abstractions are designed to be as modular and simple as possible.
Examples of these abstractions include those for language models, document loaders, embedding models, vectorstores, retrievers, and more.
The benefit of having these abstractions is that any provider can implement the required interface and then easily be used in the rest of the LangChain ecosystem.
For example, you can install other provider-specific packages like this:
pnpm install @langchain/openai
And use them as follows:
import { StringOutputParser } from "@langchain/core/output_parsers";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { ChatOpenAI } from "@langchain/openai";
const prompt = ChatPromptTemplate.fromTemplate(
`Answer the following question to the best of your ability:\n{question}`
);
const model = new ChatOpenAI({
model: "gpt-4o-mini",
temperature: 0.8,
});
const outputParser = new StringOutputParser();
const chain = prompt.pipe(model).pipe(outputParser);
const stream = await chain.stream({
question: "Why is the sky blue?",
});
for await (const chunk of stream) {
console.log(chunk);
}
/*
The
sky
appears
blue
because
of
a
phenomenon
known
as
Ray
leigh
scattering
*/
Note that for compatibility, all used LangChain packages (including the base LangChain package, which itself depends on core!) must share the same version of @langchain/core.
This means that you may need to install/resolve a specific version of @langchain/core that matches the dependencies of your used packages.
Other LangChain packages should add this package as a dependency and extend the classes within. For an example, see the @langchain/anthropic in this repo.
Because all used packages must share the same version of core, packages should never directly depend on @langchain/core. Instead they should have core as a peer dependency and a dev dependency. We suggest using a tilde dependency to allow for different (backwards-compatible) patch versions:
{
"name": "@langchain/anthropic",
"version": "0.0.3",
"description": "Anthropic integrations for LangChain.js",
"type": "module",
"author": "LangChain",
"license": "MIT",
"dependencies": {
"@anthropic-ai/sdk": "^0.10.0"
},
"peerDependencies": {
"@langchain/core": "~0.3.0"
},
"devDependencies": {
"@langchain/core": "~0.3.0"
}
}
We suggest making all packages cross-compatible with ESM and CJS using a build step like the one in
@langchain/anthropic, then running pnpm build before running npm publish.
Because @langchain/core is a low-level package whose abstractions will change infrequently, most contributions should be made in the higher-level LangChain package.
Bugfixes or suggestions should be made using the same guidelines as the main package. See here for detailed information.
Please report any security issues or concerns following our security guidelines.
Base class for all caches. All caches should extend this class.
A cache for storing LLM generations that stores data in memory.
Abstract base class for creating callback handlers in the LangChain
Manage callbacks from different components of LangChain.
Base class for run manager in LangChain.
Base class for run manager in LangChain.
Base class for run manager in LangChain.
Manages callbacks for retriever runs.
Base class for run manager in LangChain.
Base class for all chat message histories. All chat message histories
Base class for all list chat message histories. All list chat message
Class for storing chat message history in-memory. It extends the
Abstract class that provides a default implementation for the
Document loader integration with LangSmith.
Abstract base class for document transformation systems.
Interface for interacting with a document.
Class for document transformers that return exactly one transformed document
An abstract class that provides methods for embedding documents and
Error class representing a context window overflow in a language model operation.
Base error class for all LangChain errors.
Error class representing an aborted model operation in LangChain.
Base class for example selectors.
Abstract class that defines the interface for selecting a prompt for a
Concrete implementation of BasePromptSelector that selects a prompt
A specialized example selector that selects examples based on their
Class that selects examples based on semantic similarity. It extends
HashedDocument is a Document with hashes calculated.
Base class for language models, chains, tools.
Base class for language models.
Base class for chat models. It extends the BaseLanguageModel class and
An abstract class that extends BaseChatModel and provides a simple
LLM Wrapper. Takes in a prompt (or prompts) and returns a string.
LLM class that provides a simpler interface to subclass than BaseLLM.
The main stream object returned by chat model streaming.
Typed stream for reasoning content (chain-of-thought).
Typed stream for text content.
Typed stream for tool calls.
Typed stream for usage metadata.
Abstract base class for memory in LangChain's Chains. Memory refers to
Base class for all types of messages in a conversation. It includes
Represents a chunk of an AI message, which can be concatenated with
Base class for all types of messages in a conversation. It includes
Represents a chunk of a message, which can be concatenated with other
Represents a chat message in a conversation.
Represents a chunk of a chat message, which can be concatenated with
Represents a function message in a conversation.
Represents a chunk of a function message, which can be concatenated
Represents a human message in a conversation.
Represents a chunk of a human message, which can be concatenated with
Message responsible for deleting other messages.
Represents a system message in a conversation.
Represents a chunk of a system message, which can be concatenated with
Represents a tool message in a conversation.
Represents a chunk of a tool message, which can be concatenated
Represents a tool message in a conversation.
Represents a chunk of a tool message, which can be concatenated
A type of StructuredOutputParser that handles asymmetric input and
A base class for output parsers that can handle streaming input. It
Abstract base class for parsing the output of a Large Language Model
Class to parse the output of an LLM call.
Class to parse the output of an LLM call that also allows streaming inputs.
OutputParser that parses LLMResult into the top likely string and
Class to parse the output of an LLM call as a comma-separated list.
Class to parse the output of an LLM call to a list with a specific length and separator.
A specific type of StructuredOutputParser that parses JSON data
Class for parsing the output of an LLM into a JSON object.
Class to parse the output of an LLM call to a list.
Class to parse the output of an LLM call to a list.
Class to parse the output of an LLM call to a list.
Exception that output parsers should raise to signify a parsing error.
Class to parse the output of an LLM call.
OutputParser that parses LLMResult into the top likely string.
Class to parse the output of an LLM call.
A base class for output parsers that can handle streaming input. It
Class for parsing the output of an LLM into a JSON object and returning
Class for parsing the output of an LLM into a JSON object. Uses an
Class for parsing the output of an LLM. Can be configured to return
Class for parsing the output of a tool-calling LLM into a JSON object if you are
Class for parsing the output of a tool-calling LLM into a JSON object.
Output of a single generation.
Chunk of a single generation. Used for streaming.
Base PromptValue class. All prompt values should extend this class.
Class that represents a chat prompt value. It extends the
Class that represents an image prompt value. It extends the
Represents a prompt value as a string. It extends the BasePromptValue
Class that represents an AI message prompt template. It extends the
Abstract class that serves as a base for creating chat prompt
Abstract class that serves as a base for creating message prompt
Abstract class that serves as a base for creating message string prompt
Base class for prompt templates. Exposes a format method that returns a
Base class for string prompt templates. It extends the
Class that represents a chat message prompt template. It extends the
Class that represents a chat prompt. It extends the
A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or
Chat prompt template that contains few-shot examples.
Prompt template that contains few-shot examples.
Class that represents a human message prompt template. It extends the
An image prompt template for a multimodal model.
Class that represents a placeholder for messages in a chat prompt. It
Class that handles a sequence of prompts, each of which may require
Schema to represent a basic prompt for an LLM.
Interface for the input of a ChatPromptTemplate.
Class that represents a system message prompt template. It extends the
Abstract base class for a document retrieval system, designed to
Base Document Compression class. All compressors should extend this class.
A runnable that routes to a set of runnables based on Input['key'].
A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or
A runnable that assigns key-value pairs to inputs of type Record<string, unknown>.
Wraps a runnable and applies partial config upon invocation.
Class that represents a runnable branch. The RunnableBranch is
A runnable that delegates calls to another runnable
A runnable that wraps an arbitrary function that takes a single argument.
A runnable that runs a mapping of runnables in parallel,
A runnable that runs a mapping of runnables in parallel,
A runnable to passthrough inputs unchanged or with additional keys.
A runnable that assigns key-value pairs to inputs of type Record<string, unknown>.
Base class for runnables that can be retried a
A sequence of runnables, where the output of each is the input of the next.
Wraps a runnable and applies partial config upon invocation.
A Runnable that can fallback to other Runnables if it fails.
Abstract interface for a key-value store.
In-memory implementation of the BaseStore using a dictionary. Used for
Abstract class that provides a blueprint for creating specific
Class that extends the BaseTranslator class and provides concrete
Class representing a comparison filter directive. It extends the
Abstract class representing an expression. Subclasses must implement
Abstract class representing a filter directive. It extends the
A class that extends BaseTranslator to translate structured queries
Class representing an operation filter directive. It extends the
Class representing a structured query expression. It extends the
Abstract class for visiting expressions. Subclasses must implement
A fake chat model for testing, created via fakeModel.
Abstract base class for toolkits in LangChain. Toolkits are collections
A tool that can be created dynamically from a function, name, and
A tool that can be created dynamically from a function, name, and description.
Base class for Tools that accept input of any shape defined by a Zod schema.
Base class for Tools that accept input as a string.
Custom error class used to handle exceptions related to tool input parsing.
Abstract base class for creating callback handlers in the LangChain
A tracer that logs all events to the console. It extends from the
Class that extends the BaseTracer class from the
List of jsonpatch JSONPatchOperations, which describe how to create the run state
List of jsonpatch JSONPatchOperations, which describe how to create the run state
A callback handler that collects traced runs and makes it easy to fetch the traced run object from calls through any langchain object.
Interface for the input parameters of the BaseCallbackHandler class. It
A class that can be used to make async calls with concurrency and retry logic.
Base class for all chat message histories. All chat message histories
Base class for chat models. It extends the BaseLanguageModel class and
A class that provides fake embeddings by overriding the embedDocuments
Base class for all list chat message histories. All list chat message
A fake Chat Model that returns a predefined list of responses. It can be used
LLM class that provides a simpler interface to subclass than BaseLLM.
Abstract base class for a document retrieval system, designed to
A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or
Parser for comma-separated values. It splits the input text by commas
Base class for chat models. It extends the BaseLanguageModel class and
LLM class that provides a simpler interface to subclass than BaseLLM.
Base class for Tools that accept input of any shape defined by a Zod schema.
Abstract base class for creating callback handlers in the LangChain
Class that extends VectorStore to store vectors in memory. Provides
Abstract base class for creating callback handlers in the LangChain
A class that provides synthetic embeddings by overriding the
Abstract class extending VectorStore that defines a contract for saving
Abstract class representing a vector storage system for performing
Class for retrieving documents from a VectorStore based on vector similarity
Wraps a LCEL chain and manages history. It appends input messages
Dispatch a custom event.
Dispatch a custom event. Requires an explicit config object.
Waits for all promises in the queue to resolve. If the queue is
Consume a promise, either adding it to the queue or waiting for it to resolve
Get the value of a previously set context variable. Context variables
Register a callback configure hook to automatically add callback handlers to all runs.
Set a context variable. Context variables are scoped to any
Type guard function that checks if a given language model is of type
Type guard function that checks if a given language model is of type
Index data from the doc source into the vector store.
Get the context window size (max input tokens) for a given model.
Whether or not the input matches the OpenAI tool definition.
Convert an async iterable of legacy ChatGenerationChunks into
Finalize a content block for the finish event.
Pipes an LLM through an output parser, optionally wrapping the result
Creates the appropriate content-based output parser for a schema. Use this for
Creates the appropriate tool-calling output parser for a schema. Use this for
Load a LangChain object from a JSON string.
Get a unique name for the module, rather than parent class implementations.
This function is used by memory classes to select the input value
This function is used by memory classes to select the output value
Function used by memory classes to get the key of the prompt input,
'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else
Collapses an array of tool call chunks into complete tool calls.
The default text splitter function that splits text by newlines.
Filter messages based on name, type or id.
This function is used by memory classes to get a string representation
Immediately-invoked function expression.
Type guard to check if a value is a valid Message object.
Transforms an array of BaseMessage instances into an array of
Transforms an array of StoredMessage instances into an array of
Merge consecutive Messages of the same type.
Trim messages to be below a token count.
Ensure that a passed config is an object with all required keys present.
Helper function that patches runnable configs with updated properties.
Race a promise with an abort signal. If the signal is aborted, the promise will
Casts a value that might be string or number to actual string or number.
Checks if the provided value is a boolean.
Checks if a provided filter is empty. The filter can be a function, an
Checks if the provided value is a floating-point number.
Checks if the provided value is an integer.
Checks if the provided argument is an object and not an array.
Checks if the provided value is a string that cannot be parsed into a
Creates a new FakeBuiltModel for testing.
Whether or not the tool is one of StructuredTool, RunnableTool or StructuredToolParams.
Confirm whether the inputted tool is an instance of RunnableToolLike.
Confirm whether the inputted tool is an instance of StructuredToolInterface.
Confirm whether or not the tool contains the necessary properties to be considered a StructuredToolParams.
Creates a new StructuredTool instance with the provided function, name, description, and schema.
A tagged template function for creating formatted strings.
Converts a ReadableStream into a callback pattern.
Parses arbitary byte chunks into EventSource line buffers.
Parses line buffers into EventSourceMessages.
Formats a StructuredTool or RunnableToolLike instance into a format
Formats a StructuredTool or RunnableToolLike instance into a
Whether or not the tool is one of StructuredTool, RunnableTool or StructuredToolParams.
Confirm whether the inputted tool is an instance of RunnableToolLike.
Confirm whether the inputted tool is an instance of StructuredToolInterface.
Confirm whether or not the tool contains the necessary properties to be considered a StructuredToolParams.
Apply a full JSON Patch array on a JSON document.
Create an array of patches from the differences in two objects
Converts a Standard JSON schema, Zod schema or JSON schema to a JSON schema.
Validates if a JSON schema validates only strings. May return false negatives in some edge cases
This function calculates the row-wise cosine similarity between two matrices with the same number of columns.
Apply a row-wise function between two matrices with the same number of columns.
This function implements the Maximal Marginal Relevance algorithm
Check if a hostname or IP is a known cloud metadata endpoint.
Check if a hostname or IP is localhost.
Check if an IP address is private (RFC 1918, loopback, link-local, etc.)
Check if a URL is safe to connect to (non-throwing version).
Check if two URLs have the same origin (scheme, host, port).
Validate that a URL is safe to connect to.
Type guard for Standard Schema V1. Returns true if the value has a ~standard.validate interface,
Type guard for Standard JSON Schema V1. Returns true if the value has a ~standard.jsonSchema
Type guard for Standard Schema V1. Returns true if the value has a ~standard.validate
Extends a Zod object schema with additional fields, supporting both Zod v3 and v4.
Returns a getter function for the default value of a Zod schema, if one is defined.
Retrieves the shape (fields) of a Zod object schema, supporting both Zod v3 and v4.
Retrieves the description from a schema definition (v3, v4, standard schema, or plain object), if available.
Parses the input using the provided Zod schema (v3 or v4) and returns the parsed value.
Asynchronously parses the input using the provided Zod schema (v3 or v4) and returns the parsed value.
Safely parses the input using the provided Zod schema (v3 or v4) and returns a result object
Asynchronously parses the input using the provided Zod schema (v3 or v4) and returns a safe parse result.
Creates a modified version of a Zod object schema where fields matching a predicate are made optional.
Returns a partial version of a Zod object schema, making all fields optional.
Returns a passthrough version of a Zod object schema, allowing unknown keys.
Returns a strict version of a Zod object schema, disallowing unknown keys.
Returns the input type of a Zod transform schema, for both v3 and v4.
Determines if the provided value is an InteropZodLiteral (Zod v3 or v4 literal schema).
Determines if the provided value is an InteropZodObject (Zod v3 or v4 object schema).
Given either a Zod schema, or plain object, determine if the input is a Zod schema.
Determines if the provided Zod schema is "shapeless".
Determines if the provided Zod schema should be treated as a simple string schema
Backward compatible isZodSchema for Zod 3
Convert from a standard data content block to a provider's proprietary data content block format.
Utility function for ChatModelProviders. Parses a base64 data URL into a typed array or string.
Utility function for ChatModelProviders. Parses a mime type into a type, subtype, and parameters.
Compatibility bridge: converts legacy _streamResponseChunks
Chat model streaming event protocol.
Typed stream classes for chat model streaming.
Load LangChain objects from JSON strings or objects.
Interface for the input parameters of the BaseCallbackHandler class. It
Base interface for callbacks. All methods are optional. If a method is not
Interface for handlers that prefer chat model stream events instead of
Interface for handlers that can indicate a preference for streaming responses.
Interface for the indices of a new token produced by an LLM or Chat
Interface that defines the methods for loading and splitting documents.
Interface for the input parameters of the LengthBasedExampleSelector
Base interface implemented by all runnables.
Base interface for language model parameters.
Shared interface for token usage
Generic content block field update. Shallow-merge fields onto the active
Emitted for each incremental update within a content block.
Emitted when a content block is complete.
Emitted when a new content block begins streaming.
Incremental encoded data. Append data to the active multimodal block's
Emitted once when the model response is complete.
Emitted once at the start of a model response.
Passthrough for native provider events that don't map to standard types.
Incremental reasoning content. Append reasoning to the active block's
Emitted on unrecoverable stream errors.
Incremental text content. Append text to the active block's text field.
Emitted whenever the provider reports updated usage information.
Base interface for language model parameters.
Represents the capabilities and constraints of a language model.
Options for loading serialized LangChain objects.
Interface for objects that can be serialized.
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.
Reasoning output from a LLM.
Text output from a LLM.
Options for controlling merge behavior in _mergeDicts.
Represents a message object that organizes context for an LLM.
Core interface that defines the structure of messages.
Represents the input and output types of a tool that can be used in messages.
Represents a structured set of tools by mapping tool names to definitions
Standard message structured used to define the most basic message structure that's
Marker parameter for objects that tools can return directly.
A chunk of a tool call (e.g., as part of a stream).
Marker parameter for objects that tools can return directly.
A chunk of a tool call (e.g., as part of a stream).
Options for formatting instructions.
Options for formatting instructions.
Output of a single generation.
Output of a single generation.
Interface for the fields of a ChatPromptValue.
Input common to all prompt templates.
Interface for the fields of a ChatMessagePromptTemplate.
Interface for the input of a ChatPromptTemplate.
Input common to all prompt templates.
Input common to all prompt templates.
Inputs to create a ImagePromptTemplate
Interface for the fields of a MessagePlaceholder.
Interface for the fields of a MessageStringPromptTemplate.
Inputs to create a PromptTemplate
Interface for the input of a ChatPromptTemplate.
Input configuration options for initializing a retriever that extends
Interface for a base retriever that defines core functionality for
Base interface implemented by all runnables.
Base interface for the input parameters of the DynamicTool and
Interface for the input parameters of the DynamicStructuredTool class.
Interface for the input parameters of the DynamicTool class.
Interface that defines the shape of a LangChain structured tool.
Schema for defining tools.
A special interface for tools that accept a string input, usually defined with the Tool class.
Parameters for the Tool classes.
Parameters for the tool function.
Interface for the input parameters of the BaseCallbackHandler class. It
Interface for the input parameters of the BaseCallbackHandler class. It
Represents a message sent in an event stream
Interface for the input parameters specific to the Fake List Chat model.
Represents the call options for a base chat model.
Interface specific to the Fake Streaming Chat model.
Interface for the Constructor-field specific to the Fake Streaming Chat model (all optional because we fill in defaults).
Parameters for the Tool classes.
Interface for the arguments that can be passed to the
Minimal shape actually needed by bindTools
Interface defining the structure and operations of a vector store, which
Interface for a retriever that uses a vector store to store and retrieve
Utility interface for converting between standard and provider-specific data content blocks, to be
The parameters required to initialize an instance of the Embeddings
Interface for the input data of the SemanticSimilarityExampleSelector
Represents the call options for a base chat model.
Represents the parameters for a base chat model.
Represents a serialized chat model.
Represents a serialized large language model.
Union of all chat model stream event types.
Union of all content block delta types.
Finish reason for a model response.
Type alias for a record where the keys are strings and the values can
Type alias for a record where the keys are strings and the values can
Type alias for a record where the keys are strings and the values can
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
Infers the content type for a specific message type from a message structure.
Infers the content blocks for a specific message type in a message structure.
Infers the properties for a specific message type from a message structure.
Infers the type of a specific property for a message type from a message structure.
Infers the response metadata type for a specific message type from a message structure.
Helper type to infer a union of ToolCall types from the tools defined in a MessageStructure.
Helper type to infer a union of tool output types from the tools defined in a MessageStructure.
Merges two content definition objects from message structures.
Merges two discriminated unions A and B based on a discriminator key (defaults to "type").
Merges two message structures A and B into a combined structure.
Recursively merges two object types T and U, with U taking precedence over T.
Merges two output version types from message structures.
Represents a tool call block within a message structure by mapping tool names to their
Takes a message structure type T and normalizes it by merging it with the standard message structure.
Breakdown of input token counts.
Represents the output version format for message content.
Represents the possible types of messages in the system.
Breakdown of output token counts.
Provider streaming marker for raw (non-JSON) tool input.
Usage metadata for a message, such as token counts.
Represents optional parameters for a function in a JSON Schema.
Contains all relevant information returned by an LLM.
Alias for ParsedTemplateNode since it is the same for
Type that represents a node in a parsed format string. It can be either
Type that includes the name of the prompt and the prompt itself.
Type that extends the BasePromptTemplateInput type, excluding the
Represents a serialized version of a base prompt template. This type
Represents a serialized version of a few-shot template. This type
Represents a serialized version of a prompt template. This type is used
Type that specifies the format of a template.
Type for a branch in the RunnableBranch. It consists of a condition
Represents logical AND operator.
Represents a comparison operator which can be EQ, NE, LT, GT, LTE, or
Represents equality comparison operator.
A type alias for a function that takes a Document as an argument and
Represents greater than comparison operator.
Represents greater than or equal to comparison operator.
Represents less than comparison operator.
Represents less than or equal to comparison operator.
Represents inequality comparison operator.
Represents logical NOT operator.
Represents a logical operator which can be AND, OR, or NOT.
Represents logical OR operator.
Options object for the BasicTranslator class. Specifies the allowed
Represents the result of visiting a comparison expression.
Represents the result of visiting an operation expression.
Represents the result of visiting an operation or comparison
Represents the result of visiting a structured query expression.
Defines the type that will be passed into a tool handler function as a result of a tool call.
Conditional type that determines the return type of the StructuredTool.invoke method.
Runtime context automatically injected into tools.
Base type that establishes the types of input schemas that can be used for LangChain tool
Interface that represents the structure of a log entry in the
A streaming event.
Data associated with a StreamEvent.
A streaming event.
Data associated with a StreamEvent.
A function that converts data from one format to another.
A pair of bidirectional conversion functions for transforming data between two formats.
A function type for encoding hash keys.
A schema that supports both runtime validation and JSON Schema generation. Any schema passed
Represents a string value with autocompleted, but not required, suggestions.
Options for configuring a maximal marginal relevance (MMR) search.
Input configuration options for creating a VectorStoreRetriever instance.
Options for configuring a maximal marginal relevance (MMR) search
A bag of provider-specific content block types.