nestjs+langchain:Prompt Template
- 大语言模型
- 11天前
- 12热度
- 0评论
如何在 NestJS 中使用 LangChain 的 Prompt Template 构建动态提示词
引言
在开发应用时,使用静态提示词可能会限制模型的灵活性和适用范围。为了提高代码的质量与效率,在这里介绍如何利用 LangChain 提供的 PromptTemplate 和相关类来构建具备高度可配置性的动态提示词模板。
LangChain 是一个用于自然语言处理任务的强大库,能够帮助开发者构建各种复杂的提示词系统。在应用开发中,使用这些组件可以极大地简化代码,并提升系统的灵活性和适应性。
Prompt Template 的概念与分类
介绍
Prompt Template 是 LangChain 中的一个核心概念,它允许用户根据不同的输入生成动态的提示信息来传递给语言模型(LLM)或聊天模型。通过定义模板中的变量,开发者可以在运行时灵活地填充这些变量以满足特定应用场景的需求。
LangChain 支持多种类型的 Prompt Templates:
- PromptTemplate: 用于生成字符串提示。
- ChatPromptTemplate: 专门用于组合不同角色的消息模板,并传给聊天模型进行对话管理。
- XxxMessagePromptTemplate: 包含 SystemMessagePromptTemplate, HumanMessagePromptTemplate 和 AIMessagePromptTemplate 等具体消息类,用于构建更复杂的多轮次对话场景。
- PipelinePrompt: 用于组合多个提示模板的管道机制。
使用说明
通过 PromptTemplate 类可以快速创建包含变量的提示词模板,并在不同应用场景中生成定制化的提示信息。下面详细介绍其主要参数:
- template:定义提示模板的字符串,其中可包括静态文本和变量占位符(如 {name})。
- inputVariables:指定在调用时需要填充的具体变量名称列表。
- partialVariables:用于预先固定某些变量值,在每次使用时无需重复设置。
实例化方法
方法一:构造函数创建实例
import { PromptTemplate } from '@langchain/core/prompts';
const promptTemplate = new PromptTemplate({
template: '请简要描述{topic}的应用。',
inputVariables: ['topic'],
});
// 使用模板生成提示词并发送给LLM
const messages = [new HumanMessage(promptTemplate.format({ topic: '机器学习' }))];
const response = await llm.invoke(messages);
console.log('LLM 响应:', response.content);方法二:使用 fromTemplate 静态方法
import { PromptTemplate } from '@langchain/core/prompts';
const promptTemplate = PromptTemplate.fromTemplate(
'请给我一个关于{topic}的{type}解释。',
);
const prompt = await promptTemplate.format({
type: '详细',
topic: '量子力学',
});
console.log('提示词1:', prompt);部分提示模板使用
定义部分预填充变量,可以实现更灵活的动态生成:
import { PromptTemplate } from '@langchain/core/prompts';
const template = new PromptTemplate({
template: '请评价{product}的优缺点,包括{aspect1}和{aspect2}。',
inputVariables: ['product', 'aspect2'],
partialVariables: { aspect1: '电池续航' },
});
const prompt = await template.format({
product: '智能手机',
aspect2: '拍照质量',
});
console.log('提示词1:', prompt);此外,还可以通过链式调用 .partial() 方法进行预填充:
import { PromptTemplate } from '@langchain/core/prompts';
const baseTemplate = PromptTemplate.fromTemplate(
'请评价{product}的优缺点,包括{aspect1}和{aspect2}。',
);
const template = await baseTemplate.partial({ aspect1: '电池续航' });
const prompt = await template.format({
product: '智能手机',
aspect2: '拍照质量',
});
console.log('提示词1:', prompt);ChatPromptTemplate 的应用
使用说明
ChatPromptTemplate 是 LangChain 中用于构建聊天消息列表的模板类,适用于需要维护多角色和对话历史的应用场景。其主要特点包括:
- 角色支持:可以轻松定义系统、人类用户及 AI 角色的消息格式。
- 参数类型:通常以元组形式提供,如 (role: str, content: str | list[dict])。
通过使用 ChatPromptTemplate 可以更有效地处理复杂的对话逻辑和多轮次交流场景。
模板调用的几种方式
在使用 ChatPromptTemplate 时,可以通过三种主要方法来生成提示词。每种方法都有其特定的应用场景和返回类型。
1. invoke
此方法是异步的,需要使用 await 关键字进行调用。它将输入变量映射到对应的模板中,并返回一个包含完整消息对象数组的结果。
const res = await chatPromptTemplate.invoke({
role: '编程',
question: '什么是NestJS',
});2. format
此方法是同步的,并返回一个纯文本字符串。适用于需要快速生成提示词而不需要处理复杂消息对象的情况。
const res = chatPromptTemplate.format({
role: '编程',
question: '什么是NestJS',
});3. formatMessages
此方法也是异步的,返回一个包含消息对象数组的结果。这种形式非常适合需要直接处理聊天系统中的消息结构。
const res = await chatPromptTemplate.formatMessages({
role: '编程',
question: '什么是NestJS',
});插入消息列表:MessagesPlaceholder
当你希望在动态构建提示词时插入可变的消息列表,可以使用 MessagesPlaceholder。它允许你在模板中指定一个占位符位置,并在此处插入预先定义好的消息列表。
const chatPromptTemplate = ChatPromptTemplate.fromMessages([
['system', '你是一个AI助手,你的名字叫{name}'],
// 消息占位符
new MessagesPlaceholder('msgs'),
]);准备调用参数时,你可以提供一个包含实际消息对象的数组来填充这个占位符。
const result = await chatPromptTemplate.invoke({
name: '小智',
msgs: [
new HumanMessage('我的问题是:1 + 2 * 3 = ?'),
new AIMessage('1 + 2 * 3 = 7'),
],
});少量样本示例的提示词模板
在设计复杂的聊天系统时,使用少量的样本来指导模型生成更加准确和特定的答案是一种常见策略。这种方式不仅可以提高模型的理解能力,还可以确保生成的回答符合预期格式。
const examples = [
{ input: '2+2', output: '4', description: '加法运算' },
{ input: '5-2', output: '3', description: '减法运算' },
];通过将这些样例转换为对话形式,并插入到聊天模板中,可以指导模型如何处理新的输入。
const exampleMessages = examples.flatMap((example) => [
new HumanMessage(`算式:${example.input},请计算并说明`),
new AIMessage(`结果:${example.output},说明:${example.description}`),
]);最终构建一个包含这些示例的完整提示词模板。
const prompt = ChatPromptTemplate.fromMessages([
['system', '你是数学专家,参考对话示例回答问题,格式和示例保持一致'],
// 插入所有少样本对话
...exampleMessages,
// 用户新问题
['human', '算式:{input},请计算并说明'],
]);调用此模板生成提示词,并使用语言模型进行处理。
const messages = await prompt.invoke({ input: '2*5' });
const response = await this.llm.invoke(messages);
console.log(response.content); // 输出结果:结果:10,说明:乘法运算通过这种方式,你可以有效地利用少量样例来指导模型生成高质量的回答。
> 🔗 相关阅读:LangChain.js 架构设计深度剖析