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

news2024/11/25 23:23:32

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

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

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

相关文章

Graph Theory(图论)

一、图的定义 图是通过一组边相互连接的顶点的集合。 In this graph, V { A , B , C , D , E } E { AB , AC , BD , CD , DE } 二、图的类型 2.1 Finite Graph A graph consisting of finite number of vertices and edges is called as a finite graph. Null Graph Tri…

github workflow使用docker部署springboot并推送到阿里云镜像仓库

文章目录 1. 建立你的actions2. 工作流脚本2.1 触发事件2.2 密文和执行参数2.3 deploy.sh执行脚本2.4 Dockerfile 3. 阿里云镜像仓库设置 最近想通过github的workflow部署springboot项目&#xff08;CI&#xff09;&#xff0c;网上看了很多文章&#xff0c;都是有这样那样的问…

Design_transformer

磁性元件设计 思路 滤波电感设计 磁芯不要饱和&#xff08;开气隙&#xff09; 考虑铜损大于铁损 谐振电感设计 磁芯不要饱和&#xff08;开气隙&#xff09; 考虑铁损大于铜损 变压器设计 磁芯不要饱和&#xff08;开气隙&#xff09; 励磁电流产生磁场 开气隙 增加了…

1.rabbitMQ介绍

0.思考 我们以前为什么要学习java直接的框架代码,而不是用springboot整合的框架,在学习完MQ后,我的答案是,可以直接写成更灵活的MQ代码(其他框架也是,SSM我们为什么要学,在于灵活度更高,以后可能会遇到SSM的代码我就可以看得懂),springboot整合虽然完成了大多数功能,但是我要其…

SpringBoot+MyBatis搭建迷你微信小程序

课程链接&#xff1a;https://www.imooc.com/learn/945 标签组件 view view类似于HTML中的div标签是最基础的UI组件 https://blog.csdn.net/wushibo750/article/details/113802928 https://developers.weixin.qq.com/miniprogram/dev/component/view.html block flex ht…

突破1300件!腾讯数据安全专利授权量最新成绩出炉

今天是世界知识产权日&#xff0c;跟大家汇报一下我们在数据安全专利工作上的进展。 截至2023年4月&#xff0c;腾讯共获得数据安全相关专利授权量超过1300件、申请公开量超过1800件&#xff0c;涵盖数据加解密、数据库访问、数据分级分类、数据备份、数据防泄漏、机密计算等多…

音视频八股文(9)-- flv的h264六层结构和aac六层结构

flv介绍 FLV(Flash Video)是Adobe公司推出的⼀种流媒体格式&#xff0c;由于其封装后的⾳视频⽂件体积⼩、封装简单等特点&#xff0c;⾮常适合于互联⽹上使⽤。⽬前主流的视频⽹站基本都⽀持FLV。采⽤FLV格式封装的⽂件后缀为.flv。 FLV封装格式是由⼀个⽂件头(file header)…

概述篇——01 计算机网络概述

一、什么是计算机网络 计算机网络主要由一些通用的、可编程的硬件互连而成&#xff0c;通过这些硬件&#xff0c;可以传送不同类型的数据&#xff0c;并且可以支持广泛和日益增长的应用&#xff1b; 计算机网络不只是软件概念&#xff0c;还包含硬件设备&#xff1b;计算机网…

【Mysql】基础篇:DML(data manipulation language)语句:增、删、改数据库数据总结

博主简介&#xff1a;努力学习的大一在校计算机专业学生&#xff0c;热爱学习和创作。目前在学习和分享&#xff1a;数据结构、Go&#xff0c;Java等相关知识。博主主页&#xff1a; 是瑶瑶子啦所属专栏: Mysql从入门到精通近期目标&#xff1a;写好专栏的每一篇文章 目录 一、…

微搭低代码实现下拉框动态填充值

有个粉丝问我&#xff0c;微搭的下拉框如何自动填充值 想问一下&#xff0c;下拉控件需要绑定数据源里面的列表&#xff0c;这个需要怎么做&#xff0c;自己研究了蛮久也没弄出来&#xff0c;需要参考您哪一篇教程&#xff1f; 一般你字段设置为枚举类型就可以&#xff0c;如果…

数据结构入门(二)——单链表(增,删,查,改)

1.单链表的概念 概念&#xff1a;链表是一种物理存储结构上非连续、非顺序的存储结构&#xff0c;但链表在逻辑上是连续的&#xff0c;顺序的&#xff0c;而数据元素的逻辑顺序是通过链表中的指针连接次序实现的。 1.2链表的结构 我们给int重新定义一下新类型叫做SLDataType…

开源Stylegan人脸生成预训练模型

最近在研究Stylegan对抗式图像生成网络&#xff0c;使用了网络的一些预训练模型生成相应的图像&#xff0c;感觉非常有趣。下面开源一些我找到了预训练模型和代码&#xff0c;供大家一起玩。 Stylegan2官方给出的是TensorFlow版本的&#xff0c;费了半天劲找出了pytorch版本 这…

【五一创作】【Midjourney】Midjourney 连续性人物创作 ① ( 通过垫图方式生成类似图像 )

文章目录 一、Midjourney 生成图像二、通过垫图方式生成类似图像 一、Midjourney 生成图像 Midjourney 可以生成高质量的图像 , 但是 生成过程有很大的随机性 , 输入同样的提示词指令 , 其输出结果也存在很大的不同 ; 如果要 生成稳定的人物角色 , 场景 , 描述连贯的内容 , 这…

RMAN-03009、ORA-19566数据文件坏块报错处理方法

在备份数据库的时候&#xff0c;出现RMAN-03009、ORA-19566报错&#xff1a; RMAN-03009: backup 命令 (c3 通道上, 在 04/29/2023 10:58:11 上) 失败 ORA-19566: 超出损坏块限制 0 (文件 E:\APP\ADMINISTRATOR\ORADATA\JHSEMR\JHEMR2.DBF) 继续执行其他作业步骤, 将不重新运行…

React--》一些不常见的hook函数讲解

目录 Hook函数 useImperativeHandle useLayoutEffect和useInsertionEffect与useEffect区别 useDebugValue useDeferredValue useTransition Hook函数 关于React中的钩子函数&#xff0c;在我之间的文章中讲解完我们已经非常熟悉了&#xff0c;钩子函数的功能非常强大而它…

编译安卓系统源码时异常处理

编译安卓系统源码时异常处理 提示语法错误&#xff0c;如下所示&#xff1a; FAILED: out/target/product/generic/system-qemu.img /bin/bash -c "(export SGDISKout/host/linux-x86/bin/sgdisk SIMG2IMGout/host/linux-x86/bin/simg2img; device/generic/goldfis…

新安装的ubuntu,遇到的问题记录

镜像版本&#xff1a; https://mirror.nju.edu.cn/ubuntu-releases/22.04/ubuntu-22.04.1-live-server-amd64.iso 安装后无法切换 root 用户&#xff1a; 问题截图&#xff1a; null 解决办法&#xff1a; 解决ubuntu操作系统默认没有创建root账户&#xff1a; 1、sudo passwd …

云原生CAx软件:多租户的认证

云原生CAx软件是在设计时便将云平台作为部署、运行环境的CAx软件。通常&#xff0c;为了降低成本、方便管理&#xff0c;云原生CAx系统需要能为多个租户提供服务&#xff0c;即多租户(Multi-tenancy)&#xff0c;而实现这种多租户系统&#xff0c;关键是要处理好身份认证、权限…

PhotoShop如何使用图层之实例演示?

文章目录 0.引言1.创建简单的立体书效果图2.给人像制作逼真的影子3.用调整图层除去图像中的灰色4.制作有质感的口红颜色5.给黑白图像上色6.制作粉笔文字效果 0.引言 因科研等多场景需要进行绘图处理&#xff0c;笔者对PS进行了学习&#xff0c;本文通过《Photoshop2021入门教程…

Packet Tracer - 配置 IPv6 静态路由和默认路由

Packet Tracer - 配置 IPv6 静态路由和默认路由 IPv6 地址分配表 设备 接口 IPv6 地址/前缀 默认网关 R1 G0/0 2001:DB8:1:1::1/64 不适用 S0/0/0 2001:DB8:1:A001::1/64 不适用 R2 G0/0 2001:DB8:1:2::1/64 不适用 S0/0/0 2001:DB8:1:A001::2/64 不适用 S0…