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

news2024/11/16 13:24:31

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

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

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

相关文章

Flask vs. Django:选择适合你的Web开发框架【第134篇—Flask vs. Django】

Flask vs. Django&#xff1a;选择适合你的Web开发框架 在选择一个适合你项目的Web开发框架时&#xff0c;常常会遇到 Flask 和 Django 这两个流行的选择。两者都有其优势和适用场景&#xff0c;本文将探讨它们的特点&#xff0c;并通过代码实例和解析来帮助你更好地做出选择。…

环形链表的起点——细节讲解

对于一个环形链表&#xff0c;我们要找到他的起点。可以通过如下推导。 我们设置两个快慢指针&#xff0c;相遇的点为X. 到起点的距离是T&#xff0c;圈长是C&#xff0c;第一次相交的点是X &#xff08;TX&#xff09;2TNCX 化出来TN*C-X 也就是说我们把一个节点放头部重新遍…

SQLiteC/C++接口详细介绍之sqlite3类(六)

快速前往文章列表&#xff1a;SQLite—系列文章目录 上一篇&#xff1a;SQLiteC/C接口详细介绍之sqlite3类&#xff08;五&#xff09; 下一篇&#xff1a;SQLiteC/C接口详细介绍之sqlite3类&#xff08;七&#xff09; 19. sqlite3_changes与sqlite3_changes64 是SQLite中用…

手机安装Kali Linux

在数字化时代&#xff0c;信息安全和隐私保护显得尤为重要。Kali Linux&#xff0c;作为一款专业的渗透测试和安全审计工具&#xff0c;因其强大的功能和丰富的资源库而受到广大安全研究者和爱好者的青睐。然而&#xff0c;我们通常只能在传统的电脑设备上安装和使用Kali Linux…

外卖小程序-购物车模块表结构设计和后端代码

表结构设计 添加购物车代码 Service public class ShoppingCartServiceImpl implements ShoppingCartService {Autowiredprivate ShoppingCartMapper shoppingCartMapper;Autowiredprivate DishMapper dishMapper;Autowiredprivate SetmealMapper setmealMapper;/*** 添加购物…

在Linux/Ubuntu/Debian中使用7z压缩和解压文件

要在 Ubuntu 上使用 7-Zip 创建 7z 存档文件&#xff0c;你可以使用“7z”命令行工具。 操作方法如下&#xff1a; 安装 p7zip&#xff1a; 如果你尚未在 Ubuntu 系统上安装 p7zip&#xff08;7-Zip 的命令行版本&#xff09;&#xff0c;你可以使用以下命令安装它&#xff1a;…

某夕夕商品数据抓取逆向之webpack扣取

逆向网址 aHR0cHM6Ly93d3cucGluZHVvZHVvLmNvbQ 逆向链接 aHR0cHM6Ly93d3cucGluZHVvZHVvLmNvbS9ob21lL2JveXNoaXJ0 逆向接口 aHR0cHM6Ly9hcGl2Mi5waW5kdW9kdW8uY29tL2FwaS9naW5kZXgvdGYvcXVlcnlfdGZfZ29vZHNfaW5mbw 逆向过程 请求方式&#xff1a;GET 参数构成 【anti_content】…

PHP中的反序列化漏洞

PHP中的反序列化漏洞 目录 PHP 中的序列化与反序列化 概述 序列化 基本类型的序列化 对象的序列化 反序列化 示例序列化与反序列化 反序列化漏洞 - PHP 中的魔术方法 - Typecho_v1.0 中的反序列化漏洞 POP链的构造思路 pop链案例 反序列化逃逸 字符串逃逸&#xff…

GoLang:云原生时代致力于构建高性能服务器的后端语言

Go语言的介绍 概念 Golang&#xff08;也被称为Go&#xff09;是一种编程语言&#xff0c;由Google于2007年开始设计和开发&#xff0c;并于2009年首次公开发布。Golang是一种静态类型、编译型的语言&#xff0c;旨在提供高效和可靠的软件开发体验。它具有简洁的语法、高效的编…

C# wpf 使用GDI实现截屏

wpf截屏系列 第一章 使用GDI实现截屏&#xff08;本章&#xff09; 第二章 使用GDI实现截屏 第三章 使用DockPanel制作截屏框 第四章 实现截屏框热键截屏 第五章 实现截屏框实时截屏 第六章 使用ffmpeg命令行实现录屏 文章目录 wpf截屏系列前言一、导入gdi32方法一、NuGet获取…

【LeetCode: 102. 二叉树的层序遍历 + bfs】

&#x1f680; 算法题 &#x1f680; &#x1f332; 算法刷题专栏 | 面试必备算法 | 面试高频算法 &#x1f340; &#x1f332; 越难的东西,越要努力坚持&#xff0c;因为它具有很高的价值&#xff0c;算法就是这样✨ &#x1f332; 作者简介&#xff1a;硕风和炜&#xff0c;…

国产化三防笔记本丨亿道国产加固笔记本FT-2000/4处理器

国产化加固笔记本是指采用国产操作系统和处理器&#xff0c;通过技术手段对其进行硬件加固、软件加密、数据安全等多方面加强处理的产品。这种笔记本电脑通常被用于政府项目、金融行业等对安全性要求极高的领域。 在国产化加固笔记本中&#xff0c;硬件加固是重要的一环。为了保…

架构实战--以海量存储系统讲解热门话题:分布式概念

关注我&#xff0c;持续分享逻辑思维&管理思维&#xff1b; 可提供大厂面试辅导、及定制化求职/在职/管理/架构辅导&#xff1b; 有意找工作的同学&#xff0c;请参考博主的原创&#xff1a;《面试官心得--面试前应该如何准备》&#xff0c;《面试官心得--面试时如何进行自…

腾讯云轻量服务器地域选择教程,2024最新地域选择攻略

腾讯云服务器地域怎么选择&#xff1f;不同地域之间有什么区别&#xff1f;腾讯云哪个地域好&#xff1f;地域选择遵循就近原则&#xff0c;访客距离地域越近网络延迟越低&#xff0c;速度越快。腾讯云百科txybk.com告诉大家关于地域的选择还有很多因素&#xff0c;地域节点选择…

Github主页设置贪吃蛇详细教程

先看最终实现结果&#xff1a; 有条贪吃蛇放在主页还是蛮酷的哈哈哈。接下来我来讲一讲怎么在Github主页添加一条贪吃蛇。 首先要修改自己的Github的主页&#xff0c;我们得有一个特殊的仓库——这个仓库必须与你的Github用户名保持一致&#xff0c;并且需要公开&#xff0c…

ArcGIS全系列实战视频教程——9个单一课程组合+系列直播回放

《ArcGIS全系列实战视频教程》是由9个单一课程组合合成。组成一条ArcGIS入门实战各项专题深入应用学习全链条&#xff0c;让你学有方向、学有目的&#xff0c;系统全面掌握ArcGIS。 ArcGIS全系列实战视频教程——9个单一课程组合https://edu.csdn.net/combo/detail/2569 《Ar…

unity2D生成9*9格子

1.创建一个空对象和格子 2将格子做成预制体&#xff08;直接将格子拖到这里即可&#xff0c;拖了过后删掉原来的格子&#xff09; 3.创建脚本并将脚本拖到空对象上 using System.Collections; using System.Collections.Generic; using UnityEngine;public class CreateMap : M…

增删卜易——八宫六十四卦

之前看倪海厦的《天纪》笔记里面提到了六十四卦世应,觉得不知道这个世应是啥意思。很长时间就没看了,偶然间看到了张文江教授写的一本书《潘雨廷先生谈话录》提到了《卜筮正宗》,“卜筮最后的判断是非理性转义,其他一切都只是形式”,“明人的著作,从京氏易出,如今天几日…

GitHub 服务器

GitHub 服务器 公司中&#xff0c;我们可以搭建中央服务器让项目组开发人员共享代码&#xff0c;但是如果我们的开发人员都是通过互联网进行协作&#xff0c;而不是在同一个地方&#xff0c;那么开发时&#xff0c;程序文件代码的版本管理就显得更加重要&#xff0c;这就需要搭…

企业数据流动安全管理软件(深度解析文章)

企业数据重要性不言而喻&#xff0c;而同时数据的流动和共享也带来了安全风险&#xff0c;如何确保企业数据在流动过程中的安全性&#xff0c;也成为了企业需要面临的重要问题。 企业数据流动安全管理软件的主要功能是监控和管理企业数据的流动过程。 它能够对企业内部的数据…