2.langchain中的prompt模板 (FewShotPromptTemplate)

本教程将介绍如何使用 LangChain 库中的 PromptTemplateFewShotPromptTemplate 来构建和运行提示(prompt),并通过示例数据展示其应用。

安装依赖

首先,确保你已经安装了 langchain 和相关依赖:

pip install langchain langchain_core langchain_chroma langchain_community

1. 创建 PromptTemplate

PromptTemplate 用于定义一个模板,该模板可以动态地插入变量。

代码示例

from langchain_core.prompts import PromptTemplateexample_prompt = PromptTemplate.from_template("Question: {question}\n{answer}")

解释

  • PromptTemplate.from_template 方法用于从给定的模板字符串创建一个 PromptTemplate 对象。
  • 模板字符串中的 {question}{answer} 是占位符,将在后续被实际数据替换。

2. 定义示例数据

示例数据是一个列表,每个元素是一个包含 questionanswer 的字典。

代码示例

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
""",},
]

解释

  • 每个字典包含一个问题和对应的答案。
  • 答案部分详细描述了求解问题的中间步骤和最终答案。

3. 使用 PromptTemplate 调用示例

代码示例

print(example_prompt.invoke(examples[0]).to_string())

输出

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

解释

  • example_prompt.invoke(examples[0]) 方法将示例数据中的第一个元素插入到模板中。
  • to_string() 方法将结果转换为字符串形式。

4. 创建 FewShotPromptTemplate

FewShotPromptTemplate 用于结合多个示例和一个后缀模板来生成最终的提示。

代码示例

from langchain_core.prompts import FewShotPromptTemplateprompt = FewShotPromptTemplate(examples=examples,example_prompt=example_prompt,suffix="Question: {input}",input_variables=["input"],
)print(prompt.invoke({"input": "Who was the father of Mary Ball Washington?"}).to_string()
)

输出

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 AliQuestion: 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, 1952Question: 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 BallQuestion: 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: NoQuestion: Who was the father of Mary Ball Washington?

解释

  • FewShotPromptTemplate 结合了多个示例和一个后缀模板。
  • examples 参数是之前定义的示例数据。
  • example_prompt 是之前创建的 PromptTemplate
  • suffix 是一个后缀模板,用于添加到所有示例之后。
  • input_variables 定义了后缀模板中使用的变量。

5. 使用语义相似度选择示例

SemanticSimilarityExampleSelector 用于根据输入问题的语义相似度选择最相关的示例。

代码示例

from langchain_chroma import Chroma
from langchain_core.example_selectors import SemanticSimilarityExampleSelector
from langchain_community.embeddings import ZhipuAIEmbeddingsembed = ZhipuAIEmbeddings(model="embedding-3",api_key="your api key",
)example_selector = SemanticSimilarityExampleSelector.from_examples(examples,embed,Chroma,k=1,
)question = "Who was the father of Mary Ball Washington?"
selected_examples = example_selector.select_examples({"question": question})
print(f"Examples most similar to the input: {question}")
for example in selected_examples:print("\n")for k, v in example.items():print(f"{k}: {v}")

输出

Examples most similar to the input: Who was the father of Mary Ball 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 Ballquestion: Who was the maternal grandfather of George Washington?

解释

  • ZhipuAIEmbeddings 用于生成问题的嵌入向量。
  • SemanticSimilarityExampleSelector.from_examples 创建一个示例选择器,用于根据语义相似度选择示例。
  • k=1 表示选择最相似的一个示例。
  • select_examples 方法根据输入问题选择最相似的示例。

总结

本教程展示了如何使用 LangChain 中的 PromptTemplateFewShotPromptTemplate 来构建和运行提示,并通过语义相似度选择最相关的示例。这些工具在构建复杂的提示和生成高质量回答方面非常有用。希望这个教程对你有所帮助!

参考链接:https://python.langchain.com/v0.2/docs/how_to/few_shot_examples/

希望这个教程对你有所帮助!如果有任何问题,欢迎随时提问。

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

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

相关文章

如何在 Microsoft Edge 中设置代理: 快速而简单的方法

你知道在 Microsoft Edge 中设置代理可以大大提升浏览体验吗?无论您是想提高隐私保护、访问受地理位置限制的内容,还是想更高效地浏览网页,代理服务器都能改变一切。 本指南将介绍如何在 Microsoft Edge 中设置代理,解决常见的代…

【机器学习】近似分布的熵到底是p(x)lnq(x)还是q(x)lnq(x)?

【1】通信的定义 信息量(Information Content)是信息论中的一个核心概念,用于定量描述一个事件发生时所提供的“信息”的多少。它通常用随机变量 𝑥的概率分布来定义。事件 𝑥发生所携带的信息量由公式给出&#xff1…

Excel如何批量导入图片

这篇文章将介绍在Excel中如何根据某列数据,批量的导入与之匹配的图片。 准备工作 如图,我们准备了一张员工信息表以及几张员工的照片 可以看到,照片名称是每个人的名字,与Excel表中的B列(姓名)对应 的卢易…

【操作系统】操作系统的特征

操作系统的七个基本特征 并发性(Concurrence) 并发性是指操作系统在同一时间间隔内执行和调度多个程序的能力,提高资源利用率和系统效率。尽管多个任务可能在同一时刻看似同时进行,但实际上,CPU在多个任务之间快速切…

iPhone 17 Air看点汇总:薄至6mm 刷新苹果轻薄纪录

我们姑且将这款iPhone 17序列的超薄SKU称为“iPhone 17 Air”,Jeff Pu在报告中提到,我同意最近关于 iPhone 17超薄机型采用6 毫米厚度超薄设计的传言。 如果这一测量结果被证明是准确的,那么将有几个值得注意的方面。 首先,iPhone…

springboot嗨玩旅游网站

摘 要 嗨玩旅游网站是一个专为旅行爱好者打造的在线平台。我们提供丰富多样的旅游目的地信息,包括景点信息、旅游线路、商品信息、社区信息、活动推广等,帮助用户轻松规划行程。嗨玩旅游网站致力于为用户提供便捷、实用的旅行服务,让每一次旅…

LLM学习笔记(2)会话补全Chat Completions、什么是JSON?

什么是会话补全Chat Completions? 功能目标:处理多轮对话。 它模拟对话的逻辑,比如聊天机器人对用户消息的回应。使用的模型主要是针对对话型应用优化的模型,例如gpt-3.5-turbo或gpt-4。 什么是JSON? JSON 本质上是…

C++和js对比

1. 变量定义 C&#xff1a; #include <iostream> int main() {// 定义整型变量int num 10;// 定义浮点型变量double pi 3.14159;// 定义字符型变量char ch A;std::cout << "num: " << num << ", pi: " << pi << &…

SpringBoot与MongoDB深度整合及应用案例

SpringBoot与MongoDB深度整合及应用案例 在当今快速发展的软件开发领域&#xff0c;NoSQL数据库因其灵活性和可扩展性而变得越来越流行。MongoDB&#xff0c;作为一款领先的NoSQL数据库&#xff0c;以其文档导向的存储模型和强大的查询能力脱颖而出。本文将为您提供一个全方位…

潜水打捞系统的功能概率和使用方法_深圳鼎跃

潜水打捞系统是用于帮助打捞沉物&#xff0c;提供足够的浮力支持&#xff0c;确保沉物从水底浮升到水面。它是一种高强度的袋状结构&#xff0c;能够在水下提供调节浮力的功能&#xff0c;广泛应用于水下打捞、海上救援、沉船打捞等领域。 一、功能概述 潜水打捞系统主要功能为…

网络互助在中国 共筑健康保障新生态

在数字化的浪潮中,网络互助行业以其独特的普惠价值和发展潜力,迅速在中国的健康保障领域崭露头角。网络互助行业以其低门槛、普惠性特点,有效缓解了中低收入人群大病医疗资金的压力,避免了因病致贫的风险。据艾媒咨询数据显示,2019年中国网络互助行业救助总人数超过3万人,救助总…

linux:python2.7.x升级至3.13.0详细记录(含踩坑内容)

部署linux系统默认2.7.x环境&#xff0c;但是有些项目部署需3.x以上&#xff0c;由于低版本也存在高风险漏洞&#xff0c; 查看openSSL版本信息 高于1.1.1 直接安装即可 [rootlocalhost ~]# openssl version OpenSSL 1.1.1f 31 Mar 2020 [rootlocalhost ~]#直接安装python3…

SpringMVC接收请求参数

&#xff08;5&#xff09;请求参数》五种普通参数 1.普通参数 代码块 RequestMapping("/commonParam") ResponseBody public String commonParam(String name,int age){System.out.println("普通参数传递 name > "name);System.out.println("普通…

洛谷P1597

语句解析 - 洛谷 语句解析 题目背景 木有背景…… 题目描述 一串长度不超过255的 PASCAL 语言代码&#xff0c;只有 a,b,c 三个变量&#xff0c;而且只有赋值语句&#xff0c;赋值只能是一个一位的数字或一个变量&#xff0c;每条赋值语句的格式是 [变量]:[变量或一位整数…

CPU 内存加压工具 stress-ng 介绍

01 文章背景介绍 在实车测试时&#xff0c;除了感知算法外&#xff0c;往往还会有别的 APP 在同时运行&#xff0c;从而挤压算法的资源占用&#xff0c;影响模型性能&#xff0c;降低部署效果。因此在项目早期做板端验证的时候&#xff0c;我们就可以使用一些工具对 CPU 和内存…

(C语言)文件操作

目录 文件 程序文件 数据文件 文件名 ​编辑数据文件的分类 文件的打开和关闭 流 标准流 1&#xff09;stdin 2&#xff09;stdout 3&#xff09;stderr 文件指针 文件的打开和关闭 对文件内容操作的函数 1&#xff09;fgetc&#xff0c;fputc 2&#xff09;fp…

低代码开发平台搭建思考与实战

什么是低代码开发平台&#xff1f; 低代码开发平台是一种平台软件&#xff0c;人们能通过它提供的图形化配置功能&#xff0c;快速配置出满足各种特定业务需求的功能软件。 具有以下特点&#xff1a; 提供可视化界面进行程序开发0代码或少量代码快速生成应用 什么是低代码产…

Axure设计之日期时间范围选择器

在产品设计和原型制作过程中&#xff0c;日期时间范围选择器是一个常见的需求。Axure作为一个强大的原型设计工具&#xff0c;能够帮助我们快速实现这一功能。通过利用Axure的动态面板、中继器、文本框、按钮以及时间函数&#xff0c;我们可以轻松制作一个功能完备的日期时间范…

汽车资讯新趋势:Spring Boot技术解读

5系统详细实现 5.1 管理员模块的实现 5.1.1 用户信息管理 汽车资讯网站的系统管理员可以管理用户&#xff0c;可以对用户信息修改删除审核以及查询操作。具体界面的展示如图5.1所示。 图5.1 用户信息管理界面 5.1.2 汽车品牌管理 系统管理员可以汽车品牌信息进行添加&#xf…

代码随想录第三十七天

52.携带研究材料 题目描述 小明是一位科学家&#xff0c;他需要参加一场重要的国际科学大会&#xff0c;以展示自己的最新研究成果。他需要带一些研究材料&#xff0c;但是他的行李箱空间有限。这些研究材料包括实验设备、文献资料和实验样本等等&#xff0c;它们各自占据不同…