LangChain学习之提示词模板 (Prompts) - 练习(2/8)

模块 2: 提示词模板 (Prompts) - 练习

练习目标

  1. 熟练使用 PromptTemplate 创建和格式化包含变量的提示词。
  2. 熟练使用 ChatPromptTemplate 创建和格式化包含不同角色消息的聊天提示词。
  3. 理解并实践 FewShotPromptTemplate,通过示例引导模型行为。

准备工作

  1. 确保已完成模块 1 的环境搭建。
  2. 准备好您的 DeepSeek API 密钥。

练习步骤

步骤 1: 使用 PromptTemplate 生成产品描述

创建一个名为 product_description.ts 的文件,使用 PromptTemplate 为不同的产品生成描述。模板应包含 product_namefeatures 两个变量。

typescript 复制代码
// product_description.ts
import 'dotenv/config';
import { PromptTemplate } from "@langchain/core/prompts";
import { ChatOpenAI } from "@langchain/openai";
import { StringOutputParser } from "@langchain/core/output_parsers";

async function main() {
  const model = new ChatOpenAI({
    model: "deepseek-v4-flash",
    temperature: 0.7,
    apiKey: process.env.DEEPSEEK_API_KEY,
    configuration: {
      baseURL: "https://api.deepseek.com",
    },
  });
  const parser = new StringOutputParser();

  const promptTemplate = PromptTemplate.fromTemplate(
    "请为以下产品生成一个吸引人的描述。产品名称:{product_name},主要特点:{features}。"
  );

  const chain = promptTemplate.pipe(model).pipe(parser);

  console.log("正在为智能手表生成描述...");
  const result1 = await chain.invoke({
    product_name: "智能手表",
    features: "心率监测、GPS、NFC支付",
  });
  console.log("\n--- 智能手表描述 ---\n");
  console.log(result1);

  console.log("\n正在为智能音箱生成描述...");
  const result2 = await chain.invoke({
    product_name: "智能音箱",
    features: "语音助手、高保真音质、智能家居控制",
  });
  console.log("\n--- 智能音箱描述 ---\n");
  console.log(result2);
}

main().catch(console.error);

运行您的代码:

bash 复制代码
npx ts-node product_description.ts

步骤 2: 使用 ChatPromptTemplate 构建多角色对话

创建一个名为 chat_roles.ts 的文件,使用 ChatPromptTemplate 构建一个包含系统、人类和 AI 消息的对话。系统消息应定义 AI 的角色,人类消息应包含用户的问题,并预留一个 AI 消息的占位符。

typescript 复制代码
// chat_roles.ts
import 'dotenv/config';
import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate, AIMessagePromptTemplate } from "@langchain/core/prompts";
import { HumanMessage, AIMessage } from "@langchain/core/messages";

async function main() {
  const chatModel = new ChatOpenAI({
    model: "deepseek-v4-flash",
    temperature: 0.7,
    apiKey: process.env.DEEPSEEK_API_KEY,
    configuration: {
      baseURL: "https://api.deepseek.com",
    },
  });

  const chatPrompt = ChatPromptTemplate.fromMessages([
    SystemMessagePromptTemplate.fromTemplate("你是一个专业的心理咨询师,以耐心和同理心回答问题。"),
    HumanMessagePromptTemplate.fromTemplate("我最近感到压力很大,工作和生活都一团糟,我该怎么办?"),
    AIMessagePromptTemplate.fromTemplate("我理解你的感受,压力确实会让人感到困扰。我们可以一起探讨一些应对策略。\n{ai_response_placeholder}"), // 预留 AI 回复的占位符
  ]);

  // 格式化提示词,并填充 AI 回复的占位符
  const formattedMessages = await chatPrompt.formatMessages({
    ai_response_placeholder: "你愿意分享更多细节吗?比如是什么让你感到压力最大?",
  });

  console.log("正在进行心理咨询对话...");
  const response = await chatModel.invoke(formattedMessages);
  console.log("\n--- 对话结果 ---\n");
  console.log(response.content);
}

main().catch(console.error);

运行您的代码:

bash 复制代码
npx ts-node chat_roles.ts

步骤 3: 使用 FewShotPromptTemplate 进行情感分类

创建一个名为 few_shot_sentiment.ts 的文件,使用 FewShotPromptTemplate 通过少量示例来指导模型进行情感分类(正面/负面)。

typescript 复制代码
// few_shot_sentiment.ts
import 'dotenv/config';
import { ChatOpenAI } from "@langchain/openai";
import { FewShotPromptTemplate, PromptTemplate } from "@langchain/core/prompts";
import { StringOutputParser } from "@langchain/core/output_parsers";

async function main() {
  const model = new ChatOpenAI({
    model: "deepseek-v4-flash",
    temperature: 0,
    apiKey: process.env.DEEPSEEK_API_KEY,
    configuration: {
      baseURL: "https://api.deepseek.com",
    },
  });
  const parser = new StringOutputParser();// 将模型输出解析为字符串

  const examples = [
    {
      input: "这部电影太棒了,我非常喜欢!",
      output: "正面",
    },
    {
      input: "今天的会议很无聊,浪费时间。",
      output: "负面",
    },
    {
      input: "我收到了一个惊喜礼物,太开心了!",
      output: "正面",
    },
  ];

  const examplePrompt = new PromptTemplate({
    inputVariables: ["input", "output"],
    template: "文本: {input}\n情感: {output}",
  });

  const fewShotPrompt = new FewShotPromptTemplate({
    examples: examples,
    examplePrompt: examplePrompt,
    prefix: "请根据以下示例判断文本的情感(正面/负面):",
    suffix: "文本: {input}\n情感:",
    inputVariables: ["input"],
    exampleSeparator: "\n\n",
  });

  const chain = fewShotPrompt.pipe(model).pipe(parser);

  console.log("正在判断文本情感...");
  const result = await chain.invoke({
    input: "我对这次的客户服务非常不满意。",
  });
  console.log("\n--- 情感判断结果 ---\n");
  console.log(result);
}

main().catch(console.error);

运行您的代码:

bash 复制代码
npx ts-node few_shot_sentiment.ts

思考题

  1. 在什么情况下,您会选择使用 PromptTemplate 而不是 ChatPromptTemplate?反之亦然。
  2. FewShotPromptTemplate 中的 prefixsuffixexampleSeparator 参数有什么作用?尝试修改它们并观察对输出的影响。
  3. 除了情感分类,FewShotPromptTemplate 还可以应用于哪些场景?请举例说明。

纯文本任务用 PromptTemplate,对话角色用 ChatPromptTemplate

prefix 是总指令,suffix 引导输出,exampleSeparator 分隔示例

FewShot 适用于分类、抽取、格式转换、规则生成等几乎所有任务

相关推荐
小宋加油啊8 小时前
学习机械臂相关知识
学习
颜酱11 小时前
让 Agent 不再失忆:LangChain 短期记忆实战
langchain·agent
十月的皮皮12 小时前
C语言学习笔记20260606- 求月份天数三种写法
c语言·笔记·学习
马士兵教育12 小时前
Java还有前景吗?Java+AI大模型学习路线及项目?
java·人工智能·python·学习·机器学习
lizhihai_9913 小时前
股市学习心得-AI 产业链核心标的梳理清单
大数据·服务器·人工智能·科技·学习
装不满的克莱因瓶13 小时前
了解 LangChain 中的 LLM 与 ChatModel 的差异
人工智能·python·ai·langchain·llm·agent·chatmodel
吃好睡好便好13 小时前
说说科学爬山
学习·生活
颜酱13 小时前
LangChain 工具调用:从原理、入门到落地
langchain·llm
swipe14 小时前
别再把关系库和向量库拆开了:PostgreSQL 搭建 AI 长期记忆层实战
面试·langchain·llm