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

LangChain Assistant

Ask a question to get started

Enter to send•Shift+Enter new line

Menu

LangChain
UniversalHubNodeLoadSerializableEncoder BackedFile SystemIn Memory
LangChain Core
AgentsCachesBaseDispatchWebManagerPromisesChat HistoryContextBaseLangsmithDocumentsEmbeddingsErrorsExample SelectorsIndexingBaseChat ModelsLlmsProfileLoadSerializableMemoryMessagesToolOutput ParsersOpenai FunctionsOpenai ToolsOutputsPrompt ValuesPromptsRetrieversDocument CompressorsRunnablesGraphSingletonsStoresStructured QueryToolsBaseConsoleLog StreamRun CollectorTracer LangchainStreamAsync CallerChunk ArrayContextEnvEvent Source ParseFormatFunction CallingHashJson PatchJson SchemaMathSsrfStreamTestingTiktokenTypesVectorstores
Text Splitters
MCP Adapters
Language
Theme
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

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

Class

BaseListChatMessageHistory

Base class for all list chat message histories. All list chat message

Class

InMemoryChatMessageHistory

Class for storing chat message history in-memory. It extends the

Class

BaseDocumentLoader

Abstract class that provides a default implementation for the

Class

LangSmithLoader

Document loader integration with LangSmith.

Class

BaseDocumentTransformer

Abstract base class for document transformation systems.

Class

Document

Interface for interacting with a document.

Class

MappingDocumentTransformer

Class for document transformers that return exactly one transformed document

Class

Embeddings

An abstract class that provides methods for embedding documents and

Class

ContextOverflowError

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

Class

LangChainError

Base error class for all LangChain errors.

Class

ModelAbortError

Error class representing an aborted model operation in LangChain.

Class

BaseExampleSelector

Base class for example selectors.

Class

BasePromptSelector

Abstract class that defines the interface for selecting a prompt for a

Class

ConditionalPromptSelector

Concrete implementation of BasePromptSelector that selects a prompt

Class

LengthBasedExampleSelector

A specialized example selector that selects examples based on their

Class

SemanticSimilarityExampleSelector

Class that selects examples based on semantic similarity. It extends

Class

_HashedDocument

HashedDocument is a Document with hashes calculated.

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

Class

SimpleChatModel

An abstract class that extends BaseChatModel and provides a simple

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.

Class

Serializable

Class

BaseMemory

Abstract base class for memory in LangChain's Chains. Memory refers to

Class

AIMessage

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

Class

AIMessageChunk

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

Class

BaseMessage

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

Class

BaseMessageChunk

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

Class

ChatMessage

Represents a chat message in a conversation.

Class

ChatMessageChunk

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

Class

FunctionMessage

Represents a function message in a conversation.

Class

FunctionMessageChunk

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

Class

HumanMessage

Represents a human message in a conversation.

Class

HumanMessageChunk

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

Class

RemoveMessage

Message responsible for deleting other messages.

Class

SystemMessage

Represents a system message in a conversation.

Class

SystemMessageChunk

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

Class

ToolMessage

Represents a tool message in a conversation.

Class

ToolMessageChunk

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

Class

ToolMessage

Represents a tool message in a conversation.

Class

ToolMessageChunk

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

Class

AsymmetricStructuredOutputParser

A type of StructuredOutputParser that handles asymmetric input and

Class

BaseCumulativeTransformOutputParser

A base class for output parsers that can handle streaming input. It

Class

BaseLLMOutputParser

Abstract base class for parsing the output of a Large Language Model

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

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

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.

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

Class

JsonKeyOutputFunctionsParser

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

Class

JsonOutputFunctionsParser

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

Class

OutputFunctionsParser

Class for parsing the output of an LLM. Can be configured to return

Class

JsonOutputKeyToolsParser

Class for parsing the output of a tool-calling LLM into a JSON object if you are

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

Class

ImagePromptValue

Class that represents an image prompt value. It extends the

Class

StringPromptValue

Represents a prompt value as a string. It extends the BasePromptValue

Class

AIMessagePromptTemplate

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

Class

BaseChatPromptTemplate

Abstract class that serves as a base for creating chat prompt

Class

BaseMessagePromptTemplate

Abstract class that serves as a base for creating message prompt

Class

BaseMessageStringPromptTemplate

Abstract class that serves as a base for creating message string prompt

Class

BasePromptTemplate

Base class for prompt templates. Exposes a format method that returns a

Class

BaseStringPromptTemplate

Base class for string prompt templates. It extends the

Class

ChatMessagePromptTemplate

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

Class

ChatPromptTemplate

Class that represents a chat prompt. It extends the

Class

DictPromptTemplate

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

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

Class

ImagePromptTemplate

An image prompt template for a multimodal model.

Class

MessagesPlaceholder

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

Class

PipelinePromptTemplate

Class that handles a sequence of prompts, each of which may require

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

Class

BaseRetriever

Abstract base class for a document retrieval system, designed to

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'].

Class

Runnable

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

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

Class

RunnableEach

A runnable that delegates calls to another runnable

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,

Class

RunnableParallel

A runnable that runs a mapping of runnables in parallel,

Class

RunnablePassthrough

A runnable to passthrough inputs unchanged or with additional keys.

Class

RunnablePick

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

Class

RunnableRetry

Base class for runnables that can be retried a

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.

Class

RunnableWithMessageHistory

Wraps a LCEL chain and manages history. It appends input messages

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

Class

BaseTranslator

Abstract class that provides a blueprint for creating specific

Class

BasicTranslator

Class that extends the BaseTranslator class and provides concrete

Class

Comparison

Class representing a comparison filter directive. It extends the

Class

Expression

Abstract class representing an expression. Subclasses must implement

Class

FilterDirective

Abstract class representing a filter directive. It extends the

Class

FunctionalTranslator

A class that extends BaseTranslator to translate structured queries

Class

Operation

Class representing an operation filter directive. It extends the

Class

StructuredQuery

Class representing a structured query expression. It extends the

Class

Visitor

Abstract class for visiting expressions. Subclasses must implement

Class

BaseToolkit

Abstract base class for toolkits in LangChain. Toolkits are collections

Class

DynamicStructuredTool

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

Class

DynamicTool

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

Class

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.

Class

BaseTracer

Abstract base class for creating callback handlers in the LangChain

Class

ConsoleCallbackHandler

A tracer that logs all events to the console. It extends from the

Class

LogStreamCallbackHandler

Class that extends the BaseTracer class from the

Class

RunLog

List of jsonpatch JSONPatchOperations, which describe how to create the run state

Class

RunLogPatch

List of jsonpatch JSONPatchOperations, which describe how to create the run state

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.

Class

LangChainTracer

Interface for the input parameters of the BaseCallbackHandler class. It

Class

AsyncCaller

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

Class

AsyncGeneratorWithSetup

Class

IterableReadableStream

Class

FakeChatMessageHistory

Base class for all chat message histories. All chat message histories

Class

FakeChatModel

Base class for chat models. It extends the BaseLanguageModel class and

Class

FakeEmbeddings

A class that provides fake embeddings by overriding the embedDocuments

Class

FakeListChatMessageHistory

Base class for all list chat message histories. All list chat message

Class

FakeListChatModel

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

Class

FakeLLM

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

Class

FakeRetriever

Abstract base class for a document retrieval system, designed to

Class

FakeRunnable

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

Class

FakeSplitIntoListParser

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

Class

FakeStreamingChatModel

Base class for chat models. It extends the BaseLanguageModel class and

Class

FakeStreamingLLM

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

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

Class

FakeVectorStore

Class that extends VectorStore to store vectors in memory. Provides

Class

SingleRunExtractor

Abstract base class for creating callback handlers in the LangChain

Class

SyntheticEmbeddings

A class that provides synthetic embeddings by overriding the

Class

SaveableVectorStore

Abstract class extending VectorStore that defines a contract for saving

Class

VectorStore

Abstract class representing a vector storage system for performing

Class

VectorStoreRetriever

Class for retrieving documents from a VectorStore based on vector similarity

Functions

Function

deserializeStoredGeneration

Function

serializeGeneration

Function

callbackHandlerPrefersStreaming

Function

isBaseCallbackHandler

Function

dispatchCustomEvent

Dispatch a custom event.

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

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

Function

registerConfigureHook

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

Function

setContextVariable

Set a context variable. Context variables are scoped to any

Function

isChatModel

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

Function

isLLM

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

Function

_batch

Function

_deduplicateInOrder

Function

_getSourceIdAssigner

Function

_isBaseDocumentLoader

Function

index

Index data from the doc source into the vector store.

Function

calculateMaxTokens

Function

getEmbeddingContextSize

Function

getModelContextSize

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

Function

getModelNameForTiktoken

Function

isOpenAITool

Whether or not the input matches the OpenAI tool definition.

Function

load

Load a LangChain object from a JSON string.

Function

get_lc_unique_name

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

Function

getInputValue

This function is used by memory classes to select the input value

Function

getOutputValue

This function is used by memory classes to select the output value

Function

getPromptInputKey

Function used by memory classes to get the key of the prompt input,

Function

_isMessageFieldWithRole

Function

_mergeDicts

Function

_mergeLists

Exports

Interfaces

Types

Function

_mergeObj

Function

_mergeStatus

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

Function

coerceMessageLikeToMessage

Function

collapseToolCallChunks

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

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

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

Function

mapStoredMessagesToChatMessages

Transforms an array of StoredMessage instances into an array of

Function

mapStoredMessageToChatMessage

Function

mergeContent

Function

mergeMessageRuns

Merge consecutive Messages of the same type.

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

Function

castValue

Casts a value that might be string or number to actual string or number.

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

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

Function

isLangChainTool

Whether or not the tool is one of StructuredTool, RunnableTool or StructuredToolParams.

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.

Function

isBaseTracer

Function

isLogStreamHandler

Function

chunkArray

Function

context

A tagged template function for creating formatted strings.

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.

Function

getMessages

Parses line buffers into EventSourceMessages.

Function

convertToOpenAIFunction

Formats a StructuredTool or RunnableToolLike instance into a format

Function

convertToOpenAITool

Formats a StructuredTool or RunnableToolLike instance into a

Function

isLangChainTool

Whether or not the tool is one of StructuredTool, RunnableTool or StructuredToolParams.

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

sha256

Function

applyPatch

Apply a full JSON Patch array on a JSON document.

Function

compare

Create an array of patches from the differences in two objects

Function

toJsonSchema

Converts a Zod schema or JSON schema to a JSON schema.

Function

validatesOnlyStrings

Validates if a JSON schema validates only strings. May return false negatives in some edge cases

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

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

Function

validateSafeUrl

Validate that a URL is safe to connect to.

Function

atee

Function

concat

Function

pipeGeneratorWithSetup

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.

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, or plain object), if available.

Function

interopParse

Parses the input using the provided Zod schema (v3 or v4) and returns the parsed value.

Function

interopParseAsync

Asynchronously parses the input using the provided Zod schema (v3 or v4) and returns the parsed value.

Function

interopSafeParse

Safely parses the input using the provided Zod schema (v3 or v4) and returns a result object

Function

interopSafeParseAsync

Asynchronously parses the input using the provided Zod schema (v3 or v4) and returns a safe parse result.

Function

interopZodObjectMakeFieldsOptional

Creates a modified version of a Zod object schema where fields matching a predicate are made optional.

Function

interopZodObjectPartial

Returns a partial version of a Zod object schema, making all fields optional.

Function

interopZodObjectPassthrough

Returns a passthrough version of a Zod object schema, allowing unknown keys.

Function

interopZodObjectStrict

Returns a strict version of a Zod object schema, disallowing unknown keys.

Function

interopZodTransformInputSchema

Returns the input type of a Zod transform schema, for both v3 and v4.

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

Function

isSimpleStringZodSchema

Determines if the provided Zod schema should be treated as a simple string schema

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.

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/llms

Module

language_models/profile

Module

load

Load LangChain objects from JSON strings or objects.

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

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/hash

Module

utils/json_patch

Module

utils/json_schema

Module

utils/math

Module

utils/ssrf

Module

utils/stream

Module

utils/testing

Module

utils/tiktoken

Module

utils/types

Module

vectorstores

Interface

BaseCallbackHandlerInput

Interface for the input parameters of the BaseCallbackHandler class. It

Interface

CallbackHandlerMethods

Base interface for callbacks. All methods are optional. If a method is not

Interface

CallbackHandlerPrefersStreaming

Interface for handlers that can indicate a preference for streaming responses.

Interface

NewTokenIndices

Interface for the indices of a new token produced by an LLM or Chat

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

Interface

HashedDocumentInterface

Interface

RecordManagerInterface

Interface

BaseFunctionCallOptions

Interface

BaseLangChainParams

Interface

BaseLanguageModelCallOptions

Interface

BaseLanguageModelInterface

Base interface implemented by all runnables.

Interface

BaseLanguageModelParams

Base interface for language model parameters.

Interface

BaseLanguageModelTracingCallOptions

Interface

FunctionDefinition

Interface

TokenUsage

Shared interface for token usage

Interface

ToolDefinition

Interface

BaseLLMCallOptions

Interface

BaseLLMParams

Base interface for language model parameters.

Interface

ModelProfile

Represents the capabilities and constraints of a language model.

Interface

LoadOptions

Options for loading serialized LangChain objects.

Interface

BaseSerialized

Interface

SerializableInterface

Interface

SerializableLike

Interface for objects that can be serialized.

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.

Interface

Reasoning

Reasoning output from a LLM.

Interface

Text

Text output from a LLM.

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

Interface

RemoveMessageFields

Interface

StandardMessageStructure

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

Interface

StoredGeneration

Interface

StoredMessage

Interface

StoredMessageData

Interface

StoredMessageV1

Interface

SystemMessageFields

Interface

TrimMessagesFields

Interface

DirectToolOutput

Marker parameter for objects that tools can return directly.

Interface

InvalidToolCall

Interface

ToolCall

Interface

ToolCallChunk

A chunk of a tool call (e.g., as part of a stream).

Interface

ToolMessageFields

Interface

DirectToolOutput

Marker parameter for objects that tools can return directly.

Interface

InvalidToolCall

Interface

ToolCall

Interface

ToolCallChunk

A chunk of a tool call (e.g., as part of a stream).

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

Interface

BaseRetrieverInterface

Interface for a base retriever that defines core functionality for

Interface

RunnableConfig

Interface

RunnableInterface

Base interface implemented by all runnables.

Interface

RunnableToolLikeArgs

Interface

RunnableWithMessageHistoryInputs

Interface

Edge

Interface

Node

Interface

AsyncLocalStorageInterface

Interface

BaseDynamicToolInput

Base interface for the input parameters of the DynamicTool and

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.

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

AgentRun

Interface

Run

Interface

LogStreamCallbackHandlerInput

Interface for the input parameters of the BaseCallbackHandler class. It

Interface

LangChainTracerFields

Interface for the input parameters of the BaseCallbackHandler class. It

Interface

Run

Interface

RunCreate2

Interface

RunUpdate

Interface

AsyncCallerCallOptions

Interface

AsyncCallerParams

Interface

EventSourceMessage

Represents a message sent in an event stream

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

Interface

ToolSpec

Minimal shape actually needed by bindTools

Interface

VectorStoreInterface

Interface defining the structure and operations of a vector store, which

Interface

VectorStoreRetrieverInterface

Interface for a retriever that uses a vector store to store and retrieve

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

Type

AgentAction

Type

AgentFinish

Type

AgentStep

Type

HandleLLMNewTokenCallbackFields

Type

Callbacks

Type

ConfigureHook

Type

EmbeddingsParams

The parameters required to initialize an instance of the Embeddings

Type

LangChainErrorCodes

Type

BaseGetPromptAsyncOptions

Type

SemanticSimilarityExampleSelectorInput

Interface for the input data of the SemanticSimilarityExampleSelector

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

SerializedLLM

Type

Serialized

Type

InputValues

Type alias for a record where the keys are strings and the values can

Type

MemoryVariables

Type alias for a record where the keys are strings and the values can

Type

OutputValues

Type alias for a record where the keys are strings and the values can

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.

Type

$InferMessageContentBlocks

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

Type

$InferMessageProperties

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

Type

$InferMessageProperty

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

Type

$InferResponseMetadata

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

Type

$InferToolCalls

Helper type to infer a union of ToolCall types from the tools defined in a MessageStructure.

Type

$InferToolOutputs

Helper type to infer a union of tool output types from the tools defined in a MessageStructure.

Type

$MergeContentDefinition

Merges two content definition objects from message structures.

Type

$MergeDiscriminatedUnion

Merges two discriminated unions A and B based on a discriminator key (defaults to "type").

Type

$MergeMessageStructure

Merges two message structures A and B into a combined structure.

Type

$MergeObjects

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

Type

$MergeOutputVersion

Merges two output version types from message structures.

Type

$MessageToolCallBlock

Represents a tool call block within a message structure by mapping tool names to their

Type

$NormalizedMessageStructure

Takes a message structure type T and normalizes it by merging it with the standard message structure.

Type

AIMessageChunkFields

Type

BaseMessageFields

Type

BaseMessageLike

Type

Constructor

Type

Data

Type

InputTokenDetails

Breakdown of input token counts.

Type

MessageChunkUnion

Type

MessageContent

Type

MessageFieldWithRole

Type

MessageOutputVersion

Represents the output version format for message content.

Type

MessageType

Represents the possible types of messages in the system.

Type

MessageTypeOrClass

Type

MessageUnion

Type

ModalitiesTokenDetails

Type

OutputTokenDetails

Breakdown of output token counts.

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

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

Type

ParsedTemplateNode

Type that represents a node in a parsed format string. It can be either

Type

PipelinePromptParams

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

Type

PipelinePromptTemplateInput

Type that extends the BasePromptTemplateInput type, excluding the

Type

SerializedBasePromptTemplate

Represents a serialized version of a base prompt template. This type

Type

SerializedFewShotTemplate

Represents a serialized version of a few-shot template. This type

Type

SerializedPromptTemplate

Represents a serialized version of a prompt template. This type is used

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

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

Type

EQ

Represents equality comparison operator.

Type

FunctionFilter

A type alias for a function that takes a Document as an argument and

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

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

Type

VisitorStructuredQueryResult

Represents the result of visiting a structured query expression.

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.

Type

ToolRunnableConfig

Type

ToolRuntime

Runtime context automatically injected into tools.

Type

ToolSchemaBase

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

Type

RunType

Type

LogEntry

Interface that represents the structure of a log entry in the

Type

RunState

Type

SchemaFormat

Type

StreamEvent

A streaming event.

Type

StreamEventData

Data associated with a StreamEvent.

Type

IterableReadableStreamInterface

Type

StreamEvent

A streaming event.

Type

StreamEventData

Data associated with a StreamEvent.

Type

FailedAttemptHandler

Type

RuntimeEnvironment

Type

Converter

A function that converts data from one format to another.

Type

ConverterPair

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

Type

HashKeyEncoder

A function type for encoding hash keys.

Type

Operation

Type

JsonSchema7ArrayType

Type

JsonSchema7NullableType

Type

JsonSchema7NumberType

Type

JsonSchema7ObjectType

Type

JsonSchema7StringType

Type

JsonSchema7Type

Type

ToJSONSchemaParams

Type

JSONSchema

Type

IterableReadableStreamInterface

Type

ChainValues

Type

InferInteropZodInput

Type

InferInteropZodOutput

Type

InputValues

Type

InteropZodDefault

Type

InteropZodIssue

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

MaxMarginalRelevanceSearchOptions

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

Type

VectorStoreRetrieverInput

Input configuration options for creating a VectorStoreRetriever instance.

Type

VectorStoreRetrieverMMRSearchKwargs

Options for configuring a maximal marginal relevance (MMR) search

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.