自然语言处理从入门到应用——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 库࿰…...
《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。蓝…...
正交变换和仿射变换
正交变换和仿射变换 平面的正交变换 正交点变换(保距变换) 平面上的一个保持任意两点距离不变的点变换 平面正交变换性质 正交变换的乘积是正交变换恒等变换是正交变换正交变换将(不)共线的三点映射成(不)…...
Electron 多端通信桥 MessageChannelMain和 MessagePortMain 坑点汇集
简介 MessageChannelMain 是 DOM MessageChannel 对象的主进程等价对象。 它的特有功能是创建一对已连接的 MessagePortMain 对象。 Electron 本身为了灵活追加 on("message") 机制,就说明该 MessageChannelMain 已经被创建了,而 Web 开发中&a…...
Html5播放器按钮在移动端变小的问题解决方法
Html5播放器按钮在移动端变小的问题解决方法 用手机浏览器打开酷播云视频,有时会出现播放器按钮太小的情况,此时只需在<head>中加入下面这段代码即可解决: <meta name"viewport" content"widthdevice-width, initia…...
Rust 开发环境搭建【一】
Rust 开发环境 推荐 搭建: 安装 rust 语言 以及 工具链 推荐安装方法:rustup curl --proto ‘https’ --tlsv1.2 -sSf https://sh.rustup.rs | sh 在国内如果访问速度慢,可以使用清华大学提供的镜像服务: https://mirrors.tu…...
C# Blazor 学习笔记(3):路由管理
文章目录 前言路由管理App.razor设置登录页面设置空布局 前言 我们知道使用Blazor的官方模板,我们会自动得到一个拥有侧边栏的布局页面。但是我们发现我们所有新建的页面都有侧边栏。有时候我们需要跳出这个布局,比如我要做登录页面的时候,我…...
如何快速搭建你的专属Galgame社区:TouchGal一站式解决方案完整指南
如何快速搭建你的专属Galgame社区:TouchGal一站式解决方案完整指南 【免费下载链接】kun-touchgal-next TouchGAL是立足于分享快乐的一站式Galgame文化社区, 为Gal爱好者提供一片净土! 项目地址: https://gitcode.com/gh_mirrors/ku/kun-touchgal-next 你是否…...
从JDK21降到17:2025版IDEA搭建苍穹外卖项目,我踩过的那些版本坑
从JDK21降到17:2025版IDEA搭建苍穹外卖项目实战避坑指南 当你用最新版IDEA 2025和JDK 21打开一个要求JDK 17的项目时,就像穿着高跟鞋去爬山——不是不行,但绝对会走得很辛苦。最近在搭建苍穹外卖项目时,我就深刻体会到了这种&quo…...
颠覆视频剪辑:JianYingApi让自动化剪辑效率提升80%
颠覆视频剪辑:JianYingApi让自动化剪辑效率提升80% 【免费下载链接】JianYingApi Third Party JianYing Api. 第三方剪映Api 项目地址: https://gitcode.com/gh_mirrors/ji/JianYingApi 在短视频内容爆发的时代,视频创作者面临着三重核心痛点&…...
Pixel Epic部署指南:GPU显存监控+自动降级策略+OOM防护机制
Pixel Epic部署指南:GPU显存监控自动降级策略OOM防护机制 1. 像素史诗终端概述 Pixel Epic(像素史诗)是一款基于AgentCPM-Report大模型构建的研究报告辅助终端,将严肃的科研过程转化为富有游戏感的交互体验。与传统AI工具不同&a…...
百度网盘提取码智能查询工具:3秒破解资源访问密码的终极方案
百度网盘提取码智能查询工具:3秒破解资源访问密码的终极方案 【免费下载链接】baidupankey 项目地址: https://gitcode.com/gh_mirrors/ba/baidupankey 还在为百度网盘加密资源而困扰吗?当你急需下载学习资料、软件安装包或娱乐资源时࿰…...
PyTorch 2.8镜像功能体验:支持多卡计算,大幅缩短模型训练时间
PyTorch 2.8镜像功能体验:支持多卡计算,大幅缩短模型训练时间 1. PyTorch 2.8镜像概述 PyTorch 2.8镜像是一个开箱即用的深度学习环境,预装了PyTorch 2.8和CUDA工具包。这个镜像最大的亮点是支持多GPU并行计算,能够显著加速模型…...
保姆级教程:在Windows 10/11上快速搭建mosquitto MQTT服务器,并用MQTTX客户端测试(附常见错误解决)
Windows平台零门槛搭建MQTT开发环境:从Mosquitto配置到MQTTX实战 最近在调试ESP32温湿度传感器时,发现直接连接公有MQTT服务器总遇到网络延迟问题。于是决定在本地搭建一个轻量级MQTT Broker,没想到整个过程比预想的顺畅许多——从Mosquitto…...
暗黑破坏神2存档全功能解决方案:d2s-editor高效修改与管理指南
暗黑破坏神2存档全功能解决方案:d2s-editor高效修改与管理指南 【免费下载链接】d2s-editor 项目地址: https://gitcode.com/gh_mirrors/d2/d2s-editor d2s-editor是一款专为《暗黑破坏神2》玩家设计的开源存档编辑工具,提供d2s格式(…...
Step3-VL-10B效果展示:10B轻量级模型实现媲美大模型的视觉语言推理能力
Step3-VL-10B效果展示:10B轻量级模型实现媲美大模型的视觉语言推理能力 1. 引言:当“小个子”拥有了“大智慧” 想象一下,你面前有一张复杂的科学图表、一份手写的数学笔记,或者一个满是按钮的软件界面。你能看懂多少࿱…...
终极视频修复指南:如何使用Untrunc轻松恢复损坏的MP4/MOV文件
终极视频修复指南:如何使用Untrunc轻松恢复损坏的MP4/MOV文件 【免费下载链接】untrunc Restore a truncated mp4/mov. Improved version of ponchio/untrunc 项目地址: https://gitcode.com/gh_mirrors/un/untrunc 你是否曾经遇到过珍贵的视频文件突然无法播…...
