ChatGPT提示词攻略之基本原则

news2024/11/27 22:43:10

下面是调用openai的completion接口的函数。但在本文中并不是重点。了解一下就好。

import openai
import os

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())

openai.api_key  = os.getenv('OPENAI_API_KEY')

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"]

下面我们来说说,书写提示词的基本原则。

提示词的基本原则

  • 提示词的书写要清晰,带有明确的指令
  • 给模型时间去思考,即指明模型的思考过程

原则一:提示词的书写要清晰,带有明确的指令

技巧一:使用分隔符清楚地指示输入的不同部分

分隔符可以是```, “”", < >, , :

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.

这个例子中需要处理的内容和处理指令是区分开的。这样便于维护。

技巧二:指明固定格式输出结果,如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"
  }
]

技巧三:让模型检测条件是否被满足

示例1:

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!

这里设定的条件是,如果文本中有指令步骤就将其按步骤列出。同时,这里也写明了输出的格式,正如技巧二中提到的那样。

示例2:

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.

示例二中的文本没有出现类似指令步骤的文字,模型也正确判断出来了。这说明模型是有推理能力的。

技巧四:少样本学习

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.

通过给模型一个示例去学习,让模型在接下来的回答中参照示例来回答。

原则二:给模型时间去思考

技巧一:指定完成任务所需的步骤

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)

回答:

Completion for prompt 1:
1 - Siblings Jack and Jill go on a quest to fetch water from a hilltop well, but misfortune strikes as Jack trips and tumbles down the hill, with Jill following suit, yet they return home slightly battered but undeterred in their adventurous spirits. 

2 - 兄妹杰克和吉尔出发去从山顶井中取水,但不幸的是,杰克绊倒了,滚下了山坡,吉尔也跟着滚下来,但他们稍微受了点伤,回到家中得到了安慰的拥抱,尽管发生了不幸,他们的冒险精神仍然不减,继续愉快地探索。

3 - 杰克,吉尔。

4 - 
{
  "chinese_summary": "兄妹杰克和吉尔出发去从山顶井中取水,但不幸的是,杰克绊倒了,滚下了山坡,吉尔也跟着滚下来,但他们稍微受了点伤,回到家中得到了安慰的拥抱,尽管发生了不幸,他们的冒险精神仍然不减,继续愉快地探索。",
  "num_names": 2
}

模型按照我们制定的步骤输出了内容。

当我们重新制定输出格式

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 Italian summary>
Output JSON: <json with summary and num_names>

Text: <{text}>
"""
response = get_completion(prompt_2)
print("\nCompletion for prompt 2:")
print(response)

注意:这里的text指的也是上面例子中的text。

回答:

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}

模型真的理解了输出的格式要求,有点厉害了哦。

技巧二:指示模型在匆忙得出结论之前制定自己的解决方案

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.

这里学生的回答是错误的。模型却判断为正确。看样子它算数是真不好。

补救措施来了。先让模型自己找出一个方案,然后让它去和学生的解决方案进行对比。最后判断一下学生的方案是否正确。

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)

回答:

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

通过这么一顿操作,模型似乎领悟到了什么。它发现了学生在Maintenance cost中错误地将10x写成了100x

总结一下该原则,通过设置思考过程,让模型按步骤思考通常能得到更为准确的回答。

大语言模型的限制

prompt = f"""
介绍一下首飞牌电动牙刷的功能
"""
response = get_completion(prompt)
print(response)

回答:

首飞牌电动牙刷是一款高科技的电动牙刷,具有多种功能,包括:

1. 高速震动清洁:首飞牌电动牙刷采用高速震动技术,每分钟可达到40000次的震动频率,能够深入清洁牙齿,有效去除牙菌斑和牙渍。

2. 智能感应:该电动牙刷配备了智能感应技术,能够自动识别不同的牙齿区域,根据不同的清洁需求进行智能调节,让你的牙齿更加干净。

3. 多种清洁模式:首飞牌电动牙刷提供了多种清洁模式,包括标准模式、深层清洁模式、按摩模式等,可以根据个人需求进行选择。

4. 长续航时间:该电动牙刷采用高效节能的电池技术,一次充电可以使用长达30天,让你无需频繁充电。

5. 人性化设计:首飞牌电动牙刷采用人性化设计,握感舒适,操作简单,适合各种年龄段的人使用。

总之,首飞牌电动牙刷具有高速震动清洁、智能感应、多种清洁模式、长续航时间和人性化设计等多种功能,是一款高性能的电动牙刷,可以帮助你轻松保持口腔健康。

事实上,并没有首飞牌电动牙刷,但模型描述的挺欢快的。一本正经地胡编乱造。这就是模型表现出来的幻想。要尽量避免这种情况,就需要将提示词写的准确,清晰和指令化。

参考:

https://learn.deeplearning.ai/chatgpt-prompt-eng/lesson/2/guidelines


觉得有用就点个赞吧!

我是首飞,做有趣的事情,拿出来分享。

我也准备了一份提示词的文档。有涉及到各个领域的提示词模板。
在这里插入图片描述
您可以在《首飞》公众号中回复“ 提示词 ” 获取该文档。

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

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

相关文章

[LeetCode周赛复盘] 第 348场周赛20230604

[LeetCode周赛复盘] 第 348场周赛20230604 一、本周周赛总结6462. 最小化字符串长度1. 题目描述2. 思路分析3. 代码实现 6424. 半有序排列1. 题目描述2. 思路分析3. 代码实现 6472. 查询后矩阵的和1. 题目描述2. 思路分析3. 代码实现 6396. 统计整数数目1. 题目描述2. 思路分析…

10.全局配置 app.json 与页面配置

常用的配置项有 pages 小程序的所有页面window 小程序窗口的外观tabBar 小程序底部的tabBar效果&#xff0c;就是底部的切换那部分style 组件样式版本 目录 1 window 2 tabBar 3 页面配置 1 window 小程序由下面三个部分组成&#xff0c;window可以配置 导航栏区域 与…

JavaSE_day43(多线程单线程区别,图解main方法若是单多线程该如何执行,如何使用多线程2种方式)

1 A.java * 学习多线程之前&#xff0c;我们先要了解几个关于多线程有关的概念。 A:进程&#xff1a;进程指正在运行的程序。确切的来说&#xff0c;当一个程序进入内存运行&#xff0c;即变成一个进程&#xff0c;进程是处于运行过程中的程序&#xff0c;并且具有一定…

【生成数据】绘制简单的折线图

使用scatter绘制散点图并设置其样式 plt.scatter(2, 4, s200)#设置图表标题并给坐标轴加上标签 plt.title("Square Number", fontsize24) plt.xlabel("Value", fontsize14) plt.ylabel("Square of Value", fontsize14)#设置刻度标记的大小 plt.…

2022年,Rust与Go哪一个更好?

这是每一个程序员和开发人员都问过的问题&#xff0c;还有很多人仍然在问&#xff0c;即使他们已经做出了自己的决定。Rust vs. Go。2022年&#xff0c;我应该选择哪一个&#xff1f;或选择哪种语言--Golang或Rust。 Golang和Rust是目前使用的最年轻的编程语言。Go于2009年在谷…

最新ChatGPT4.0Plus开通教程-支付宝购买苹果礼品卡-亲测可用

2023.06.04亲测可用ChatGPT开通Plus教程 前言&#xff1a;一、准备工作二、购买苹果礼品卡一、官网购买礼品卡二、支付宝方式购买 三、AppStore充值礼品卡四、ChatGPT Plus 订阅五、iOS 端 ChatGPT Plus 订阅失败解决方法六、美区AppStore账号ID注册教程&#xff1a; 之前&…

【Svelte】一个简单的前端框架

Svelte.js的学习成本高吗&#xff1f; Svelte是新手编码初学者的完美平台。只需一个HTML/CSS和JavaScript技能组合&#xff0c;您就可以从头开始构建您的第一个网站&#xff0c;而无需额外的知识。 这使得学习曲线非常小&#xff0c;不像它的大多数替代方案。除此之外&#xf…

ChatGLM-6b 多任务微调

ChatGLM-6b也是一种预训练模型&#xff0c;它也可以通过微调来适应下游任务。实验表明&#xff0c;使用ChatGLM-6b微调和Bert类预训练模型微调的效果相近。如果采用多任务设计&#xff0c;ChatGLM-6b的效果会更好。你可以在这里了解更多关于ChatGLM-6B的信息: ChatGLM-6Bhttps:…

边缘化中FEJ图例的理解

如图所示&#xff0c;在解释为什么需要FEJ(First Estimation Jacobian)时&#xff0c;通常会将这个图拿出来说事。但是&#xff0c;很多时候只是一笔带过&#xff0c;这个图看的云里雾里的&#xff0c;不是非常明白(可能是我理解力的问题&#xff09;&#xff0c;所以&#xff…

AngularJs学习笔记--bootstrap

AngularJs学习笔记系列第一篇&#xff0c;希望我可以坚持写下去。本文内容主要来自 AngularJS 文档的内容&#xff0c;但也加入些许自己的理解与尝试结果。 一、总括 本文用于解释Angular初始化的过程&#xff0c;以及如何在你有需要的时候对Angular进行手工初始化。 二、An…

【云原生-K8s】k8s可视化管理界面安装配置及比较【Kubesphere篇】

总览 安装了k8s控制面板&#xff0c;方便日常的问题处理&#xff0c;查看资源状态信息&#xff0c;也可以增加子账号进行开放给其他人员使用&#xff0c;减少命令操作&#xff0c;提升工作效率 前置条件 须有一个正常使用的k8s集群附k8s v1.23版本搭建&#xff1a;https://…

JavaScript实例(Visual Studio Code)(一)

JavaScript程序本身不能独立存在 它是依附于某个HTML页面 在浏览器端运行的 基本语法&#xff1a; <script type"text/javascript" [src"外部js文件"]>... </script> 语法说明&#xff1a; script为脚本标记&#xff0c;它必须以<scri…

【小沐学Web】Rust实现Web服务器

文章目录 1、简介2、开发环境配置2.1 下载2.2 安装2.3 编辑工具2.4 构建工具2.5 自动化工具 3、Hello World4、TCP/UDP通信5、Web服务器结语 1、简介 https://www.rust-lang.org/ Rust: 一种使每个人都能够构建可靠且高效的软件的语言。 如今&#xff0c;全球有数百家公司在生…

谈谈Memcached与Redis

1. Memcached简介 Memcached是以LiveJurnal旗下Danga Interactive公司的Bard Fitzpatric为首开发的高性能分布式内存缓存服务器。其本质上就是一个内存key-value数据库&#xff0c;但是不支持数据的持久化&#xff0c;服务器关闭之后数 据全部丢失。Memcached使用C语言开发&am…

【01】水仙花数算法

水仙花数 是指一个n位数&#xff08;n ≥ 3&#xff09;&#xff0c;它的每个位上的数字的n次幂之和等于该数本身。换句话说&#xff0c;对于一个三位数而言&#xff0c;如果它满足条件&#xff1a;各个位上的数字的立方和等于该三位数本身&#xff0c;那么这个数就被称为水仙花…

chatgpt赋能python:Python操作——去除非字母元素优化SEO

Python操作——去除非字母元素优化SEO 介绍 在做SEO优化时&#xff0c;处理关键词是必不可少的环节。我们需要对关键词进行一些处理&#xff0c;使其更加规范、简洁、且易于搜索引擎的识别和分类。其中一个重要的环节&#xff0c;就是去除非字母元素&#xff0c;即去除关键词…

大模型训练和部署的关键技术

自2016年至今&#xff0c;模型大小每18个月增长40倍&#xff0c;自2019年到现在&#xff0c;更是每18个月增长340倍。 然而相比之下&#xff0c;硬件增长速度较慢&#xff0c;自2016年至今&#xff0c;GPU的性能增长每18个月1.7倍&#xff0c;模型大小和硬件增长的差距逐渐扩大…

LeetCode110. 平衡二叉树

题目 leetcode110. 平衡二叉树 思路 只有每个节点的左右子树高度差不超过1才是平衡二叉树&#xff0c;因此可以递归解决。 递归的2要素&#xff1a; ①终止条件&#xff1a;当左右子树高度差超过1时返回false&#xff1b;递归到空节点和叶子节点时&#xff0c;由于空节点和…

每日学术速递5.31

CV - 计算机视觉 | ML - 机器学习 | RL - 强化学习 | NLP 自然语言处理 Subjects: cs.CV 1.Prompt-Free Diffusion: Taking "Text" out of Text-to-Image Diffusion Models 标题&#xff1a;无提示扩散&#xff1a;从文本到图像扩散模型中提取“文本” 作者&…

单片机GD32F303RCT6 (Macos环境)开发 (三十五)—— 数字加速度计 (ADXL345 ) 使能中断获取运动与静止状态

数字加速度计 &#xff08;ADXL345&#xff09;- 使能中断获取运动与静止状态 1、几个与运动、静止检测相关的寄存器 a、寄存器 0x24—THRESH_ACT(读/写) THRESH_ACT寄存器为8位寄存器&#xff0c;保存检测活动的阈 值。数据格式无符号&#xff0c;因此&#xff0c;活动事件…