吴恩达 Chatgpt prompt 工程--1.Guidelines

这篇具有很好参考价值的文章主要介绍了吴恩达 Chatgpt prompt 工程--1.Guidelines。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

课程链接

Setup

#安装
!pip install openai
#设置key
!export OPENAI_API_KEY='sk-...'
# or
#import openai
#openai.api_key = "sk-..."
import openai
import os

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

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

我们可以通过指示模型首先制定自己的解决方案来解决这个问题。
吴恩达 Chatgpt prompt 工程--1.Guidelines

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

模型限制:一本正经的胡说八道(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时,可能会考虑提示中的换行符是否会影响模型的性能。文章来源地址https://www.toymoban.com/news/detail-439113.html

到了这里,关于吴恩达 Chatgpt prompt 工程--1.Guidelines的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

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

    出处:https://download.csdn.net/download/weixin_45766780/87746321 感谢中文版翻译https://github.com/datawhalechina/prompt-engineering-for-developers/tree/main/content 国内 == 需要对openapi的endpoint做一个反向代理,并修改本地openai包的源代码== 如下图: completion 原则一:编写清晰、具体的指令 你应该通过提供

    2024年02月05日
    浏览(37)
  • 吴恩达与OpenAI官方合作的ChatGPT提示工程课程笔记

    🥸 下述代码均在煮皮特上运行喔 Base LLM:基于文本训练数据来预测做“文字接龙” Instruction Tuned LLM(指令调整型LLM):接受了遵循指示的培训,可以根据提前培训的输入输出对结果进行调整 编写明确和具体的指令(明确 ≠ 短) 策略一:用分隔符清楚的指示输入的不同部分

    2024年02月07日
    浏览(35)
  • 【AI提示】ChatGPT提示工程课程(吴恩达&OpenAI)转换文本(中文chatgpt版)

    设置 翻译 通用翻译器 语调变换 格式转换 拼写检查/语法检查。 转换 在本笔记中,我们将探索如何使用大型语言模型进行文本转换任务,例如语言翻译、拼写和语法检查、语气调整和格式转换。 ChatGPT 使用多种语言的资源进行训练。这使模型能够进行翻译。以下是如何使用

    2024年02月07日
    浏览(68)
  • 【AI提示】ChatGPT提示工程课程(吴恩达&OpenAI)推理文本(中文chatgpt版)

    设置 Setup 产品评论文本 情感(正面/负面)Sentiment (positive/negative) 识别情绪类型 从客户评论中提取产品和公司名称 一次完成多项任务 Inferring topics 推断主题 为某些主题制作新闻提醒 Inferring 推理 在本课中,您将从产品评论和新闻文章中推断情绪和主题。 设置 Setup 产品评论

    2024年02月07日
    浏览(71)
  • 吴恩达 GPT Prompting 课程

    In this lesson, you’ll practice two prompting principles and their related tactics in order to write effective prompts for large language models. Principle 1: Write clear and specific instructions Use delimiters to clearly indicate distinct parts of the input Ask for a structured output Ask the model to check whether conditions are satisfied “Few-shot”

    2024年02月11日
    浏览(26)
  • 吴恩达 & OpenAI 的Prompt教程笔记 - ChatGPT Prompt Engineering for Developers

    课程标题:ChatGPT Prompt Engineering for Developers (Andrew Ng Isa Fulford) 课程章节: 课程简介(Introduction) 提示工程关键原则 (Guidelines) 提示工程需要迭代(lterative) 总结类应用(Summarizing) 推理类应用(Inferring) 转换类应用(Transforming) 扩展类应用(Expanding) 打造聊天机器人(Chatbot) 课程总结(Concl

    2024年02月07日
    浏览(28)
  • 学习笔记:吴恩达ChatGPT提示工程

    以下为个人笔记,原课程网址Short Courses | Learn Generative AI from DeepLearning.AI 1.1 基础LLM 输入 输出 输入 输出 之所以这样输出的原因是,基础LLM的输出基于它的训练数据,可能会产生我们不想得到的信息 1.2 指令微调型LLM 输入 输出 首先使用1.1中经过大量文本数据训练过的基础L

    2024年02月08日
    浏览(38)
  • 吴恩达ChatGPT网课笔记Prompt Engineering——训练ChatGPT前请先训练自己

    主要是吴恩达的网课,还有部分github的prompt-engineering-for-developers项目,以及部分自己的经验。 prompt最好是英文的,如果是中文的prompt,大概会是英文的1.5~2倍的token数量。一方面成本提升,另一方面对于较长的prompt可能会超过上下文上限。 “”\\\" ``` - - - XML 标签: tag /tag 下图

    2024年02月07日
    浏览(34)
  • 【笔记】跟吴恩达和IsaFulford学提示词工程(初级开发者入门课程)

    标签: #Prompt #LLM 创建时间:2023-04-28 17:05:45 链接:课程(含JupyterNotebook) ,中文版 讲师:Andrew Ng,Isa Fulford 这是一篇入门的教程,入门的意思是指大部分内容,可能你都已经知道了,但是知道不等于掌握,Prompt是一门实践经验主义科学,LLM是个黑盒,你只要不断去“实践”

    2024年02月03日
    浏览(27)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包