【LangChain】使用LangChain的提示词模板:技巧与总结

news2024/9/21 2:47:50

在这里插入图片描述

😁 作者简介:前端开发爱好者,致力学习前端开发技术
⭐️个人主页:夜宵饽饽的主页
❔ 系列专栏:JavaScript小贴士
👐学习格言:成功不是终点,失败也并非末日,最重要的是继续前进的勇气

​🔥​前言:

这里是关于LangChain框架中的提示词模板使用的技巧,希望可以帮助到大家,欢迎大家的补充和纠正

文章目录

    • 一、使用LangChain的提示词模板:技巧与总结
      • 1、格式化示例集
      • 2、示例选择器来组合提示词模板
      • 3、在聊天模型中使用合适的少数示例
      • 4、如何部分格式化提示词模板

一、使用LangChain的提示词模板:技巧与总结

1、格式化示例集

我们可以使用使用FewShotPromptTemplate来格式化示例集

const examples = [
  {
    question: "Who lived longer, Muhammad Ali or Alan Turing?",
    answer: `
  Are follow up questions needed here: Yes.
  Follow up: How old was Muhammad Ali when he died?
  Intermediate answer: Muhammad Ali was 74 years old when he died.
  Follow up: How old was Alan Turing when he died?
  Intermediate answer: Alan Turing was 41 years old when he died.
  So the final answer is: Muhammad Ali
  `,
  },
  {
    question: "When was the founder of craigslist born?",
    answer: `
  Are follow up questions needed here: Yes.
  Follow up: Who was the founder of craigslist?
  Intermediate answer: Craigslist was founded by Craig Newmark.
  Follow up: When was Craig Newmark born?
  Intermediate answer: Craig Newmark was born on December 6, 1952.
  So the final answer is: December 6, 1952
  `,
  },
  {
    question: "Who was the maternal grandfather of George Washington?",
    answer: `
  Are follow up questions needed here: Yes.
  Follow up: Who was the mother of George Washington?
  Intermediate answer: The mother of George Washington was Mary Ball Washington.
  Follow up: Who was the father of Mary Ball Washington?
  Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
  So the final answer is: Joseph Ball
  `,
  },
  {
    question:
      "Are both the directors of Jaws and Casino Royale from the same country?",
    answer: `
  Are follow up questions needed here: Yes.
  Follow up: Who is the director of Jaws?
  Intermediate Answer: The director of Jaws is Steven Spielberg.
  Follow up: Where is Steven Spielberg from?
  Intermediate Answer: The United States.
  Follow up: Who is the director of Casino Royale?
  Intermediate Answer: The director of Casino Royale is Martin Campbell.
  Follow up: Where is Martin Campbell from?
  Intermediate Answer: New Zealand.
  So the final answer is: No
  `,
  },
];

const examplePrompt = PromptTemplate.fromTemplate(
  "Question:{question} \n {answer}"
)

const prompt = new FewShotPromptTemplate({
  examples,
  examplePrompt,
  suffix: "Question:{input}",
  inputVariables: ["input"]
})

const formatted = await prompt.format({
  input: "Who was the father of Mary Ball Washington?"
})

console.log(formatted)

最后输出的示例中,会将examples中的示例加入到提示词模板的前面,组合成为完整的示例

//提示词模板输出结果
Question:Who lived longer, Muhammad Ali or Alan Turing? 
 
  Are follow up questions needed here: Yes.
  Follow up: How old was Muhammad Ali when he died?
  Intermediate answer: Muhammad Ali was 74 years old when he died.
  Follow up: How old was Alan Turing when he died?
  Intermediate answer: Alan Turing was 41 years old when he died.
  So the final answer is: Muhammad Ali
  

Question:When was the founder of craigslist born? 
 
  Are follow up questions needed here: Yes.
  Follow up: Who was the founder of craigslist?
  Intermediate answer: Craigslist was founded by Craig Newmark.
  Follow up: When was Craig Newmark born?
  Intermediate answer: Craig Newmark was born on December 6, 1952.
  So the final answer is: December 6, 1952
  

Question:Who was the maternal grandfather of George Washington? 
 
  Are follow up questions needed here: Yes.
  Follow up: Who was the mother of George Washington?
  Intermediate answer: The mother of George Washington was Mary Ball Washington.
  Follow up: Who was the father of Mary Ball Washington?
  Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
  So the final answer is: Joseph Ball
  

Question:Are both the directors of Jaws and Casino Royale from the same country? 
 
  Are follow up questions needed here: Yes.
  Follow up: Who is the director of Jaws?
  Intermediate Answer: The director of Jaws is Steven Spielberg.
  Follow up: Where is Steven Spielberg from?
  Intermediate Answer: The United States.
  Follow up: Who is the director of Casino Royale?
  Intermediate Answer: The director of Casino Royale is Martin Campbell.
  Follow up: Where is Martin Campbell from?
  Intermediate Answer: New Zealand.
  So the final answer is: No
  

Question:Who was the father of Mary Ball Washington?

2、示例选择器来组合提示词模板

我们可以使用 SemanticSimilarityExampleSelector类来使用嵌入模型来计算输入样本和少数样本之间的相似性,并使用向量存储来执行最近邻搜索

let AzureOpenAIEmbedding = await getAzureEmbeddings()

const exampleSelecttor = await SemanticSimilarityExampleSelector.fromExamples(
  examples,
  AzureOpenAIEmbedding,
  MemoryVectorStore,
  {
    k: 1
  }
)
const question = "Who was the father of Mary Ball Washington?"
const selectedExamples = await exampleSelecttor.selectExamples({ question })
console.log("🚀 ~ mainScript2 ~ selectedExamples:", selectedExamples)/**
🚀 ~ mainScript2 ~ selectedExamples: [
  {
    question: 'Who was the maternal grandfather of George Washington?',
    answer: '\n' +
      '  Are follow up questions needed here: Yes.\n' +
      '  Follow up: Who was the mother of George Washington?\n' +
      '  Intermediate answer: The mother of George Washington was Mary Ball Washington.\n' +
      '  Follow up: Who was the father of Mary Ball Washington?\n' +
      '  Intermediate answer: The father of Mary Ball Washington was Joseph Ball.\n' +
      '  So the final answer is: Joseph Ball\n' +
      '  '
  }
]
**/

当调用exampleSelecttor中的selectExamples方法的时候,它会根据输入的question来使用向量搜索从示例集中找出与输入的问题最相似的示例集

3、在聊天模型中使用合适的少数示例

在提示词结构中有一个重要的概念是示例,给大模型的输入中提供示例会让输出结果更加精准,而示例选择器可以实现一个效果:根据用户的输入选择合适的示例

在langchian中是可以实现这个功能的,使用SemanticSimilarityExampleSelector示例选择器,根据用户的输入使用向量数据库匹配更加合适的例子

实现步骤:

  • 先准备一些示例数据-最好是数组形式的
  • 然后再实例化向量大模型
  • 创建好向量数据库
  • 使用模型选择器

完整的代码如下:

  //1、先准备一个例子,这个例子是数组对象类型的,对象需要拥有input哥output
  const examples = [
    { input: "2+2", output: "4" },
    { input: "2+3", output: "5" },
    { input: "2+4", output: "6" },
    { input: "What did the cow say to the moon?", output: "nothing at all" },
    {
      input: "Write me a poem about the moon",
      output:
        "One for the moon, and one for me, who are we to talk about the moon?",
    },
  ];

  //2、从例子中格式化数据,准备好插入到向量数据库中
  const toVectorize=examples.map(
    (examples)=>`${examples.input}${examples.output}`
  )

  //3、实例化向量数据库的查询
  const vectorStore=await MemoryVectorStore.fromTexts(
    toVectorize,
    examples,
    await getAzureEmbeddings()
  )

  //4、创建一个选择器
  const exampleSelect=new SemanticSimilarityExampleSelector({
    vectorStore,
    k:1
  })

  //5、使用
  const result=await exampleSelect.selectExamples({input:"hourse"})
  // console.log("🚀 ~ mainScript4 ~ result:", result)

  //6、和动态模版添加方法组合
  const messsageTemplate=ChatPromptTemplate.fromMessages([
    ["user","{input}"],
    ["ai","{output}"]
  ])
  const fewPrompt=new FewShotChatMessagePromptTemplate({
    examplePrompt:messsageTemplate,
    // examples:result,
    exampleSelector:exampleSelect,
    inputVariables:['input']
  })

  //  //原文档有bug,这里是修复的,不可以直接传入fewShotPrompt,而是需要实例化一下,封装成为消息类型
  const finalPrompt=ChatPromptTemplate.fromMessages([
    ["system","You are a wondrous wizard of math."],
    ChatPromptTemplate.fromMessages((await fewPrompt.invoke({})).toChatMessages()),
    ["user","{input}"],
  ])

  //7、模型结合使用
  const azureModel=await getAzureModel()
  const chain = finalPrompt.pipe(azureModel);

  console.log(await chain.invoke({ input: "What's 3+3?" }))

4、如何部分格式化提示词模板

想要对提示模板进行部分分配的一个常见用例是,如果您在其他变量之前访问提示中的某些变量。例如,假设您有一个需要两个变量(foobaz)的提示模板。如果你在链的早期获得 foo 值,但后来获得 baz 值,那么在链中完全传递这两个变量可能会很不方便。相反,你可以用 foo 值对 prompt 模板进行部分化处理,然后传递部分 prompt 模板并使用它

// 第一种使用,在partial方法中进行实例化
const prompt = new PromptTemplate({
    template: "{foo}{bar}",
    inputVariables: ["foo", "bar"]
})

const partialPrompt = await prompt.partial({
    foo: "foo"
})

const fromattedPrompt = await partialPrompt.format({
    bar: "baz"
})

console.log(fromattedPrompt)

// 第二种使用,在模板初始化中进行实例化
const prompt = new PromptTemplate({
  template: "{foo}{bar}",
  inputVariables: ["bar"],
  partialVariables: {
      foo: "foo"
  }
})

const formattedPrompt = await prompt.format({
  bar: "baz",
})
// console.log("🚀 ~ mainScript2 ~ formattedPrompt:", formattedPrompt)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2095438.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【困难】 猿人学web第一届 第15题 备周则意怠,常见则不疑

数据接口分析 数据接口 https://match.yuanrenxue.cn/api/match/15 请求时需要携带 page 页码,m为加密参数 cookie中没有加密信息,携带 SessionId请求即可 加密参数还原 查看数据接口对应的 requests 栈 m参数 是通过 window.m() 方法执行后得到的 打上…

【免费分享】2024最新优化算法-黑翅鸢算法BKA

黑翅鸢优化算法(Black-winged kite algorithm,BKA)是一种受自然界启发的群体智能优化算法,其设计灵感源自黑翅鸢(Black-winged kite)的生存策略。黑翅鸢在攻击和迁徙过程中展现出的高度适应性和智能行为&am…

3分钟带你手把手安装一款音乐制作神器——FL Studio 24.1.1.4285中文版

大家好,今天我要给大家介绍一款音乐制作神器——FL Studio 24.1.1.4285中文版。这款软件可是音乐制作界的翘楚,无论是专业人士还是音乐爱好者,都会为它的强大功能和易用性所折服。 我们来看看FL Studio的特点。这是一款全能型的音乐工作站&am…

ACL实验配置学习笔记

拓扑描述: R1作为所有PC的网关; 财务部用户:192.168.1.0/24 市场部用户:192.168.2.0/24 Server1:HTTP服务器地址为7.7.7.7/24 PC 2:192.168.1.2 PC 5::192.168.2.2 PC 3:&…

干货分享|分享一款高效的软件卸载神器 Geek Uninstaller

问题:卸载软件时,时常会留下残留文件和注册表。当遇到流氓软件,还常常卸载失败。 1.软件介绍 特点:高效快速,小巧便携。100% 免费 2.下载方法 官方下载网站:Geek Uninstaller - the best FREE uninstaller …

《深入理解JAVA虚拟机(第2版)》- 第6章 - 学习笔记

第6章 类文件结构 6.1 概述 字节码和二级制本地机器码(Native Code)是用来存储程序编译后的结果的,是二种程序存储结构。 6.2 无关性的基石 这里说的无关性,分为:平台无关性和语言无关性。 平台无关性:…

Codeforces Round 913 (Div. 3) D. Jumping Through Segments (二分*1400)

很容易看出这道题应该二分答案,本题的难点在于对于mid的验证。 找距离肯定是不难,难就难在我们输入的区间并不是按照左右顺序排列的,有的区间可能涵盖住了另一个区间,也就是说在这里我们需要进行的是左右的移动。 那么我们根本无…

VBA数据库解决方案第十四讲:如何在数据库中动态删除和建立数据表

《VBA数据库解决方案》教程(版权10090845)是我推出的第二套教程,目前已经是第二版修订了。这套教程定位于中级,是学完字典后的另一个专题讲解。数据库是数据处理的利器,教程中详细介绍了利用ADO连接ACCDB和EXCEL的方法…

【楼兰图腾】

题目 思路 本质上这个问题就是在求分别在一个数左边和右边的,大于该数的个数的乘积(小于同理) 维护一个下标指元素大小的线段树来方便求大于和小于某数值的元素个数 通过从左到右遍历,来确定此时的线段树状态一定不包括右边 因为…

【C++ Primer Plus习题】8.3

问题: 解答: #include <iostream> #include <string> #include <cctype> using namespace std;void function(string& str) {for (int i 0; i < str.size(); i){str[i]toupper(str[i]);} }int main() {string str;while (true){cout << "…

【超详细】深度学习的Hello World:使用pytroch训练一个自定义的手写体数字识别模型完整流程【附数据集与完整源码】

《博主简介》 小伙伴们好&#xff0c;我是阿旭。专注于人工智能、AIGC、python、计算机视觉相关分享研究。 &#x1f44d;感谢小伙伴们点赞、关注&#xff01; 《------往期经典推荐------》 一、AI应用软件开发实战专栏【链接】 项目名称项目名称1.【人脸识别与管理系统开发…

Unet改进15:添加TripletAttention||减少冗余计算和同时存储访问

本文内容:在不同位置添加TripletAttention注意力机制 目录 论文简介 1.步骤一 2.步骤二 3.步骤三 4.步骤四 论文简介 由于注意机制具有在通道或空间位置之间建立相互依赖关系的能力,近年来在各种计算机视觉任务中得到了广泛的研究和应用。在本文中,我们研究了轻量级但…

龙芯+FreeRTOS+LVGL实战笔记(新)——01准备开发环境

本专栏是笔者另一个专栏《龙芯RT-ThreadLVGL实战笔记》的姊妹篇&#xff0c;主要的区别在于实时操作系统的不同&#xff0c;章节的安排和任务的推进保持一致&#xff0c;并对源码做了改进和优化&#xff0c;各位可以先到本人主页下去浏览另一专栏的博客列表&#xff08;目前已撰…

C++STL之vector类:相关习题解析

目录 只出现一次的数字| 只出现一次的数字|| 只出现一次的数字||| 杨辉三角(vector>的理解) 删除排序数组中的重复项 删除排序数组中的重复项|| 数组中出现次数超过一半的数字 只出现一次的数字| . - 力扣&#xff08;LeetCode&#xff09; 思路&#xff1a; 我们都…

★ 算法OJ题 ★ 力扣15 - 三数之和

Ciallo&#xff5e;(∠・ω< )⌒☆ ~ 今天&#xff0c;芝麻凛将和大家一起做一道双指针算法题--三数之和~ 目录 一 题目 二 算法解析 三 编写算法 一 题目 15. 三数之和 - 力扣&#xff08;LeetCode&#xff09; 二 算法解析 解法一&#xff1a;排序 暴力枚举 利…

JavaEE:多线程进阶(常见的锁策略)

文章目录 常见的锁策略各种锁的概念 synchronized特点加锁过程 锁消除(编译器的优化策略)锁粗化(编译器的优化策略) 常见的锁策略 锁是一个非常广义的问题. synchronized只是市面上五花八门的锁的一种典型的实现.它是Java内置的,推荐使用的锁. 各种锁的概念 下面这些概念,一…

JavaScript程序结构

程序结构有三种&#xff1a;选择结构、循环结构 、顺序结构 一、选择结构 1、简介 根据条件进行判断&#xff0c;从而执行不同的操作&#xff0c;称为选择结构&#xff08;分支结构&#xff09;&#xff0c;其实就是条件判断 选择结构的类型&#xff1a;if、switch 2、if结…

第十七篇——九变篇:紧扣战略重心,别跑题

目录 一、背景介绍二、思路&方案三、过程1.思维导图2.文章中经典的句子理解3.学习之后对于投资市场的理解4.通过这篇文章结合我知道的东西我能想到什么&#xff1f; 四、总结五、升华 一、背景介绍 九变种前面偏向宏观给讲解了九变的含义&#xff1b;这一篇通过更加微观的…

如何基于numpy和scipy实现曲面的最大梯度计算与显示

大家在做三维可视化研究过程中,经常需要做三维曲面的绘制和相交分析,在不知道三维曲面方程的情况下,如何基于曲面散点数据计算曲面的最大梯度点和梯度线的三维可视化是大家基于曲面分析研究中的重点关注的问题,本文在python环境下,基于numpy、pandas、scipy和matplotlib等…

MYSQL————联合查询

联合多个表进行查询 设计数据时把表进行拆分&#xff0c;为了消除表中字段的依赖关系&#xff0c;比如部分函数依赖&#xff0c;传递依赖&#xff0c;这时会导致一条SQL查出来的数据&#xff0c;对于业务来说是不完整的&#xff0c;我们就可以使用联合查询把关系中的数据全部查…