当前位置: 首页 > news >正文

自然语言处理从入门到应用——LangChain:提示(Prompts)-[提示模板:创建自定义提示模板和含有Few-Shot示例的提示模板]

分类目录:《自然语言处理从入门到应用》总目录


创建自定义提示模板

假设我们希望LLM根据函数名称生成该函数的英文语言解释。为了实现这个任务,我们将创建一个自定义的提示模板,以函数名称作为输入,并格式化提示模板以提供函数的源代码。LangChain提供了一组默认的提示模板,可用于生成各种任务的提示。但是,在某些情况下,默认的提示模板可能无法满足我们的需求。例如,我们可能希望创建一个具有特定动态指令的提示模板,以适应我们的语言模型。在这种情况下,我们可以创建自定义的提示模板。

有两种不同的提示模板:

  • 字符串提示模板:提供一个简单的字符串格式提示
  • 聊天提示模板:生成一个更结构化的聊天API使用的提示

在本文中,我们将使用字符串提示模板创建一个自定义提示。要创建自定义字符串提示模板,有两个要求:

  • 它具有input_variables属性,用于公开提示模板期望的输入变量
  • 它公开一个format方法,该方法接受与预期的input_variables相对应的关键字参数,并返回格式化的提示

我们将创建一个自定义的提示模板,它以函数名称作为输入,并格式化提示以提供函数的源代码。为了实现这一点,让我们首先创建一个函数,该函数将根据函数名称返回函数的源代码。

import inspectdef get_source_code(function_name):# Get the source code of the functionreturn inspect.getsource(function_name)

接下来,我们将创建一个自定义的提示模板,该模板以函数名称作为输入,并格式化提示模板以提供函数的源代码:

from langchain.prompts import StringPromptTemplate
from pydantic import BaseModel, validatorclass FunctionExplainerPromptTemplate(StringPromptTemplate, BaseModel):"""一个自定义的提示模板,接受函数名作为输入,并格式化提示模板以提供函数的源代码。"""@validator("input_variables")def validate_input_variables(cls, v):"""验证输入变量的正确性。"""if len(v) != 1 or "function_name" not in v:raise ValueError("function_name必须是唯一的输入变量。")return vdef format(self, **kwargs) -> str:# 获取函数的源代码source_code = get_source_code(kwargs["function_name"])# 生成要发送给语言模型的提示prompt = f"""给定函数名和源代码,生成一个关于函数的英文语言解释。函数名:{kwargs["function_name"].__name__}源代码:{source_code}解释:"""return promptdef _prompt_type(self):return "function-explainer"

现在我们已经创建了一个自定义的提示模板,我们可以使用它来生成我们任务的提示:

fn_explainer = FunctionExplainerPromptTemplate(input_variables=["function_name"])# 为函数"get_source_code"生成一个提示
prompt = fn_explainer.format(function_name=get_source_code)
print(prompt)

输出:

给定函数名和源代码,生成一个关于函数的英文语言解释。
函数名:get_source_code
源代码:
def get_source_code(function_name):# Get the source code of the functionreturn inspect.getsource(function_name)解释:

创建含有Few-Shot示例的提示模板

在下文中,我们将学习如何创建含有Few-Shot示例的提示模板。我们将使用FewShotPromptTemplate类来创建一个含有Few-Shot示例的提示模板。该类可以接受一组示例或者一个ExampleSelector对象。在下文中,我们将分别为自我提问与搜索配置Few-Shot示例讨论这两种选项。

使用示例集

首先,创建一个Few-Shot示例的列表。每个示例应该是一个字典,其中键是输入变量,值是这些输入变量的值。

from langchain.prompts.few_shot import FewShotPromptTemplate
from langchain.prompts.prompt import PromptTemplateexamples = [{"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
"""}
]

然后,我们可以为Few Shot示例创建格式化程序。配置一个将Few Shot示例格式化为字符串的格式化程序。该格式化程序应该是一个PromptTemplate对象。

example_prompt = PromptTemplate(input_variables=["question", "answer"], template="Question: {question}\n{answer}")print(example_prompt.format(**examples[0]))
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

最后,创建一个FewShotPromptTemplate对象。该对象接受Few Shot示例和Few Shot示例的格式化程序作为输入。

prompt = FewShotPromptTemplate(examples=examples, example_prompt=example_prompt, suffix="Question: {input}", input_variables=["input"]
)print(prompt.format(input="Who was the father of Mary Ball Washington?"))

输出:

    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对象中,我们将把它们输入到一个ExampleSelector对象中。在下文中,我们将使用SemanticSimilarityExampleSelector类。该类根据示例与输入之间的相似度选择Few-Shot示例。它使用嵌入模型计算输入与Few-Shot示例之间的相似度,并使用向量存储执行最近邻搜索。

from langchain.prompts.example_selector import SemanticSimilarityExampleSelector
from langchain.vectorstores import Chroma
from langchain.embeddings import OpenAIEmbeddingsexample_selector = SemanticSimilarityExampleSelector.from_examples(# 这是可供选择的示例列表。examples,# 这是用于生成嵌入的嵌入类,用于衡量语义相似度。OpenAIEmbeddings(),# 这是用于存储嵌入并进行相似度搜索的向量存储类。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}")

输出:

Running Chroma using direct local API.
Using DuckDB in-memory for database. Data will be transient.
Examples most similar to the input: Who was the father of Mary Ball Washington?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

我们还可以将示例选择器应用于FewShotPromptTemplate。创建一个FewShotPromptTemplate对象。该对象接收示例选择器和用于Few-Shot示例的格式化程序:

prompt = FewShotPromptTemplate(example_selector=example_selector, example_prompt=example_prompt, suffix="Question: {input}", input_variables=["input"]
)print(prompt.format(input="Who was the father of Mary Ball Washington?"))

输出:

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: Who was the father of Mary Ball Washington?

参考文献:
[1] LangChain 🦜️🔗 中文网,跟着LangChain一起学LLM/GPT开发:https://www.langchain.com.cn/
[2] LangChain中文网 - LangChain 是一个用于开发由语言模型驱动的应用程序的框架:http://www.cnlangchain.com/

相关文章:

自然语言处理从入门到应用——LangChain:提示(Prompts)-[提示模板:创建自定义提示模板和含有Few-Shot示例的提示模板]

分类目录:《自然语言处理从入门到应用》总目录 创建自定义提示模板 假设我们希望LLM根据函数名称生成该函数的英文语言解释。为了实现这个任务,我们将创建一个自定义的提示模板,以函数名称作为输入,并格式化提示模板以提供函数的…...

d3dx9_30.dll如何修复,分享几种一键修复方法

d3dx9_30.dll是DirectX 的一个动态链接库文件,它包含了一些用于图形和游戏的函数和资源。在了解d3dx9_30.dll的解决方法和丢失原因之前,我们先来了解一下DirectX。DirectX是一套由微软开发的多媒体和游戏编程接口(API)集合。它提供…...

6.8 稀疏数组

6.8 稀疏数组 稀疏数组是一种数据结构,在程序中数据结构的思想,是非常重要的。例如 需求:编写五子棋游戏中,有存盘退出和续上盘的功能。分析问题:因为该二维数组的很多值是默认值0,因此记录了很多没有意义…...

ROS版本的ORB-SLAM3用RealSense D455相机实时运行测试

配置环境 1. C11 检查G版本,查看是否支持C11 一般g版本大于4.7即可 g -v 2. Pangolon 地址:https://github.com/stevenlovegrove/Pangolin 先安装OpenGL,Glew ### 编译orb-slam3发现pangolin编译错误排查的环境问题 sudo apt install p…...

Vue中对对象内容调用的Demo

目录 1.对象作为数据: 2.对象数组 在Vue中,你可以通过对象的键来调用对象中的各个部分的内容。下面是一些使用Vue调用对象各部分内容的示例: 1.对象作为数据: 如果你在Vue实例的数据中有一个对象,你可以使用点语法来…...

语音识别 — 特征提取 MFCC 和 PLP

一、说明 语音识别是一种技术,通过计算机和软件系统,将人们的口头语言转换为计算机可读的文本或命令。它使用语音信号处理算法来识别和理解人类语言,并将其转换为计算机可处理的格式。语音识别技术被广泛应用于许多领域,如语音助手…...

BES 平台 SDK之按键的配置

本文章是基于BES2700 芯片,其他BESxxx 芯片可做参考,如有不当之处,欢迎评论区留言指出。仅供参考学习用! BES 平台 SDK之LED的配置_谢文浩的博客-CSDN博客 关于系统LED简介可参考上一篇文章。链接如上所示! 一&…...

【Golang系统开发】搜索引擎(1) 如何快速判断网页是否已经被爬取

文章目录 1. 写在前面2. 数组存储3. 位图存储3.1 位图简介3.2 链表法3.3 开放寻址法 1. 写在前面 在实际工作中,我们经常需要判断一个对象是否存在,比如判断用户注册登陆时候,需要判断用户是否存在,再比如搜索引擎中的爬虫&#x…...

记录--一个好用的轮子 turn.js 实现仿真翻书的效果

这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助 国际惯例,官网链接 官网传送门 Github地址 github上有几个demos例子,介绍了基础用法。 我参考官网的例子,写了一个demo示例 安装 turn.js 依赖 jquery 库&#xff0…...

《Spring Boot源码解读与原理分析》书籍推荐

Spring Boot是目前Java EE开发中颇受欢迎的框架之一。依托于底层Spring Framework的基础支撑,以及完善强大的特性设计,Spring Boot已成为业界流行的应用和微服务开发基础框架。 《Spring Boot源码解读与原理分析》共14章,分为4个部分。第一部…...

C++ 什么时候使用 vector、list、以及 deque?

如果需要高效地快速访问(随即存取),并且不在乎插入和删除的效率,使用 vector 如果需要大量的插入和删除,而且不关心快速访问 (随即存取) ,使用 list 如果需要快速访问 (随即存取) ,并且关心两端数据插入和删除&#…...

视频创作者福音,蝰蛇峡谷NUC12SNKI7视频剪辑测评

英特尔NUC绝对是PC市场里最为特殊的产品,相比众多OEM设计制造的台式机而言,英特尔NUC主打小体积、高度集成化、强扩展性以及尽可能优异的性能表现。尤其是在主打游戏体验的NUC产品出现之后,更是将极致体验演绎到了极致。 在搭载独显的幻影峡谷…...

使用Qt中的QDir类进行目录操作

文章目录 概述QDir类的基本功能获取当前目录创建目录列出目录内容筛选目录内容筛选特定命名文件 复制文件和目录删除文件和目录更改文件名 应用场景总结 概述 Qt是一个跨平台的C应用程序开发框架,其中提供了许多方便的类来处理文件和目录操作。其中,QDi…...

qt服务器 网络聊天室

widget.cpp #include "widget.h" #include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget) {ui->setupUi(this);//给服务器指针实例化空间server new QTcpServer(this); }Widget::~Widget() {delete ui; }//启动…...

meanshift算法通俗讲解【meanshift实例展示】

meanshift算法原理 meanshift算法的原理很简单。假设你有一堆点集,还有一个小的窗口,这个窗口可能是圆形的,现在你可能要移动这个窗口到点集密度最大的区域当中。 如下图: 最开始的窗口是蓝色圆环的区域,命名为C1。蓝…...

正交变换和仿射变换

正交变换和仿射变换 平面的正交变换 正交点变换(保距变换) 平面上的一个保持任意两点距离不变的点变换 平面正交变换性质 正交变换的乘积是正交变换恒等变换是正交变换正交变换将(不)共线的三点映射成(不&#xff09…...

Electron 多端通信桥 MessageChannelMain和 MessagePortMain 坑点汇集

简介 MessageChannelMain 是 DOM MessageChannel 对象的主进程等价对象。 它的特有功能是创建一对已连接的 MessagePortMain 对象。 Electron 本身为了灵活追加 on("message") 机制,就说明该 MessageChannelMain 已经被创建了,而 Web 开发中&a…...

Html5播放器按钮在移动端变小的问题解决方法

Html5播放器按钮在移动端变小的问题解决方法 用手机浏览器打开酷播云视频&#xff0c;有时会出现播放器按钮太小的情况&#xff0c;此时只需在<head>中加入下面这段代码即可解决&#xff1a; <meta name"viewport" content"widthdevice-width, initia…...

Rust 开发环境搭建【一】

Rust 开发环境 推荐 搭建&#xff1a; 安装 rust 语言 以及 工具链 推荐安装方法&#xff1a;rustup curl --proto ‘https’ --tlsv1.2 -sSf https://sh.rustup.rs | sh 在国内如果访问速度慢&#xff0c;可以使用清华大学提供的镜像服务&#xff1a; https://mirrors.tu…...

C# Blazor 学习笔记(3):路由管理

文章目录 前言路由管理App.razor设置登录页面设置空布局 前言 我们知道使用Blazor的官方模板&#xff0c;我们会自动得到一个拥有侧边栏的布局页面。但是我们发现我们所有新建的页面都有侧边栏。有时候我们需要跳出这个布局&#xff0c;比如我要做登录页面的时候&#xff0c;我…...

int[]数组转Integer[]、List、Map「结合leetcode:第414题 第三大的数、第169题 多数元素 介绍」

文章目录 1、int[ ] 转 Integer[ ]:2、两道leetcode题遇到的场景:2.1、int[ ] 转 List<Integer> :2.2、int[ ] 转 Map: 1、int[ ] 转 Integer[ ]: public static void main(String[] args) {int[] nums {1, 2, 3}; Integer[] array Arrays.stream(nums).boxed().to…...

vue子传父的一种新方法:this.$emit(‘input‘, value)可实现实时向父组件传值

今天要说的就是利用v-model和this.$emit(‘input’,value)实现子传父。 众所周知&#xff0c;v-model是给input绑定&#xff0c;方便对表单的双向绑定。 其实&#xff0c;v-model是个语法糖&#xff0c;具体案例如下所示。 <input v-model"inputValue">相当于…...

【Web】web

dns与域名 网络是基于tcp/ip协议进行通信和连接的 应用层——传输层——网络层——数据链路层——物理层 每一定的台主机都有一个唯一且固定的地址标识——IP地址 IP地址的做用&#xff1a;1.区分用户和计算机&#xff1b;2.进行通信 IP地址由32位二进制数组成&#xff0c;…...

css中的bfc是什么?

什么bfc&#xff1f; BFC&#xff08;Block Formatting Context&#xff09;块级 格式化 上下文。 BFC就是页面上的一个隔离的独立盒子&#xff0c;容器里面的子元素和外面的元素不会相互影响。 为什么要bfc? bfc是我们去主动触发的,并不是自动就存在的,它是帮助我们解决cs…...

【前端知识】React 基础巩固(四十四)——其他Hooks(useContext、useReducer、useCallback)

React 基础巩固(四十四)——其他Hooks&#xff08;useContext、useReducer、useCallback&#xff09; 一、useContext的使用 在类组件开发时&#xff0c;我们通过 类名.contextType MyContext的方式&#xff0c;在类中获取context&#xff0c;多个Context或者在函数式组件中…...

华为云hcip核心知识笔记(数据库服务规划)

华为云hcip核心知识笔记&#xff08;数据库服务规划&#xff09; 1.云数据接库优势 1.1云数据库优点有&#xff1a; 易用性强&#xff1a;能欧快速部署和运行 高扩展&#xff1a;开放式架构和云计算存储分离 低成本&#xff1a;按需使用&#xff0c;成本更加低廉 2.云数据库r…...

【有趣的】关于Map的一些小测试

Map在代码中用到得非常多&#xff0c;它是无序的、key-value结构的&#xff0c;其读取会非常快。 今天看了个小文章Map判空 、空字符串、空key值等各种判断方法&#xff0c;你都掌握了吗&#xff1f;便自己也玩一下。 一、判空 因为对象已经new出来了&#xff0c;所以map指向的…...

【MATLAB第63期】基于MATLAB的改进敏感性分析方法IPCC,拥挤距离与皮尔逊系数法结合实现回归与分类预测

【MATLAB第63期】基于MATLAB的改进敏感性分析方法IPCC&#xff0c;拥挤距离与皮尔逊系数法结合实现回归与分类预测 思路 考虑拥挤距离指标与PCC皮尔逊相关系数法相结合&#xff0c;对回归或分类数据进行降维&#xff0c;通过SVM支持向量机交叉验证得到平均指标&#xff0c;来…...

AI 绘画Stable Diffusion 研究(二)sd模型ControlNet1.1 介绍与安装

部署包作者:秋葉aaaki 免责声明: 本安装包及启动器免费提供 无任何盈利目的 大家好&#xff0c;我是风雨无阻。 众所周知&#xff0c;StableDiffusion 是非常强大的AI绘图工具&#xff0c;需要详细了解StableDiffusion的朋友&#xff0c;可查看我之前的这篇文章&#xff1a; …...

接口参数设计原则

1. 不能太动态. 不相信客户端的原则 例如传递 filterFields , 推送一个表的某些字段给上游. 2. 可以服务端提供一些封装. 这个封装可以是写死的组合, 也可以是后端配置的. 最好的是 代码里的领域类bean 1,1对应一个名称. 可以是 classReference. 运营态有很多字段是给用户看的…...