翻译: 面向开发人员的GPT提示工程 GPT Prompt Engineering for Developers

news2024/11/29 12:38:17

在这里插入图片描述

1. 提示指南Guidelines for Prompting

在本课中,您将练习两个提示原则及其相关策略,以便为大型语言模型编写有效的提示。
In this lesson, you’ll practice two prompting principles and their related tactics in order to write effective prompts for large language models.

2. 设置Setup

加载 API 密钥和相关的 Python 库。
Load the API key and relevant Python libaries.
在本课程中,我们提供了一些代码来为您加载 OpenAI API 密钥。
In this course, we’ve provided some code that loads the OpenAI API key for you.

import openai
import os

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())

openai.api_key  = os.getenv('OPENAI_API_KEY')

2.1 辅助函数helper function

在整个课程中,我们将使用 OpenAI 的 gpt-3.5-turbo 模型和聊天完成。
Throughout this course, we will use OpenAI’s gpt-3.5-turbo model and the chat completions endpoint.
这个辅助函数将使使用提示和查看生成的输出变得更加容易:
This helper function will make it easier to use prompts and look at the generated outputs:

def get_completion(prompt, model="gpt-3.5-turbo"):
    messages = [{"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
    )
    return response.choices[0].message["content"]

3. 提示原则Prompting Principles

  • Principle 1: 编写清晰具体的说明Write clear and specific instructions
  • Principle 2: 给模型时间“思考”Give the model time to “think”

策略 Tactics

3.1 Tactic 1: 策略 1:使用定界符清楚地指示输入的不同部分Use delimiters to clearly indicate distinct parts of the input

分隔符可以是任何东西Delimiters can be anything like: ` ````, “”", < >, , :

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)

应提供明确和具体的说明来指导模型获得所需的输出,更长的提示可以为模型提供更多的清晰度和上下文,从而产生更详细和相关的输出。
Clear and specific instructions should be provided to guide a model towards the desired output, and longer prompts can provide more clarity and context for the model, leading to more detailed and relevant outputs.

3.2 Tactic 2: 策略 2:要求结构化输出 Ask for a structured output

JSON, HTML

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 Lost City of Zorath",
    "author": "Aria Blackwood",
    "genre": "Fantasy"
  },
  {
    "book_id": 2,
    "title": "The Last Survivors",
    "author": "Ethan Stone",
    "genre": "Science Fiction"
  },
  {
    "book_id": 3,
    "title": "The Secret of the Haunted Mansion",
    "author": "Lila Rose",
    "genre": "Mystery"
  }
]

3.3 Tactic 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!

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.

3.4 Tactic 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)

<祖父母>:韧性就像一棵树,随风而弯,但从不折断。它是从逆境中恢复过来并继续前进的能力,即使遇到困难也是如此。就像一棵树在经历过每一次风暴后都会变得更强壮一样,韧性是一种可以随着时间的推移而发展和加强的品质。
: Resilience is like a tree that bends with the wind but never breaks. It is the ability to bounce back from adversity and keep moving forward, even when things get tough. Just like a tree that grows stronger with each storm it weathers, resilience is a quality that can be developed and strengthened over time.

4. Principle 2: 原则 2:给模型时间“思考”Give the model time to “think”

4.1 Tactic 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 Chinese.
3 - List each name in the Chinese summary.
4 - Output a json object that contains the following \
keys: Chinese_summary, num_names.

Separate your answers with line breaks.

Text:
```{text}```
"""
response = get_completion(prompt_1)
print("Completion for prompt 1:")
print(response)

完成提示 1: 杰克和吉尔两兄妹去山顶的井里打水,不幸降临,双双跌下山坡,回家时虽然伤痕累累,但冒险精神丝毫未减。

Completion for prompt 1:
Two siblings, Jack and Jill, go on a quest to fetch water from a hilltop well, but misfortune strikes as they both fall down the hill, yet they return home slightly battered but with their adventurous spirits undimmed.

两个兄弟杰克和吉尔前往山顶的井取水,但不幸的是他们都滚下了山,尽管他们受了些伤,但他们的冒险精神仍然不减。 
杰克,吉尔

4.1.1 请求指定格式的输出Ask for output in a specified format

prompt_2 = f"""
Your task is to perform the following actions: 
1 - Summarize the following text delimited by 
  <> with 1 sentence.
2 - Translate the summary into Chinese.
3 - List each name in the Chinese summary.
4 - Output a json object that contains the 
  following keys: Chinese_summary, num_names.

Use the following format:
Text: <text to summarize>
Summary: <summary>
Translation: <summary translation>
Names: <list of names in summary>
Output JSON: <json with summary and num_names>

Text: <{text}>
"""
response = get_completion(prompt_2)
print("\nCompletion for prompt 2:")
print(response)

Completion for prompt 2:
Summary: Jack and Jill go on a quest to fetch water, but misfortune strikes and they tumble down a hill, returning home slightly battered but with undimmed adventurous spirits.
Translation: Jack 和 Jill 去取水,但不幸的是他们跌倒了,回家时有些受伤,但他们的冒险精神仍然不减,继续愉快地探索。
Names: Jack, Jill
Output JSON: {“Chinese_summary”: “Jack 和 Jill 去取水,但不幸的是他们跌倒了,回家时有些受伤,但他们的冒险精神仍然不减,继续愉快地探索。”, “num_names”: 2}

4.2 Tactic 2: 4.2 策略 2:在匆忙下结论之前指导模型自己制定解决方案Instruct the model to work out its own solution before rushing to a conclusion

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.

请注意,该学生的解决方案实际上是不正确的。
我们可以通过指示模型首先计算出自己的解决方案来解决这个问题。

Note that the student’s solution is actually not correct.
We can fix this by instructing the model to work out its own solution first.

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. 
- 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)

设 x 是以平方英尺为单位的安装尺寸。

费用:

  1. 土地成本:100x
  2. 太阳能电池板成本:250x
  3. 维护费用:100,000+10x

总成本:100x + 250x + 100,000 + 10x = 360x + 100,000

学生的解是否与刚刚计算的实际解相同: 不

学生打分: 不正确

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 + 10x

Total cost: 100x + 250x + 100,000 + 10x = 360x + 100,000

Is the student’s solution the same as actual solution just calculated:
No

Student grade:
Incorrect

5. 模型局限性:幻觉Model Limitations: Hallucinations

Boie是一家真实的公司,产品名称不是真实的Boie is a real company, the product name is not real.

prompt = f"""
Tell me about AeroGlide UltraSlim Smart Toothbrush by Boie
"""
response = get_completion(prompt)
print(response)

Boie 的 AeroGlide UltraSlim 智能牙刷是一款高科技牙刷,采用先进的声波技术提供深层彻底的清洁。它采用纤巧时尚的设计,易于握持和操作,并具有一系列智能功能,可帮助您优化刷牙程序。
The AeroGlide UltraSlim Smart Toothbrush by Boie is a high-tech toothbrush that uses advanced sonic technology to provide a deep and thorough clean. It features a slim and sleek design that makes it easy to hold and maneuver, and it comes with a range of smart features that help you optimize your brushing routine.

AeroGlide UltraSlim 智能牙刷的主要特点之一是其先进的声波技术,它使用高频振动来分解牙齿和牙龈上的牙菌斑和细菌。这项技术非常有效地去除最顽固的污渍和堆积物,让您的牙齿感觉干净清爽。
One of the key features of the AeroGlide UltraSlim Smart Toothbrush is its advanced sonic technology, which uses high-frequency vibrations to break up plaque and bacteria on your teeth and gums. This technology is highly effective at removing even the toughest stains and buildup, leaving your teeth feeling clean and refreshed.

除了其声波技术,AeroGlide UltraSlim 智能牙刷还配备了一系列智能功能,可帮助您优化刷牙程序。其中包括一个内置计时器,可确保您按推荐的两分钟刷牙时间,以及一个压力传感器,可在您刷牙太用力时提醒您。
In addition to its sonic technology, the AeroGlide UltraSlim Smart Toothbrush also comes with a range of smart features that help you optimize your brushing routine. These include a built-in timer that ensures you brush for the recommended two minutes, as well as a pressure sensor that alerts you if you’re brushing too hard.

总体而言,Boie 的 AeroGlide UltraSlim 智能牙刷是一款非常先进且有效的牙刷,非常适合希望将口腔卫生提升到一个新水平的任何人。凭借其先进的声波技术和智能功能,它可提供深度彻底的清洁,让您的牙齿感觉清新健康。
Overall, the AeroGlide UltraSlim Smart Toothbrush by Boie is a highly advanced and effective toothbrush that is perfect for anyone looking to take their oral hygiene to the next level. With its advanced sonic technology and smart features, it provides a deep and thorough clean that leaves your teeth feeling fresh and healthy.

6. 在课堂外使用 OpenAI API 的注意事项Notes on using the OpenAI API outside of this classroom

安装 OpenAI Python 库 To install the OpenAI Python library:

!pip install openai

该库需要使用您帐户的密钥进行配置,该密钥可在网站上找到。
The library needs to be configured with your account’s secret key, which is available on the website.
您可以在使用库之前将其设置为 OPENAI_API_KEY 环境变量
You can either set it as the OPENAI_API_KEY environment variable before using the library:

 !export OPENAI_API_KEY='sk-...'

Or, set openai.api_key to its value:

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

7. 关于反斜杠的注释A note about the backslash

  • 在本课程中,我们使用反斜杠 \ 使文本适合屏幕,而无需插入换行符“\n”。In the course, we are using a backslash \ to make the text fit on the screen without inserting newline ‘\n’ characters.
  • 无论您是否插入换行符,GPT-3 都不会受到真正的影响。但是在一般情况下使用 LLM 时,您可能会考虑提示中的换行符是否会影响模型的性能。GPT-3 isn’t really affected whether you insert newline characters or not. But when working with LLMs in general, you may consider whether newline characters in your prompt may affect the model’s performance.

参考

https://learn.deeplearning.ai/chatgpt-prompt-eng/lesson/2/guidelines

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

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

相关文章

7搜索管理

7搜索管理 7.1 准备环境 7.1.1 创建映射 创建xc_course索引库。 创建如下映射 post&#xff1a;http://localhost:9200/xc_course/doc/_mapping 参考 “资料”–》搜索测试-初始化数据.txt { "properties": { "description": { "type": &…

C语言操作符详解

该内容全部代码请看&#xff1a;gitee仓库 第一部分&#xff1a; 板书部分&#xff1a; 1、操作符的分类&#xff1a; 注意&#xff1a; 移位操作符和位操作符 单目操作符中有sizeof 逗号表达式 2、算术操作符&#xff1a; 注意&#xff1a; 除法的使用 取模运算 3、移位操…

485接口的温湿度传感器和RJ45接口的温湿度传感器选择分析

工业以太网RJ45接口 网口温湿度传感器和RS485信号输出温湿度传感器的分析对比 主要适用场合&#xff1a;大型厂房、跨区域机房、多机房、机柜、数据机房、服务器机房、大数据中心、户外电站等 主要区别&#xff1a;以太网温湿度传感器输出信号RJ45&#xff0c;RS485温湿度传…

【JAVA面试】缓存穿透、缓存击穿、缓存雪崩

提示&#xff1a;文章先作为初版&#xff0c;等后续时间充足后&#xff0c;补充更深的内容 文章目录 缓存穿透、缓存击穿、缓存雪崩一、区别二、线程安全问题 缓存穿透、缓存击穿、缓存雪崩 一、区别 缓存穿透&#xff08;Cache Penetration&#xff09;&#xff1a; 缓存穿…

展会邀请丨虹科诚邀您5月12日于北京参与制药行业质量控制技术论坛

2023年上半年&#xff0c;虹科圆满举办了成都CPQC与杭州药安大会&#xff0c;在两场顺利进行的展会上&#xff0c;虹科的产品广受青睐&#xff0c;也获得了许多客户的认可与信赖&#xff0c;虹科也将继续以优质的产品和解决方案解决您的问题。 5月12-5月13日&#xff0c;虹科将…

卷积神经网络(CNN):基于PyTorch的遥感影像、无人机影像的地物分类、目标检测、语义分割和点云分类

我国高分辨率对地观测系统重大专项已全面启动&#xff0c;高空间、高光谱、高时间分辨率和宽地面覆盖于一体的全球天空地一体化立体对地观测网逐步形成&#xff0c;将成为保障国家安全的基础性和战略性资源。随着小卫星星座的普及&#xff0c;对地观测已具备多次以上的全球覆盖…

arm安装pyrealsense

arm安装pyrealsense – Step 1 – conda install numba pip install opencv-python pip install scipy – Step 2 pyrealsense2 – 参考 https://github.com/35selim/RealSense-Jetson 编译安装pyrealsense2 git clone -b v2.50.0 --depth1 https://github.com/IntelRealSens…

【Java】哈希冲突(哈希碰撞)

文章目录 为什么发生哈希冲突&#xff08;哈希碰撞&#xff09;能否完全避免哈希冲突常用处理哈希冲突的方法1.开放地址法1.1线性探测再散列缺点&#xff1a;二次聚集 1.2二次探测再散列1.3伪随机探测再散列 2.再哈希地址法3.链地址法4.建立公共溢出区 为什么发生哈希冲突&…

2C 兼容和小技巧 合集

这里写自定义目录标题 2C 兼容小技巧 合集修改input date默认框的小图标 2C 兼容小技巧 合集 以前一直是2b端没遇到过啥兼容性 或者 奇奇怪怪改UI的地方&#xff0c;现在换成C端业务&#xff0c;就在这里记录下遇到的奇奇怪怪的需求以及解决办法吧。 这篇文章争取 长久更新&am…

Kali-linux枚举服务

枚举是一类程序&#xff0c;它允许用户从一个网络中收集某一类的所有相关信息。本节将介绍DNS枚举和SNMP枚举技术。DNS枚举可以收集本地所有DNS服务和相关条目。DNS枚举可以帮助用户收集目标组织的关键信息&#xff0c;如用户名、计算机名和IP地址等&#xff0c;为了获取这些信…

Redis持久化:RDB和AOF

Redis持久化&#xff1a;RDB和AOF Redis 数据存储在内存中&#xff0c;如果不想办法将数据保存到硬盘上&#xff0c;一旦Redis重启(退出/故障)&#xff0c;内存的数据将会全部丢失。我们肯定不想 Redis 里的数据由于某些故障全部丢失(导致所有请求都走 MySQL)&#xff0c;即便发…

软考A计划-重点考点-专题九(数据结构知识)

点击跳转专栏>Unity3D特效百例点击跳转专栏>案例项目实战源码点击跳转专栏>游戏脚本-辅助自动化点击跳转专栏>Android控件全解手册点击跳转专栏>Scratch编程案例 &#x1f449;关于作者 专注于Android/Unity和各种游戏开发技巧&#xff0c;以及各种资源分享&am…

解决报错‘cross-env‘ is not recognized as an internal...

目录 一、问题 1.1 问题描述 二、解决 2.1 解决 2.2 其它启动报错问题 一、问题 1.1 问题描述 今天在安装Ant Design Pro的后&#xff0c;执行 yarn start 时意外报错 cross-env is not recognized as an internal or external comman 报错后自然项目也就无法启动&…

组合数学第一讲

加法原则 432 9 879 96 乘法原则 3 * 2 6 800 2^55^2 因子可写成2^x5^y&#xff0c;其中x 0,1,2,3,4,5 y 0,1,2 6*3 18 4 3 * 2 10 数学归纳法 关键&#xff1a;假设n是正确的&#xff0c;证明n1也是正确的 Horse paradox&#xff08;马悖论&#xff09; 用PMI证…

如何提取文件名称到excel

如何提取文件名称到excel&#xff1f;在市场中很多小伙伴&#xff08;例如公司行政和文员&#xff09;就会碰到这个问题&#xff0c;将一些文件的名全部提取出来然后保存到excel表格中。当你在工作中如果遇到这个问题时&#xff0c;你却还在使用最传统的方法一个一个复制粘贴进…

深入剖析12大WEB安全漏洞与PAS防范措施

本文先介绍了12种常见WEB安全漏洞的原理和防范措施&#xff0c;然后介绍了PAS在安全漏洞防范上采取的措施。 目 录 01 WEB安全的基本介绍‍‍‍‍‍ 02 常见WEB安全漏洞的原理和防范‍‍‍‍‍‍ 03 PAS安全漏洞的防范‍‍‍‍ 01 WEB安全的基本介绍‍ WEB安全的前世今生 WE…

从FPGA说起的深度学习(十)

这是新的系列教程&#xff0c;在本教程中&#xff0c;我们将介绍使用 FPGA 实现深度学习的技术&#xff0c;深度学习是近年来人工智能领域的热门话题。 在本教程中&#xff0c;旨在加深对深度学习和 FPGA 的理解。 用 C/C 编写深度学习推理代码高级综合 (HLS) 将 C/C 代码转换为…

亚马逊云科技工业数据湖解决方案,助力企业打通各业务场景数据壁垒

数字化浪潮蓬勃发展&#xff0c;制造行业数字化转型热度迭起&#xff0c;根据麦肯锡面向全球400多家制造型企业的调研表明&#xff0c;几乎所有细分行业都在大力推进数字化转型&#xff0c;高达94%的受访者都称&#xff0c;数字化转型是他们危机期间维持正常运营的关键。 数字…

springboot第21集:SSO

单点登录单点登出支持跨域单点登录支持跨域单点登出 前台站点&#xff1a;业务站点A&#xff0c;业务站点B SSO站点&#xff1a;登录&#xff0c;退出 SSO服务&#xff1a;登录&#xff0c;登录状态&#xff0c;登出 数据库&#xff0c;登录状态缓存在Redis 登录时序图 客户端&…

【Swift】String与Sbustring区别与联系

String 还是字符串&#xff0c;始终如一。Substring 是string的切片。它们与base string共享内存buffer&#xff0c;并拥有一对范围索引。StringProtocol 抽取出字符串的特征以及如何访问其功能&#xff0c;放进一个协议中。String及Substring都遵循StringProtocol。 字符串在不…