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

LangChain Assistant

Ask a question to get started

Enter to send•Shift+Enter new line

Menu

LangChain
BrowserUniversalHubNodeLoadSerializableEncoder BackedFile SystemIn MemoryTools
LangChain Core
AgentsCachesBaseDispatchWebManagerPromisesChat HistoryContextBaseLangsmithDocumentsEmbeddingsErrorsExample SelectorsIndexingBaseChat ModelsCompatEventLlmsOpenai Completions StreamProfileStreamStructured OutputLoadSerializableMemoryMessagesToolOutput ParsersOpenai FunctionsOpenai ToolsOutputsPrompt ValuesPromptsRetrieversDocument CompressorsRunnablesGraphSingletonsStoresStructured QueryTestingToolsBaseConsoleLog StreamRun CollectorTracer LangchainStreamAsync CallerChunk ArrayContextEnvEvent Source ParseFormatFunction CallingGatewayHashJson PatchJson SchemaMathSsrfStandard SchemaStreamTestingTiktokenTypesUuidVectorstores
Text Splitters
MCP Adapters
Language
Theme
JavaScript@langchain/core

@langchain/core

Description

🦜🍎️ @langchain/core

npm License: MIT Twitter

@langchain/core contains the core abstractions and schemas of LangChain.js, including base classes for language models, chat models, vectorstores, retrievers, and runnables.

💾 Quick Install

pnpm install @langchain/core

🤔 What is this?

@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.

📦 Creating your own package

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.

💁 Contributing

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.

Classes

Class

BaseCache

Base class for all caches. All caches should extend this class.

Class

InMemoryCache

A cache for storing LLM generations that stores data in memory.

Class

BaseCallbackHandler

Abstract base class for creating callback handlers in the LangChain framework. It provides a set of optional methods that can be overridden in derived classes to handle various events during the execu

Class

BaseCallbackManager

Manage callbacks from different components of LangChain.

Class

BaseRunManager

Base class for run manager in LangChain.

Class

CallbackManager

Class

CallbackManagerForChainRun

Base class for run manager in LangChain.

Class

CallbackManagerForLLMRun

Base class for run manager in LangChain.

Class

CallbackManagerForRetrieverRun

Manages callbacks for retriever runs.

Class

CallbackManagerForToolRun

Base class for run manager in LangChain.

Class

BaseChatMessageHistory

Base class for all chat message histories. All chat message histories should extend this class.

Class

BaseListChatMessageHistory

Base class for all list chat message histories. All list chat message histories should extend this class.

Class

InMemoryChatMessageHistory

Class for storing chat message history in-memory. It extends the BaseListChatMessageHistory class and provides methods to get, add, and clear messages.

Class

BaseDocumentLoader

Abstract class that provides a default implementation for the loadAndSplit() method from the DocumentLoader interface. The load() method is left abstract and needs to be implemented by subclasses.

Class

LangSmithLoader

Document loader integration with LangSmith.

Constructor args

Class

BaseDocumentTransformer

Abstract base class for document transformation systems.

A document transformation system takes an array of Documents and returns an array of transformed Documents. These arrays do not necessarily ha

Class

Document

Interface for interacting with a document.

Class

MappingDocumentTransformer

Class for document transformers that return exactly one transformed document for each input document.

Class

Embeddings

An abstract class that provides methods for embedding documents and queries using LangChain.

Class

ContextOverflowError

Error class representing a context window overflow in a language model operation.

This error is thrown when the combined input to a language model (such as prompt tokens, historical messages, and/or

Class

LangChainError

Base error class for all LangChain errors.

All LangChain error classes should extend this class (directly or indirectly). Use LangChainError.isInstance(obj) to check if an object is any LangChain e

Class

ModelAbortError

Error class representing an aborted model operation in LangChain.

This error is thrown when a model operation (such as invocation, streaming, or batching) is cancelled before it completes, commonly d

Class

BaseExampleSelector

Base class for example selectors.

Class

BasePromptSelector

Abstract class that defines the interface for selecting a prompt for a given language model.

Class

ConditionalPromptSelector

Concrete implementation of BasePromptSelector that selects a prompt based on a set of conditions. It has a default prompt that it returns if none of the conditions are met.

Class

LengthBasedExampleSelector

A specialized example selector that selects examples based on their length, ensuring that the total length of the selected examples does not exceed a specified maximum length.

Class

SemanticSimilarityExampleSelector

Class that selects examples based on semantic similarity. It extends the BaseExampleSelector class.

Class

_HashedDocument

HashedDocument is a Document with hashes calculated. Hashes are calculated based on page content and metadata. It is used for indexing.

Class

RecordManager

Class

BaseLangChain

Base class for language models, chains, tools.

Class

BaseLanguageModel

Base class for language models.

Class

BaseChatModel

Base class for chat models. It extends the BaseLanguageModel class and provides methods for generating chat based on input messages.

Class

SimpleChatModel

An abstract class that extends BaseChatModel and provides a simple implementation of _generate.

Class

BaseLLM

LLM Wrapper. Takes in a prompt (or prompts) and returns a string.

Class

LLM

LLM class that provides a simpler interface to subclass than BaseLLM.

Requires only implementing a simpler _call method instead of _generate.

Class

ChatModelStream

The main stream object returned by chat model streaming.

Implements AsyncIterable<ChatModelStreamEvent> for raw event access and PromiseLike<AIMessage> for simple await usage.

Class

ReasoningContentStream

Typed stream for reasoning content (chain-of-thought). Same interface as TextContentStream but for reasoning blocks.

Class

TextContentStream

Typed stream for text content.

  • Iterate: yields incremental text deltas.
  • Await: resolves to the complete concatenated text.
  • .full: yields the running accumulated text after each de
Class

ToolCallsStream

Typed stream for tool calls.

  • Iterate: yields individual ToolCall objects as each completes.
  • Await: resolves to the full array.
  • .full: yields the accumulated array after each new
Class

UsageMetadataStream

Typed stream for usage metadata.

Class

Serializable

Class

BaseMemory

Abstract base class for memory in LangChain's Chains. Memory refers to the state in Chains. It can be used to store information about past executions of a Chain and inject that information into the in

Class

AIMessage

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().

Class

AIMessageChunk

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

Class

BaseMessage

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().

Class

BaseMessageChunk

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

Class

ChatMessage

Represents a chat message in a conversation.

Class

ChatMessageChunk

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

Class

FunctionMessage

Represents a function message in a conversation.

Class

FunctionMessageChunk

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

Class

HumanMessage

Represents a human message in a conversation.

Class

HumanMessageChunk

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

Class

RemoveMessage

Message responsible for deleting other messages.

RemoveMessage is intentionally not generic over MessageStructure. Its content is always [] (empty), so carrying a structure type parameter would

Class

SystemMessage

Represents a system message in a conversation.

Class

SystemMessageChunk

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

Class

ToolMessage

Represents a tool message in a conversation.

Class

ToolMessageChunk

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

Class

ToolMessage

Represents a tool message in a conversation.

Class

ToolMessageChunk

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

Class

AsymmetricStructuredOutputParser

A type of StructuredOutputParser that handles asymmetric input and output schemas.

Class

BaseCumulativeTransformOutputParser

A base class for output parsers that can handle streaming input. It extends the BaseTransformOutputParser class and provides a method for converting parsed outputs into a diff format.

Class

BaseLLMOutputParser

Abstract base class for parsing the output of a Large Language Model (LLM) call. It provides methods for parsing the result of an LLM call and invoking the parser with a given input.

Class

BaseOutputParser

Class to parse the output of an LLM call.

Class

BaseTransformOutputParser

Class to parse the output of an LLM call that also allows streaming inputs.

Class

BytesOutputParser

OutputParser that parses LLMResult into the top likely string and encodes it into bytes.

Class

CommaSeparatedListOutputParser

Class to parse the output of an LLM call as a comma-separated list.

Class

CustomListOutputParser

Class to parse the output of an LLM call to a list with a specific length and separator.

Class

JsonMarkdownStructuredOutputParser

A specific type of StructuredOutputParser that parses JSON data formatted as a markdown code snippet.

Class

JsonOutputParser

Class for parsing the output of an LLM into a JSON object.

Class

ListOutputParser

Class to parse the output of an LLM call to a list.

Class

MarkdownListOutputParser

Class to parse the output of an LLM call to a list.

Class

NumberedListOutputParser

Class to parse the output of an LLM call to a list.

Class

OutputParserException

Exception that output parsers should raise to signify a parsing error.

This exists to differentiate parsing errors from other code or execution errors that also may arise inside the output parser. Ou

Class

StandardSchemaOutputParser

Class to parse the output of an LLM call.

Class

StringOutputParser

OutputParser that parses LLMResult into the top likely string.

Class

StructuredOutputParser

Class to parse the output of an LLM call.

Class

XMLOutputParser

A base class for output parsers that can handle streaming input. It extends the BaseTransformOutputParser class and provides a method for converting parsed outputs into a diff format.

Class

JsonKeyOutputFunctionsParser

Class for parsing the output of an LLM into a JSON object and returning a specific attribute. Uses an instance of JsonOutputFunctionsParser to parse the output.

Class

JsonOutputFunctionsParser

Class for parsing the output of an LLM into a JSON object. Uses an instance of OutputFunctionsParser to parse the output.

Class

OutputFunctionsParser

Class for parsing the output of an LLM. Can be configured to return only the arguments of the function call in the output.

Class

JsonOutputKeyToolsParser

Class for parsing the output of a tool-calling LLM into a JSON object if you are expecting only a single tool to be called.

Class

JsonOutputToolsParser

Class for parsing the output of a tool-calling LLM into a JSON object.

Class

ChatGenerationChunk

Output of a single generation.

Class

GenerationChunk

Chunk of a single generation. Used for streaming.

Class

BasePromptValue

Base PromptValue class. All prompt values should extend this class.

Class

ChatPromptValue

Class that represents a chat prompt value. It extends the BasePromptValue and includes an array of BaseMessage instances.

Class

ImagePromptValue

Class that represents an image prompt value. It extends the BasePromptValue and includes an ImageURL instance.

Class

StringPromptValue

Represents a prompt value as a string. It extends the BasePromptValue class and overrides the toString and toChatMessages methods.

Class

AIMessagePromptTemplate

Class that represents an AI message prompt template. It extends the BaseMessageStringPromptTemplate.

Class

BaseChatPromptTemplate

Abstract class that serves as a base for creating chat prompt templates. It extends the BasePromptTemplate.

Class

BaseMessagePromptTemplate

Abstract class that serves as a base for creating message prompt templates. It defines how to format messages for different roles in a conversation.

Class

BaseMessageStringPromptTemplate

Abstract class that serves as a base for creating message string prompt templates. It extends the BaseMessagePromptTemplate.

Class

BasePromptTemplate

Base class for prompt templates. Exposes a format method that returns a string prompt given a set of input values.

Class

BaseStringPromptTemplate

Base class for string prompt templates. It extends the BasePromptTemplate class and overrides the formatPromptValue method to return a StringPromptValue.

Class

ChatMessagePromptTemplate

Class that represents a chat message prompt template. It extends the BaseMessageStringPromptTemplate.

Class

ChatPromptTemplate

Class that represents a chat prompt. It extends the BaseChatPromptTemplate and uses an array of BaseMessagePromptTemplate instances to format a series of messages for a conversation.

Class

DictPromptTemplate

A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or transformed.

Class

FewShotChatMessagePromptTemplate

Chat prompt template that contains few-shot examples.

Class

FewShotPromptTemplate

Prompt template that contains few-shot examples.

Class

HumanMessagePromptTemplate

Class that represents a human message prompt template. It extends the BaseMessageStringPromptTemplate.

Class

ImagePromptTemplate

An image prompt template for a multimodal model.

Class

MessagesPlaceholder

Class that represents a placeholder for messages in a chat prompt. It extends the BaseMessagePromptTemplate.

Class

PipelinePromptTemplate

Class that handles a sequence of prompts, each of which may require different input variables. Includes methods for formatting these prompts, extracting required input values, and handling partial pro

Class

PromptTemplate

Schema to represent a basic prompt for an LLM.

Class

StructuredPrompt

Interface for the input of a ChatPromptTemplate.

Class

SystemMessagePromptTemplate

Class that represents a system message prompt template. It extends the BaseMessageStringPromptTemplate.

Class

BaseRetriever

Abstract base class for a document retrieval system, designed to process string queries and return the most relevant documents from a source.

BaseRetriever provides common properties and methods fo

Class

BaseDocumentCompressor

Base Document Compression class. All compressors should extend this class.

Class

RouterRunnable

A runnable that routes to a set of runnables based on Input['key']. Returns the output of the selected runnable.

Class

Runnable

A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or transformed.

Class

RunnableAssign

A runnable that assigns key-value pairs to inputs of type Record<string, unknown>.

Class

RunnableBinding

Wraps a runnable and applies partial config upon invocation.

Class

RunnableBranch

Class that represents a runnable branch. The RunnableBranch is initialized with an array of branches and a default branch. When invoked, it evaluates the condition of each branch in order and executes

Class

RunnableEach

A runnable that delegates calls to another runnable with each element of the input sequence.

Class

RunnableLambda

A runnable that wraps an arbitrary function that takes a single argument.

Class

RunnableMap

A runnable that runs a mapping of runnables in parallel, and returns a mapping of their outputs.

Class

RunnableParallel

A runnable that runs a mapping of runnables in parallel, and returns a mapping of their outputs.

Class

RunnablePassthrough

A runnable to passthrough inputs unchanged or with additional keys.

This runnable behaves almost like the identity function, except that it can be configured to add additional keys to the output, if

Class

RunnablePick

A runnable that assigns key-value pairs to inputs of type Record<string, unknown>. Useful for streaming, can be automatically created and chained by calling runnable.pick();.

Class

RunnableRetry

Base class for runnables that can be retried a specified number of times.

Class

RunnableSequence

A sequence of runnables, where the output of each is the input of the next.

Class

RunnableToolLike

Wraps a runnable and applies partial config upon invocation.

Class

RunnableWithFallbacks

A Runnable that can fallback to other Runnables if it fails. External APIs (e.g., APIs for a language model) may at times experience degraded performance or even downtime.

In these cases, it can be u

Class

Graph

Class

MockAsyncLocalStorage

Class

BaseStore

Abstract interface for a key-value store.

Class

InMemoryStore

In-memory implementation of the BaseStore using a dictionary. Used for storing key-value pairs in memory.

Class

BaseTranslator

Abstract class that provides a blueprint for creating specific translator classes. Defines two abstract methods: formatFunction and mergeFilters.

Class

BasicTranslator

Class that extends the BaseTranslator class and provides concrete implementations for the abstract methods. Also declares three types: VisitOperationOutput, VisitComparisonOutput, and VisitStructuredQ

Class

Comparison

Class representing a comparison filter directive. It extends the FilterDirective class.

Class

Expression

Abstract class representing an expression. Subclasses must implement the exprName property and the accept method.

Class

FilterDirective

Abstract class representing a filter directive. It extends the Expression class.

Class

FunctionalTranslator

A class that extends BaseTranslator to translate structured queries into functional filters.

Class

Operation

Class representing an operation filter directive. It extends the FilterDirective class.

Class

StructuredQuery

Class representing a structured query expression. It extends the Expression class.

Class

Visitor

Abstract class for visiting expressions. Subclasses must implement visitOperation, visitComparison, and visitStructuredQuery methods.

Class

FakeBuiltModel

A fake chat model for testing, created via fakeModel.

Queue responses with .respond() and .respondWithTools(), then pass the instance directly wherever a chat model is expected. Responses are con

Class

BaseToolkit

Abstract base class for toolkits in LangChain. Toolkits are collections of tools that agents can use. Subclasses must implement the tools property to provide the specific tools for the toolkit.

Class

DynamicStructuredTool

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

Class

DynamicTool

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

Class

StructuredTool

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

Class

Tool

Base class for Tools that accept input as a string.

Class

ToolInputParsingException

Custom error class used to handle exceptions related to tool input parsing. It extends the built-in Error class and adds an optional output property that can hold the output that caused the except

Class

BaseTracer

Abstract base class for creating callback handlers in the LangChain framework. It provides a set of optional methods that can be overridden in derived classes to handle various events during the execu

Class

ConsoleCallbackHandler

A tracer that logs all events to the console. It extends from the BaseTracer class and overrides its methods to provide custom logging functionality.

Class

LogStreamCallbackHandler

Class that extends the BaseTracer class from the langchain.callbacks.tracers.base module. It represents a callback handler that logs the execution of runs and emits RunLog instances to a `RunLog

Class

RunLog

List of jsonpatch JSONPatchOperations, which describe how to create the run state from an empty dict. This is the minimal representation of the log, designed to be serialized as JSON and sent over the

Class

RunLogPatch

List of jsonpatch JSONPatchOperations, which describe how to create the run state from an empty dict. This is the minimal representation of the log, designed to be serialized as JSON and sent over the

Class

RunCollectorCallbackHandler

A callback handler that collects traced runs and makes it easy to fetch the traced run object from calls through any langchain object. For instance, it makes it easy to fetch the run ID and then do th

Class

LangChainTracer

Interface for the input parameters of the BaseCallbackHandler class. It allows to specify which types of events should be ignored by the callback handler.

Class

AsyncCaller

A class that can be used to make async calls with concurrency and retry logic.

This is useful for making calls to any kind of "expensive" external resource, be it because it's rate-limited, subject t

Class

AsyncGeneratorWithSetup

Class

IterableReadableStream

Class

FakeChatMessageHistory

Base class for all chat message histories. All chat message histories should extend this class.

Class

FakeChatModel

Base class for chat models. It extends the BaseLanguageModel class and provides methods for generating chat based on input messages.

Class

FakeEmbeddings

A class that provides fake embeddings by overriding the embedDocuments and embedQuery methods to return fixed values.

Class

FakeListChatMessageHistory

Base class for all list chat message histories. All list chat message histories should extend this class.

Class

FakeListChatModel

A fake Chat Model that returns a predefined list of responses. It can be used for testing purposes.

Class

FakeLLM

LLM class that provides a simpler interface to subclass than BaseLLM.

Requires only implementing a simpler _call method instead of _generate.

Class

FakeRetriever

Abstract base class for a document retrieval system, designed to process string queries and return the most relevant documents from a source.

BaseRetriever provides common properties and methods fo

Class

FakeRunnable

A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or transformed.

Class

FakeSplitIntoListParser

Parser for comma-separated values. It splits the input text by commas and trims the resulting values.

Class

FakeStreamingChatModel

Base class for chat models. It extends the BaseLanguageModel class and provides methods for generating chat based on input messages.

Class

FakeStreamingLLM

LLM class that provides a simpler interface to subclass than BaseLLM.

Requires only implementing a simpler _call method instead of _generate.

Class

FakeTool

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

Class

FakeTracer

Abstract base class for creating callback handlers in the LangChain framework. It provides a set of optional methods that can be overridden in derived classes to handle various events during the execu

Class

FakeVectorStore

Class that extends VectorStore to store vectors in memory. Provides methods for adding documents, performing similarity searches, and creating instances from texts, documents, or an existing index.

Class

SingleRunExtractor

Abstract base class for creating callback handlers in the LangChain framework. It provides a set of optional methods that can be overridden in derived classes to handle various events during the execu

Class

SyntheticEmbeddings

A class that provides synthetic embeddings by overriding the embedDocuments and embedQuery methods to generate embeddings based on the input documents. The embeddings are generated by converting each

Class

SaveableVectorStore

Abstract class extending VectorStore that defines a contract for saving and loading vector store instances.

The SaveableVectorStore class allows vector store implementations to persist their data

Class

VectorStore

Abstract class representing a vector storage system for performing similarity searches on embedded documents.

VectorStore provides methods for adding precomputed vectors or documents, removing docu

Class

VectorStoreRetriever

Class for retrieving documents from a VectorStore based on vector similarity or maximal marginal relevance (MMR).

VectorStoreRetriever extends BaseRetriever, implementing methods for adding doc

Class

RunnableWithMessageHistory

deprecated

Wraps a LCEL chain and manages history. It appends input messages and chain outputs as history, and adds the current history messages to the chain input.

Functions

Function

deserializeStoredGeneration

Function

serializeGeneration

Function

callbackHandlerPrefersChatModelStreamEvents

Function

callbackHandlerPrefersStreaming

Function

isBaseCallbackHandler

Function

dispatchCustomEvent

Dispatch a custom event.

Note: this method is only supported in non-web environments due to usage of async_hooks to infer config.

If you are using this method in the browser, please import and use f

Function

dispatchCustomEvent

Dispatch a custom event. Requires an explicit config object.

Function

ensureHandler

Function

parseCallbackConfigArg

Function

awaitAllCallbacks

Waits for all promises in the queue to resolve. If the queue is undefined, it immediately resolves a promise.

Function

consumeCallback

Consume a promise, either adding it to the queue or waiting for it to resolve

Function

getContextVariable

Get the value of a previously set context variable. Context variables are scoped to any child runnables called by the current runnable, or globally if set outside of any runnable.

Function

registerConfigureHook

Register a callback configure hook to automatically add callback handlers to all runs.

There are two ways to use this:

  1. Using a context variable:
    • Set contextVar to specify the variable name
Function

setContextVariable

Set a context variable. Context variables are scoped to any child runnables called by the current runnable, or globally if set outside of any runnable.

Function

getRetryable

Read an error's retryability mark.

Function

stampRetryable

Mark an error as safe or unsafe to retry.

Sets a non-enumerable symbol on the error itself, leaving its class and shape untouched, so it is safe to apply to a provider SDK's own error.

Function

isChatModel

Type guard function that checks if a given language model is of type BaseChatModel.

Function

isLLM

Type guard function that checks if a given language model is of type BaseLLM.

Function

_batch

Function

_deduplicateInOrder

Function

_getSourceIdAssigner

Function

_isBaseDocumentLoader

Function

index

Index data from the doc source into the vector store.

Indexing functionality uses a manager to keep track of which documents are in the vector store.

This allows us to keep track of which documents

Function

calculateMaxTokens

Function

getEmbeddingContextSize

Function

getModelContextSize

Get the context window size (max input tokens) for a given model.

Context window sizes are sourced from official model documentation:

  • OpenAI: https://platform.openai.com/docs/models
  • Anthropic: ht
Function

getModelNameForTiktoken

Function

isOpenAITool

Whether or not the input matches the OpenAI tool definition.

Function

convertChunksToEvents

Convert an async iterable of legacy ChatGenerationChunks into ChatModelStreamEvents with typed deltas.

Function

finalizeContentBlock

Finalize a content block for the finish event. For tool calls, parse the accumulated JSON args string.

Function

convertOpenAICompletionsStream

Convert an async iterable of OpenAI Chat Completions-shaped stream chunks into LangChain ChatModelStreamEvents with typed deltas.

Function

assembleStructuredOutputPipeline

Pipes an LLM through an output parser, optionally wrapping the result to include the raw LLM response alongside the parsed output.

When includeRaw is true, returns `{ raw: BaseMessage, parsed: RunO

Function

createContentParser

Creates the appropriate content-based output parser for a schema. Use this for jsonMode/jsonSchema methods where the LLM returns JSON text.

  • Zod schema -> StructuredOutputParser (Zod validation)
  • S
Function

createFunctionCallingParser

Creates the appropriate tool-calling output parser for a schema. Use this for function calling / tool use methods where the LLM returns structured tool calls.

  • Zod schema -> parser with Zod validati
Function

load

Load a LangChain object from a JSON string.

WARNING — insecure deserialization risk. This function instantiates classes and invokes constructors based on the contents of text. If text origina

Function

get_lc_unique_name

Get a unique name for the module, rather than parent class implementations. Should not be subclassed, subclass lc_name above instead.

Function

getInputValue

This function is used by memory classes to select the input value to use for the memory. If there is only one input value, it is used. If there are multiple input values, the inputKey must be specifie

Function

getOutputValue

This function is used by memory classes to select the output value to use for the memory. If there is only one output value, it is used. If there are multiple output values, the outputKey must be spec

Function

getPromptInputKey

Function used by memory classes to get the key of the prompt input, excluding any keys that are memory variables or the "stop" key. If there is not exactly one prompt input key, an error is thrown.

Function

_isMessageFieldWithRole

Function

_mergeDicts

Function

_mergeLists

Function

_mergeObj

Function

_mergeStatus

'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else it will return 'success'.

Function

coerceMessageLikeToMessage

Function

collapseToolCallChunks

Collapses an array of tool call chunks into complete tool calls.

This function groups tool call chunks by their id and/or index, then attempts to parse and validate the accumulated arguments for each

Function

convertToChunk

Function

defaultTextSplitter

The default text splitter function that splits text by newlines.

Function

filterMessages

Filter messages based on name, type or id.

Function

getBufferString

This function is used by memory classes to get a string representation of the chat message history, based on the message content and role.

Produces compact output like:

Human: What's the weather?

Exports

Interfaces

Types

Function

iife

Immediately-invoked function expression.

Function

isFunctionMessage

Function

isFunctionMessageChunk

Function

isMessage

Type guard to check if a value is a valid Message object.

Function

isOpenAIToolCallArray

Function

mapChatMessagesToStoredMessages

Transforms an array of BaseMessage instances into an array of StoredMessage instances. It does this by calling the toDict method on each BaseMessage, which returns a StoredMessage. This func

Function

mapStoredMessagesToChatMessages

Transforms an array of StoredMessage instances into an array of BaseMessage instances. It uses the mapV1MessageToStoredMessage function to ensure all messages are in the StoredMessage format,

Function

mapStoredMessageToChatMessage

Function

mergeContent

Function

mergeMessageRuns

Merge consecutive Messages of the same type.

NOTE: ToolMessages are not merged, as each has a distinct tool call id that can't be merged.

Function

mergeResponseMetadata

Function

mergeUsageMetadata

Function

trimMessages

Trim messages to be below a token count.

Function

defaultToolCallParser

Function

isDirectToolOutput

Function

defaultToolCallParser

Function

isDirectToolOutput

Function

parseJsonMarkdown

Function

parsePartialJson

Function

parseXMLMarkdown

Function

convertLangChainToolCallToOpenAI

Function

makeInvalidToolCall

Function

parseToolCall

Function

checkValidTemplate

Function

interpolateFString

Function

interpolateMustache

Function

parseFString

Function

parseMustache

Function

parseTemplate

Function

renderTemplate

Function

_coerceToRunnable

Function

ensureConfig

Ensure that a passed config is an object with all required keys present.

Function

getCallbackManagerForConfig

Function

mergeConfigs

Function

patchConfig

Helper function that patches runnable configs with updated properties.

Function

pickRunnableConfigKeys

Function

raceWithSignal

Race a promise with an abort signal. If the signal is aborted, the promise will be rejected with the error from the signal. If the promise is rejected, the signal will be aborted.

Function

castValue

Casts a value that might be string or number to actual string or number. Since LLM might return back an integer/float as a string, we need to cast it back to a number, as many vector databases can't h

Function

isBoolean

Checks if the provided value is a boolean.

Function

isFilterEmpty

Checks if a provided filter is empty. The filter can be a function, an object, a string, or undefined.

Function

isFloat

Checks if the provided value is a floating-point number.

Function

isInt

Checks if the provided value is an integer.

Function

isObject

Checks if the provided argument is an object and not an array.

Function

isString

Checks if the provided value is a string that cannot be parsed into a number.

Function

fakeModel

Creates a new FakeBuiltModel for testing.

Returns a chainable builder — queue responses, then pass the model anywhere a chat model is expected. Responses are consumed in FIFO order, one per `invoke()

Function

toContainToolCall

Function

toHaveBeenInterrupted

Function

toHaveStructuredResponse

Function

toHaveToolCallCount

Function

toHaveToolCalls

Function

toHaveToolMessages

Function

asAsyncIterable

Function

openAIReasoningTextChunks

Function

openAITextOnlyChunks

Function

openAITextOnlyChunksWithUsage

Function

openAIToolCallChunks

Function

sseResponseFromOpenAIChunks

Function

isLangChainTool

Whether or not the tool is one of StructuredTool, RunnableTool or StructuredToolParams. It returns is StructuredToolParams since that is the most minimal interface of the three, while still containi

Function

isRunnableToolLike

Confirm whether the inputted tool is an instance of RunnableToolLike.

Function

isStructuredTool

Confirm whether the inputted tool is an instance of StructuredToolInterface.

Function

isStructuredToolParams

Confirm whether or not the tool contains the necessary properties to be considered a StructuredToolParams.

Function

tool

Creates a new StructuredTool instance with the provided function, name, description, and schema.

Schema can be provided as Zod or JSON schema, and both will be validated.

Function

isBaseTracer

Function

isLogStreamHandler

Function

classifyRateLimitError

Function

parseRetryAfterMs

Function

chunkArray

Function

context

A tagged template function for creating formatted strings.

This utility provides a clean, template literal-based API for string formatting that can be used for prompts, descriptions, and other text f

Function

getEnv

Function

getEnvironmentVariable

Function

getRuntimeEnvironment

Function

isBrowser

Function

isDeno

Function

isJsDom

Function

isNode

Function

isWebWorker

Function

convertEventStreamToIterableReadableDataStream

Function

getBytes

Converts a ReadableStream into a callback pattern.

Function

getLines

Parses arbitary byte chunks into EventSource line buffers. Each line should be of the format "field: value" and ends with \r, \n, or \r\n.

Function

getMessages

Parses line buffers into EventSourceMessages.

Function

convertToOpenAIFunction

Formats a StructuredTool or RunnableToolLike instance into a format that is compatible with OpenAI function calling. If StructuredTool or RunnableToolLike has a zod schema, the output will be

Function

convertToOpenAITool

Formats a StructuredTool or RunnableToolLike instance into a format that is compatible with OpenAI tool calling. If StructuredTool or RunnableToolLike has a zod schema, the output will be conv

Function

isLangChainTool

Whether or not the tool is one of StructuredTool, RunnableTool or StructuredToolParams. It returns is StructuredToolParams since that is the most minimal interface of the three, while still containi

Function

isRunnableToolLike

Confirm whether the inputted tool is an instance of RunnableToolLike.

Function

isStructuredTool

Confirm whether the inputted tool is an instance of StructuredToolInterface.

Function

isStructuredToolParams

Confirm whether or not the tool contains the necessary properties to be considered a StructuredToolParams.

Function

resolveLangSmithGatewayConfig

Function

sha256

Function

applyPatch

Apply a full JSON Patch array on a JSON document. Returns the {newDocument, result} of the patch. It modifies the document object and patch - it gets the values by reference. If you would like to

Function

compare

Create an array of patches from the differences in two objects

Function

toJsonSchema

Converts a Standard JSON schema, Zod schema or JSON schema to a JSON schema. Results are cached by schema reference when no custom params are passed.

Function

validatesOnlyStrings

Validates if a JSON schema validates only strings. May return false negatives in some edge cases (like recursive or unresolvable refs).

Function

cosineSimilarity

This function calculates the row-wise cosine similarity between two matrices with the same number of columns.

Function

euclideanDistance

Function

innerProduct

Function

matrixFunc

Apply a row-wise function between two matrices with the same number of columns.

Function

maximalMarginalRelevance

This function implements the Maximal Marginal Relevance algorithm to select a set of embeddings that maximizes the diversity and relevance to a query embedding.

Function

normalize

Function

isCloudMetadata

Check if a hostname or IP is a known cloud metadata endpoint.

Function

isLocalhost

Check if a hostname or IP is localhost.

Function

isPrivateIp

Check if an IP address is private (RFC 1918, loopback, link-local, etc.)

Function

isSafeUrl

Check if a URL is safe to connect to (non-throwing version).

Function

isSameOrigin

Check if two URLs have the same origin (scheme, host, port). Uses semantic URL parsing to prevent SSRF bypasses via URL variations.

Function

validateSafeUrl

Validate that a URL is safe to connect to. Performs static validation checks against hostnames and direct IP addresses. Does not perform DNS resolution.

Function

isSerializableSchema

Type guard for Standard Schema V1. Returns true if the value has a ~standard.validate interface, indicating it can validate unknown values at runtime (e.g. for parsing LLM output).

Function

isStandardJsonSchema

Type guard for Standard JSON Schema V1. Returns true if the value has a ~standard.jsonSchema interface, indicating it can be converted to a JSON Schema object (e.g. for sending as a tool definition

Function

isStandardSchema

Type guard for Standard Schema V1. Returns true if the value has a ~standard.validate interface, indicating it can validate unknown values at runtime (e.g. for parsing LLM output).

Function

atee

Function

concat

Function

pipeGeneratorWithSetup

Function

asAsyncIterable

Function

openAIReasoningTextChunks

Function

openAITextOnlyChunks

Function

openAITextOnlyChunksWithUsage

Function

openAIToolCallChunks

Function

sseResponseFromOpenAIChunks

Function

encodingForModel

Function

getEncoding

Function

extendInteropZodObject

Extends a Zod object schema with additional fields, supporting both Zod v3 and v4.

Function

getInteropZodDefaultGetter

Returns a getter function for the default value of a Zod schema, if one is defined. Supports both Zod v3 and v4 schemas. If the schema has a default value, the returned function will return that value

Function

getInteropZodObjectShape

Retrieves the shape (fields) of a Zod object schema, supporting both Zod v3 and v4.

Function

getSchemaDescription

Retrieves the description from a schema definition (v3, v4, standard schema, or plain object), if available.

Function

interopParse

Parses the input using the provided Zod schema (v3 or v4) and returns the parsed value. Throws an error if parsing fails or if the schema is not a recognized Zod v3 or v4 schema.

Function

interopParseAsync

Asynchronously parses the input using the provided Zod schema (v3 or v4) and returns the parsed value. Throws an error if parsing fails or if the schema is not a recognized Zod v3 or v4 schema.

Function

interopSafeParse

Safely parses the input using the provided Zod schema (v3 or v4) and returns a result object indicating success or failure. This function is compatible with both Zod v3 and v4 schemas.

Function

interopSafeParseAsync

Asynchronously parses the input using the provided Zod schema (v3 or v4) and returns a safe parse result. This function handles both Zod v3 and v4 schemas, returning a result object indicating success

Function

interopZodObjectMakeFieldsOptional

Creates a modified version of a Zod object schema where fields matching a predicate are made optional. Supports both Zod v3 and v4 schemas and preserves the original schema version.

Function

interopZodObjectPartial

Returns a partial version of a Zod object schema, making all fields optional. Supports both Zod v3 and v4.

Function

interopZodObjectPassthrough

Returns a passthrough version of a Zod object schema, allowing unknown keys. Supports both Zod v3 and v4 object schemas. If recursive is true, applies passthrough recursively to all nested object sc

Function

interopZodObjectStrict

Returns a strict version of a Zod object schema, disallowing unknown keys. Supports both Zod v3 and v4 object schemas. If recursive is true, applies strictness recursively to all nested object schem

Function

interopZodTransformInputSchema

Returns the input type of a Zod transform schema, for both v3 and v4. If the schema is not a transform, returns undefined. If recursive is true, recursively processes nested object schemas and array

Function

isInteropZodError

Function

isInteropZodLiteral

Determines if the provided value is an InteropZodLiteral (Zod v3 or v4 literal schema).

Function

isInteropZodObject

Determines if the provided value is an InteropZodObject (Zod v3 or v4 object schema).

Function

isInteropZodSchema

Given either a Zod schema, or plain object, determine if the input is a Zod schema.

Function

isShapelessZodSchema

Determines if the provided Zod schema is "shapeless". A shapeless schema is one that does not define any object shape, such as ZodString, ZodNumber, ZodBoolean, ZodAny, etc. For ZodObject, it must hav

Function

isSimpleStringZodSchema

Determines if the provided Zod schema should be treated as a simple string schema that maps to DynamicTool. This aligns with the type-level constraint of InteropZodType<string | undefined> which only

Function

isZodArrayV4

Function

isZodLiteralV3

Function

isZodLiteralV4

Function

isZodNullableV4

Function

isZodObjectV3

Function

isZodObjectV4

Function

isZodOptionalV4

Function

isZodSchema

Backward compatible isZodSchema for Zod 3

Function

isZodSchemaV3

Function

isZodSchemaV4

Function

addLangChainErrorFields

deprecated
Function

convertToOpenAIImageBlock

deprecated
Function

convertToProviderContentBlock

deprecated

Convert from a standard data content block to a provider's proprietary data content block format.

Don't override this method. Instead, override the more specific conversion methods and use this metho

Function

isAIMessage

deprecated
Function

isAIMessageChunk

deprecated
Function

isBase64ContentBlock

deprecated
Function

isBaseMessage

deprecated
Function

isBaseMessageChunk

deprecated
Function

isChatMessage

deprecated
Function

isChatMessageChunk

deprecated
Function

isDataContentBlock

deprecated
Function

isHumanMessage

deprecated
Function

isHumanMessageChunk

deprecated
Function

isIDContentBlock

deprecated
Function

isPlainTextContentBlock

deprecated
Function

isSystemMessage

deprecated
Function

isSystemMessageChunk

deprecated
Function

isURLContentBlock

deprecated
Function

parseBase64DataUrl

deprecated

Utility function for ChatModelProviders. Parses a base64 data URL into a typed array or string.

Function

parseMimeType

deprecated

Utility function for ChatModelProviders. Parses a mime type into a type, subtype, and parameters.

Function

isToolMessage

deprecated
Function

isToolMessageChunk

deprecated
Function

isToolMessage

deprecated
Function

isToolMessageChunk

deprecated
Module

agents

Module

caches

Module

callbacks/base

Module

callbacks/dispatch

Module

callbacks/dispatch/web

Module

callbacks/manager

Module

callbacks/promises

Module

chat_history

Module

context

Module

document_loaders/base

Module

document_loaders/langsmith

Module

documents

Module

embeddings

Module

errors

Module

example_selectors

Module

index

Module

indexing

Module

language_models/base

Module

language_models/chat_models

Module

language_models/compat

Compatibility bridge: converts legacy _streamResponseChunks (ChatGenerationChunk / AIMessageChunk) output to the new ChatModelStreamEvent protocol.

Module

language_models/event

Chat model streaming event protocol.

Defines a content-block-centric event model for streaming chat model responses. Events carry LangChain ContentBlock types on lifecycle boundaries and explicit del

Module

language_models/llms

Module

language_models/openai_completions_stream

Converts OpenAI Chat Completions-shaped stream chunks into ChatModelStreamEvents.

Used by @langchain/openai and OpenAI-compatible providers (Groq, Mistral, OpenRouter, IBM watsonx, etc.) without re

Module

language_models/profile

Module

language_models/stream

Typed stream classes for chat model streaming.

Module

language_models/structured_output

Module

load

Load LangChain objects from JSON strings or objects.

**WARNING: load() deserializes data by instantiating classes and invoking constructors. Never call load() on untrusted or user-supplied input.

Module

load/serializable

Module

memory

Module

messages

Module

messages/tool

Module

output_parsers

Module

output_parsers/openai_functions

Module

output_parsers/openai_tools

Module

outputs

Module

prompt_values

Module

prompts

Module

retrievers

Module

retrievers/document_compressors

Module

runnables

Module

runnables/graph

Module

singletons

Module

stores

Module

structured_query

Module

testing

Module

tools

Module

tracers/base

Module

tracers/console

Module

tracers/log_stream

Module

tracers/run_collector

Module

tracers/tracer_langchain

Module

types/stream

Module

utils/async_caller

Module

utils/chunk_array

Module

utils/context

Module

utils/env

Module

utils/event_source_parse

Module

utils/format

Module

utils/function_calling

Module

utils/gateway

Module

utils/hash

Module

utils/json_patch

Module

utils/json_schema

Module

utils/math

Module

utils/ssrf

Module

utils/standard_schema

Module

utils/stream

Module

utils/testing

Module

utils/tiktoken

Module

utils/types

Module

utils/uuid

Module

vectorstores

Interface

BaseCallbackHandlerInput

Interface for the input parameters of the BaseCallbackHandler class. It allows to specify which types of events should be ignored by the callback handler.

Interface

CallbackHandlerMethods

Base interface for callbacks. All methods are optional. If a method is not implemented, it will be ignored. If a method is implemented, it will be called at the appropriate time. All methods are calle

Interface

CallbackHandlerPrefersChatModelStreamEvents

Interface for handlers that prefer chat model stream events instead of legacy token/chunk callbacks.

Interface

CallbackHandlerPrefersStreaming

Interface for handlers that can indicate a preference for streaming responses. When implemented, this allows the handler to signal whether it prefers to receive streaming responses from language model

Interface

NewTokenIndices

Interface for the indices of a new token produced by an LLM or Chat Model in streaming mode.

Interface

BaseCallbackConfig

Interface

CallbackManagerOptions

Interface

DocumentLoader

Interface that defines the methods for loading and splitting documents.

Interface

LangSmithLoaderFields

Interface

DocumentInput

Interface

DocumentInterface

Interface

EmbeddingsInterface

Interface

LengthBasedExampleSelectorInput

Interface for the input parameters of the LengthBasedExampleSelector class.

Interface

HashedDocumentInterface

Interface

RecordManagerInterface

Interface

BaseFunctionCallOptions

Interface

BaseLangChainParams

Interface

BaseLanguageModelCallOptions

Interface

BaseLanguageModelInterface

Base interface implemented by all runnables. Used for cross-compatibility between different versions of LangChain core.

Should not change on patch releases.

Interface

BaseLanguageModelParams

Base interface for language model parameters. A subclass of BaseLanguageModel should have a constructor that takes in a parameter that extends this interface.

Interface

BaseLanguageModelTracingCallOptions

Interface

FunctionDefinition

Interface

TokenUsage

Shared interface for token usage return type from LLM calls.

Interface

ToolDefinition

Interface

BlockDelta

Generic content block field update. Shallow-merge fields onto the active content block.

Interface

ContentBlockDeltaEvent

Emitted for each incremental update within a content block.

The delta field carries the incremental content block update. Accumulation rules:

  • text-delta → append text to the active block's te
Interface

ContentBlockFinishEvent

Emitted when a content block is complete.

Interface

ContentBlockStartEvent

Emitted when a new content block begins streaming.

Interface

DataDelta

Incremental encoded data. Append data to the active multimodal block's data field.

Interface

MessageFinishEvent

Emitted once when the model response is complete.

Interface

MessageStartEvent

Emitted once at the start of a model response.

Interface

ProviderEvent

Passthrough for native provider events that don't map to standard types.

Interface

ReasoningDelta

Incremental reasoning content. Append reasoning to the active block's reasoning field.

Interface

StreamErrorEvent

Emitted on unrecoverable stream errors.

Interface

TextDelta

Incremental text content. Append text to the active block's text field.

Interface

UsageUpdateEvent

Emitted whenever the provider reports updated usage information. Each event carries a running snapshot (not an additive delta).

Interface

BaseLLMCallOptions

Interface

BaseLLMParams

Base interface for language model parameters. A subclass of BaseLanguageModel should have a constructor that takes in a parameter that extends this interface.

Interface

ConvertOpenAICompletionsStreamOptions

Interface

OpenAICompletionsDelta

Interface

OpenAICompletionsStreamChoice

Interface

OpenAICompletionsStreamChunk

Interface

OpenAICompletionsToolCallDelta

Interface

OpenAICompletionsUsage

Interface

ModelProfile

Represents the capabilities and constraints of a language model.

This interface defines the various features and limitations that a model may have, including input/output constraints, multimodal supp

Interface

LoadOptions

Options for loading serialized LangChain objects.

Interface

BaseSerialized

Interface

SerializableInterface

Interface

SerializableLike

Interface for objects that can be serialized. This is a duck-typed interface to avoid circular imports.

Interface

SerializedConstructor

Interface

SerializedNotImplemented

Interface

SerializedSecret

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.

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

Interface

Reasoning

Reasoning output from a LLM.

Interface

Text

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.

Interface

AIMessageFields

Interface

ChatMessageFields

Interface

ContentBlock

Interface

FilterMessagesFields

Interface

FunctionCall

Interface

FunctionMessageFields

Interface

HumanMessageFields

Interface

MergeDictsOptions

Options for controlling merge behavior in _mergeDicts.

Interface

Message

Represents a message object that organizes context for an LLM.

Interface

MessageStructure

Core interface that defines the structure of messages.

Interface

MessageToolDefinition

Represents the input and output types of a tool that can be used in messages.

Interface

MessageToolSet

Represents a structured set of tools by mapping tool names to definitions that can be used in messages.

Interface

RemoveMessageFields

Interface

StandardMessageStructure

Standard message structured used to define the most basic message structure that's used throughout the library.

This is also the message structure that's used when a message structure is not provided

Interface

StoredGeneration

Interface

StoredMessage

Interface

StoredMessageData

Interface

StoredMessageV1

Interface

SystemMessageFields

Interface

TrimMessagesFields

Interface

DirectToolOutput

Marker parameter for objects that tools can return directly.

If a custom BaseTool is invoked with a ToolCall and the output of custom code is not an instance of DirectToolOutput, the output will auto

Interface

InvalidToolCall

Interface

ToolCall

Interface

ToolCallChunk

A chunk of a tool call (e.g., as part of a stream). When merging ToolCallChunks (e.g., via AIMessageChunk.add), all string attributes are concatenated. Chunks are only merged if their values of `i

Interface

ToolMessageFields

Interface

DirectToolOutput

Marker parameter for objects that tools can return directly.

If a custom BaseTool is invoked with a ToolCall and the output of custom code is not an instance of DirectToolOutput, the output will auto

Interface

InvalidToolCall

Interface

ToolCall

Interface

ToolCallChunk

A chunk of a tool call (e.g., as part of a stream). When merging ToolCallChunks (e.g., via AIMessageChunk.add), all string attributes are concatenated. Chunks are only merged if their values of `i

Interface

ToolMessageFields

Interface

AsymmetricStructuredOutputParserFields

Interface

FormatInstructionsOptions

Options for formatting instructions.

Interface

JsonMarkdownFormatInstructionsOptions

Options for formatting instructions.

Interface

XMLOutputParserFields

Interface

ChatGeneration

Output of a single generation.

Interface

ChatResult

Interface

Generation

Output of a single generation.

Interface

BasePromptValueInterface

Interface

ChatPromptValueFields

Interface for the fields of a ChatPromptValue.

Interface

ChatPromptValueInterface

Interface

ImagePromptValueFields

Interface

StringPromptValueInterface

Interface

BasePromptTemplateInput

Input common to all prompt templates.

Interface

ChatMessagePromptTemplateFields

Interface for the fields of a ChatMessagePromptTemplate.

Interface

ChatPromptTemplateInput

Interface for the input of a ChatPromptTemplate.

Interface

FewShotChatMessagePromptTemplateInput

Input common to all prompt templates.

Interface

FewShotPromptTemplateInput

Input common to all prompt templates.

Interface

ImagePromptTemplateInput

Inputs to create a ImagePromptTemplate

Interface

MessagesPlaceholderFields

Interface for the fields of a MessagePlaceholder.

Interface

MessageStringPromptTemplateFields

Interface for the fields of a MessageStringPromptTemplate.

Interface

PromptTemplateInput

Inputs to create a PromptTemplate

Interface

StructuredPromptInput

Interface for the input of a ChatPromptTemplate.

Interface

BaseRetrieverInput

Input configuration options for initializing a retriever that extends the BaseRetriever class. This interface provides base properties common to all retrievers, allowing customization of callback fu

Interface

BaseRetrieverInterface

Interface for a base retriever that defines core functionality for retrieving relevant documents from a source based on a query.

The BaseRetrieverInterface standardizes the getRelevantDocuments m

Interface

RunnableConfig

Interface

RunnableInterface

Base interface implemented by all runnables. Used for cross-compatibility between different versions of LangChain core.

Should not change on patch releases.

Interface

RunnableToolLikeArgs

Interface

RunnableWithMessageHistoryInputs

Interface

Edge

Interface

Node

Interface

AsyncLocalStorageInterface

Interface

LangChainMatchers

Custom assertion helpers for values returned by BaseChatModel.streamEvents().

These matchers consume the stream lazily through the corresponding ChatModelStream promise-backed properties.

Interface

StreamMatchers

Custom assertion helpers for values returned by BaseChatModel.streamEvents().

These matchers consume the stream lazily through the corresponding ChatModelStream promise-backed properties.

Interface

BaseDynamicToolInput

Base interface for the input parameters of the DynamicTool and DynamicStructuredTool classes.

Interface

DynamicStructuredToolInput

Interface for the input parameters of the DynamicStructuredTool class.

Interface

DynamicToolInput

Interface for the input parameters of the DynamicTool class.

Interface

StructuredToolInterface

Interface that defines the shape of a LangChain structured tool.

A structured tool is a tool that uses a schema to define the structure of the arguments that the LLM generates as part of its ToolCall

Interface

StructuredToolParams

Schema for defining tools.

Interface

ToolInterface

A special interface for tools that accept a string input, usually defined with the Tool class.

Interface

ToolParams

Parameters for the Tool classes.

Interface

ToolWrapperParams

Parameters for the tool function. Schema can be provided as Zod or JSON schema. Both schema types will be validated.

Interface

AgentRun

Interface

Run

Interface

LogStreamCallbackHandlerInput

Interface for the input parameters of the BaseCallbackHandler class. It allows to specify which types of events should be ignored by the callback handler.

Interface

LangChainTracerFields

Interface for the input parameters of the BaseCallbackHandler class. It allows to specify which types of events should be ignored by the callback handler.

Interface

Run

Interface

RunCreate2

Interface

RunUpdate

Interface

AsyncCallerCallOptions

Interface

AsyncCallerParams

Interface

EventSourceMessage

Represents a message sent in an event stream https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format

Interface

LangSmithGatewayConfig

Interface

LangSmithGatewayConfigOptions

Interface

FakeChatInput

Interface for the input parameters specific to the Fake List Chat model.

Interface

FakeListChatModelCallOptions

Represents the call options for a base chat model.

Interface

FakeStreamingChatModelCallOptions

Interface specific to the Fake Streaming Chat model.

Interface

FakeStreamingChatModelFields

Interface for the Constructor-field specific to the Fake Streaming Chat model (all optional because we fill in defaults).

Interface

FakeToolParams

Parameters for the Tool classes.

Interface

FakeVectorStoreArgs

Interface for the arguments that can be passed to the FakeVectorStore constructor. It includes an optional similarity function.

Interface

ToolSpec

Minimal shape actually needed by bindTools

Interface

StreamMatchers

Custom assertion helpers for values returned by BaseChatModel.streamEvents().

These matchers consume the stream lazily through the corresponding ChatModelStream promise-backed properties.

Interface

InteropZodError

Interface

InteropZodIssue

Interface

ZodV3EffectsLike

Interface

ZodV3Like

Interface

ZodV3ObjectLike

Interface

ZodV3TypeDef

Interface

ZodV4ArrayLike

Interface

ZodV4Internals

Interface

ZodV4Like

Interface

ZodV4NullableLike

Interface

ZodV4ObjectLike

Interface

ZodV4OptionalLike

Interface

ZodV4PipeLike

Interface

VectorStoreInterface

Interface defining the structure and operations of a vector store, which facilitates the storage, retrieval, and similarity search of document vectors.

VectorStoreInterface provides methods for add

Interface

VectorStoreRetrieverInterface

Interface for a retriever that uses a vector store to store and retrieve document embeddings. This retriever interface allows for adding documents to the underlying vector store and conducting retriev

Interface

Base64ContentBlock

deprecated
Interface

BaseDataContentBlock

deprecated
Interface

IDContentBlock

deprecated
Interface

PlainTextContentBlock

deprecated
Interface

URLContentBlock

deprecated
Interface

StandardContentBlockConverter

deprecated

Utility interface for converting between standard and provider-specific data content blocks, to be used when implementing chat model providers.

Meant to be used with convertToProviderContentBlock and

Type

AgentAction

Type

AgentFinish

Type

AgentStep

Type

HandleLLMNewTokenCallbackFields

Type

Callbacks

Type

ConfigureHook

Type

EmbeddingsParams

The parameters required to initialize an instance of the Embeddings class.

Type

BrandedClass

The return type of Namespace.brand(): the original base class intersected with a polymorphic isInstance type guard.

Type

LangChainErrorCodes

Type

BaseGetPromptAsyncOptions

Type

SemanticSimilarityExampleSelectorInput

Interface for the input data of the SemanticSimilarityExampleSelector class.

Type

CleanupMode

Type

IndexOptions

Type

ListKeyOptions

Type

UpdateOptions

Type

BaseLanguageModelInput

Type

FunctionCallOption

Type

LanguageModelLike

Type

LanguageModelOutput

Type

SerializedLLM

Type

StructuredOutputMethodOptions

Type

StructuredOutputType

Type

BaseChatModelCallOptions

Represents the call options for a base chat model.

Type

BaseChatModelParams

Represents the parameters for a base chat model.

Type

BindToolsInput

Type

LangSmithParams

Type

SerializedChatModel

Represents a serialized chat model.

Type

SerializedLLM

Represents a serialized large language model.

Type

ToolChoice

Type

ChatModelStreamEvent

Union of all chat model stream event types.

Type

ContentBlockDelta

Union of all content block delta types.

Type

FinishReason

Finish reason for a model response.

  • "stop": Natural end of generation.
  • "length": Hit max token limit.
  • "tool_use": Model is requesting tool execution.
  • "content_filter": Content was fil
Type

SerializedLLM

Type

OpenAICompletionsFinishReason

Type

Serialized

Type

InputValues

Type alias for a record where the keys are strings and the values can be any type. This is used to represent the input values for a Chain.

Type

MemoryVariables

Type alias for a record where the keys are strings and the values can be any type. This is used to represent the memory variables in a Chain.

Type

OutputValues

Type alias for a record where the keys are strings and the values can be any type. This is used to represent the output values from a Chain.

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

Multimodal

Type

Standard

Type

Tools

Type

Data

Type

$Expand

Type

$InferMessageContent

Infers the content type for a specific message type from a message structure.

This utility type determines the appropriate content type based on the message structure's output version and the specifi

Type

$InferMessageContentBlocks

Infers the content blocks for a specific message type in a message structure.

This utility type extracts the content block type that corresponds to a given message type from the message structure's c

Type

$InferMessageProperties

Infers the properties for a specific message type from a message structure.

This utility type extracts the properties object that corresponds to a given message type from the message structure's prop

Type

$InferMessageProperty

Infers the type of a specific property for a message type from a message structure.

This utility type extracts the type of a single property by name from the properties object that corresponds to a g

Type

$InferResponseMetadata

Infers the response metadata type for a specific message type from a message structure.

This utility type extracts the response_metadata property type for a given message type.

Type

$InferToolCalls

Helper type to infer a union of ToolCall types from the tools defined in a MessageStructure. This is used to type the tool_calls array in AIMessage based on the available tools.

Type

$InferToolOutputs

Helper type to infer a union of tool output types from the tools defined in a MessageStructure. This is used to type the content of ToolMessage based on the available tool outputs.

Type

$MergeContentDefinition

Merges two content definition objects from message structures.

This utility type combines content definitions from two message structures, handling the merging of content block types for each message

Type

$MergeDiscriminatedUnion

Merges two discriminated unions A and B based on a discriminator key (defaults to "type"). For each possible value of the discriminator across both unions:

  • If B has a member with that discriminator
Type

$MergeMessageStructure

Merges two message structures A and B into a combined structure. This is a type utility that handles merging of tools, content blocks, and properties from two message structures. The resulting type is

Type

$MergeObjects

Recursively merges two object types T and U, with U taking precedence over T.

This utility type performs a deep merge of two object types:

  • For keys that exist in both T and U:
    • If both values ar
Type

$MergeOutputVersion

Merges two output version types from message structures.

This utility type determines the resulting output version when combining two message structures. The merge logic follows these rules:

  • If bo
Type

$MessageToolCallBlock

Represents a tool call block within a message structure by mapping tool names to their corresponding tool call formats, including the input arguments and an optional identifier.

Type

$NormalizedMessageStructure

Takes a message structure type T and normalizes it by merging it with the standard message structure. If T is already a standard message structure, returns T unchanged.

This ensures that any custom m

Type

AIMessageChunkFields

Type

BaseMessageFields

Type

BaseMessageLike

Type

Constructor

Type

Data

Type

InputTokenDetails

Breakdown of input token counts.

Does not need to sum to full input token count. Does not need to have all keys.

Type

MessageChunkUnion

Type

MessageContent

Type

MessageFieldWithRole

Type

MessageOutputVersion

Represents the output version format for message content.

This type determines how the content field is structured in a message:

  • "v0": Content is represented as a simple string or array of content
Type

MessageType

Represents the possible types of messages in the system. Includes standard message types ("ai", "human", "tool", "system") and allows for custom string types that are non-null.

Type

MessageTypeOrClass

Type

MessageUnion

Type

ModalitiesTokenDetails

Type

OutputTokenDetails

Breakdown of output token counts.

Does not need to sum to full output token count. Does not need to have all keys.

Type

PartialContentBlock

Type

RawInputToolCallChunk

Provider streaming marker for raw (non-JSON) tool input. Not part of the public ToolCallChunk type; integrations may attach isCustomTool at runtime and pass chunks typed as this alias.

Type

ResponseMetadata

Type

UsageMetadata

Usage metadata for a message, such as token counts.

Type

BaseCumulativeTransformOutputParserInput

Type

Content

Type

JsonMarkdownStructuredOutputParserInput

Type

XMLResult

Type

FunctionParameters

Represents optional parameters for a function in a JSON Schema.

Type

JsonOutputKeyToolsParserParams

Type

JsonOutputKeyToolsParserParamsInterop

Type

JsonOutputKeyToolsParserParamsSerializable

Type

JsonOutputToolsParserParams

Type

ParsedToolCall

Type

ChatGenerationChunkFields

Type

GenerationChunkFields

Type

LLMResult

Contains all relevant information returned by an LLM.

Type

ImageContent

Type

BaseMessagePromptTemplateLike

Type

Example

Type

ExtractedFStringParams

Type

ParamsFromFString

Type

ParsedFStringNode

Alias for ParsedTemplateNode since it is the same for both f-string and mustache templates.

Type

ParsedTemplateNode

Type that represents a node in a parsed format string. It can be either a literal text or a variable name.

Type

PipelinePromptParams

Type that includes the name of the prompt and the prompt itself.

Type

PipelinePromptTemplateInput

Type that extends the BasePromptTemplateInput type, excluding the inputVariables property. It includes an array of pipelinePrompts and a finalPrompt.

Type

SerializedBasePromptTemplate

Represents a serialized version of a base prompt template. This type can be either a SerializedFewShotTemplate or a SerializedPromptTemplate.

Type

SerializedFewShotTemplate

Represents a serialized version of a few-shot template. This type includes an _type field set to 'few_shot', input_variables which are an array of strings representing the variables to be used in

Type

SerializedPromptTemplate

Represents a serialized version of a prompt template. This type is used to create dynamic prompts for language models. It contains an optional _type field which, if present, is set to 'prompt'. It a

Type

TemplateFormat

Type that specifies the format of a template.

Type

TypedPromptInputValues

Type

Branch

Type for a branch in the RunnableBranch. It consists of a condition runnable and a branch runnable. The condition runnable is used to determine whether the branch should be executed, and the branch ru

Type

BranchLike

Type

RouterInput

Type

RunnableBatchOptions

Type

RunnableBindingArgs

Type

RunnableFunc

Type

RunnableIOSchema

Type

RunnableLike

Type

RunnableRetryFailedAttemptHandler

Type

AND

Represents logical AND operator.

Type

Comparator

Represents a comparison operator which can be EQ, NE, LT, GT, LTE, or GTE.

Type

EQ

Represents equality comparison operator.

Type

FunctionFilter

A type alias for a function that takes a Document as an argument and returns a boolean. This function is used as a filter for documents.

Type

GT

Represents greater than comparison operator.

Type

GTE

Represents greater than or equal to comparison operator.

Type

LT

Represents less than comparison operator.

Type

LTE

Represents less than or equal to comparison operator.

Type

NE

Represents inequality comparison operator.

Type

NOT

Represents logical NOT operator.

Type

Operator

Represents a logical operator which can be AND, OR, or NOT.

Type

OR

Represents logical OR operator.

Type

TranslatorOpts

Options object for the BasicTranslator class. Specifies the allowed operators and comparators.

Type

VisitorComparisonResult

Represents the result of visiting a comparison expression.

Type

VisitorOperationResult

Represents the result of visiting an operation expression.

Type

VisitorResult

Represents the result of visiting an operation or comparison expression.

Type

VisitorStructuredQueryResult

Represents the result of visiting a structured query expression.

Type

StreamOutputExpectation

Type

StreamToolCallExpectation

Type

StreamUsageExpectation

Type

ClientTool

Type

ContentAndArtifact

Type

ResponseFormat

Type

ServerTool

Type

StructuredToolCallInput

Defines the type that will be passed into a tool handler function as a result of a tool call.

Type

ToolReturnType

Conditional type that determines the return type of the StructuredTool.invoke method.

  • If the input is a ToolCall, it returns a ToolMessage
  • If the config is a runnable config and contains a toolCal
Type

ToolRunnableConfig

Type

ToolRuntime

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

Type

ToolSchemaBase

Base type that establishes the types of input schemas that can be used for LangChain tool definitions.

Type

RunType

Type

LogEntry

Interface that represents the structure of a log entry in the LogStreamCallbackHandler.

Type

RunState

Type

SchemaFormat

Type

StreamEvent

A streaming event.

Schema of a streaming event which is produced from the streamEvents method.

Type

StreamEventData

Data associated with a StreamEvent.

Type

IterableReadableStreamInterface

Type

StreamEvent

A streaming event.

Schema of a streaming event which is produced from the streamEvents method.

Type

StreamEventData

Data associated with a StreamEvent.

Type

FailedAttemptHandler

Type

RuntimeEnvironment

Type

Converter

A function that converts data from one format to another.

This is commonly used for transforming message content blocks between different provider-specific formats and standardized internal represent

Type

ConverterPair

A pair of bidirectional conversion functions for transforming data between two formats.

This type is used throughout the message system to enable conversion between provider-specific message formats

Type

HashKeyEncoder

A function type for encoding hash keys. Accepts any number of string arguments (such as prompt and LLM key) and returns a single string to be used as the hash key.

Type

Operation

Type

JsonSchema7ArrayType

Type

JsonSchema7NullableType

Type

JsonSchema7NumberType

Type

JsonSchema7ObjectType

Type

JsonSchema7StringType

Type

JsonSchema7Type

Type

ToJSONSchemaParams

Type

JSONSchema

Type

SerializableSchema

A schema that supports both runtime validation and JSON Schema generation. Any schema passed to withStructuredOutput must satisfy both interfaces.

Type

IterableReadableStreamInterface

Type

StreamOutputExpectation

Type

StreamToolCallExpectation

Type

StreamUsageExpectation

Type

ChainValues

Type

InferInteropZodInput

Type

InferInteropZodOutput

Type

InputValues

Type

InteropZodDefault

Type

InteropZodLiteral

Type

InteropZodObject

Type

InteropZodObjectShape

Type

InteropZodOptional

Type

InteropZodType

Type

Mutable

Type

PartialValues

Type

StringWithAutocomplete

Represents a string value with autocompleted, but not required, suggestions.

Type

ZodDefaultV3

Type

ZodDefaultV4

Type

ZodNullableV4

Type

ZodObjectMain

Type

ZodObjectV3

Type

ZodObjectV4

Type

ZodObjectV4Classic

Type

ZodOptionalV3

Type

ZodOptionalV4

Type

ZodStringV3

Type

ZodStringV4

Type

NonSharedArrayBuffer

Type

UUIDTypes

Type

Version1Options

Type

Version4Options

Type

Version6Options

Type

Version7Options

Type

MaxMarginalRelevanceSearchOptions

Options for configuring a maximal marginal relevance (MMR) search.

MMR search optimizes for both similarity to the query and diversity among the results, balancing the retrieval of relevant documents

Type

VectorStoreRetrieverInput

Input configuration options for creating a VectorStoreRetriever instance.

This type combines properties from BaseRetrieverInput with specific settings for the VectorStoreRetriever, including op

Type

VectorStoreRetrieverMMRSearchKwargs

Options for configuring a maximal marginal relevance (MMR) search when using the VectorStoreRetriever.

These parameters control how the MMR algorithm balances relevance to the query and diversity a

Type

StructuredOutputMethodParams

deprecated
Type

DataContentBlock

deprecated
Type

DataContentBlockType

deprecated
Type

StandardAudioBlock

deprecated
Type

StandardFileBlock

deprecated
Type

StandardImageBlock

deprecated
Type

StandardTextBlock

deprecated
Type

ImageDetail

deprecated
Type

MessageContentComplex

deprecated
Type

MessageContentImageUrl

deprecated
Type

MessageContentText

deprecated
Type

OpenAIToolCall

deprecated
Type

ProviderFormatTypes

deprecated

A bag of provider-specific content block types.

Allows implementations of StandardContentBlockConverter and related to be defined only in terms of the types they support. Also allows for forward comp