【LangChain.js学习】 提示词模板

37 阅读4分钟

核心说明

LangChain.js 提供多种提示词模板(PromptTemplate),用于规范化构建大模型输入,替代硬编码的字符串拼接,提升交互的精准性、复用性和可维护性。以下结合通义千问翻译场景,讲解三类核心模板的用法和适用场景。

基础提示词模板(PromptTemplate)

核心特点

最基础的模板类型,通过 {变量名} 占位符动态填充内容,语法简洁,学习成本低,适用于单轮、无复杂格式要求的指令构建。

调用代码

import { PromptTemplate } from "@langchain/core/prompts"
import { ChatOpenAI } from "@langchain/openai"// 1. 定义基础模板,通过{text}占位符指定动态参数
const promptTemplate = PromptTemplate.fromTemplate("请帮我将中文翻译成英文:{text}")
​
// 2. 填充模板参数,生成最终提示词
const promptTemplateStr = await promptTemplate.format({ text: "你好" })
​
// 3. 初始化通义千问对话模型
const chatModel = new ChatOpenAI({
    // 模型版本:qwen-max(旗舰版)/qwen-plus(标准版)
    model: "qwen-max",
    configuration: {
        // 阿里百炼OpenAI兼容接口固定地址,不可修改
        baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
        // 替换为个人有效阿里百炼API Key(从阿里云灵积平台获取)
        apiKey: "[你的阿里百炼API Key]",
    },
})
​
// 4. 调用模型并输出结果(await需包裹在async函数中)
async function callBasicTemplate() {
    const response = await chatModel.invoke(promptTemplateStr)
    console.log(response.content) // 输出示例:Hello
}
​
callBasicTemplate();

少样本提示词模板(FewShotPromptTemplate)

核心特点

通过「示例(examples)」引导模型学习输出格式/风格,解决模型输出不规范的问题,适合固定格式翻译、结构化输出、风格对齐等场景。

调用代码

import { FewShotPromptTemplate, PromptTemplate } from "@langchain/core/prompts"
import { ChatOpenAI } from "@langchain/openai"// 1. 定义少样本模板
const fewShotPromptTemplate = new FewShotPromptTemplate({
    // 前缀:定义任务核心要求(固定文本)
    prefix: "请帮我将中文翻译成英文",
    // 后缀:定义动态输入的占位符
    suffix: "中文:{text}",
    // 示例模板:定义单个示例的展示格式
    examplePrompt: PromptTemplate.fromTemplate("中文:{text}\n英文:{translation}"),
    // 示例数据:提供参考示例,引导模型输出风格
    examples: [
        { text: "你好", translation: "Hello" },
        { text: "你好吗?", translation: "How are you?" },
    ],
    // 输入变量:声明需要动态填充的参数名(必填)
    inputVariables: ["text"],
})
​
// 2. 填充模板参数
const promptTemplateStr = await fewShotPromptTemplate.format({ text: "你好" })
​
// 3. 初始化模型
const chatModel = new ChatOpenAI({
    model: "qwen-max",
    configuration: {
        baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
        apiKey: "[你的阿里百炼API Key]",
    },
})
​
// 4. 调用模型
async function callFewShotTemplate() {
    const res = await chatModel.invoke(promptTemplateStr)
    console.log(res.content) // 输出示例:Hello
}
​
callFewShotTemplate();

对话提示词模板(ChatPromptTemplate)

核心特点

专为对话模型设计,原生支持 system/human/ai 多角色设定,能精准预设模型行为和上下文,是多轮对话、角色化交互的首选模板。

调用代码

import { ChatPromptTemplate } from "@langchain/core/prompts"
import { ChatOpenAI } from "@langchain/openai"// 1. 定义对话模板,指定多角色消息
const chatPromptTemplate = ChatPromptTemplate.fromMessages([
    // system角色:预设模型身份、能力和行为规则
    ["system", "你是一个专业的翻译,将用户输入的中文翻译成英文,仅返回翻译结果"],
    // human角色:定义用户输入的占位符
    ["human", "{text}"]
])
​
// 2. 填充模板参数
const promptTemplateStr = await chatPromptTemplate.format({ text: "你好" })
​
// 3. 初始化模型
const chatModel = new ChatOpenAI({
    model: "qwen-max",
    configuration: {
        baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
        apiKey: "[你的阿里百炼API Key]",
    },
})
​
// 4. 调用模型
async function callChatTemplate() {
    const res = await chatModel.invoke(promptTemplateStr)
    console.log(res.content) // 输出示例:Hello
}
​
callChatTemplate();

三类模板对比与选型建议

模板类型核心优势适用场景核心参数/语法
PromptTemplate简单易用、轻量化单轮简单指令、无格式要求的文本生成fromTemplate + 单个占位符
FewShotPromptTemplate示例引导、输出格式可控固定格式翻译、结构化输出、模型风格对齐prefix/suffix + examples
ChatPromptTemplate多角色设定、上下文感知多轮对话、精准预设模型行为(如翻译/客服)fromMessages + system/human角色

核心总结

  • 所有模板的核心逻辑是「模板定义 → 参数填充 → 模型调用」,通过占位符实现提示词的动态复用,避免硬编码字符串;
  • ChatPromptTemplate 是对话模型的最佳搭配,支持多角色设定,能精准约束模型行为,交互性和实用性最强;
  • FewShotPromptTemplate 适合需要模型学习示例的场景,示例越多,输出格式越规范,尤其适合结构化输出需求;
  • PromptTemplate 作为基础模板,适合快速实现简单需求,是学习其他复杂模板的基础;