外观
消息是 LangChain 中模型上下文的基本单位。它们代表模型的输入和输出,承载了与 LLM 交互时表示对话状态所需的内容和元数据。
消息是包含以下内容的对象:
- 角色(Role) - 标识消息类型(如
system、user) - 内容(Content) - 表示消息的实际内容(如文本、图像、音频、文档等)
- 元数据(Metadata) - 可选字段,如响应信息、消息 ID 和 token 用量
LangChain 提供了一种适用于所有模型提供商的标准消息类型,确保无论调用哪个模型,行为都保持一致。
基本用法
使用消息最简单的方式是创建消息对象,并在调用时将其传递给模型。
python
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage, AIMessage, SystemMessage
model = init_chat_model("gpt-5-nano")
system_msg = SystemMessage("You are a helpful assistant.")
human_msg = HumanMessage("Hello, how are you?")
# 与对话模型一起使用
messages = [system_msg, human_msg]
response = model.invoke(messages) # 返回 AIMessagetypescript
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); // 返回 AIMessageTIP
多轮对话的智能体会累积很长的消息历史。LangSmith 会记录每一轮对话、工具结果和模型响应,因此你可以检查完整的对话。按照追踪快速入门启用追踪。
我们还建议你设置 LangSmith Engine,它可以监控你的追踪、检测问题并提出修复建议。
文本提示词
文本提示词是字符串——非常适合你无需保留对话历史的简单生成任务。
python
response = model.invoke("Write a haiku about spring")typescript
const response = await model.invoke("Write a haiku about spring");在以下情况下使用文本提示词:
- 你有一个单一的独立请求
- 你不需要对话历史
- 你想要最少的代码复杂度
消息提示词
另外,你也可以通过提供消息对象列表,将消息列表传递给模型。
python
from langchain.messages import SystemMessage, HumanMessage, AIMessage
messages = [
SystemMessage("You are a poetry expert"),
HumanMessage("Write a haiku about spring"),
AIMessage("Cherry blossoms bloom...")
]
response = model.invoke(messages)typescript
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);在以下情况下使用消息提示词:
- 管理多轮对话
- 处理多模态内容(图像、音频、文件)
- 包含系统指令
字典格式
你也可以直接用 OpenAI chat completions 格式指定消息。
python
messages = [
{"role": "system", "content": "You are a poetry expert"},
{"role": "user", "content": "Write a haiku about spring"},
{"role": "assistant", "content": "Cherry blossoms bloom..."}
]
response = model.invoke(messages)typescript
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);消息类型
系统消息
SystemMessage 表示一组初始指令,用于初始化模型的行为。你可以使用系统消息来设定语气、定义模型的角色,并为响应建立指导方针。
python
system_msg = SystemMessage("You are a helpful coding assistant.")
messages = [
system_msg,
HumanMessage("How do I create a REST API?")
]
response = model.invoke(messages)typescript
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);python
from langchain.messages import SystemMessage, HumanMessage
system_msg = SystemMessage("""
You are a senior Python developer with expertise in web frameworks.
Always provide code examples and explain your reasoning.
Be concise but thorough in your explanations.
""")
messages = [
system_msg,
HumanMessage("How do I create a REST API?")
]
response = model.invoke(messages)typescript
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);人类消息
HumanMessage 表示用户输入和交互。它们可以包含文本、图像、音频、文件以及任意数量的多模态内容。
文本内容
python
response = model.invoke([
HumanMessage("What is machine learning?")
])python
# 使用字符串是单个 HumanMessage 的快捷方式
response = model.invoke("What is machine learning?")typescript
const response = await model.invoke([
new HumanMessage("What is machine learning?"),
]);typescript
const response = await model.invoke("What is machine learning?");消息元数据
python
human_msg = HumanMessage(
content="Hello!",
name="alice", # 可选:标识不同的用户
id="msg_123", # 可选:用于追踪的唯一标识符
)typescript
const humanMsg = new HumanMessage({
content: "Hello!",
name: "alice",
id: "msg_123",
});INFO
name 字段的行为因提供商而异——有些提供商用它来识别用户,其他提供商则忽略它。如需确认,请参阅模型提供商的参考文档。
AI 消息
AIMessage 表示一次模型调用的输出。它们可以包含多模态数据、工具调用以及你之后可以访问的提供商特定元数据。
python
response = model.invoke("Explain AI")
print(type(response)) # <class 'langchain.messages.AIMessage'>typescript
const response = await model.invoke("Explain AI");
console.log(typeof response); // AIMessage调用模型时会返回 AIMessage 对象,其中包含响应中的所有相关元数据。
不同提供商对消息类型的权重/语境化处理方式不同,这意味着有时手动创建新的 AIMessage 对象并像来自模型那样将其插入消息历史会很有帮助。
python
from langchain.messages import AIMessage, SystemMessage, HumanMessage
# 手动创建 AI 消息(例如,用于对话历史)
ai_msg = AIMessage("I'd be happy to help you with that question!")
# 添加到对话历史
messages = [
SystemMessage("You are a helpful assistant"),
HumanMessage("Can you help me?"),
ai_msg, # 像来自模型那样插入
HumanMessage("Great! What's 2+2?")
]
response = model.invoke(messages)typescript
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, // 像来自模型那样插入
new HumanMessage("Great! What's 2+2?")
]
const response = await model.invoke(messages);属性
(string):消息的文本内容。
(string | dict[]):消息的原始内容。
(ContentBlock[]):消息标准化的内容块。
(dict[] | None):模型发出的工具调用。 如果没有调用工具则为空。
(string):消息的唯一标识符(由 LangChain 自动生成或在提供商响应中返回)
(dict | None):消息的使用元数据,在可用时可包含 token 计数。
(ResponseMetadata | None):消息的响应元数据。
(string):消息的文本内容。
(string | ContentBlock[]):消息的原始内容。
(ContentBlock.Standard[]):消息标准化的内容块。(参见内容)
(ToolCall[] | None):模型发出的工具调用。 如果没有调用工具则为空。
(string):消息的唯一标识符(由 LangChain 自动生成或在提供商响应中返回)
(UsageMetadata | None):消息的使用元数据,在可用时可包含 token 计数。参见
UsageMetadata。(ResponseMetadata | None):消息的响应元数据。
工具调用
当模型进行工具调用时,它们会包含在 AIMessage 中:
python
from langchain.chat_models import init_chat_model
model = init_chat_model("gpt-5-nano")
def get_weather(location: str) -> str:
"""Get the weather at a location."""
...
model_with_tools = model.bind_tools([get_weather])
response = model_with_tools.invoke("What's the weather in Paris?")
for tool_call in response.tool_calls:
print(f"Tool: {tool_call['name']}")
print(f"Args: {tool_call['args']}")
print(f"ID: {tool_call['id']}")typescript
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}`);
}其他结构化数据(如推理过程或引用)也可能出现在消息内容中。
Token 用量
AIMessage 可以在其 usage_metadata 字段中保存 token 计数和其他使用元数据:
python
from langchain.chat_models import init_chat_model
model = init_chat_model("gpt-5-nano")
response = model.invoke("Hello!")
response.usage_metadata{'input_tokens': 8,
'output_tokens': 304,
'total_tokens': 312,
'input_token_details': {'audio': 0, 'cache_read': 0},
'output_token_details': {'audio': 0, 'reasoning': 256}}typescript
import { initChatModel } from "langchain";
const model = await initChatModel("gpt-5-nano");
const response = await model.invoke("Hello!");
console.log(response.usage_metadata);json
{
"output_tokens": 304,
"input_tokens": 8,
"total_tokens": 312,
"input_token_details": {
"cache_read": 0
},
"output_token_details": {
"reasoning": 256
}
}有关详细信息,请参见 UsageMetadata。
流式输出与分块
在流式输出期间,你会收到 AIMessageChunk 对象,可以将它们组合成一个完整的消息对象:
python
chunks = []
full_message = None
for chunk in model.stream("Hi"):
chunks.append(chunk)
print(chunk.text)
full_message = chunk if full_message is None else full_message + chunktypescript
import { AIMessageChunk } from "langchain";
let finalChunk: AIMessageChunk | undefined;
for (const chunk of chunks) {
finalChunk = finalChunk ? finalChunk.concat(chunk) : chunk;
}工具消息
对于支持工具调用的模型,AI 消息可以包含工具调用。工具消息用于将单次工具执行的结果传回模型。
工具可以直接生成 ToolMessage 对象。下面我们展示一个简单的示例。更多内容请阅读工具指南。
python
from langchain.messages import AIMessage
from langchain.messages import ToolMessage
# 在模型发起工具调用之后
# (为简洁起见,这里演示手动创建消息)
ai_message = AIMessage(
content=[],
tool_calls=[{
"name": "get_weather",
"args": {"location": "San Francisco"},
"id": "call_123"
}]
)
# 执行工具并创建结果消息
weather_result = "Sunny, 72°F"
tool_message = ToolMessage(
content=weather_result,
tool_call_id="call_123" # 必须与调用 ID 匹配
)
# 继续对话
messages = [
HumanMessage("What's the weather in San Francisco?"),
ai_message, # 模型的工具调用
tool_message, # 工具执行结果
]
response = model.invoke(messages) # 模型处理结果typescript
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, // 模型的工具调用
toolMessage, // 工具执行结果
];
const response = await model.invoke(messages); // 模型处理结果属性
- (string)(必填):工具调用的字符串化输出。
- (string)(必填):此消息所响应的工具调用的 ID。必须与
AIMessage中工具调用的 ID 匹配。 - (string)(必填):被调用的工具的名称。
- (dict):不会发送给模型但可通过编程方式访问的附加数据。
INFO
artifact 字段存储不会发送给模型但可以通过编程方式访问的补充数据。这对于存储原始结果、调试信息或用于下游处理的数据很有用,而不会使模型的上下文变得杂乱。
示例:使用 artifact 存储检索元数据
例如,[检索](/oss/deepagents/retrieval)工具可以从文档中检索一段文字供模型参考。消息的 `content` 包含模型将引用的文本,而 `artifact` 可以包含应用程序可以使用的文档标识符或其他元数据(例如,用于渲染页面)。示例如下:
python
from langchain.messages import ToolMessage
# 发送给模型
message_content = "It was the best of times, it was the worst of times."
# 下游可用的 artifact
artifact = {"document_id": "doc_123", "page": 0}
tool_message = ToolMessage(
content=message_content,
tool_call_id="call_123",
name="search_books",
artifact=artifact,
)typescript
import { ToolMessage } from "langchain";
// 下游可用的 artifact
const artifact = { document_id: "doc_123", page: 0 };
const toolMessage = new ToolMessage({
content: "It was the best of times, it was the worst of times.",
tool_call_id: "call_123",
name: "search_books",
artifact
});有关使用 LangChain 构建检索[智能体](/oss/langchain/agents)的端到端示例,请参见 [RAG 教程](/oss/deepagents/rag)。
消息内容
你可以将消息的内容视为发送给模型的数据负载。消息有一个类型宽松的 content 属性,支持字符串和未类型化对象的列表(例如字典)。这使 LangChain 对话模型可以直接支持提供商原生结构,如多模态内容和其他数据。
此外,LangChain 还为文本、推理过程、引用、多模态数据、服务端工具调用以及其他消息内容提供了专用的内容类型。请参见下面的内容块。
LangChain 对话模型接受 content 属性中的消息内容。
它可以包含以下任一种:
- 字符串
- 提供商原生格式的内容块列表
- LangChain 标准内容块的列表
下面是一个使用多模态输入的示例:
python
from langchain.messages import HumanMessage
# 字符串内容
human_message = HumanMessage("Hello, how are you?")
# 提供商原生格式(例如 OpenAI)
human_message = HumanMessage(content=[
{"type": "text", "text": "Hello, how are you?"},
{"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}
])
# 标准内容块列表
human_message = HumanMessage(content_blocks=[
{"type": "text", "text": "Hello, how are you?"},
{"type": "image", "url": "https://example.com/image.jpg"},
])TIP
在初始化消息时指定 content_blocks 仍会填充消息的 content,但它为此提供了一种类型安全的接口。
typescript
import { HumanMessage } from "langchain";
// 字符串内容
const humanMessage = new HumanMessage("Hello, how are you?");
// 提供商原生格式(例如 OpenAI)
const humanMessage = new HumanMessage({
content: [
{ type: "text", text: "Hello, how are you?" },
{
type: "image_url",
image_url: { url: "https://example.com/image.jpg" },
},
],
});
// 标准内容块列表
const humanMessage = new HumanMessage({
contentBlocks: [
{ type: "text", text: "Hello, how are you?" },
{ type: "image", url: "https://example.com/image.jpg" },
],
});标准内容块
LangChain 提供了一种适用于各提供商的标准化消息内容表示形式。
消息对象实现了一个 content_blocks 属性,它会将 content 属性惰性解析为标准的、类型安全的表示形式。例如,由 ChatAnthropic 或 ChatOpenAI 生成的消息会包含相应提供商格式的 thinking 或 reasoning 块,但可以惰性解析为一致的 ReasoningContentBlock 表示形式:
Anthropic
python
from langchain.messages import AIMessage
message = AIMessage(
content=[
{"type": "thinking", "thinking": "...", "signature": "WaUjzkyp..."},
{"type": "text", "text": "..."},
],
response_metadata={"model_provider": "anthropic"}
)
message.content_blocks[{'type': 'reasoning',
'reasoning': '...',
'extras': {'signature': 'WaUjzkyp...'}},
{'type': 'text', 'text': '...'}]OpenAI
python
from langchain.messages import AIMessage
message = AIMessage(
content=[
{
"type": "reasoning",
"id": "rs_abc123",
"summary": [
{"type": "summary_text", "text": "summary 1"},
{"type": "summary_text", "text": "summary 2"},
],
},
{"type": "text", "text": "...", "id": "msg_abc123"},
],
response_metadata={"model_provider": "openai"}
)
message.content_blocks[{'type': 'reasoning', 'id': 'rs_abc123', 'reasoning': 'summary 1'},
{'type': 'reasoning', 'id': 'rs_abc123', 'reasoning': 'summary 2'},
{'type': 'text', 'text': '...', 'id': 'msg_abc123'}]消息对象实现了一个 contentBlocks 属性,它会将 content 属性惰性解析为标准的、类型安全的表示形式。例如,由 ChatAnthropic 或 ChatOpenAI 生成的消息会包含相应提供商格式的 thinking 或 reasoning 块,但可以惰性解析为一致的 ReasoningContentBlock 表示形式:
Anthropic
typescript
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);OpenAI
typescript
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);查看集成指南以开始使用你选择的推理提供商。
INFO
序列化标准内容
如果 LangChain 之外的应用需要访问标准内容块表示形式,你可以选择将内容块存储在消息内容中。
为此,你可以将 LC_OUTPUT_VERSION 环境变量设置为 v1。或者,使用 output_version="v1" 初始化任何对话模型:
python
from langchain.chat_models import init_chat_model
model = init_chat_model("gpt-5-nano", output_version="v1")为此,你可以将 LC_OUTPUT_VERSION 环境变量设置为 v1。或者,使用 outputVersion: "v1" 初始化任何对话模型:
typescript
import { initChatModel } from "langchain";
const model = await initChatModel(
"gpt-5-nano",
{ outputVersion: "v1" }
);多模态
多模态(Multimodality) 指的是处理以不同形式(如文本、音频、图像和视频)呈现的数据的能力。LangChain 为这些数据提供了可在各提供商之间使用的标准类型。
对话模型可以接受多模态数据作为输入,并将其作为输出生成。下面我们展示以多模态数据为特色的输入消息的简短示例。
python
# 从 URL
message = {
"role": "user",
"content": [
{"type": "text", "text": "Describe the content of this image."},
{"type": "image", "url": "https://example.com/path/to/image.jpg"},
]
}
# 从 base64 数据
message = {
"role": "user",
"content": [
{"type": "text", "text": "Describe the content of this image."},
{
"type": "image",
"base64": "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2...",
"mime_type": "image/jpeg",
},
]
}
# 从提供商管理的文件 ID
message = {
"role": "user",
"content": [
{"type": "text", "text": "Describe the content of this image."},
{"type": "image", "file_id": "file-abc123"},
]
}python
# 从 URL
message = {
"role": "user",
"content": [
{"type": "text", "text": "Describe the content of this document."},
{"type": "file", "url": "https://example.com/path/to/document.pdf"},
]
}
# 从 base64 数据
message = {
"role": "user",
"content": [
{"type": "text", "text": "Describe the content of this document."},
{
"type": "file",
"base64": "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2...",
"mime_type": "application/pdf",
},
]
}
# 从提供商管理的文件 ID
message = {
"role": "user",
"content": [
{"type": "text", "text": "Describe the content of this document."},
{"type": "file", "file_id": "file-abc123"},
]
}python
# 从 base64 数据
message = {
"role": "user",
"content": [
{"type": "text", "text": "Describe the content of this audio."},
{
"type": "audio",
"base64": "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2...",
"mime_type": "audio/wav",
},
]
}
# 从提供商管理的文件 ID
message = {
"role": "user",
"content": [
{"type": "text", "text": "Describe the content of this audio."},
{"type": "audio", "file_id": "file-abc123"},
]
}python
# 从 base64 数据
message = {
"role": "user",
"content": [
{"type": "text", "text": "Describe the content of this video."},
{
"type": "video",
"base64": "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2...",
"mime_type": "video/mp4",
},
]
}
# 从提供商管理的文件 ID
message = {
"role": "user",
"content": [
{"type": "text", "text": "Describe the content of this video."},
{"type": "video", "file_id": "file-abc123"},
]
}typescript
// 从 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"
},
],
});
// 从 base64 数据
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...",
},
],
});
// 从提供商管理的文件 ID
const message = new HumanMessage({
content: [
{ type: "text", text: "Describe the content of this image." },
{ type: "image", source_type: "id", id: "file-abc123" },
],
});typescript
// 从 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" },
],
});
// 从 base64 数据
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",
},
],
});
// 从提供商管理的文件 ID
const message = new HumanMessage({
content: [
{ type: "text", text: "Describe the content of this document." },
{ type: "file", source_type: "id", id: "file-abc123" },
],
});typescript
// 从 base64 数据
const message = new HumanMessage({
content: [
{ type: "text", text: "Describe the content of this audio." },
{
type: "audio",
source_type: "base64",
data: "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2...",
},
],
});
// 从提供商管理的文件 ID
const message = new HumanMessage({
content: [
{ type: "text", text: "Describe the content of this audio." },
{ type: "audio", source_type: "id", id: "file-abc123" },
],
});typescript
// 从 base64 数据
const message = new HumanMessage({
content: [
{ type: "text", text: "Describe the content of this video." },
{
type: "video",
source_type: "base64",
data: "AAAAIGZ0eXBtcDQyAAAAAGlzb21tcDQyAAACAGlzb2...",
},
],
});
// 从提供商管理的文件 ID
const message = new HumanMessage({
content: [
{ type: "text", text: "Describe the content of this video." },
{ type: "video", source_type: "id", id: "file-abc123" },
],
});WARNING
并非所有模型都支持所有文件类型。请查看模型提供商的参考文档,了解支持的格式和大小限制。
内容块参考
内容块(在创建消息或访问 content_blocks 属性时)表示为类型化字典的列表。列表中的每一项都必须符合以下块类型之一:
核心
TextContentBlock
**用途:** 标准文本输出
type (string)(必填):始终为
"text"text (string)(必填):文本内容
annotations (object[]):文本的标注列表
extras (object):额外的提供商特定数据
**示例:**
python
{
"type": "text",
"text": "Hello world",
"annotations": []
}ReasoningContentBlock
**用途:** 模型推理步骤
type (string)(必填):始终为
"reasoning"reasoning (string):推理内容
extras (object):额外的提供商特定数据
**示例:**
python
{
"type": "reasoning",
"reasoning": "The user is asking about...",
"extras": {"signature": "abc123"},
}多模态
ImageContentBlock
**用途:** 图像数据
type (string)(必填):始终为
"image"url (string):指向图像位置的 URL。
base64 (string):Base64 编码的图像数据。
id (string):此内容块的唯一标识符(由提供商或 LangChain 生成)。
mime_type (string):图像 MIME 类型(例如
image/jpeg、image/png)。base64 数据必填。
AudioContentBlock
**用途:** 音频数据
type (string)(必填):始终为
"audio"url (string):指向音频位置的 URL。
base64 (string):Base64 编码的音频数据。
id (string):此内容块的唯一标识符(由提供商或 LangChain 生成)。
mime_type (string):音频 MIME 类型(例如
audio/mpeg、audio/wav)。base64 数据必填。
VideoContentBlock
**用途:** 视频数据
type (string)(必填):始终为
"video"url (string):指向视频位置的 URL。
base64 (string):Base64 编码的视频数据。
id (string):此内容块的唯一标识符(由提供商或 LangChain 生成)。
mime_type (string):视频 MIME 类型(例如
video/mp4、video/webm)。base64 数据必填。
FileContentBlock
**用途:** 通用文件(PDF 等)
type (string)(必填):始终为
"file"url (string):指向文件位置的 URL。
base64 (string):Base64 编码的文件数据。
id (string):此内容块的唯一标识符(由提供商或 LangChain 生成)。
mime_type (string):文件 MIME 类型(例如
application/pdf)。base64 数据必填。
PlainTextContentBlock
**用途:** 文档文本(`.txt`、`.md`)
type (string)(必填):始终为
"text-plain"text (string):文本内容
mime_type (string):文本的 MIME 类型(例如
text/plain、text/markdown)
工具调用
ToolCall
**用途:** 函数调用
type (string)(必填):始终为
"tool_call"name (string)(必填):要调用的工具的名称
args (object)(必填):传递给工具的参数
id (string)(必填):此工具调用的唯一标识符
**示例:**
python
{
"type": "tool_call",
"name": "search",
"args": {"query": "weather"},
"id": "call_123"
}ToolCallChunk
**用途:** 流式工具调用片段
type (string)(必填):始终为
"tool_call_chunk"name (string):正在被调用的工具的名称
args (string):部分工具参数(可能是不完整的 JSON)
id (string):工具调用标识符
index (number | string):此块在流中的位置
InvalidToolCall
**用途:** 格式错误的调用,用于捕获 JSON 解析错误。
type (string)(必填):始终为
"invalid_tool_call"name (string):未能被调用的工具的名称
args (object):传递给工具的参数
error (string):出错原因的说明
服务端工具执行
ServerToolCall
**用途:** 在服务端执行的工具调用。
type (string)(必填):始终为
"server_tool_call"id (string)(必填):与此工具调用关联的标识符。
name (string)(必填):将被调用的工具的名称。
args (string)(必填):部分工具参数(可能是不完整的 JSON)
ServerToolCallChunk
**用途:** 流式服务端工具调用片段
type (string)(必填):始终为
"server_tool_call_chunk"id (string):与此工具调用关联的标识符。
name (string):正在被调用的工具的名称
args (string):部分工具参数(可能是不完整的 JSON)
index (number | string):此块在流中的位置
ServerToolResult
**用途:** 搜索结果
type (string)(必填):始终为
"server_tool_result"tool_call_id (string)(必填):相应服务端工具调用的标识符。
id (string):与服务端工具结果关联的标识符。
status (string)(必填):服务端工具的执行状态。
"success"或"error"。output:已执行工具的输出。
提供商特定块
NonStandardContentBlock
**用途:** 提供商特定的逃生通道
type (string)(必填):始终为
"non_standard"value (object)(必填):提供商特定的数据结构
**用途:** 用于实验性或提供商独有的功能 更多提供商特定的内容类型可以在每个模型提供商的[参考文档](/oss/integrations/providers/overview)中找到。
内容块(在创建消息或访问 contentBlocks 字段时)表示为类型化对象的列表。列表中的每一项都必须符合以下块类型之一:
核心
ContentBlock.Text
**用途:** 标准文本输出
type (string)(必填):始终为
"text"text (string)(必填):文本内容
annotations (Citation[]):文本的标注列表
**示例:**
typescript
{
type: "text",
text: "Hello world",
annotations: []
}ContentBlock.Reasoning
**用途:** 模型推理步骤
type (string)(必填):始终为
"reasoning"reasoning (string)(必填):推理内容
**示例:**
typescript
{
type: "reasoning",
reasoning: "The user is asking about..."
}多模态
ContentBlock.Multimodal.Image
**用途:** 图像数据
type (string)(必填):始终为
"image"url (string):指向图像位置的 URL。
data (string):Base64 编码的图像数据。
fileId (string):对外部文件存储系统(如 OpenAI 或 Anthropic 的 Files API)中图像的引用。
mimeType (string):图像 MIME 类型(例如
image/jpeg、image/png)。base64 数据必填。
ContentBlock.Multimodal.Audio
**用途:** 音频数据
type (string)(必填):始终为
"audio"url (string):指向音频位置的 URL。
data (string):Base64 编码的音频数据。
fileId (string):对外部文件存储系统(如 OpenAI 或 Anthropic 的 Files API)中音频文件的引用。
mimeType (string):音频 MIME 类型(例如
audio/mpeg、audio/wav)。base64 数据必填。
ContentBlock.Multimodal.Video
**用途:** 视频数据
type (string)(必填):始终为
"video"url (string):指向视频位置的 URL。
data (string):Base64 编码的视频数据。
fileId (string):对外部文件存储系统(如 OpenAI 或 Anthropic 的 Files API)中视频文件的引用。
mimeType (string):视频 MIME 类型(例如
video/mp4、video/webm)。base64 数据必填。
ContentBlock.Multimodal.File
**用途:** 通用文件(PDF 等)
type (string)(必填):始终为
"file"url (string):指向文件位置的 URL。
data (string):Base64 编码的文件数据。
fileId (string):对外部文件存储系统(如 OpenAI 或 Anthropic 的 Files API)中文件的引用。
mimeType (string):文件 MIME 类型(例如
application/pdf)。base64 数据必填。
ContentBlock.Multimodal.PlainText
**用途:** 文档文本(`.txt`、`.md`)
type (string)(必填):始终为
"text-plain"text (string)(必填):文本内容
title (string):文本内容的标题
mimeType (string):文本的 MIME 类型(例如
text/plain、text/markdown)
工具调用
ContentBlock.Tools.ToolCall
**用途:** 函数调用
type (string)(必填):始终为
"tool_call"name (string)(必填):要调用的工具的名称
args (object)(必填):传递给工具的参数
id (string)(必填):此工具调用的唯一标识符
**示例:**
typescript
{
type: "tool_call",
name: "search",
args: { query: "weather" },
id: "call_123"
}ContentBlock.Tools.ToolCallChunk
**用途:** 流式工具片段
type (string)(必填):始终为
"tool_call_chunk"name (string):正在被调用的工具的名称
args (string):部分工具参数(可能是不完整的 JSON)
id (string):工具调用标识符
index (number | string)(必填):此块在流中的位置
ContentBlock.Tools.InvalidToolCall
**用途:** 格式错误的调用
type (string)(必填):始终为
"invalid_tool_call"name (string):未能被调用的工具的名称
args (string):解析失败的原始参数
error (string)(必填):出错原因的说明
**常见错误:** 无效的 JSON、缺少必填字段
服务端工具执行
ContentBlock.Tools.ServerToolCall
**用途:** 在服务端执行的工具调用。
type (string)(必填):始终为
"server_tool_call"id (string)(必填):与此工具调用关联的标识符。
name (string)(必填):将被调用的工具的名称。
args (string)(必填):部分工具参数(可能是不完整的 JSON)
ContentBlock.Tools.ServerToolCallChunk
**用途:** 流式服务端工具调用片段
type (string)(必填):始终为
"server_tool_call_chunk"id (string):与此工具调用关联的标识符。
name (string):正在被调用的工具的名称
args (string):部分工具参数(可能是不完整的 JSON)
index (number | string):此块在流中的位置
ContentBlock.Tools.ServerToolResult
**用途:** 搜索结果
type (string)(必填):始终为
"server_tool_result"tool_call_id (string)(必填):相应服务端工具调用的标识符。
id (string):与服务端工具结果关联的标识符。
status (string)(必填):服务端工具的执行状态。
"success"或"error"。output:已执行工具的输出。
提供商特定块
ContentBlock.NonStandard
**用途:** 提供商特定的逃生通道
type (string)(必填):始终为
"non_standard"value (object)(必填):提供商特定的数据结构
**用途:** 用于实验性或提供商独有的功能 更多提供商特定的内容类型可以在每个模型提供商的[参考文档](/oss/integrations/providers/overview)中找到。
上面提到的每个内容块在导入 ContentBlock 类型时都可以作为类型单独引用。
typescript
import { ContentBlock } from "langchain";
// 文本块
const textBlock: ContentBlock.Text = {
type: "text",
text: "Hello world",
}
// 图像块
const imageBlock: ContentBlock.Multimodal.Image = {
type: "image",
url: "https://example.com/image.png",
mimeType: "image/png",
}TIP
在 API 参考 中查看规范的类型定义。
INFO
LangChain v1 在消息上引入了内容块这一新属性,以在跨提供商之间标准化内容格式,同时保持与现有代码的向后兼容性。
内容块不是 content 属性的替代品,而是一个可用于以标准化格式访问消息内容的新属性。
与对话模型一起使用
对话模型接受一系列消息对象作为输入,并返回 AIMessage 作为输出。交互通常是无状态的,因此简单的对话循环就涉及用不断增长的消息列表来调用模型。
请参阅以下指南了解更多:
- 持久化并管理对话历史的内置功能
- 管理上下文窗口的策略,包括修剪和摘要消息