Messages

Purpose and Scope

Messages are the shared representation for conversational context in LangChain. They carry the role of a turn, the content being exchanged, and metadata needed by model providers, tools, tracing systems, and user interfaces. In the Python core package, the message module is explicitly introduced as objects used in prompts and chat conversations, and the base class defines messages as the inputs and outputs of a chat model. That scope is intentionally broader than plain text: messages can contain structured content blocks, provider payload details, response metadata, tool call data, and streaming chunks.

Sources: libs/core/langchain_core/messages/init.py, libs/core/langchain_core/messages/base.py

A developer normally meets messages when invoking a chat model, composing a prompt, inspecting an agent trace, or rendering a conversation in a frontend. The public exports include human, AI, system, tool, function, chat, and remove message classes, plus chunk variants for streamed output. The same module also exports conversion and utility helpers for turning dict representations into messages, trimming histories, merging adjacent runs, filtering message lists, and converting to OpenAI-style messages. Treat this package as the canonical import surface for message primitives rather than importing implementation modules directly.

Sources: libs/core/langchain_core/messages/init.py

Relevant Source Files

  • libs/core/langchain_core/messages/init.py - Public message package surface, lazy imports, exported classes, content block types, tool call types, and utility functions.
  • libs/core/langchain_core/messages/base.py - Base message data model, shared fields, text access behavior, serialization helpers, content merging, and reasoning extraction support.
  • libs/core/langchain_core/messages/ai.py - AI message-specific structures, usage metadata, token detail typed dictionaries, tool call parsing, chunk merging, and provider response handling.
  • libs/core/langchain_core/messages/block_translators/init.py - Registry for provider-specific content block translators and fallback behavior for content block parsing.
  • libs/core/langchain_core/messages/block_translators/anthropic.py - Anthropic content conversion into standard v1 content blocks while preserving unrecognized provider fields.
  • libs/core/langchain_core/messages/block_translators/bedrock_converse.py - Amazon Bedrock Converse content conversion, including text, document, image, and binary-to-base64 handling.

Core Primitives

The central primitive is BaseMessage. It stores content, additional_kwargs, response_metadata, and a unique string type. The content may be a string or a list containing strings and dictionaries, which is what lets LangChain represent both simple chat turns and multimodal payloads. The additional keyword field is reserved for provider-specific payload data, such as raw tool calls encoded by a model provider, while response metadata is intended for response headers, log probabilities, token counts, and model names. This separation keeps the user-visible message body distinct from transport and provider bookkeeping.

Sources: libs/core/langchain_core/messages/base.py

LangChain also exposes a compatibility layer for reading textual content. The TextAccessor behaves like a string and supports modern property access through message.text, while still allowing older method-style message.text() calls with a deprecation warning. That matters when upgrading applications to newer message APIs: user interfaces and agent logs can move to property access without immediately breaking older helper code. The base module also includes reasoning extraction from additional_kwargs, recognizing provider conventions such as a string reasoning_content and returning a standard reasoning block when present.

Sources: libs/core/langchain_core/messages/base.py

The package export list is a practical map of the message taxonomy. HumanMessage represents user input, AIMessage represents model output, SystemMessage carries system-level instructions, and ToolMessage represents tool results that are fed back into the conversation. ChatMessage and FunctionMessage support additional role or function-oriented use cases, while chunk classes represent partial messages produced during streaming. Content block types include text, plain text, image, audio, video, file, data, reasoning, citation, annotation, server tool call, server tool result, invalid tool call, and non-standard content.

Sources: libs/core/langchain_core/messages/init.py

AI Messages, Tool Calls, and Usage Metadata

AIMessage adds the model-output concerns that do not belong on every message type. Its implementation imports tool call and tool call chunk types, default parsers, invalid tool call constructors, merge helpers, partial JSON parsing, and usage utilities. The file defines UsageMetadata as a standard representation of token usage across models, including input token count, output token count, total token count, and optional detailed breakdowns. This lets downstream code inspect cost- and latency-related information without depending on each provider’s native accounting shape.

Sources: libs/core/langchain_core/messages/ai.py

The token detail structures are deliberately flexible. InputTokenDetails can include audio tokens, cache creation tokens, and cache read tokens, and it explicitly does not need to sum to the full input token count or contain every possible key. OutputTokenDetails similarly includes audio and reasoning tokens while allowing provider-specific extras. That design reflects real provider differences: some models expose cache hits, some expose hidden reasoning accounting, and some report additional categories. Application code should therefore read the standard totals first and treat detailed keys as optional diagnostics.

Sources: libs/core/langchain_core/messages/ai.py

Tool calling is another reason AI messages need richer structure than plain assistant text. The AI implementation imports ToolCall, ToolCallChunk, default parsers, invalid tool call constructors, and merge utilities for lists and dictionaries. In practice, this means a streamed model response can accumulate partial tool call information and then normalize it into standard tool call objects. When a provider emits malformed or incomplete tool call JSON, the invalid tool call representation gives the runtime a way to preserve what happened instead of silently dropping provider output.

Sources: libs/core/langchain_core/messages/ai.py

Content Blocks and Provider Translation

Content blocks are the bridge between provider-native payloads and LangChain’s standard message shape. The translator registry maps a provider name to two functions: one for complete AIMessage content and one for AIMessageChunk content. When content_blocks is requested and response_metadata contains a model_provider, the matching translator is used. If no provider is set, or if the provider has no registered translator, LangChain falls back to best-effort parsing in the base message implementation. Integration packages can register their own translators by calling the public registration function.

Sources: libs/core/langchain_core/messages/block_translators/init.py

The Anthropic translator shows how provider-specific content is normalized without losing information. It attempts to convert document blocks into file blocks for base64, URL, or provider file identifiers, and into plain text blocks when the document source is text. Image blocks and other Anthropic shapes are handled by the same conversion flow. When a block contains fields that are not part of the known standard mapping, the translator places them into an extras dictionary. If conversion fails, the original provider block remains available as a non-standard block.

Sources: libs/core/langchain_core/messages/block_translators/anthropic.py

The Bedrock Converse translator follows the same preservation-first pattern for Amazon content. A one-key text payload becomes a standard text block. PDF document bytes are base64 encoded and represented as a file block with an application PDF MIME type, while text documents become plain text blocks. Image and other content shapes are converted when they match recognized Bedrock Converse formats. Otherwise, the translator yields a non-standard block containing the original value. This behavior is important for forward compatibility because providers can add new block shapes before LangChain has a standard mapping.

Sources: libs/core/langchain_core/messages/block_translators/bedrock_converse.py

System-to-Code Mapping

The message system is layered so callers can use simple imports while provider integrations retain specialized behavior. The package initializer defines the public API and lazy dynamic import map. The base class defines shared persistence, display, and content behavior. AI messages extend that foundation with provider output details, usage accounting, tool calls, and streaming chunk support. Translator modules sit beside the message classes and are selected by provider metadata. This means a user can pass the same high-level message list to different chat models while the runtime still knows how to decode provider-native content.

Sources: libs/core/langchain_core/messages/init.py, libs/core/langchain_core/messages/base.py, libs/core/langchain_core/messages/ai.py, libs/core/langchain_core/messages/block_translators/init.py

ConcernPublic names or behaviorSource
Public importsAIMessage, HumanMessage, SystemMessage, ToolMessage, chunks, content blocks, conversion helperslibs/core/langchain_core/messages/__init__.py
Shared fieldscontent, additional_kwargs, response_metadata, typelibs/core/langchain_core/messages/base.py
Usage accountingUsageMetadata, InputTokenDetails, OutputTokenDetailslibs/core/langchain_core/messages/ai.py
Provider translationregister_translator, get_translator, PROVIDER_TRANSLATORSlibs/core/langchain_core/messages/block_translators/__init__.py
Anthropic normalizationdocument, file, text, extras, non-standard preservationlibs/core/langchain_core/messages/block_translators/anthropic.py
Bedrock Converse normalizationtext, PDF, plain text, base64 conversion, non-standard preservationlibs/core/langchain_core/messages/block_translators/bedrock_converse.py

Execution Flow and Practical Usage

A typical chat call begins with a list of messages such as a system instruction followed by one or more human turns. The model returns an AI message, potentially with text, structured content blocks, usage metadata, and tool calls. If the response is streamed, chunks are merged until a complete message can be inspected or persisted. A tracing system such as LangSmith can then render the ordered conversation as user prompts, model responses, tool calls, and tool results. Frontends can render the same message history, including markdown emitted by AI responses, while preserving role-specific handling.

Sources: libs/core/langchain_core/messages/init.py, libs/core/langchain_core/messages/ai.py

For robust applications, preserve both the standard fields and the provider-specific escape hatches. Store response_metadata when model name, headers, token counts, or provider identifiers matter. Preserve additional_kwargs when tool call payloads or reasoning fields may be needed later. Prefer standard content blocks for UI rendering and retrieval pipelines, but do not discard non-standard blocks because they may carry new provider capabilities. When writing integrations, set model_provider in response metadata so registered translators can produce consistent blocks instead of relying only on best-effort parsing.

Sources: libs/core/langchain_core/messages/base.py, libs/core/langchain_core/messages/block_translators/init.py

API Reference Snapshot

  • BaseMessage - abstract message class for chat model inputs and outputs, with content and metadata fields.
  • AIMessage - model response message with usage metadata, tool call handling, and chunk-aware behavior.
  • UsageMetadata - standard token count structure with input, output, total, and optional detailed breakdowns.
  • register_translator(provider, translate_content, translate_content_chunk) - adds provider-specific content block translators.
  • get_translator(provider) - retrieves registered translator functions or returns no translator for fallback parsing.
  • merge_content, message_to_dict, messages_to_dict, messages_from_dict - serialization and content utilities exported from the package surface.
  • convert_to_messages, convert_to_openai_messages, trim_messages, filter_messages, merge_message_runs - utility helpers for adapting and shaping message histories.

Next Steps

If you are building an agent, read the agent configuration and tools pages next because message histories carry instructions, tool calls, and tool results through the runtime. If you are implementing a provider integration, study the translator registry and the Anthropic or Bedrock Converse translators before adding custom content block support. If you are building a frontend, treat message role, text content, content blocks, and metadata as separate concerns so the UI can render human input, AI markdown, tool activity, and diagnostics without conflating them.