1. 消息介绍
在 LangChain 中,消息是模型上下文的基本单元。它们代表模型的输入和输出,携带与 LLM 交互时表示对话状态所需的内容和元数据。消息是包含以下内容的对象:
- 角色(role)- 标识消息类型(例如system,user)
- 内容(content)——指消息的实际内容(例如文本、图像、音频、文档等)。
- 元数据(metadata)- 可选字段,例如响应信息、消息 ID 和令牌使用情况 LangChain 提供了一种适用于所有模型提供程序的标准消息类型,确保无论调用哪个模型,行为都保持一致。
消息类型
- 系统消息(SystemMessage)——告诉模型如何运行,并为交互提供上下文。代表一组初始指令,用于启动模型的行为。您可以使用系统消息来设定基调、定义模型的角色并建立响应准则。
- 人类消息(HumanMessage)——代表用户输入以及与模型的交互。
- AI消息(AIMessage)——模型生成的响应,包括文本内容、工具调用和元数据。
- 工具消息(ToolMessage)——表示工具调用的输出
下面使用代码进行演示:
2. 实战演示
2.1 导入相关依赖模块
import dotenv from "dotenv" // 加载环境变量中的模型 API 密钥
import { ChatOpenAI } from "@langchain/openai"
dotenv.config()
2.2 创建模型对象
const llm = new ChatOpenAI({
model: "qwen-plus",
apiKey: process.env.QWEN_API_KEY,
temperature: 0.7,
streamUsage: false, // 是否开启流式返回,默认 false
// maxTokens: 1000, // 最大Tokens
// maxRetries: 6 , // 最大重试次数,
// timeout: undefined, // 超时时间
logprobs: true,
configuration: {
baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"
}
})
2.3 消息的基本使用
将多种类型的消息一并发送给模型,模型会根据消息的类型和内容进行响应。一般用于有记忆的多轮对话场景中,模型会根据之前的消息内容进行上下文理解和回复。
import {HumanMessage, SystemMessage,AIMessage } from "langchain";
const systemMsg = new SystemMessage("你是一个有用的智能助手!");
const humanMsg1 = new HumanMessage("我叫小军,请问明朝什么时候建立?");
const aiMessage = new AIMessage("明朝建立于**1368年**。");
const humanMsg2 = new HumanMessage("我叫什么名字,刚刚我问的问题是什么?");
const messages = [systemMsg, humanMsg1, aiMessage, humanMsg2];
const response = await llm.invoke(messages);
console.log(response.content); // Returns AIMessage
你叫**小军** 😊
刚刚你问的问题是:**“明朝什么时候建立?”**
(我记住了你的名字,也记得我们刚才的对话~)
需要我再讲讲明朝建立的背景、开国皇帝朱元璋的故事,或者明朝的重要事件吗?
以上是使用框架代码的方式将各种类型的消息组装在一起并发送给大模型,实际上也可以手动组装消息,例如:
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);
对于 HumanMessage 类型消息,具体消息结构如下,用于标识用户消息的角色与会话 ID:
const humanMsg = new HumanMessage({
content: "Hello!",
name: "alice",
id: "msg_123",
});
有时手动创建一个新AIMessage对象并将其插入消息历史记录中会很有帮助,就像它来自模型一样。AIMessage 并不一定需要从模型中获取,也可以手动构建,因为不同模型的厂商对各种消息的参考权重不同。
2.3 工具消息 ToolMessage
工具消息即大模型调用某个工具接口后的响应消息,对于支持工具调用的模型,AI 消息可以包含工具调用。工具消息用于将单次工具执行的结果传递回模型。下面我们展示一个简单的示例。
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 llm.invoke(messages); // Model processes the result