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
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
  • 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
  • Hash
  • Json Patch
  • Json Schema
  • Math
  • Ssrf
  • Standard Schema
  • 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
BrowserUniversalHubNodeLoadSerializableEncoder BackedFile SystemIn Memory
LangChain Core
AgentsCachesBaseDispatchWebManagerPromisesChat HistoryContextBaseLangsmithDocumentsEmbeddingsErrorsExample SelectorsIndexingBaseChat ModelsLlmsProfileStructured OutputLoadSerializableMemoryMessagesToolOutput ParsersOpenai FunctionsOpenai ToolsOutputsPrompt ValuesPromptsRetrieversDocument CompressorsRunnablesGraphSingletonsStoresStructured QueryTestingToolsBaseConsoleLog StreamRun CollectorTracer LangchainStreamAsync CallerChunk ArrayContextEnvEvent Source ParseFormatFunction CallingHashJson PatchJson SchemaMathSsrfStandard SchemaStreamTestingTiktokenTypesVectorstores
Text Splitters
MCP Adapters
Language
Theme
JavaScript@langchain/coremessages
Module●Since v0.3

messages

Copy
import { ... } from "@langchain/core/messages";

Functions

function
_isMessageFieldWithRole→ x is MessageFieldWithRole
function
_mergeDicts→ Record<string, any> | undefined
function
_mergeLists→ Content[] | undefined
function
_mergeObj→ T | undefined
function
_mergeStatus→ "success" | "error" | undefined

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

function
coerceMessageLikeToMessage→ BaseMessage
function
collapseToolCallChunks→ __type

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 group. Successfully parsed tool calls are returned as valid ToolCall objects, while malformed ones are returned as InvalidToolCall objects.

function
convertToChunk→ AIMessageChunk<MessageStructure<MessageToolSet>> | ChatMessageChunk<MessageStructure<MessageToolSet>> | FunctionMessageChunk<MessageStructure<MessageToolSet>> | HumanMessageChunk<MessageStructure<MessageToolSet>> | SystemMessageChunk<MessageStructure<MessageToolSet>>
function
defaultTextSplitter→ Promise<string[]>

The default text splitter function that splits text by newlines.

function
filterMessages→ Runnable<BaseMessage<MessageStructure<MessageToolSet>, MessageType>[], BaseMessage<MessageStructure<MessageToolSet>, MessageType>[]>

Filter messages based on name, type or id.

function
getBufferString→ string

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?
AI: Let me check...[tool_calls]
Tool: 72°F and sunny

This avoids token inflation from metadata when stringifying message objects directly.

function
iife→ T

Immediately-invoked function expression.

function
isFunctionMessage→ x is FunctionMessage<MessageStructure<MessageToolSet>>
function
isFunctionMessageChunk→ x is FunctionMessageChunk<MessageStructure<MessageToolSet>>
function
isMessage→ message is Message<StandardMessageStructure, MessageType>

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

function
isOpenAIToolCallArray→ value is OpenAIToolCall[]
function
mapChatMessagesToStoredMessages→ StoredMessage[]

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 function is used to prepare chat messages for storage.

function
mapStoredMessagesToChatMessages→ BaseMessage<MessageStructure<MessageToolSet>, MessageType>[]

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, then creates new instances of the appropriate BaseMessage subclass based on the type of each message. This function is used to prepare stored messages for use in a chat context.

function
mapStoredMessageToChatMessage→ HumanMessage<MessageStructure<MessageToolSet>> | AIMessage<MessageStructure<MessageToolSet>> | SystemMessage<MessageStructure<MessageToolSet>> | FunctionMessage<MessageStructure<MessageToolSet>> | ToolMessage<MessageStructure<MessageToolSet>> | ChatMessage<MessageStructure<MessageToolSet>>
function
mergeContent→ MessageContent
function
mergeMessageRuns→ Runnable<BaseMessage<MessageStructure<MessageToolSet>, MessageType>[], BaseMessage<MessageStructure<MessageToolSet>, MessageType>[]>

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→ ResponseMetadata
function
mergeUsageMetadata→ UsageMetadata
function
trimMessages→ Runnable<BaseMessage<MessageStructure<MessageToolSet>, MessageType>[], BaseMessage<MessageStructure<MessageToolSet>, MessageType>[]>

Trim messages to be below a token count.

function
defaultToolCallParser→ [ToolCall<string, Record<string, any>>[], InvalidToolCall<string>[]]
function
isDirectToolOutput→ x is DirectToolOutput
deprecatedfunction
convertToOpenAIImageBlock→ __type
deprecatedfunction
convertToProviderContentBlock→ Formats[keyof Formats]

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 method unmodified.

deprecatedfunction
isAIMessage→ x is AIMessage<TStructure>
deprecatedfunction
isAIMessageChunk→ x is AIMessageChunk<TStructure>
deprecatedfunction
isBase64ContentBlock→ content_block is Base64ContentBlock
deprecatedfunction
isBaseMessage→ messageLike is BaseMessage<MessageStructure<MessageToolSet>, MessageType>
deprecatedfunction
isBaseMessageChunk→ messageLike is BaseMessageChunk<MessageStructure<MessageToolSet>, MessageType>
deprecatedfunction
isChatMessage→ x is ChatMessage<MessageStructure<MessageToolSet>>
deprecatedfunction
isChatMessageChunk→ x is ChatMessageChunk<MessageStructure<MessageToolSet>>
deprecatedfunction
isDataContentBlock→ content_block is DataContentBlock
deprecatedfunction
isHumanMessage→ x is HumanMessage<TStructure>
deprecatedfunction
isHumanMessageChunk→ x is HumanMessageChunk<TStructure>
deprecatedfunction
isIDContentBlock→ content_block is IDContentBlock
deprecatedfunction
isPlainTextContentBlock→ content_block is PlainTextContentBlock
deprecatedfunction
isSystemMessage→ x is SystemMessage<TStructure>
deprecatedfunction
isSystemMessageChunk→ x is SystemMessageChunk<TStructure>
deprecatedfunction
isURLContentBlock→ content_block is URLContentBlock
deprecatedfunction
parseBase64DataUrl→ __type | undefined

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

deprecatedfunction
parseMimeType→ __type

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

deprecatedfunction
isToolMessage→ x is ToolMessage<MessageStructure<MessageToolSet>>
deprecatedfunction
isToolMessageChunk→ x is ToolMessageChunk<MessageStructure<MessageToolSet>>

Classes

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 BaseMessageChunk into this one. It also overrides the __add__() method to support concatenation of BaseMessageChunk instances.

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.

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.

Interfaces

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 automatically be coerced to a string and wrapped in a ToolMessage.

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 index are equal and not None.

interface
ToolMessageFields
deprecatedinterface
StandardContentBlockConverter

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 convertToStandardContentBlock rather than being consumed directly.

Type Aliases

typeAlias
$Expand: T extends U ? { [K in keyof U]: U[K] } : never
typeAlias
$InferMessageContent: TRole extends "tool" ? $InferToolOutputs<TStructure> extends TOutput ? [TOutput] extends [never] ? string | ContentBlock | Text[] : [unknown] extends [TOutput] ? string | ContentBlock | Text[] : TOutput | string | ContentBlock | Text[] : string | ContentBlock | Text[] : TStructure["outputVersion"] extends "v1" ? $InferMessageContentBlocks<TStructure, TRole>[] : string | ContentBlock | Text[]

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 specified message type. The content type varies depending on the output version (see MessageOutputVersion)

typeAlias
$InferMessageContentBlocks: $NormalizedMessageStructure<TStructure> extends S ? S extends MessageStructure ? S["content"] extends C ? C extends Record<PropertyKey, ContentBlock> ? TRole extends keyof C ? [$MessageToolCallBlock<TStructure>] extends [never] ? C[TRole] : $MergeDiscriminatedUnion<NonNullable<C[TRole]>, $MessageToolCallBlock<TStructure>, "type"> : never : never : never : never : never

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 content definition.

typeAlias
$InferMessageProperties: $NormalizedMessageStructure<TStructure> extends S ? S extends MessageStructure ? S["properties"] extends P | undefined ? P extends Record<PropertyKey, unknown> ? TRole extends keyof P ? Omit<P[TRole], "content" | "type"> : Record<string, unknown> : Record<string, unknown> : Record<string, unknown> : never : never

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 properties definition, and excludes the reserved "content" and "type" properties to avoid conflicts with the core message structure.

If the specified type is not defined in the message structure's properties, it returns a generic Record<string, unknown> type to allow for arbitrary properties.

typeAlias
$InferMessageProperty: K extends keyof $InferMessageProperties<TStructure, TRole> ? $InferMessageProperties<TStructure, TRole>[K] : never

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 given message type. If the specified property key does not exist in the type's properties, it returns never.

typeAlias
$InferResponseMetadata: $InferMessageProperty<TStructure, TRole, "response_metadata"> extends P ? [P] extends [never] ? Record<string, unknown> : P : never

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.

typeAlias
$InferToolCalls: NonNullable<TStructure["tools"]> extends MessageToolSet ? NonNullable<TStructure["tools"]> extends TTools ? { [K in keyof TTools]: K extends string ? TTools[K] extends MessageToolDefinition ? __type : never : never }[keyof TTools] : never : __type

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.

typeAlias
$InferToolOutputs: NonNullable<TStructure["tools"]> extends MessageToolSet ? NonNullable<TStructure["tools"]> extends TTools ? { [K in keyof TTools]: TTools[K] extends MessageToolDefinition ? TTools[K]["output"] : never }[keyof TTools] : unknown : unknown

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.

typeAlias
$MergeContentDefinition: { [K in keyof T | keyof U]: K extends keyof T ? K extends keyof U ? $MergeDiscriminatedUnion<Extract<T[K], ContentBlock>, Extract<U[K], ContentBlock>, "type"> : Extract<T[K], ContentBlock> : K extends keyof U ? Extract<U[K], ContentBlock> : never }

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. The merge logic follows these rules:

  • For keys that exist in both T and U: Merges the content blocks using discriminated union merging based on the "type" property. This allows combining different content block types (e.g., text + image) for the same message type.
  • For keys that exist only in T: Uses T's content definition as-is
  • For keys that exist only in U: Uses U's content definition as-is
typeAlias
$MergeDiscriminatedUnion: { [T in A[Key] | B[Key]]: [Extract<B, Record<Key, T>>] extends [never] ? Extract<A, Record<Key, T>> : [Extract<A, Record<Key, T>>] extends [never] ? Extract<B, Record<Key, T>> : $MergeObjects<Extract<A, Record<Key, T>>, Extract<B, Record<Key, T>>> }[A[Key] | B[Key]]

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 value, use B's member
  • Otherwise use A's member with that discriminator value This effectively merges the unions while giving B's members precedence over A's members.
typeAlias
$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 usable as its own message structure.

typeAlias
$MergeObjects: $OnlyIndexSignatures<U> extends true ? U : $OnlyIndexSignatures<T> extends true ? U : { [K in keyof T | keyof U]: K extends keyof T ? K extends keyof U ? T[K] extends Record<string, unknown> ? U[K] extends Record<string, unknown> ? $MergeObjects<T[K], U[K]> : U[K] : U[K] : T[K] : K extends keyof U ? U[K] : never }

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 are objects (Record<string, unknown>), recursively merge them
    • Otherwise, U's value takes precedence
  • For keys that exist only in T, use T's value
  • For keys that exist only in U, use U's value
typeAlias
$MergeOutputVersion: $NormalizeMessageOutputVersion<T> extends TV ? $NormalizeMessageOutputVersion<U> extends UV ? [TV, UV] extends [undefined, undefined] ? "v0" : [TV] extends [undefined] ? Exclude<UV, undefined> : [UV] extends [undefined] ? Exclude<TV, undefined> : UV : never : never

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 both T and U are undefined, defaults to "v0" for backwards compatibility
  • If T is undefined but U is defined, uses U's version
  • If U is undefined but T is defined, uses T's version
  • If both T and U are defined, U takes precedence (later structure wins)
typeAlias
$MessageToolCallBlock: TStructure["tools"] extends MessageToolSet ? { [K in keyof TStructure["tools"]]: K extends string ? TStructure["tools"][K] extends MessageToolDefinition ? ToolCall<K, TStructure["tools"][K]["input"]> : never : never }[keyof TStructure["tools"]] : never

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.

typeAlias
$NormalizedMessageStructure: T extends StandardMessageStructure ? T : $MergeMessageStructure<StandardMessageStructure, T>

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 message structure includes all the standard message structure fields by default while allowing overrides and extensions.

typeAlias
AIMessageChunkFields: AIMessageFields<TStructure> & __type
typeAlias
BaseMessageFields: Pick<Message, "id" | "name"> & __type
typeAlias
BaseMessageLike: BaseMessage | MessageFieldWithRole | [MessageType, MessageContent] | string | __type & BaseMessageFields & Record<string, unknown> | SerializedConstructor
typeAlias
Constructor: (args: unknown[])
typeAlias
Data: never
typeAlias
InputTokenDetails: ModalitiesTokenDetails & __type

Breakdown of input token counts.

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

typeAlias
MessageChunkUnion: typeof HumanMessageChunk | typeof AIMessageChunk | typeof SystemMessageChunk | typeof FunctionMessageChunk | typeof ToolMessageChunk | typeof ChatMessageChunk | typeof RemoveMessage
typeAlias
MessageContent: string | ContentBlock[]
typeAlias
MessageFieldWithRole: __type & Record<string, unknown>
typeAlias
MessageOutputVersion: "v0" | "v1"

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 blocks
    • provides backward compatibility with simpler content representations
  • "v1": Content follows the structured ContentBlock format with typed discriminated unions
    • enables full type safety and structured content block handling
typeAlias
MessageType: "ai" | "human" | "tool" | "system" | string & NonNullable<unknown>

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.

typeAlias
MessageTypeOrClass: MessageType | MessageUnion | MessageChunkUnion
typeAlias
MessageUnion: typeof HumanMessage | typeof AIMessage | typeof SystemMessage | typeof ChatMessage | typeof FunctionMessage | typeof ToolMessage | typeof RemoveMessage
typeAlias
ModalitiesTokenDetails
typeAlias
OutputTokenDetails: ModalitiesTokenDetails & __type

Breakdown of output token counts.

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

typeAlias
ResponseMetadata
typeAlias
UsageMetadata

Usage metadata for a message, such as token counts.

deprecatedtypeAlias
ImageDetail: "auto" | "low" | "high"
deprecatedtypeAlias
MessageContentComplex: MessageContentText | MessageContentImageUrl | Record<string, any> & __type | Record<string, any> & __type
deprecatedtypeAlias
MessageContentImageUrl
deprecatedtypeAlias
MessageContentText
deprecatedtypeAlias
OpenAIToolCall
deprecatedtypeAlias
ProviderFormatTypes

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 compatibility as the set of known standard types grows, as the set of types can be extended without breaking existing implementations of the aforementioned interfaces.

Variables

variable
DEFAULT_MERGE_IGNORE_KEYS: readonly string[]

Default keys that should be preserved (not merged) when concatenating message chunks. These are identification and timestamp fields that shouldn't be summed or concatenated.

variable
KNOWN_BLOCK_TYPES: string[]

Namespaces

namespace
ContentBlock
namespace
Data
View source on GitHub