LangChain:1. Prompt基本使用

news/2024/9/19 0:52:37/ 标签: langchain, prompt, java

1. Prompt基本使用

from langchain_core.prompts import PromptTemplate
from langchain_core.prompts import ChatPromptTemplate

这里有两种prompt,其对应两种形式:PromptTemplate 和 ChatPromptTemplate

从某种意义来说,前者是一个通用形式,后者是在chat领域的一个特殊表达。

from langchain_core.prompts import PromptTemplateprompt_template = PromptTemplate.from_template("Tell me a {adjective} joke about {content}."
)
prompt_template.format(adjective="funny", content="chickens")
# 'Tell me a funny joke about chickens.'

PromptTemplate做的操作很简单,相当于把 f'Tell me a {adjective} joke about {content}.' 从变量带入字符串中分离开了,Template都可以使用format函数转化为字符串,但是这里要注意的是,参数是变量了并不是字典。

ChatPromptTemplate相当于在PromptTemplate做了一个对话的快捷方式,一般来说对话是这样的:

System: You are a helpful AI bot. Your name is Bob.
Human: Hello, how are you doing?
AI: I'm doing well, thanks!
Human: What is your name?

但是ChatPromptTemplate将其分解得具体了,其有两种表达形式,一种使用列表,一种使用更具体的ChatMessagePromptTemplate,AIMessagePromptTemplate,HumanMessagePromptTemplate

#  使用列表
from langchain_core.prompts import ChatPromptTemplatechat_template = ChatPromptTemplate.from_messages([("system", "You are a helpful AI bot. Your name is {name}."),("human", "Hello, how are you doing?"),("ai", "I'm doing well, thanks!"),("human", "{user_input}"),]
)# 转化为字符串
messages = chat_template.format(name="Bob", user_input="What is your name?")
# 转化为列表 可以具体看看是 SystemMessage HumanMessage AIMessage 还是其他的 Message
messages = chat_template.format_messages(name="Bob", user_input="What is your name?")# 使用细分的方式
from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, AIMessagePromptTemplate, HumanMessagePromptTemplatec1 = SystemMessagePromptTemplate.from_template("You are a helpful AI bot. Your name is {name}.")
c2 = HumanMessagePromptTemplate.from_template("You are a helpful AI bot. Your name is {name}.")
c3 = AIMessagePromptTemplate.from_template("You are a helpful AI bot. Your name is {name}.")
c4 = HumanMessagePromptTemplate.from_template("You are a helpful AI bot. Your name is {name}.")chat_template = ChatPromptTemplate.from_messages([c1, c2, c3, c4])
# 效果如上
messages = chat_template.format(name="Bob", user_input="What is your name?")
messages = chat_template.format_messages(name="Bob", user_input="What is your name?")

在这里要注意的是,使用列表的话元组前面一个字符串只能是 one of 'human', 'user', 'ai', 'assistant', or 'system'.,不然会报错。其中还有一个ChatMessagePromptTemplate,其from_template参数中还有一个role参数,可以自定义对话实体,不需要必须满足'human', 'user', 'ai', 'assistant', or 'system'其中的一个。

在定义好template之后,就可以搭配模型使用chain了

from langchain_community.llms import Ollama
from langchain_core.prompts import ChatPromptTemplatellm = Ollama(model='llama3', temperature=0.0)
chat_template = ChatPromptTemplate.from_messages([("system", "You are a helpful AI bot. Your name is {name}."),("human", "Hello, how are you doing?"),("ai", "I'm doing well, thanks!"),("human", "{user_input}"),]
)
chain = chat_template | llm
chain.invoke({'name': 'Bob', 'user_input': 'What is your name?'})
# "Nice to meet you! My name is Bob, and I'm here to help answer any questions or provide assistance you may need. How can I help you today?"

2. 进阶Prompt

2.1 MessagesPlaceholder

MessagesPlaceholder: 当暂时不确定使用什么角色需要占位时

from langchain_core.prompts import ChatPromptTemplate, HumanMessagePromptTemplate, MessagesPlaceholder
from langchain_core.messages import AIMessage, HumanMessage # 这里与AIMessagePromptTemplate的区别在与前者是不能使用input_variables的human_prompt = "Summarize our conversation so far in {word_count} words."  
human_message_template = HumanMessagePromptTemplate.from_template(human_prompt)  # 在这里使用MessagesPlaceholder进行占位
chat_prompt = ChatPromptTemplate.from_messages(  
[MessagesPlaceholder(variable_name="conversation"), human_message_template]  
)# 在这里添加,添加参数为占位时设置的variable_name
human_message = HumanMessage(content="What is the best way to learn programming?")
ai_message = AIMessage(content="""1.Choose a programming language: Decide on a programming language that you want to learn. 2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures. 3. Practice, practice, practice: The best way to learn programming is through hands-on experience"""
)# 这里的 word_count 对应 chat_prompt 中的 input_variables
chat_prompt.format_prompt(conversation=[human_message, ai_message], word_count="10"
).to_messages()

利用示例让LLM模仿输出进而获得一个更好的效果在prompt工程中很常见,但是大量的实例会造成一个问题,那就是模型的输入长度是由限制的,大量的实例可能会导致在input_variables输入时出现长度过长模型无法输入的问题。这里就需要引入selectors

2.2 selectors

selectors:通过对示例进行选择的方式来减少示例,进而减少文本长度。要注意的是使用selectors后并不会立刻就删除示例,示例是在FewShotPromptTemplate中被删除的。

from langchain_core.prompts import PromptTemplateexamples = [{"input": "happy", "output": "sad"},{"input": "tall", "output": "short"},{"input": "energetic", "output": "lethargic"},{"input": "sunny", "output": "gloomy"},{"input": "windy", "output": "calm"},
]example_prompt = PromptTemplate(input_variables=["input", "output"],template="Input: {input}\nOutput: {output}",
)# 要注意的是format_prompt是不可以使用列表的,只能一个参数参数输入
example_prompt.format_prompt(**examples[0])
2.2.1 LengthBasedExampleSelector

LengthBasedExampleSelector: 根据文本长度来选择

from langchain_core.example_selectors import LengthBasedExampleSelector
from langchain_core.prompts import FewShotPromptTemplate# 定义example_selector
example_selector = LengthBasedExampleSelector(examples=examples,example_prompt=example_prompt,# 这里max_length是针对 one example 的max_length=25,# get_text_length 是用来计算 example_prompt 的长度的# get_text_length: Callable[[str], int] = lambda x: len(re.split("\n| ", x))
)FewShotPromptTemplate(example_selector=example_selector,example_prompt=example_prompt,prefix="Give the antonym of every input",suffix="Input: {adjective}\nOutput:",# 这里的input_variables与suffix中的adjective对应input_variables=["adjective"],
)

2.2.2 NGramOverlapExampleSelector

NGramOverlapExampleSelector: 根据 ngram 重叠分数,根据与输入最相似的示例 NGramOverlapExampleSelector 来选择和排序示例。ngram 重叠分数是介于 0.0 和 1.0 之间的浮点数,包括 0.0(含)。ngram 重叠分数小于或等于阈值的示例被排除在外。默认情况下,阈值设置为 -1.0,因此不会排除任何示例,只会对它们重新排序。将阈值设置为 0.0 将排除与输入没有 ngram 重叠的示例。

from langchain_community.example_selector.ngram_overlap import NGramOverlapExampleSelectorexample_selector = NGramOverlapExampleSelector(  
examples=examples,  
example_prompt=example_prompt,  
# threshold 阈值默认设置为 -1.0
threshold=-1.0,  
# 阈值小于 0.0:选择器按 ngram 重叠分数对示例进行排序,不排除任何示例。 
# 阈值大于 1.0: Selector 排除所有示例,返回一个空列表。 
# 阈值等于 0.0: 选择器按 ngram 重叠分数对示例进行排序, 并排除那些与输入没有 ngram 重叠的词。
)  
dynamic_prompt = FewShotPromptTemplate(  
# We provide an ExampleSelector instead of examples.  
example_selector=example_selector,  
example_prompt=example_prompt,  
prefix="Give the Spanish translation of every input",  
suffix="Input: {sentence}\nOutput:",  
input_variables=["sentence"],  
)

2.2.3 SemanticSimilarityExampleSelector

SemanticSimilarityExampleSelector:此对象根据与输入的相似性选择示例。它通过查找具有与输入具有最大余弦相似度的嵌入的示例来实现此目的。

from langchain_chroma import Chroma  
from langchain_core.example_selectors import SemanticSimilarityExampleSelector  
from langchain_core.prompts import FewShotPromptTemplate  
from langchain_openai import OpenAIEmbeddingsexample_selector = SemanticSimilarityExampleSelector.from_examples(  
examples,  
# 使用 embedding 层来判断文本相似性 
OpenAIEmbeddings(),  
# Chroma用于生成嵌入的嵌入类,用于度量语义相似度。
Chroma,  
# k表示要生成的示例数量
k=1, 
)  
similar_prompt = FewShotPromptTemplate(  
example_selector=example_selector,  
example_prompt=example_prompt,  
prefix="Give the antonym of every input",  
suffix="Input: {adjective}\nOutput:",  
input_variables=["adjective"],  
)

2.2.4 MaxMarginalRelevanceExampleSelector

MaxMarginalRelevanceExampleSelector:与输入最相似的示例组合来选择示例,同时还针对多样性进行了优化。为此,它找到具有与输入具有最大余弦相似度的嵌入的示例,然后迭代添加它们,同时惩罚它们与已选定示例的接近程度。

example_selector = MaxMarginalRelevanceExampleSelector.from_examples(  
examples,  
OpenAIEmbeddings(),  
# FAISS 和 Chroma 一样用于生成嵌入的嵌入类,用于度量语义相似度。 
FAISS,  
k=2,  
)
mmr_prompt = FewShotPromptTemplate(  
# We provide an ExampleSelector instead of examples.  
example_selector=example_selector,  
example_prompt=example_prompt,  
prefix="Give the antonym of every input",  
suffix="Input: {adjective}\nOutput:",  
input_variables=["adjective"],  
)

http://www.ppmy.cn/news/1449140.html

相关文章

【大模型学习】Transformer(学习笔记)

Transformer介绍 word2vec Word2Vec是一种用于将词语映射到连续向量空间的技术,它是由Google的Tomas Mikolov等人开发的。Word2Vec模型通过学习大量文本数据中的词语上下文信息,将每个词语表示为高维空间中的向量。在这个向量空间中,具有相似…

6.python网络编程

文章目录 1.生产者消费者-生成器版2.生产者消费者--异步版本3.客户端/服务端-多线程版4.IO多路复用TCPServer模型4.1Select4.2Epoll 5.异步IO多路复用TCPServer模型 1.生产者消费者-生成器版 import time# 消费者 def consumer():cnt yieldwhile True:if cnt < 0:# 暂停、…

如何彻底删除python

点击菜单栏中的“开始”&#xff0c;打开“运行”。 在运行上输入“cmd”&#xff0c;点击“确定”&#xff0c;接着输入“python --version”&#xff0c;得到一个程序的版本。 然后到这个网上下载对应的程序的版本&#xff0c;接着点击这个版本软件&#xff0c;点击这个卸载。…

【一刷《剑指Offer》】面试题 9:斐波那契数列(扩展:青蛙跳台阶、矩阵覆盖)

力扣对应链接&#xff1a;LCR 126. 斐波那契数 - 力扣&#xff08;LeetCode&#xff09; 牛客对应链接&#xff1a;斐波那契数列_牛客题霸_牛客网 (nowcoder.com) 核心考点&#xff1a;空间复杂度&#xff0c;fib 理解&#xff0c;剪枝重复计算。 一、《剑指Offer》内容 二、分…

【MATLAB源码-第200期】基于matlab的鸡群优化算法(CSO)机器人栅格路径规划,输出做短路径图和适应度曲线。

操作环境&#xff1a; MATLAB 2022a 1、算法描述 鸡群优化算法&#xff08;Chicken Swarm Optimization&#xff0c;简称CSO&#xff09;是一种启发式搜索算法&#xff0c;它的设计灵感来源于鸡群的社会行为。这种算法由Xian-bing Meng等人于2014年提出&#xff0c;旨在解决…

数据结构——排序算法分析与总结

一、插入排序 1、直接插入排序 核心思想&#xff1a;把后一个数插入到前面的有序区间&#xff0c;使得整体有序 思路&#xff1a;先取出数组中第一个值&#xff0c;然后再用tmp逐渐取出数组后面的值&#xff0c;与前面的值进行比较&#xff0c;假如我们进行的是升序排序&…

带宽的理解-笔记

带宽的理解 带宽(频带宽度)&#xff1a;是指电磁波最高频率和最低频率的差值&#xff0c;这一段频率被称为带宽。 举例说明 人耳能听到的频率范围是20赫兹到2万赫兹。换句话说&#xff0c;人而只对20赫兹至2万赫兹的声音频率有反应&#xff0c;超出或低于这一频率范围的声音我…

Tensorflow2.0笔记 - ResNet实践

本笔记记录使用ResNet18网络结构&#xff0c;进行CIFAR100数据集的训练和验证。由于参数较多&#xff0c;训练时间会比较长&#xff0c;因此只跑了10个epoch&#xff0c;准确率还没有提升上去。 import os import time import tensorflow as tf from tensorflow import keras …

沪深websocket level2/level1行情推送接入示例

行情接入包 golang packge: package hangqingimport ("bufio""bytes""compress/flate""encoding/json""github.com/gorilla/websocket""io/ioutil""log""net/http""net/url"&quo…

字节跳动发起AI战争 寻找下一个TikTok

现如今在字节跳动&#xff0c;已近乎隐退的张一鸣&#xff0c;只重点关注两件事&#xff1a;其一&#xff0c;是风暴中的TikTok&#xff1b;其二&#xff0c;就是字节跳动正在全力追赶的AI战略业务。 提及字节的AI战略远望,多个接近字节的人士均认为,以Flow部门出品最为“正统…

OpenCV 实现重新映射(53)

返回:OpenCV系列文章目录&#xff08;持续更新中......&#xff09; 上一篇&#xff1a;OpenCV 实现霍夫圆变换(52) 下一篇 :OpenCV实现仿射变换(54) 目标 在本教程中&#xff0c;您将学习如何&#xff1a; 一个。使用 OpenCV 函数 cv&#xff1a;&#xff1a;remap 实现简…

机器学习day4

超参数选择方法 交叉验证 1.交叉验证定义 交叉验证是一种数据集的分割方法&#xff0c;将训练集划分为n份&#xff0c;拿一份做测试集&#xff0c;其他n-1份做训练集 2.交叉验证法原理 将数据集划分为 cv4 份 1. 第一次&#xff1a;把第一份数据做验证集&#xff0c;其他数…

【CSS】基础

文章目录 一、CSS 是什么二、基本语法规范 一、CSS 是什么 层叠样式表 (Cascading Style Sheets). CSS 能够对网页中元素位置的排版进行像素级精确控制, 实现美化页面的效果. 能够做到页面的样式和结构分离. 二、基本语法规范 选择器 {一条/N条声明} 选择器决定针对谁修改 …

1.DNS 协议是什么

概念&#xff1a; DNS 是域名系统 (Domain Name System) 的缩写&#xff0c;提供的是一种主机名到 IP 地址的转换服务&#xff0c;就是我们常说的域名系统。它是一个由分层的 DNS 服务器组成的分布式数据库&#xff0c;是定义了主机如何查询这个分布式数据库的方式的应用层协议…

Java设计模式 _结构型模式_桥接模式

一、桥接模式 1、桥接模式 桥接模式&#xff08;Bridge Pattern&#xff09;是一种结构型设计模式。用于把一个类中多个维度的抽象化与实现化解耦&#xff0c;使得二者可以独立变化。 2、实现思路 使用桥接模式&#xff0c;一定要找到这个类中两个变化的维度&#xff1a;如支…

虚拟机网络桥接模式无法通信,获取到的ip为169.254.X.X

原因&#xff1a;VMware自动选择的网卡可能不对 解决&#xff1a;编辑-虚拟网络编辑器-更改桥接模式-选择宿主机物理网卡&#xff0c;断开虚拟机网络连接后重新连接即可

python可视化学习笔记折线图问题-起始点问题

问题描述&#xff1a; 起始点的位置不对 from pyecharts.charts import Line import pyecharts.options as opts # 示例数据 x_data [1,2,3,4,5] y_data [1, 2, 3, 4, 5] # 创建 Line 图表 line Line() line.add_xaxis(x_data) line.add_yaxis("test", y_data) li…

Linux第四章

&#x1f436;博主主页&#xff1a;ᰔᩚ. 一怀明月ꦿ ❤️‍&#x1f525;专栏系列&#xff1a;线性代数&#xff0c;C初学者入门训练&#xff0c;题解C&#xff0c;C的使用文章&#xff0c;「初学」C&#xff0c;linux &#x1f525;座右铭&#xff1a;“不要等到什么都没有了…

【UnityRPG游戏制作】Unity_RPG项目之场景环境搭建和解析

&#x1f468;‍&#x1f4bb;个人主页&#xff1a;元宇宙-秩沅 &#x1f468;‍&#x1f4bb; hallo 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! &#x1f468;‍&#x1f4bb; 本文由 秩沅 原创 &#x1f468;‍&#x1f4bb; 收录于专栏&#xff1a;Uni…

单片机与Python串口通讯

一、单片机端 串口是一条城乡之间的窄道(连接单片机和外设)&#xff0c;一次只能并排走八个人(8位)&#xff0c;但大部分城市(单片机)里的人(ADC数据)喜欢12个人并排走&#xff0c;所以只能分开传高八位、第八位。此处以ESP32的函数为例&#xff0c;假设有四个通道(其它单片机只…