本页还没有译文
本页 166 段还没译成한국어,下面显示的是英文原文。Messages
还没翻译译自英文(docs.langchain.com)本页 166 段都还没译
Messages are the fundamental unit of context for models in LangChain. They represent the input and output of models, carrying both the content and metadata needed to represent the state of a conversation when interacting with an LLM.
Messages are objects that contain:
- Role - Identifies the message type (e.g.
system,user) - Content - Represents the actual content of the message (like text, images, audio, documents, etc.)
- Metadata - Optional fields such as response information, message IDs, and token usage
LangChain provides a standard message type that works across all model providers, ensuring consistent behavior regardless of the model being called.
Basic usage
The simplest way to use messages is to create message objects and pass them to a model when invoking.
import { initChatModel, HumanMessage, SystemMessage } from "langchain";
const model = await initChatModel("gpt-5-nano");
const systemMsg = new SystemMessage("You are a helpful assistant.");
const humanMsg = new HumanMessage("Hello, how are you?");
const messages = [systemMsg, humanMsg];
const response = await model.invoke(messages); // Returns AIMessageTip
Multi-turn agents accumulate long message histories. LangSmith records each turn, tool result, and model response so you can inspect the full conversation. Follow the tracing quickstart to enable tracing.
We recommend you also set up LangSmith Engine which monitors your traces, detects issues, and proposes fixes.
Text prompts
Text prompts are strings - ideal for straightforward generation tasks where you don't need to retain conversation history.
const response = await model.invoke("Write a haiku about spring");Use text prompts when:
- You have a single, standalone request
- You don't need conversation history
- You want minimal code complexity
Message prompts
Alternatively, you can pass in a list of messages to the model by providing a list of message objects.
import { SystemMessage, HumanMessage, AIMessage } from "langchain";
const messages = [
new SystemMessage("You are a poetry expert"),
new HumanMessage("Write a haiku about spring"),
new AIMessage("Cherry blossoms bloom..."),
];
const response = await model.invoke(messages);Use message prompts when:
- Managing multi-turn conversations
- Working with multimodal content (images, audio, files)
- Including system instructions
Dictionary format
You can also specify messages directly in OpenAI chat completions format.
const messages = [
{ role: "system", content: "You are a poetry expert" },
{ role: "user", content: "Write a haiku about spring" },
{ role: "assistant", content: "Cherry blossoms bloom..." },
];
const response = await model.invoke(messages);Message types
- System message - Tells the model how to behave and provide context for interactions
- Human message - Represents user input and interactions with the model
- AI message - Responses generated by the model, including text content, tool calls, and metadata
- Tool message - Represents the outputs of tool calls
System message
A SystemMessage represent an initial set of instructions that primes the model's behavior. You can use a system message to set the tone, define the model's role, and establish guidelines for responses.
import { SystemMessage, HumanMessage, AIMessage } from "langchain";
const systemMsg = new SystemMessage("You are a helpful coding assistant.");
const messages = [
systemMsg,
new HumanMessage("How do I create a REST API?"),
];
const response = await model.invoke(messages);import { SystemMessage, HumanMessage } from "langchain";
const systemMsg = new SystemMessage(`
You are a senior TypeScript developer with expertise in web frameworks.
Always provide code examples and explain your reasoning.
Be concise but thorough in your explanations.
`);
const messages = [
systemMsg,
new HumanMessage("How do I create a REST API?"),
];
const response = await model.invoke(messages);Human message
A HumanMessage represents user input and interactions. They can contain text, images, audio, files, and any other amount of multimodal content.
Text content
const response = await model.invoke([
new HumanMessage("What is machine learning?"),
]);const response = await model.invoke("What is machine learning?");Message metadata
const humanMsg = new HumanMessage({
content: "Hello!",
name: "alice",
id: "msg_123",
});Note
The name field behavior varies by provider—some use it for user identification, others ignore it. To check, refer to the model provider's reference.
AI message
An AIMessage represents the output of a model invocation. They can include multimodal data, tool calls, and provider-specific metadata that you can later access.
const response = await model.invoke("Explain AI");
console.log(typeof response); // AIMessageAIMessage objects are returned by the model when calling it, which contains all of the associated metadata in the response.
Providers weigh/contextualize types of messages differently, which means it is sometimes helpful to manually create a new AIMessage object and insert it into the message history as if it came from the model.
import { AIMessage, SystemMessage, HumanMessage } from "langchain";
const aiMsg = new AIMessage("I'd be happy to help you with that question!");
const messages = [
new SystemMessage("You are a helpful assistant"),
new HumanMessage("Can you help me?"),
aiMsg, // Insert as if it came from the model
new HumanMessage("Great! What's 2+2?")
]
const response = await model.invoke(messages);Tool calls
When models make tool calls, they're included in the AIMessage:
const modelWithTools = model.bindTools([getWeather]);
const response = await modelWithTools.invoke("What's the weather in Paris?");
for (const toolCall of response.tool_calls) {
console.log(`Tool: ${toolCall.name}`);
console.log(`Args: ${toolCall.args}`);
console.log(`ID: ${toolCall.id}`);
}Other structured data, such as reasoning or citations, can also appear in message content.
Token usage
An AIMessage can hold token counts and other usage metadata in its usage_metadata field:
import { initChatModel } from "langchain";
const model = await initChatModel("gpt-5-nano");
const response = await model.invoke("Hello!");
console.log(response.usage_metadata);{
"output_tokens": 304,
"input_tokens": 8,
"total_tokens": 312,
"input_token_details": {
"cache_read": 0
},
"output_token_details": {
"reasoning": 256
}
}See UsageMetadata for details.
Streaming and chunks
During streaming, you'll receive AIMessageChunk objects that can be combined into a full message object:
import { AIMessageChunk } from "langchain";
let finalChunk: AIMessageChunk | undefined;
for (const chunk of chunks) {
finalChunk = finalChunk ? finalChunk.concat(chunk) : chunk;
}Tool message
For models that support tool calling, AI messages can contain tool calls. Tool messages are used to pass the results of a single tool execution back to the model.
Tools can generate ToolMessage objects directly. Below, we show a simple example. Read more in the tools guide.
import { AIMessage, ToolMessage } from "langchain";
const aiMessage = new AIMessage({
content: [],
tool_calls: [{
name: "get_weather",
args: { location: "San Francisco" },
id: "call_123"
}]
});
const toolMessage = new ToolMessage({
content: "Sunny, 72°F",
tool_call_id: "call_123"
});
const messages = [
new HumanMessage("What's the weather in San Francisco?"),
aiMessage, // Model's tool call
toolMessage, // Tool execution result
];
const response = await model.invoke(messages); // Model processes the resultNote
The artifact field stores supplementary data that won't be sent to the model but can be accessed programmatically. This is useful for storing raw results, debugging information, or data for downstream processing without cluttering the model's context.
Message content
You can think of a message's content as the payload of data that gets sent to the model. Messages have a content attribute that is loosely-typed, supporting strings and lists of untyped objects (e.g., dictionaries). This allows support for provider-native structures directly in LangChain chat models, such as multimodal content and other data.
Separately, LangChain provides dedicated content types for text, reasoning, citations, multi-modal data, server-side tool calls, and other message content. See content blocks below.
LangChain chat models accept message content in the content attribute.
This may contain either:
- A string
- A list of content blocks in a provider-native format
- A list of LangChain's standard content blocks
See below for an example using multimodal inputs:
import { HumanMessage } from "langchain";
// String content
const humanMessage = new HumanMessage("Hello, how are you?");
// Provider-native format (e.g., OpenAI)
const humanMessage = new HumanMessage({
content: [
{ type: "text", text: "Hello, how are you?" },
{
type: "image_url",
image_url: { url: "https://example.com/image.jpg" },
},
],
});
// List of standard content blocks
const humanMessage = new HumanMessage({
contentBlocks: [
{ type: "text", text: "Hello, how are you?" },
{ type: "image", url: "https://example.com/image.jpg" },
],
});Standard content blocks
LangChain provides a standard representation for message content that works across providers.
Message objects implement a contentBlocks property that will lazily parse the content attribute into a standard, type-safe representation. For example, messages generated from ChatAnthropic or ChatOpenAI will include thinking or reasoning blocks in the format of the respective provider, but can be lazily parsed into a consistent ReasoningContentBlock representation:
import { AIMessage } from "@langchain/core/messages";
const message = new AIMessage({
content: [
{
"type": "thinking",
"thinking": "...",
"signature": "WaUjzkyp...",
},
{
"type":"text",
"text": "...",
"id": "msg_abc123",
},
],
response_metadata: { model_provider: "anthropic" },
});
console.log(message.contentBlocks);import { AIMessage } from "@langchain/core/messages";
const message = new AIMessage({
content: [
{
"type": "reasoning",
"id": "rs_abc123",
"summary": [
{"type": "summary_text", "text": "summary 1"},
{"type": "summary_text", "text": "summary 2"},
],
},
{"type": "text", "text": "..."},
],
response_metadata: { model_provider: "openai" },
});
console.log(message.contentBlocks);See the integrations guides to get started with the inference provider of your choice.
Note
Serializing standard content
If an application outside of LangChain needs access to the standard content block representation, you can opt-in to storing content blocks in message content.
To do this, you can set the LC_OUTPUT_VERSION environment variable to v1. Or,
initialize any chat model with outputVersion: "v1":
import { initChatModel } from "langchain";
const model = await initChatModel(
"gpt-5-nano",
{ outputVersion: "v1" }
);Multimodal
Multimodality refers to the ability to work with data that comes in different forms, such as text, audio, images, and video. LangChain includes standard types for these data that can be used across providers.
Chat models can accept multimodal data as input and generate it as output. Below we show short examples of input messages featuring multimodal data.
Note
Extra keys can be included top-level in the content block or nested in "extras": {"key": value}.
OpenAI, for example, requires a filename for PDFs. See the provider page for your chosen model for specifics.
// From URL
const message = new HumanMessage({
content: [
{ type: "text", text: "Describe the content of this image." },
{
type: "image",
source_type: "url",
url: "https://example.com/path/to/image.jpg"
},
],
});
// From base64 data
const message = new HumanMessage({
content: [
{ type: "text", text: "Describe the content of this image." },
{
type: "image",
source_type: "base64",
mime_type: "image/jpeg",
data: "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2...",
},
],
});
// From provider-managed File ID
const message = new HumanMessage({
content: [
{ type: "text", text: "Describe the content of this image." },
{ type: "image", source_type: "id", id: "file-abc123" },
],
});// From URL
const message = new HumanMessage({
content: [
{ type: "text", text: "Describe the content of this document." },
{ type: "file", source_type: "url", url: "https://example.com/path/to/document.pdf", mime_type: "application/pdf" },
],
});
// From base64 data
const message = new HumanMessage({
content: [
{ type: "text", text: "Describe the content of this document." },
{
type: "file",
source_type: "base64",
data: "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2...",
mime_type: "application/pdf",
},
],
});
// From provider-managed File ID
const message = new HumanMessage({
content: [
{ type: "text", text: "Describe the content of this document." },
{ type: "file", source_type: "id", id: "file-abc123" },
],
});// From base64 data
const message = new HumanMessage({
content: [
{ type: "text", text: "Describe the content of this audio." },
{
type: "audio",
source_type: "base64",
data: "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2...",
},
],
});
// From provider-managed File ID
const message = new HumanMessage({
content: [
{ type: "text", text: "Describe the content of this audio." },
{ type: "audio", source_type: "id", id: "file-abc123" },
],
});// From base64 data
const message = new HumanMessage({
content: [
{ type: "text", text: "Describe the content of this video." },
{
type: "video",
source_type: "base64",
data: "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2...",
},
],
});
// From provider-managed File ID
const message = new HumanMessage({
content: [
{ type: "text", text: "Describe the content of this video." },
{ type: "video", source_type: "id", id: "file-abc123" },
],
});Warning
Not all models support all file types. Check the model provider's reference for supported formats and size limits.
Content block reference
Content blocks are represented (either when creating a message or accessing the contentBlocks field) as a list of typed objects. Each item in the list must adhere to one of the following block types:
Each of these content blocks mentioned above are individually addressable as types when importing the ContentBlock type.
import { ContentBlock } from "langchain";
// Text block
const textBlock: ContentBlock.Text = {
type: "text",
text: "Hello world",
}
// Image block
const imageBlock: ContentBlock.Multimodal.Image = {
type: "image",
url: "https://example.com/image.png",
mimeType: "image/png",
}Tip
View the canonical type definitions in the API reference.
Info
Content blocks were introduced as a new property on messages in LangChain v1 to standardize content formats across providers while maintaining backward compatibility with existing code.
Content blocks are not a replacement for the content property, but rather a new property that can be used to access the content of a message in a standardized format.
Serialization
You can serialize messages to plain objects for storage and deserialize back to message instances. This is useful for persisting conversation history and resuming sessions.
import { HumanMessage } from "@langchain/core/messages";
import { load } from "@langchain/core/load";
const message = new HumanMessage("What is the capital of France?");
// Serialize to a plain object
const serialized = message.toJSON();
// Deserialize back to a message object
const restored = await load<HumanMessage>(JSON.stringify(serialized));Warning
load() deserializes data by instantiating classes and invoking constructors. Never call load() on untrusted or user-supplied input. Only deserialize data that originates from a source you control, such as your own database.
Use with chat models
Chat models accept a sequence of message objects as input and return an AIMessage as output. Interactions are often stateless, so that a simple conversational loop involves invoking a model with a growing list of messages.
Refer to the below guides to learn more:
- Built-in features for persisting and managing conversation histories
- Strategies for managing context windows, including trimming and summarizing messages