当前位置: 首页 > 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;我…...

C++实现分布式网络通信框架RPC(3)--rpc调用端

目录 一、前言 二、UserServiceRpc_Stub 三、 CallMethod方法的重写 头文件 实现 四、rpc调用端的调用 实现 五、 google::protobuf::RpcController *controller 头文件 实现 六、总结 一、前言 在前边的文章中&#xff0c;我们已经大致实现了rpc服务端的各项功能代…...

java_网络服务相关_gateway_nacos_feign区别联系

1. spring-cloud-starter-gateway 作用&#xff1a;作为微服务架构的网关&#xff0c;统一入口&#xff0c;处理所有外部请求。 核心能力&#xff1a; 路由转发&#xff08;基于路径、服务名等&#xff09;过滤器&#xff08;鉴权、限流、日志、Header 处理&#xff09;支持负…...

基于距离变化能量开销动态调整的WSN低功耗拓扑控制开销算法matlab仿真

目录 1.程序功能描述 2.测试软件版本以及运行结果展示 3.核心程序 4.算法仿真参数 5.算法理论概述 6.参考文献 7.完整程序 1.程序功能描述 通过动态调整节点通信的能量开销&#xff0c;平衡网络负载&#xff0c;延长WSN生命周期。具体通过建立基于距离的能量消耗模型&am…...

在rocky linux 9.5上在线安装 docker

前面是指南&#xff0c;后面是日志 sudo dnf config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo sudo dnf install docker-ce docker-ce-cli containerd.io -y docker version sudo systemctl start docker sudo systemctl status docker …...

Auto-Coder使用GPT-4o完成:在用TabPFN这个模型构建一个预测未来3天涨跌的分类任务

通过akshare库&#xff0c;获取股票数据&#xff0c;并生成TabPFN这个模型 可以识别、处理的格式&#xff0c;写一个完整的预处理示例&#xff0c;并构建一个预测未来 3 天股价涨跌的分类任务 用TabPFN这个模型构建一个预测未来 3 天股价涨跌的分类任务&#xff0c;进行预测并输…...

在四层代理中还原真实客户端ngx_stream_realip_module

一、模块原理与价值 PROXY Protocol 回溯 第三方负载均衡&#xff08;如 HAProxy、AWS NLB、阿里 SLB&#xff09;发起上游连接时&#xff0c;将真实客户端 IP/Port 写入 PROXY Protocol v1/v2 头。Stream 层接收到头部后&#xff0c;ngx_stream_realip_module 从中提取原始信息…...

Ascend NPU上适配Step-Audio模型

1 概述 1.1 简述 Step-Audio 是业界首个集语音理解与生成控制一体化的产品级开源实时语音对话系统&#xff0c;支持多语言对话&#xff08;如 中文&#xff0c;英文&#xff0c;日语&#xff09;&#xff0c;语音情感&#xff08;如 开心&#xff0c;悲伤&#xff09;&#x…...

微信小程序云开发平台MySQL的连接方式

注&#xff1a;微信小程序云开发平台指的是腾讯云开发 先给结论&#xff1a;微信小程序云开发平台的MySQL&#xff0c;无法通过获取数据库连接信息的方式进行连接&#xff0c;连接只能通过云开发的SDK连接&#xff0c;具体要参考官方文档&#xff1a; 为什么&#xff1f; 因为…...

根据万维钢·精英日课6的内容,使用AI(2025)可以参考以下方法:

根据万维钢精英日课6的内容&#xff0c;使用AI&#xff08;2025&#xff09;可以参考以下方法&#xff1a; 四个洞见 模型已经比人聪明&#xff1a;以ChatGPT o3为代表的AI非常强大&#xff0c;能运用高级理论解释道理、引用最新学术论文&#xff0c;生成对顶尖科学家都有用的…...

SpringTask-03.入门案例

一.入门案例 启动类&#xff1a; package com.sky;import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCach…...