[LangChain] 06.Message消息对象
| 类名 | 用途 |
|---|---|
ChatPromptTemplate |
构造整个多轮提示词结构 |
SystemMessagePromptTemplate |
设置系统规则 / 行为模式 |
HumanMessagePromptTemplate |
模拟用户输入 |
AIMessagePromptTemplate |
模拟模型输出(上下文中使用) |
简单回忆一下:
import {
ChatPromptTemplate,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
} from "@langchain/core/prompts";
// 定义一个聊天 prompt 模版
const chatPrompt = ChatPromptTemplate.fromMessages([
SystemMessagePromptTemplate.fromTemplate("你是一个乐于助人的助手"),
HumanMessagePromptTemplate.fromTemplate("请把以下句子翻译成英文:{text}"),
]);
// 渲染成消息数组
const messages = await chatPrompt.formatMessages({ text: "你好" });
console.log(messages);
效果:
[
SystemMessage {
"content": "你是一个乐于助人的助手",
"additional_kwargs": {},
"response_metadata": {}
},
HumanMessage {
"content": "请把以下句子翻译成英文:你好",
"additional_kwargs": {},
"response_metadata": {}
}
]
Message对象
Message 模块是 LangChain.js 中和大模型进行交互的 基本单位,用来表达谁说了什么,并且能携带额外的元信息。
常见的 Message 类型有:
- HumanMessage:用户输入
- AIMessage:模型输出
- SystemMessage:系统指令,例如告诉模型「你是一个助手」这种角色设定
- FunctionMessage / ToolMessage:Function Calling 或 MCP 工具调用的结果
- ChatMessage:通用的消息格式,可以指定角色
对象成员
1. content
消息的主要内容,最核心的字段。
- 一般是 字符串(最常见)
- 也可以是 对象数组(比如多模态:文字 + 图片)
例子 1:纯文本
new HumanMessage("你好!")
{ content: "你好!" }
例子 2:多模态内容
new HumanMessage({
content: [
{ type: "text", text: "请描述这张图片" },
{ type: "image_url", image_url: "https://example.com/cat.png" }
]
})
{
content: [
{ type: "text", text: "请描述这张图片" },
{ type: "image_url", image_url: "https://example.com/cat.png" }
]
}
2. additional_kwargs
附加参数,用来保存与 OpenAI/其他模型 API 兼容的扩展字段。
它通常是空的 {},但在某些场景下会被用到,例如 Function Calling 的场景:
new AIMessage({
content: "",
additional_kwargs: {
function_call: {
name: "getWeather",
arguments: '{ "city": "北京" }'
}
}
})
这是早期的 OpenAI Function Calling 格式(GPT-3.5/4 2023-06-13 那一代)。这种格式只支持一次函数调用。
- 字段名是
function_call,里面直接放name+arguments - arguments 是 JSON 字符串,需要开发者自己
JSON.parse()
new AIMessage({
content: "",
additional_kwargs: {
tool_calls: [
{
id: "tool_123",
type: "function",
function: { name: "search", arguments: "{ \"query\": \"LangChain\" }" }
}
]
}
})
这是 OpenAI 新版 Tool Calling 格式(从 GPT-4-1106-preview 开始引入)。
- 支持 多次调用(
tool_calls是数组,可以一次性返回多个工具调用) - 每个调用有
id(唯一标识符),方便你追踪调用 → 响应 type明确标注了调用类型(现在主要是"function")- LangChain.js 会自动解析成标准化的
tool_calls字段,arguments会从字符串转成对象
不过现在,在最新的 LangChain.js 中,推荐使用tool_calls 字段,而非塞到 additional_kwargs 里:
new AIMessage({
content: "",
tool_calls: [
{
id: "tool_123",
name: "getWeather",
args: { city: "北京" },
},
],
});
3. invalid_tool_calls
当模型给出的工具调用结果无法被 LangChain 标准化时(例如 解析失败 或 结构不合法),这些调用不会出现在 AIMessage.tool_calls,而是被放进 AIMessage.invalid_tool_calls,方便你做兜底与修复。
4. response_metadata
用于保存「消息是怎么来的」的元信息,常见于 模型输出。里面的内容取决于 LLM 的返回信息,比如:
例子 1:OpenAI 返回的 token 消耗
new AIMessage({
content: "你好,我是 AI 助手。",
response_metadata: {
tokenUsage: { promptTokens: 10, completionTokens: 20, totalTokens: 30 },
model_name: "gpt-4o-mini",
finish_reason: "stop"
}
})
例子 2:Ollama 返回的时间戳
new AIMessage({
content: "好的。",
response_metadata: {
created: 1724453430,
model: "llama3"
}
})
例子 3:自定义的元信息
new HumanMessage({
content: "请帮我翻译",
response_metadata: { source: "wechat" }
})
5. text
获取纯文本内容的便捷取值器。
import { HumanMessage } from "@langchain/core/messages";
const msg = new HumanMessage({
content: [
{ type: "text", text: "请描述这张图片" },
{ type: "image_url", image_url: "https://example.com/cat.png" },
],
});
console.log(msg.text); // 请描述这张图片
console.log(msg.content); // [{type:...},{type:...}]
6. getType()方法
返回消息类型。
import { HumanMessage } from "@langchain/core/messages";
const msg = new HumanMessage({
content: [
{ type: "text", text: "请描述这张图片" },
{ type: "image_url", image_url: "https://example.com/cat.png" },
],
});
console.log(msg.getType()); // human
getType() 方法常用语根据不同消息类型进行不同的处理。
@langchain/core/messages 里面还提供了一组守卫方法:
import { HumanMessage } from "@langchain/core/messages";
const msg = new HumanMessage("你好,我叫小明");
console.log(isHumanMessage.isInstance(msg)); // true
课堂练习:执行下面的代码,观察其结果
import { ChatOllama } from "@langchain/ollama";
import { HumanMessage } from "@langchain/core/messages";
const chatModel = new ChatOllama({
model: "llama3",
temperature: 0.7,
});
const response = await chatModel.invoke([
new HumanMessage("用中文给我讲一个笑话"),
]);
console.log(response);
-EOF-

浙公网安备 33010602011771号