大模型笔记:吴恩达 ChatGPT Prompt Engineering for Developers(1) prompt的基本原则和策略

1 intro

基础大模型 VS 用指令tune 过的大模型

  • 基础大模型 只会对prompt的文本进行续写
    • 所以当你向模型发问的时候,它往往会像复读机一样续写几个问题
    • 这是因为在它见过的语料库文本(通常大多来自互联网)中,通常会连续列举出N个问题
  • 经过指令微调(如RLHF)之后,模型才会像人一样进行有效答复

2 prompt 的原则

2.0 open-ai准备代码

2.0.1  设置& 使用OpenAI的API密钥


import openai
import osfrom dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())
'''
首先使用 find_dotenv() 函数查找 .env 文件的路径
然后 load_dotenv() 函数加载该文件中的环境变量。这样做可以使我们的应用程序读取这些环境变量
'''openai.api_key  = os.getenv('OPENAI_API_KEY')
openai.api_key
'''
'eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhcHAiLCJzdWIiOiIxODE0MDkyIiwiYXVkIjoiV0VCIiwiaWF0IjoxNzEwMzQyODYwLCJleHAiOjE3MTI5MzQ4NjB9.cxiUyxEBRFvSs0xxnpFTAkHs_neQihbbypAvDF9P2Uw'
'''
#从环境变量中读取 OPENAI_API_KEY 的值,并将其设置为 openai 库中 api_key 的值

 当然下面这种方式设置密钥也是可以的

import openai
openai.api_key = "sk-..."

2.0.2  函数:根据用户的输入提示 prompt 生成一个回答,并返回这个回答的文本内容

def get_completion(prompt, model="gpt-3.5-turbo"):messages = [{"role": "user", "content": prompt}]'''创建了一个包含单个字典的列表 messages,字典包含两个键:"role" 和 "content"。"role" 键的值是 "user",表示这个消息是用户输入的。"content" 键的值是函数参数 prompt,表示用户的输入内容。'''response = openai.ChatCompletion.create(model=model,messages=messages,temperature=0, # this is the degree of randomness of the model's output)'''调用 openai.ChatCompletion.create 方法,使用上面定义的 messages、函数参数 model,
以及一个指定的 temperature 参数来创建一个聊天完成(即模型的回答)temperature 参数控制输出的随机性程度,这里被设置为 0,意味着模型的输出将是确定性的,
即在给定相同输入和条件的情况下,模型每次都会生成相同的输出。'''return response.choices[0].message["content"]'''返回从 response 对象中提取的实际生成文本。通过访问 response 对象的 choices 列表的第一个元素,然后从这个元素中提取 message 字典的 "content" 键的值,即模型生成的回答'''

注:对于openai版本1.0.0之后的,需要这样:

client = openai.OpenAI()def get_completion(prompt, model="gpt-3.5-turbo"):messages = [{"role": "user", "content": prompt}]response = client.chat.completions.create(model=model,messages=messages,temperature=0)return response.choices[0].message.content

 

2.1 原则1:提供清晰和具体的指令 (Write clear and specific instructions)

2.1.1 策略1:使用分隔符清楚地指示输入的不同部分(Use delimiters to clearly indicate distinct parts of the input)

  • 使用分隔符的意义在于避免用户输入的文本可能存在一些误导性的话语对应用功能造成干扰
  • 分隔符可以是: ```, """, < >, <tag> </tag>
text = f"""
You should express what you want a model to do by \ 
providing instructions that are as clear and \ 
specific as you can possibly make them. \ 
This will guide the model towards the desired output, \ 
and reduce the chances of receiving irrelevant \ 
or incorrect responses. Don't confuse writing a \ 
clear prompt with writing a short prompt. \ 
In many cases, longer prompts provide more clarity \ 
and context for the model, which can lead to \ 
more detailed and relevant outputs.
"""prompt = f"""
Summarize the text delimited by triple backticks \ 
into a single sentence.
```{text}```
"""response = get_completion(prompt)
print(response)
'''
Providing clear and specific instructions to a model is essential for guiding it towards the desired output and reducing the chances of irrelevant or incorrect responses, with longer prompts often providing more clarity and context for more detailed and relevant outputs.
'''

复习一下,这里prompt 以f开头的用法:python基础:-CSDN博客

2.1.2 策略2 要求结构化的输出(Ask for a structured output)

这样有助于模型输出结果直接用于程序,比如输出的json可以直接被python程序读取并转换为字典格式。

prompt = f"""
Generate a list of three made-up book titles along \ 
with their authors and genres. 
Provide them in JSON format with the following keys: 
book_id, title, author, genre.
"""
response = get_completion(prompt)
print(response)
'''
[{"book_id": 1,"title": "The Midnight Garden","author": "Elena Nightingale","genre": "Fantasy"},{"book_id": 2,"title": "Echoes of the Past","author": "Lucas Blackwood","genre": "Mystery"},{"book_id": 3,"title": "Whispers in the Wind","author": "Aria Silvermoon","genre": "Romance"}
]
'''

上面的“provide them in JSON format”就是策略2

2.1.3 策略 3: 让模型检查是否满足条件(Ask the model to check whether conditions are satisfied)

text_1 = f"""
Making a cup of tea is easy! First, you need to get some \ 
water boiling. While that's happening, \ 
grab a cup and put a tea bag in it. Once the water is \ 
hot enough, just pour it over the tea bag. \ 
Let it sit for a bit so the tea can steep. After a \ 
few minutes, take out the tea bag. If you \ 
like, you can add some sugar or milk to taste. \ 
And that's it! You've got yourself a delicious \ 
cup of tea to enjoy.
"""
prompt = f"""
You will be provided with text delimited by triple quotes. 
If it contains a sequence of instructions, \ 
re-write those instructions in the following format:Step 1 - ...
Step 2 - …
…
Step N - …If the text does not contain a sequence of instructions, \ 
then simply write \"No steps provided.\"\"\"\"{text_1}\"\"\"
"""
response = get_completion(prompt)
print("Completion for Text 1:")
print(response)
'''
Completion for Text 1:
Step 1 - Get some water boiling.
Step 2 - Grab a cup and put a tea bag in it.
Step 3 - Once the water is hot enough, pour it over the tea bag.
Step 4 - Let it sit for a bit so the tea can steep.
Step 5 - After a few minutes, take out the tea bag.
Step 6 - Add some sugar or milk to taste.
Step 7 - Enjoy your delicious cup of tea.
'''

这里的“If the text does not contain a sequence of instructions, \ 
then simply write \"No steps provided.\"就是策略3

反例(无法划分成一个一个step的):

text_2 = f"""
The sun is shining brightly today, and the birds are \
singing. It's a beautiful day to go for a \ 
walk in the park. The flowers are blooming, and the \ 
trees are swaying gently in the breeze. People \ 
are out and about, enjoying the lovely weather. \ 
Some are having picnics, while others are playing \ 
games or simply relaxing on the grass. It's a \ 
perfect day to spend time outdoors and appreciate the \ 
beauty of nature.
"""
prompt = f"""
You will be provided with text delimited by triple quotes. 
If it contains a sequence of instructions, \ 
re-write those instructions in the following format:Step 1 - ...
Step 2 - …
…
Step N - …If the text does not contain a sequence of instructions, \ 
then simply write \"No steps provided.\"\"\"\"{text_2}\"\"\"
"""
response = get_completion(prompt)
print("Completion for Text 2:")
print(response)
'''
Completion for Text 2:
No steps provided.
'''

2.1.4 策略4:少样本提示( "Few-shot" prompting)

通过提供给模型一个或多个样本的提示,模型可以更加清楚需要你预期的输出。

prompt = f"""
Your task is to answer in a consistent style.<child>: Teach me about patience.<grandparent>: The river that carves the deepest \ 
valley flows from a modest spring; the \ 
grandest symphony originates from a single note; \ 
the most intricate tapestry begins with a solitary thread.<child>: Teach me about resilience.
"""
response = get_completion(prompt)
print(response)
'''
<grandparent>: The tallest trees weather the strongest storms; the brightest stars shine in the darkest nights; the strongest hearts endure the greatest trials.
'''

2.2 原则2:给模型时间来“思考”(Give the model time to “think” )

利用了思维链的方法,将复杂任务拆成N个顺序的子任务,这样可以让模型一步一步思考,从而给出更精准的输出

2.2.1 策略1:指定完成任务所需的步骤 (Specify the steps required to complete a task)

text = f"""
In a charming village, siblings Jack and Jill set out on \ 
a quest to fetch water from a hilltop \ 
well. As they climbed, singing joyfully, misfortune \ 
struck—Jack tripped on a stone and tumbled \ 
down the hill, with Jill following suit. \ 
Though slightly battered, the pair returned home to \ 
comforting embraces. Despite the mishap, \ 
their adventurous spirits remained undimmed, and they \ 
continued exploring with delight.
"""
# example 1
prompt_1 = f"""
Perform the following actions: 
1 - Summarize the following text delimited by triple \
backticks with 1 sentence.
2 - Translate the summary into French.
3 - List each name in the French summary.
4 - Output a json object that contains the following \
keys: french_summary, num_names.Separate your answers with line breaks.Text:
```{text}```
"""
response = get_completion(prompt_1)
print("Completion for prompt 1:")
print(response)
'''
Completion for prompt 1:
1 - Jack and Jill go on a quest to fetch water from a hilltop well, but misfortune strikes as Jack trips on a stone and tumbles down the hill with Jill following suit, yet they return home slightly battered but with their adventurous spirits undimmed.2 - Jack et Jill partent en quête d'eau d'un puits au sommet d'une colline, mais la malchance frappe alors que Jack trébuche sur une pierre et dégringole la colline avec Jill qui suit, pourtant ils rentrent chez eux légèrement meurtris mais avec leurs esprits aventureux intacts.3 - Jack, Jill4 - 
{"french_summary": "Jack et Jill partent en quête d'eau d'un puits au sommet d'une colline, mais la malchance frappe alors que Jack trébuche sur une pierre et dégringole la colline avec Jill qui suit, pourtant ils rentrent chez eux légèrement meurtris mais avec leurs esprits aventureux intacts.","num_names": 2
}
'''

在prompt中,让大模型分成四步,一步一步解决

2.2.2 策略2:在匆忙得出结论之前,让模型自己找出解决方案(Instruct the model to work out its own solution before rushing to a conclusion)

  • 反例prompt(模型匆忙地给出了错误的答案)
prompt = f"""
Determine if the student's solution is correct or not.Question:
I'm building a solar power installation and I need \help working out the financials. 
- Land costs $100 / square foot
- I can buy solar panels for $250 / square foot
- I negotiated a contract for maintenance that will cost \ 
me a flat $100k per year, and an additional $10 / square \
foot
What is the total cost for the first year of operations 
as a function of the number of square feet.Student's Solution:
Let x be the size of the installation in square feet.
Costs:
1. Land cost: 100x
2. Solar panel cost: 250x
3. Maintenance cost: 100,000 + 100x
Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000
"""
response = get_completion(prompt)
print(response)
'''
The student's solution is correct. The total cost for the first year of operations as a function of the number of square feet is indeed 450x + 100,000.
'''
  • 好的prompt(告诉模型,让模型先找出自己的解决方案)
prompt = f"""
Your task is to determine if the student's solution \
is correct or not.
To solve the problem do the following:
- First, work out your own solution to the problem including the final total. 
- Then compare your solution to the student's solution \ 
and evaluate if the student's solution is correct or not. 
Don't decide if the student's solution is correct until 
you have done the problem yourself.Use the following format:
Question:
```
question here
```
Student's solution:
```
student's solution here
```
Actual solution:
```
steps to work out the solution and your solution here
```
Is the student's solution the same as actual solution \
just calculated:
```
yes or no
```
Student grade:
```
correct or incorrect
```Question:
```
I'm building a solar power installation and I need help \
working out the financials. 
- Land costs $100 / square foot
- I can buy solar panels for $250 / square foot
- I negotiated a contract for maintenance that will cost \
me a flat $100k per year, and an additional $10 / square \
foot
What is the total cost for the first year of operations \
as a function of the number of square feet.
``` 
Student's solution:
```
Let x be the size of the installation in square feet.
Costs:
1. Land cost: 100x
2. Solar panel cost: 250x
3. Maintenance cost: 100,000 + 100x
Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000
```
Actual solution:
"""
response = get_completion(prompt)
print(response)
'''
Let x be the size of the installation in square feet.
Costs:
1. Land cost: $100 * x
2. Solar panel cost: $250 * x
3. Maintenance cost: $100,000 + $10 * x
Total cost: $100 * x + $250 * x + $100,000 + $10 * x = $360 * x + $100,000The total cost for the first year of operations as a function of the number of square feet is $360x + $100,000.
```
Is the student's solution the same as actual solution just calculated:
```
No
```
Student grade:
```
incorrect
'''

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

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

相关文章

linux_aarch64_qt环境搭建

平台环境&#xff1a; ubuntu 16.04&#xff1a; gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.12) aarch64 gnu gcc版本&#xff1a; gcc-linaro-5.4.1-2017.05-x86_64_aarch64-linux-gnu.tar.xz Qt交叉编译版本: qt-everywhere-src-5.12.9.tar.xz 一、aarch64编…

BMW配送流程:通过EDI对接VDLP

BMW的汽车配送流程始于汽车“生产结束”&#xff0c;结束于“交付给宝马经销商”。BMW与其物流服务供应商之间没有直接的接口&#xff0c;EDI信息将会通过BMW的EDI供应商提供的VDLP&#xff08;车辆分销物流平台&#xff09;进行交换。 近期我们收到来自国内某汽车行业供应商L公…

ISIS多区域实验简述

为支持大型路由网络&#xff0c;IS-IS在路由域内采用两级分层结构。 IS-IS网络中三种级别的路由设备&#xff1a;将Level-1路由设备部署在区域内&#xff0c;Level-2路由设备部署在区域间&#xff0c;Level-1-2路由设备部署在Level-1和Level-2路由设备的中间。 实验拓扑图&…

Linux字符设备与I2C驱动结合使用

引言 在Linux操作系统中&#xff0c;设备驱动程序充当硬件和软件之间的桥梁。字符设备驱动是一种特殊类型的驱动&#xff0c;它允许用户以字节流的形式访问硬件设备。这些设备包括键盘、鼠标、串口等。在本博客中&#xff0c;我们将探讨Linux字符设备驱动的基础知识&#xff0…

LeetCode每日一题 将有序数组转换为二叉搜索树(分治)

题目描述 给你一个整数数组 nums &#xff0c;其中元素已经按 升序 排列&#xff0c;请你将其转换为一棵平衡二叉搜索树。 示例 1&#xff1a; 输入&#xff1a;nums [-10,-3,0,5,9] 输出&#xff1a;[0,-3,9,-10,null,5] 解释&#xff1a;[0,-10,5,null,-3,null,9] 也将被视…

49、C++/友元、常成员函数和常对象、运算符重载学习20240314

一、封装类 用其成员函数实现&#xff08;对该类的&#xff09;数学运算符的重载&#xff08;加法&#xff09;&#xff0c;并封装一个全局函数实现&#xff08;对该类的&#xff09;数学运算符的重载&#xff08;减法&#xff09;。 代码&#xff1a; #include <iostream…

力扣刷题 Days18-第二题-完全二叉树的节点个数(js)

1,题目 给你一棵 完全二叉树 的根节点 root &#xff0c;求出该树的节点个数。 完全二叉树 的定义如下&#xff1a;在完全二叉树中&#xff0c;除了最底层节点可能没填满外&#xff0c;其余每层节点数都达到最大值&#xff0c;并且最下面一层的节点都集中在该层最左边的若干位…

有没有能用蓝牙的游泳耳机?四大年度最佳游泳耳机由衷推荐

随着科技的不断发展&#xff0c;游泳爱好者们对于游泳耳机的追求也越来越高。在游泳过程中&#xff0c;音乐和播客是许多泳者们的最佳伴侣&#xff0c;它能帮助他们保持节奏、提高兴趣。然而&#xff0c;传统的有线耳机在水下容易产生拉扯&#xff0c;不仅影响游泳体验&#xf…

【Linux操作系统】:Linux进程概念(2)

一、Z(zombie)-僵尸进程 1.僵尸进程概念 故事 张三每天都有跑步的习惯&#xff0c;这一天他和往常一样跑步&#xff0c;跑了两三圈&#xff0c;突然跑在它前面的一个人倒在地上不动了&#xff0c;作为热心市民张三赶紧报警并且拨打120。很快120就来了&#xff0c;但是没过几分…

使用 QLoRA 在 Google Colab 中微调 Mistral 7b(完整指南)

使用 QLoRA 在 Google Colab 中微调 Mistral 7b&#xff08;完整指南&#xff09; 在本文中&#xff0c;我们将在一个名为 Enlighten 的游戏的整个代码库上微调 Mistral 7b&#xff0c;所有这些都在 Google Colab&#xff08;或 Kaggle&#xff09;中免费提供合成数据。在我们的…

深度学习 精选笔记(11)深度学习计算相关:GPU、参数、读写、块

学习参考&#xff1a; 动手学深度学习2.0Deep-Learning-with-TensorFlow-bookpytorchlightning ①如有冒犯、请联系侵删。 ②已写完的笔记文章会不定时一直修订修改(删、改、增)&#xff0c;以达到集多方教程的精华于一文的目的。 ③非常推荐上面&#xff08;学习参考&#x…

中科数安 | 企业办公透明加密系统,终端文件数据 \ 资料防泄密管理软件

#公司办公文件数据 \ 资料防泄密软件系统# "中科数安"是一家专注于数据安全领域的公司&#xff0c;其提供的企业办公加密系统是一种针对企事业单位内部数据安全需求而设计的解决方案。该系统通过先进的加密技术&#xff0c;对企业在日常办公过程中产生的各类敏感信息…

突飞猛进,智能饮品机器人如何助力实体经济?

近日&#xff0c;财务部公布了2024年第一季度及全年财报。数据显示&#xff0c;连锁品牌增长速度惊人&#xff0c;这其中不得不提到智能饮品机器人的使用&#xff0c;为不同的品牌门店拼速度、抢点位立下了不小的功劳&#xff0c;那么智能饮品机器人到底如何助力各门店&#xf…

Outlook API发送邮件的方法?如何设置接口?

如何使用Outlook API发送电子邮件&#xff1f;怎么调用API接口&#xff1f; 为了满足更高级别的需求&#xff0c;我们可能需要通过编程的方式来操作Outlook&#xff0c;这时候&#xff0c;Outlook API就显得尤为重要了。那么&#xff0c;如何使用Outlook API发送邮件呢&#x…

Spring Security自定义认证授权过滤器

自定义认证授权过滤器 自定义认证授权过滤器1、SpringSecurity内置认证流程2、自定义Security认证过滤器2.1 自定义认证过滤器2.2 定义获取用户详情服务bean2.3 定义SecurityConfig类2.4 自定义认证流程测试 3、 基于JWT实现无状态认证3.1 认证成功响应JWT实现3.2 SpringSecuri…

OceanBase中binlog service 功能的试用

OBLogProxy简介 OBLogProxy即OceanBase的增量日志代理服务&#xff0c;它可与OceanBase建立连接并读取增量日志&#xff0c;从而为下游服务提供了变更数据捕获&#xff08;CDC&#xff09;的功能。 关于OBLogProxy的详尽介绍与具体的安装指引&#xff0c;您可以参考这篇官方OB…

基于R语言的水文、水环境模型优化技术及快速率定方法与多模型教程

原文链接&#xff1a;基于R语言的水文、水环境模型优化技术及快速率定方法与多模型教程https://mp.weixin.qq.com/s?__bizMzUzNTczMDMxMg&mid2247597847&idx7&snd71869f1290d0ef9dd7fd3f74dd7ca33&chksmfa823ef0cdf5b7e655af5e773a3d3a1b200632a5981f99fe72f0…

普林斯顿算法讲义(一)

原文&#xff1a;普林斯顿大学算法课程 译者&#xff1a;飞龙 协议&#xff1a;CC BY-NC-SA 4.0 1. 基础知识 原文&#xff1a;algs4.cs.princeton.edu/10fundamentals 译者&#xff1a;飞龙 协议&#xff1a;CC BY-NC-SA 4.0 概述。 本书的目标是研究各种重要和有用的算法——…

多线程编程

多线程写作类 倒计时协调器CountDownLatch 某个线程需要等待其他线程执行到特定操作结束即可。例如&#xff1a;在多Web服务中&#xff0c;在启动指定服务时需要启动若干启动过程中比较耗时的服务&#xff0c;为了尽可能减少服务启动过程的总耗时&#xff0c;该服务会使用专门…

深入探讨MES管理系统与MOM系统之间的关系

在制造业的信息化浪潮中&#xff0c;各种系统与技术层出不穷&#xff0c;其中MES制造执行系统和MOM制造运营管理无疑是备受瞩目的两大主角。尽管它们都是制造业信息化不可或缺的部分&#xff0c;但许多人对它们之间的区别与联系仍感到困惑。本文将对MES管理系统和MOM系统进行深…