大模型笔记:吴恩达 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 os

from 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" 键的值,即模型生成的回答
    '''

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, Jill

4 - 
{
  "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,000

The 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
'''

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【软考】UML中的图之对象图

目录 1. 说明2. 图示3. 特性 1. 说明 1.对象图即object diagram2.展现了某一时刻一组对象以及它们之间的关系3.描述了在类图中所建立的事物的实例的静态快照4.对象图一般包括对象和链5.对象图展示的是对象之间关系&#xff0c;不存在交互&#xff0c;所以不是交互图 2. 图示 …

【FPGA】DDR3学习笔记(二)丨从SDRAM到DDR3的IP核设计

本篇文章包含的内容 一、DDR SDRAM1.1 基本概述1.2 工作时序&#xff08;以读取为例&#xff09; 二、DDR2 SDRAM2.1 基本概述2.2 工作时序 三、DDR3 SDRAM3.1 基本概述3.2 硬件设计3.3 读写时序3.4 MIG IP核设计3.5 读写代码设计 开发板&#xff1a;正点原子的达芬奇开发板&am…

鸿蒙Harmony应用开发—ArkTS声明式开发(容器组件:GridCol)

栅格子组件&#xff0c;必须作为栅格容器组件(GridRow)的子组件使用。 说明&#xff1a; 该组件从API Version 9开始支持。后续版本如有新增内容&#xff0c;则采用上角标单独标记该内容的起始版本。 子组件 可以包含单个子组件。 接口 GridCol(option?:{span?: number | …

#QT(一种朴素的计算器实现方法)

1.IDE&#xff1a;QTCreator 2.实验&#xff1a;这是全靠自己想法写的计算器&#xff0c;没有参考任何教程。 &#xff08;1&#xff09;这个计算器只要有运算符敲入就会进行一次运算&#xff0c;所以他没有先后之后&#xff0c;无法满足运算优先级。 &#xff08;2&#xff…

linux安全--Nginx与Tomcat实现负载均衡

目录 1.实验拓扑原理图&#xff0c;前提实现全网互通 2.找到nginx的conf目录中的nginx.conf文件 3.实验效果 1.实验拓扑原理图&#xff0c;前提实现全网互通 搭建全网互通可以看https://blog.csdn.net/m0_74313947/article/details/136008513?spm1001.2014.3001.5501 搭建N…

JavaEE之多线程(创建线程的五种写法)详解

&#x1f63d;博主CSDN主页: 小源_&#x1f63d; &#x1f58b;️个人专栏: JavaEE &#x1f600;努力追逐大佬们的步伐~ 目录 1. 前言 2. 操作系统"内核" 3. 创建线程的五种写法 (我们重点要掌握最后一种写法!!) 3.1 继承 Thread, 重写 run 3. 2 实现 Runnabl…

北京保险服务中心携手镜舟科技,助推新能源车险市场规范化

2022 年&#xff0c;一辆新能源汽车在泥泞的小路上不慎拖底&#xff0c;动力电池底壳受损&#xff0c;电池电量低。车主向保险公司报案&#xff0c;希望能够得到赔偿。然而&#xff0c;在定损过程中&#xff0c;保司发现这辆车的电池故障并非由拖底事件引起&#xff0c;而是由于…

电脑坏了去维修,第一家报价800,第三家说报废!

这篇文章主要讲的是修理坏掉的电脑。 第一家报价300&#xff0c;第二家报价800&#xff0c;第三家说要报废&#xff01; 相信很多朋友对于修电脑坏了要多少钱有很多困惑&#xff0c;修电脑坏了要多少钱&#xff0c;到底去正规售后服务还是去非品牌店维修一台坏掉的电脑。 今天高…

基于单片机的电子琴设计

基于单片机的电子琴设计 摘 要 读书、看电影、听音乐&#xff0c;都是最常见的丰富内心世界的良剂。听音乐&#xff0c;作为陶冶情操、提升境界最便捷的方式&#xff0c;正受到越来越多人们的欢迎。音乐可以很轻松的融入各种场合&#xff0c;给人们带来很轻松的氛围&#xff…

基础---nginx 启动不了,跟 Apache2 服务冲突

文章目录 查看 nginx 服务状态nginx 启动后 访问页面 127.0.0.1停止 nginx 服务&#xff0c;访问不了页面停止/启动 Apache2 服务&#xff0c;启动 Apache2 页面访问显示正确nginx 莫名启动不了卸载 Apache2 服务器 启动 nginx &#xff0c;但是总是不能实现反向代理&#xff0…

微服务分布式springcloud的体育场地预约系统演kdm1z

体育场馆设施预约系统是在实际应用和软件工程的开发原理之上&#xff0c;运用java语言以及Springcloud框架进行开发。首先要进行需求分析&#xff0c;分析出体育场馆设施预约系统的主要功能&#xff0c;然后设计了系统结构。整体设计包括系统的功能、系统总体结构、系统数据结构…

Annaconda环境下ChromeDriver配置及爬虫编写

Anaconda环境的chromedriver安装配置_anaconda 配置chromedriver-CSDN博客 Chromedriver驱动( 121.0.6167.85 ) - 知乎 下载好的驱动文件解压&#xff0c;将exe程序复制到Annaconda/Scripts目录以及Chrome/Application目录下 注意要提前pip install selenium包才能运行成功&a…

若依Vue3图片预览大图遮罩层和表格的border css层级冲突

样式层级出现问题&#xff0c;表格的层级高于图片的层级 1.解决方式一&#xff1a;设置此文件的该属性&#xff08;z-index&#xff09;为继承&#xff0c;则显示正常 .el-table .el-table__cell { z-index: inherit; } 2.解决方式二&#xff1a;将此属性设置为true(本人试了…

【Python】快捷找到最大最小 N 个元素

heapq 简单数据结构取出最大最小N个元素复杂数据结构中取出最大最小N个元素代码解析&#xff1a;lambda Python 中有 heapq 模块可以快捷找到数组中最大最小的 N 个元素&#xff1b; heapq.nlargest(num, arr) # 从arr数组中取出最大num个元素 heapq.nsmallest(num, arr) # …

[论文笔记]LLaMA: Open and Efficient Foundation Language Models

引言 今天带来经典论文 LLaMA: Open and Efficient Foundation Language Models 的笔记&#xff0c;论文标题翻译过来就是 LLaMA:开放和高效的基础语言模型。 LLaMA提供了不可多得的大模型开发思路&#xff0c;为很多国产化大模型打开了一片新的天地&#xff0c;论文和代码值…

npm报错,显示certificate has expired

从报错信息就可以知道是因为之前设置的淘宝镜像已过期&#xff0c;解决方法就是要把之前设置的淘宝镜像改成新的 第一种方法 第一步&#xff1a;清空缓存 npm cache clean --force第二步&#xff1a;重新设置新的镜像源 npm config set registry https://registry.npmmirror…

使用canvas实现图纸标记及回显

图纸 图纸标记后的效果图 最近做的一个qms项目里面&#xff0c;需要前端在图纸上实现标记及标记后的内容还要能够回显&#xff0c;然后后端通过标记的点&#xff0c;去读取标记图纸的内容&#xff0c;如一些公式、数据之类的&#xff0c;目前实现的功能有 在图纸上面进行矩形…

点云配准论文阅读1-Research on Three-Dimensional Point Cloud Registration Algorithm

Research on Three-Dimensional Point Cloud Registration Algorithm三维点云配准算法研究 Publisher: IEEE发行者 &#xff1a; IEEE Cite This引用此内容 PDF Yuqing Zhang; Shilong Sun; Jingjing Shang; Minghan Yang张玉清;孙世龙; 尚晶晶;杨明翰 Abstract: Accordi…

88. 合并两个有序数组 (Swift版本)

题目 给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2&#xff0c;另有两个整数 m 和 n &#xff0c;分别表示 nums1 和 nums2 中的元素数目。 请你 合并 nums2 到 nums1 中&#xff0c;使合并后的数组同样按 非递减顺序 排列。 注意&#xff1a;最终&#xff0c;合并…

【C++ 设计模式】简单工厂模式

文章目录 前言一、简单工厂模式是什么&#xff1f;二、实现原理三、UML类图四、简单工厂模式具体代码总结 前言 在软件开发中&#xff0c;设计模式是解决特定问题的可复用解决方案。其中&#xff0c;简单工厂模式是一种创建型设计模式&#xff0c;旨在封装对象的创建过程&…