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

在这里插入图片描述

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 osfrom 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.rhkb.cn/news/13140.html

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

相关文章

14个在你的WordPress网站上使用OpenAI的最好方法(2003)

您是否想知道如何在您的WordPress网站上使用OpenAI和ChatGPT&#xff1f; OpenAI可以提供一切帮助&#xff0c;从为您的帖子生成元描述到撰写电子邮件销售文案。您可以在您的WordPress网站上使用OpenAI来节省时间、降低成本、改善您的搜索引擎优化和工作流程&#xff0c;并发展…

吴恩达OpenAI最新课程:prompt-engineering-for-developers读书笔记

文章目录 一、前言二、Prompt编写原则2.1 环境配置2.2 编写清晰、具体的指令2.2.1 使用分隔符2.2.2 结构化输出&#xff08;JSON、HTML等&#xff09;2.2.3 要求模型检查条件是否满足2.2.4 提供少量示例&#xff08;Few-shot Prompting&#xff09; 2.3 指导模型思考2.3.1 指定…

chatgpt赋能python:Python打折简单程序:节省金钱和时间的利器

Python打折简单程序&#xff1a;节省金钱和时间的利器 作为程序员&#xff0c;我们总是在寻找更好的&#xff0c;更高效的解决方案。在购物时&#xff0c;这也是如此。现在&#xff0c;我们可以通过编写一个简单的Python程序来实现节省金钱和时间的目的。 什么是Python打折简…

《花雕学AI》29:5秒钟就能为你的想法想出新点子?ChatGPT新点子指令模型告诉你怎么做

引言 你有没有遇到过这样的情况&#xff0c;你想出了一个想法&#xff0c;但是不知道怎么扩展或改进它&#xff1f;你有没有想过有一个工具&#xff0c;可以帮你在短时间内为你的想法生成各种新的点子&#xff1f;如果你有这样的需求&#xff0c;那么你一定要了解ChatGPT。 C…

AI大模型应用时代,如何通过数据“造好品,卖好品”?

在数字化时代的浪潮中&#xff0c;品牌营销正面临着前所未有的挑战和机遇。随着技术的迅猛发展&#xff0c;消费者的行为和期望也在不断演变。 新的市场环境下&#xff0c;消费者的需求和购买行为发生了哪些变化&#xff1f; 数码家电转战社媒平台&#xff0c;竞争白热化如…

使用chatGPT编写的支付宝沙箱支付

支付宝沙箱支付指的是在支付宝开放平台的沙箱环境中进行的模拟支付操作。开发者可通过支付宝开放平台的沙箱环境模拟真实的支付流程&#xff0c;包括创建订单、模拟用户付款、模拟用户退款等操作&#xff0c;从而测试自己的支付功能是否正常。沙箱环境中的交易数据和资金均为虚…

ChatGPT提示词工程(一):Guidelines准则

目录 一、说明二、安装环境三、Guidelines准则一&#xff1a;写出明确而具体的说明方法1&#xff1a;使用分隔符清楚地表示输入的不同部分方法2&#xff1a;用结构化输出&#xff1a;如直接要求它以HTML或者JSON格式输出方法3&#xff1a;请模型检查是否满足条件方法4&#xff…

ChatGPT - 使用故事和隐喻来帮助记忆

文章目录 Prompt Prompt 我目前正在学习[主题]。将该主题的关键教训转化为引人入胜的故事和隐喻&#xff0c;以帮助我记忆。

Redisson分布式限流RRateLimiter的实现原理

我们目前在工作中遇到一个性能问题&#xff0c;我们有个定时任务需要处理大量的数据&#xff0c;为了提升吞吐量&#xff0c;所以部署了很多台机器&#xff0c;但这个任务在运行前需要从别的服务那拉取大量的数据&#xff0c;随着数据量的增大&#xff0c;如果同时多台机器并发…

详解Redisson分布式限流的实现原理

我们目前在工作中遇到一个性能问题&#xff0c;我们有个定时任务需要处理大量的数据&#xff0c;为了提升吞吐量&#xff0c;所以部署了很多台机器&#xff0c;但这个任务在运行前需要从别的服务那拉取大量的数据&#xff0c;随着数据量的增大&#xff0c;如果同时多台机器并发…

聊聊Sentinel集群限流探索

最近看了下关于分布式限流的部分&#xff0c;看到Sentinel的分布式限流&#xff0c;也就是集群限流的部分&#xff0c;想搭个环境看看&#xff0c;结果发现网上关于这方面的内容基本可以说没有&#xff0c;你甚至很难跑起来他的demo&#xff0c;就算能跑起来&#xff0c;估计也…

ChatGPT专业应用:生成生日主题

正文共 925 字&#xff0c;阅读大约需要 4 分钟 人力资源等必备技巧&#xff0c;您将在4分钟后获得以下超能力&#xff1a; 生成生日主题 Beezy评级 &#xff1a;A级 *经过寻找和一段时间的学习&#xff0c;一部分人能掌握。主要提升效率并增强自身技能。 推荐人 | Kim 编辑者…

UI设计如何结合AIGC工具?轻松设计出彩的UI界面

大家好。我是不知名设计师 l1m0_&#xff0c;今天分享内容为&#xff1a;UI设计如何结合AIGC工具发挥“奇”效。文中我会针对UI设计的流程和几款人工智能AI工具的功能&#xff0c;来向大家进行介绍AIGC如何在这个过程中发挥作用。对UI设计和AI工具感兴趣的朋友一定不能错过&…

chatgpt赋能python:Python声音处理入门指南

Python声音处理入门指南 如果你是一个音乐爱好者或者处理声音的工程师&#xff0c;Python语言是值得你考虑的一种工具&#xff0c;它拥有丰富的库&#xff0c;可以帮助你在声音分析、编辑、压缩和转换等方面做出成果。 Python声音处理库 Python语言拥有一个大量的声音处理库…

【回答问题】ChatGPT上线了!给我推荐比较流行的音频处理算法模型

给我推荐比较流行的音频处理算法模型 音频处理算法模型有很多种,我给你列举一些比较流行的: 声音分类:用于将声音信号分成不同的类别,比如人声、自然声、机器声等。 声音分离:用于从混合的声音信号中分离出单独的声音源。 语音识别:用于将语音转换成文本。 语音合成…

AIGC领域优秀的资源汇总(应用、论文、开源项目)

AIGC领域介绍&#xff0c;及一些比较优秀的应用&#xff0c;和论文&#xff0c;开源项目汇总。 AIGC大纲 一、AIGC概念 ​ AIGC&#xff0c;全名“AI generated content”&#xff0c;又称生成式AI&#xff0c;意为人工智能生成内容。例如AI文本续写&#xff0c;文字转图像的…

白嫖GPT-4最强竞品!20秒速通92页论文,不怕跟不上技术进展了

梦晨 发自 凹非寺量子位 | 公众号 QbitAI GPT-4最强竞品Claude前两天来了个史诗升级&#xff0c;支持十万token上下文&#xff0c;可以一次输入一本书&#xff0c;把大模型卷到新高度。 可惜的是&#xff0c;从Anthropic官网申请试用要收费&#xff0c;不少感兴趣的读者表示想玩…

将springboot单体项目部署到腾讯云服务器上

前言 在服务器上运行springboot项目&#xff0c;需要有jdk环境&#xff0c;而此文的项目案例使用的数据库是mysql&#xff0c;所以也需要安装mysql&#xff0c;教程如下&#xff1a; CentOS7安装jdk8CentOS7快速安装mysql 1.打包springboot单体项目 1.springboot单体小项目…

【干货贴】当人工智能与艺术碰撞 | AI写诗

生成式人工智能产品&#xff08;AIGC&#xff09; ​前几天&#xff0c;扎克伯格称&#xff1a;Meta 将组建顶级 AI 团队&#xff0c;专注生成式人工智能产品&#xff0c;在短期内&#xff0c;公司将专注于构建创造性和表现力的工具。 说到富有创造力和表现力的艺术行为&#…

ChatGPT被广泛应用,潜在的法律风险有哪些?

ChatGPT由OpenAI开发&#xff0c;2022年11月一经面世便引发热烈讨论&#xff0c;用户数持续暴涨。2023年初&#xff0c;微软成功将ChatGPT接入其搜索引擎Bing中&#xff0c;市场影响力迅速提升&#xff0c;几乎同一时间&#xff0c;谷歌宣布其研发的一款类似人工智能应用Bard上…