课程链接

Setup

#安装
!pip install openai
#设置key
!export OPENAI_API_KEY='sk-...'
# or
#import openai
#openai.api_key = "sk-..."
import openai
import osfrom dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())openai.api_key  = os.getenv('OPENAI_API_KEY')
# https://platform.openai.com/docs/guides/chat
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"]

Prompting 原则

  • 原则1: Write clear and specific instructions(写清楚具体的说明)
  • 原则 2: Give the model time to “think”(给模型时间“思考”)

策略(原则1)

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

分隔符可以是任何符号,比如

```, """, < >, <tag> </tag>, :
ext = 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.
策略 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 Life of Bees","author": "Lila Rose","genre": "Romance"}
]
策略 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.
策略 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)
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)
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>: 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.

策略(原则2)

策略 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:
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.Deux frères et sœurs, Jack et Jill, partent en quête d'eau d'un puits au sommet d'une colline, mais ils tombent tous les deux et retournent chez eux légèrement meurtris mais avec leur esprit d'aventure intact.
Noms: Jack, Jill.{"french_summary": "Deux frères et sœurs, Jack et Jill, partent en quête d'eau d'un puits au sommet d'une colline, mais ils tombent tous les deux et retournent chez eux légèrement meurtris mais avec leur esprit d'aventure intact.",
"num_names": 2
}
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 French.
3 - List each name in the French summary.
4 - Output a json object that contains the following keys: french_summary, num_names.Use the following format:
Text: <text to summarize>
Summary: <summary>
Translation: <summary translation>
Names: <list of names in Italian 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 the hill, returning home slightly battered but with their adventurous spirits undimmed.
Translation: Jack et Jill partent en quête d'eau, mais un malheur frappe et ils tombent de la colline, rentrant chez eux légèrement meurtris mais avec leurs esprits aventureux intacts.
Names: Jack, Jill
Output JSON: {"french_summary": "Jack et Jill partent en quête d'eau, mais un malheur frappe et ils tombent de la colline, rentrant chez eux légèrement meurtris mais avec leurs esprits aventureux intacts.", "num_names": 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.

请注意,学生的解决方案实际上是不正确的。

我们可以通过指示模型首先制定自己的解决方案来解决这个问题。

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 + 10xTotal cost: 100x + 250x + 100,000 + 10x = 360x + 100,000Is the student's solution the same as actual solution just calculated:
NoStudent grade:
Incorrect

模型限制:一本正经的胡说八道(Hallucinations)

  • Boie 是一家真实存在的公司,但是产品不是真的
prompt = f"""
Tell me about AeroGlide UltraSlim Smart Toothbrush by Boie
"""
response = get_completion(prompt)
print(response)
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.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.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.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.

PS

使用反斜杠使文本适合屏幕,而不插入换行符“\n”。
无论是否插入换行符,GPT-3都不会真正受到影响。但是,在一般使用LLM时,可能会考虑提示中的换行符是否会影响模型的性能。

吴恩达 Chatgpt prompt 工程--1.Guidelines相关推荐

  1. 吴恩达 Chatgpt prompt 工程--6.Expanding

    生成客户服务电子邮件,这些电子邮件针对每个客户的评论进行定制. Setup import openai import osfrom dotenv import load_dotenv, find_do ...

  2. 第三课总结吴恩达 ChatGPT Prompt 免费视频

    前两课在这里: 总结吴恩达 ChatGPT Prompt 免费课程 第二弹进阶吴恩达 ChatGPT Prompt 技巧 今天第三课,两个技巧 第一个,Prompt 迭代开发 熟悉我号<有关SQ ...

  3. 总结吴恩达 ChatGPT Prompt 免费课程

    吴恩达联合 OpenAI 官方,发布了免费的 ChatGPT Prompt 视频教程. 链接:https://learn.deeplearning.ai/chatgpt-prompt-eng/less ...

  4. LLM 系列 | 07:吴恩达ChatGPT Prompt课程实践:以智能客服邮件为例

    简介 漠漠水田飞白鹭,阴阴夏木啭黄鹂.小伙伴们好,我是微信公众号<小窗幽记机器学习>的小编:卖铁观音的小女孩. 更多.更新文章欢迎关注 微信公众号:小窗幽记机器学习.后续会持续整理模型加速 ...

  5. 【简单入门】ChatGPT prompt engineering (中文版)笔记 |吴恩达ChatGPT 提示工程

    目录 思维导图 一.资料 二. 指南 环境配置 两个基本原则(最重要!!!!) 原则一:编写清晰.具体的指令 **策略一:使用分隔符清晰地表示输入的不同部分**,**分隔符可以是:```," ...

  6. 吴恩达ChatGPT网课笔记Prompt Engineering——训练ChatGPT前请先训练自己

    吴恩达ChatGPT网课笔记Prompt Engineering--训练ChatGPT前请先训练自己 主要是吴恩达的网课,还有部分github的prompt-engineering-for-devel ...

  7. GitHub-3KStar吴恩达ChatGPT课程最新中文版Prompt+ChatGPT API+LangChain——面向开发者的 LLM 入门课程开源,小白也可学

    目录 导言 面向开发者的 LLM 入门课程 项目简介 项目意义 项目受众 项目亮点 内容大纲 一.面向开发者的 Prompt Engineering 二.搭建基于 ChatGPT 的问答系统 三.使用 ...

  8. 【ChatGPT】吴恩达『提示工程』课程完全笔记下载

    版权说明:『ChatGPT Prompt Engineering for Developers』是DeepLearning.AI出品的免费课程,版权属于DeepLearning.AI(https:// ...

  9. 刚刚,吴恩达 ChatGPT 新课三连发!

    你有没有想过,你可以自己构建一个AI系统,或者开发一个使用大语言模型(LLM)的应用,甚至理解并创建扩散模型?我在吴恩达的三门新课程中找到了答案,这些课程让我看到了AI的无限可能性. 好消息!就在昨天 ...

最新文章

  1. parquet java_Apache Parquet Java API的文档?
  2. SQL where 1=1 的详细解释
  3. 女人必知:10个好习惯 让老公不想出轨
  4. DUTCTF 201x RE20
  5. 小米获京东自营安卓平板销量冠军 小米平板5 Pro全版本闪降100元
  6. nginx 上传图片出现跨域
  7. 循环增加li id_循环老化对于锂离子电池中锂和电解液分布的影响
  8. 【bzoj 3433】{Usaco2014 Jan} Recording the Moolympics(算法效率--贪心)
  9. MATLAB平台学习(9)信道模型
  10. php随机给用户抽奖,PHP随机按百分比抽奖
  11. Android 登陆界面
  12. Windows下的hiberfil.sys文件及其作用
  13. js 冒泡倒序 反转数组 去掉数组中重复性数据
  14. Syclover-Web题解
  15. 印刷纸张都有哪些类型?
  16. 现在的男生为什么不主动追求女生了
  17. mysql实现经纬度查询并按距离排序
  18. Linux命令卸载谷歌浏览器,UBUNTU16.04安装谷歌浏览器卸载firefox浏览器
  19. ue4网格转地形_【魔改UE4】Rtx实时焦散的一次尝试
  20. python画龙猫_Python:制作动态字符图

热门文章

  1. 商标注册流程?商标注册需要准备哪些资料
  2. c语言程序代码中的间隔,c语言时间间隔代码怎么弄?
  3. MYSQL Failed to initialize DD Storage Engine
  4. 英文写作——The Elements of Style知识点解读6—位于句首的分词短语必须和句子的语法主语相关
  5. Tripletloss实现
  6. Keras的Tokenizer分词器
  7. 【数学建模】2016年B题
  8. text.Tokenizer类
  9. 【美】约翰.佩里 - 拖拉一点也无妨(2013年11月4日)
  10. 123大学计算机,大学计算机及程序设计Ⅲ(贺兴亚)-中国大学mooc-题库零氪