吴恩达 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.

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

我们可以通过指示模型首先制定自己的解决方案来解决这个问题。
在这里插入图片描述

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时,可能会考虑提示中的换行符是否会影响模型的性能。

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

记一次SSRF漏洞的学习和利用

导语&#xff1a;本文主要记录一次我们在复盘嘶吼网站渗透报告时遇到的一个SSRF漏洞。 1.前言 本文主要记录一次我们在复盘嘶吼网站渗透报告时遇到的一个SSRF漏洞。此漏洞并结合腾讯云的API接口&#xff0c;可以获取大量嘶吼服务器的敏感信息。利用这些敏感信息&#xff0c;又…

android10 关闭默认输入法的“更正建议”

1. 场景 使用系统默认的输入法&#xff0c;在进行输入时&#xff0c;在输入法上方&#xff0c;会显示更正建议列表&#xff0c;同时会干扰我们的输入内容&#xff1a;会自动补全到输入框&#xff0c;而且删除不掉&#xff0c;甚至越删越多&#xff0c;非常讨厌。 如下&#x…

一段凄惨Android 面试经历分享,败在了项目架构原理上……

大家应该看过很多分享面试成功的经验&#xff0c;但根据幸存者偏差的理论&#xff0c;也许多看看别人面试失败在哪里&#xff0c;对自己才更有帮助。 这是一位网友分享的面试经历&#xff0c;他准备了3个月&#xff0c;刚刚参加完字节跳动的第三面&#xff0c;视频面&#xff…

都23年了你还记得渐进式框架是什么意思吗

vue 文章目录 vue前言一、眼见为实举个栗子二、渐进式的优势 前言 渐进式框架是一种能够逐步增强应用功能的框架&#xff0c;它允许开发者在不影响应用性能的情况下&#xff0c;逐步添加新的功能和特性。Vue.js提供了一些基础功能&#xff0c;如数据绑定和组件化&#xff0c;然…

这8个摸鱼神器,千万别让你老板知道!

工欲善其事&#xff0c;必先利其器&#xff0c;对于程序员来说也是如此&#xff0c;想早点下班就不能死脑筋&#xff0c;必须借助于一些开发工具来提高自己的工作效率&#xff0c;小编选取了8款任务/项目管理工具&#xff0c;能助你[打通任督二脉]&#xff0c;工作效率大大提升…

React之动态路由创建以及解决刷新白屏问题

动态路由的创建和动态菜单的创建几乎类似&#xff0c;只不过的是&#xff0c;动态路由需要导入组件。这样才能完成跳转。 动态路由与动态菜单一样都需要封装一个转化函数&#xff0c;将后端传来的数据进行转换&#xff0c;转换成我们需要的格式。 需要导入的依赖 导入路由use…

【ChatGPT】阿里版 ChatGPT 突然官宣意味着什么?

Yan-英杰的主页 悟已往之不谏 知来者之可追 C程序员&#xff0c;2024届电子信息研究生 目录 阿里版 ChatGPT 突然官宣 ​ ChatGPT 技术在 AI 领域的重要性 自然语言生成 上下文连续性 多语言支持 ChatGPT 未来可能的应用场景 社交领域 商业领域 ​编辑 医疗领域…

网络安全常用术语

肉鸡 肉鸡指的就是被黑客成功入侵并取得控制权限的电脑。黑客们可以随意的控制肉鸡&#xff0c;就像在使用自己的电脑一样&#xff0c;很形象的比喻&#xff0c;就像是养的肉鸡&#xff0c;任黑客宰杀和利用。关键的是&#xff0c;在成为肉鸡后&#xff0c;只要黑客不对电脑进…

linux|进程间通信如何加锁

进程间通信有一种[共享内存]方式&#xff0c;大家有没有想过&#xff0c;这种通信方式中如何解决数据竞争问题&#xff1f;我们可能自然而然的就会想到用锁。但我们平时使用的锁都是用于解决线程间数据竞争问题&#xff0c;貌似没有看到过它用在进程中&#xff0c;那怎么办&…

Java——把数组排成最小的数

题目链接 牛客网在线oj题——把数组排成最小的数 题目描述 输入一个非负整数数组numbers&#xff0c;把数组里所有数字拼接起来排成一个数&#xff0c;打印能拼接出的所有数字中最小的一个。 例如输入数组[3&#xff0c;32&#xff0c;321]&#xff0c;则打印出这三个数字能…

如何提高三维模型OSGB格式转换3DTILES的转换速度和数据质量

如何提高三维模型OSGB格式转换3DTILES的转换速度和数据质量 提高三维模型从OSGB格式转换为3DTILES格式的转换速度和数据质量&#xff0c;可以从以下几个方面进行优化&#xff1a; 1、选用高效的转换工具&#xff1a;选择高效的转换工具是提高转换速度和数据质量的关键。目前市…

【react从入门到精通】深入理解React生命周期

文章目录 前言React技能树React的生命周期是什么React v16.0前的生命周期组件初始化(initialization)阶段组件挂载(Mounting)阶段组件更新(update)阶段组件销毁阶段 React v16.4 的生命周期总结写在最后 前言 在上一篇文章《react入门这一篇就够了》中我们已经掌握了React的基本…

ABTEST平台建设思路与方案

导读 ABTest的作用&#xff1a; 用ABTEST的结果数据&#xff0c;论证是因为某个业务方案的调整&#xff0c;对产品能力的影响。ABTEST是一个过程&#xff0c;只是为了证明改动的效果&#xff0c;其最终的阶段一定是对某个方案进行推全结束实验&#xff0c;避免稳定的业务流程…

docker 安装 datax和datax-web 之 datax-web登录时提示账号或密码错误

docker 安装docker 安装 datax和datax-web 安装教程地址&#xff1a; https://www.cnblogs.com/leihongnu/p/16612273.html 根据该博客的教程安装成功后&#xff0c;登录页面能打开&#xff0c;但是所提供的账户密码一直报错&#xff0c;这个就需要根据日志一步步去寻找原因了…

管理后台项目-07-菜单管理和动态展示菜单和按钮

目录 1-菜单管理 1.1-菜单管理列表 1.2-添加|修改功能 1.3-删除菜单 2-动态菜单按钮展示 2.1-路由文件的整理 2.2-动态展示不同的路由 1-菜单管理 当用户点击菜单管理的时候&#xff0c;会展示当前所有菜单&#xff0c;树型结构展示...并且可以对菜单进行新增编辑删除操…

2023-04-27:用go语言重写ffmpeg的remuxing.c示例。

2023-04-27&#xff1a;用go语言重写ffmpeg的remuxing.c示例。 答案2023-04-27&#xff1a; ffmpeg的remuxing.c是一个用于将多媒体文件从一种容器格式转换为另一种容器格式的命令行工具。它可以将音频、视频和字幕等元素从源文件中提取出来&#xff0c;并按照用户指定的方式…

基于SAM的二次开发案例收集分享

一、AnyLabeling[1]——制作人&#xff1a;vietanhdev AnyLabeling LabelImg Labelme Improved UI Autolabeling AnyLabeling软件是一个集成了YOLO、Segment Anything模型&#xff08;AI支持&#xff09;的高效数据标注工具&#xff0c;它可以通过点击目标的方式完成目标检…

Windows Vscode 远程连接Ubuntu, vscode检测到#include错误请更新includePath的解决方法

&#xff08;闭坑&#xff09;首先&#xff0c;我们要明白一点&#xff0c;就是我们在windows用vscode 远程连接了Ubuntu后&#xff0c;我们的Vscode的环境就是Ubuntu,不再是window了&#xff0c;所以出现问题&#xff0c;应该想到的是Ubuntu上的环境问题&#xff0c;而不是win…

机器学习与深度学习——通过SVM线性支持向量机分类鸢尾花数据集iris求出错误率并可视化

线性支持向量机 先来看一下什么叫数据近似线性可分&#xff0c;如下图所示&#xff0c;蓝色圆点和红色圆点分别代表正类和负类&#xff0c;显然我们不能找到一个线性的分离超平面将这两类完全正确的分开&#xff1b;但是如果将数据中的某些特异点(黑色箭头指向的点)去除之后&a…

根据cadence设计图学习硬件知识day06 了解一些电源转化芯片和 稳压器 和 开关芯片

1. TPL920 (高精度线性稳压器) 1.1.TPL920 介绍 TPL920系列产品是2A大电流、6μVRMS低噪声、高PSRR、高精度线性稳压器&#xff0c;通常具有在2A负载条件下的110 mV超低电压降。这TPL920系列产品同时支持固定输出电压范围从0.8伏到3.95伏&#xff0c;输出电压可调范围为0.8V至…