ChatGPT提示词工程(一):Guidelines准则

news/2024/12/28 19:12:18/

目录

  • 一、说明
  • 二、安装环境
  • 三、Guidelines
    • 准则一:写出明确而具体的说明
      • 方法1:使用分隔符清楚地表示输入的不同部分
      • 方法2:用结构化输出:如直接要求它以HTML或者JSON格式输出
      • 方法3:请模型检查是否满足条件
      • 方法4:Prompt中包含少量样本
    • 准则二:给模型一些思考的时间
      • 方法1:指定完成任务所需的步骤
      • 方法2:指示模型在匆忙得出结论之前制定出自己的解决方案
  • 四、模型的限制

一、说明

这是吴恩达 《ChatGPT Prompt Engineering for Developers》 的课程笔记系列。
本文是第二讲的内容:Guidelines
课程主讲:Andrew Ng,Isa Fulford
Isa Fulford也是《OpenAI Cookbook》的主要贡献者之一

二、安装环境

1. 下载openai

pip install openai 

如果是在jupyter notebook上安装,前面需要带英文感叹号(!),之后需要执行bash指令的地方都这样

!pip install openai 

2. 导入openai,并配置openai api key

import openai
import osfrom dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())openai.api_key = os.getenv('OPENAI_API_KEY')

这里的OPENAI_API_KEY是设置在环境变量里的值,为你的openai api key
设置环境变量bash指令:

!export OPENAI_API_KEY='sk-...'		

或者,在代码中直接这样写:

openai.api_key = 'sk-...'    

3. 辅助函数
调用openai接口

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


三、Guidelines

准则一:写出明确而具体的说明

方法1:使用分隔符清楚地表示输入的不同部分

分隔符可以是:

 ```,  """,  < >,  <tag> </tag>,  :   

它可以防止prompt注入,以免给模型产生混乱的理解

例子:

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)

{text} 就是使用符合 ```分隔的内容
以上代码输出的结果为,打印的一句话总结的text的结果:
在这里插入图片描述

方法2:用结构化输出:如直接要求它以HTML或者JSON格式输出

例子:

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)

代码中,要求生成三个虚拟的图书,以JSON格式输出,运行结果:
在这里插入图片描述

方法3:请模型检查是否满足条件

要求检查:要求模型先检查是否满足某个条件后,再进行输出,如果条件不满足可以直接告知。
例子:

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)

代码中,text的内容是泡一杯茶的步骤,prompt要求模型理解这段内容,告知是否能把它分解成一步一步的步骤的结构,如果能,则按照步骤描述重写,如果不能则给出则返回No steps provided。代码输出结果:
在这里插入图片描述
下面这个例子则给出的是不能分解成步骤的一段话:

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)

在这里插入图片描述

方法4:Prompt中包含少量样本

例子:

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)

代码中,给了一个child和grandparent对话的样本,要求再次按照这个样本给出grandparent的答复,运行结果:
在这里插入图片描述

https://blog.csdn.net/Jay_Xio/article/details/130450026



准则二:给模型一些思考的时间

方法1:指定完成任务所需的步骤

例子:

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.
"""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)

代码中,prompt给出模型要执行任务的步骤
步骤1,用一句话总结text内容
步骤2,翻译成法语
步骤3,列出名字
步骤4,以JSON格式输出
执行代码,模型按照这个步骤输出:
在这里插入图片描述

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

在这里插入图片描述

方法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)

代码中,要求模型判断学生的结题是否正确,运行结果:
在这里插入图片描述
明显第3部,MainTenance const: 应该是 100000 + 10x,而学生给出的是错误的,模型没有判断出这个步骤有误,因为它只判断了 Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000 是正确的,就给出了正确的结论。

下面的示例,要求模型先自己按照步骤一步一步给出解题步骤,然后再判断学生的解题步骤是否正确:

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)

运行结果: 给出了正确解法,并判断学生的是错误的
在这里插入图片描述

https://blog.csdn.net/Jay_Xio/article/details/130450026



四、模型的限制

prompt = f"""
Tell me about AeroGlide UltraSlim Smart Toothbrush by Boie
"""
response = get_completion(prompt)
print(response)

要求模型介绍Boie这个公司的电动牙刷,其实这个公司不存在,产品也不存在,但是模型会煞有其事的介绍
在这里插入图片描述
这种模型的限制,称为模型的幻觉。

要减少这种幻觉,需要模型先从文本中找到任何相关的引用,然后请它使用这些引用来回答问题,并且把回答追溯到源文件


http://www.ppmy.cn/news/953108.html

相关文章

还不懂如何与AI高效交流?保姆级且全面的chatGPT提示词工程教程来啦!(一)基础篇

还不懂如何与chatGPT高效交流&#xff1f;保姆级且全面的chatGPT提示词工程教程来啦&#xff01;&#xff08;一&#xff09;基础篇 文章目录 还不懂如何与chatGPT高效交流&#xff1f;保姆级且全面的chatGPT提示词工程教程来啦&#xff01;&#xff08;一&#xff09;基础篇一…

ChatGPT提示词学习手册

前言 欢迎来到《ChatGPT提示的艺术&#xff1a;制作清晰和有效提示的指南》&#xff01;在这本全面的指南中&#xff0c;您将学习到关于制作清晰和有效的ChatGPT提示的一切知识&#xff0c;以推动引人入胜和信息丰富的对话。 无论您是初学者还是有经验的ChatGPT用户&#xf…

ChatGPT提示词技巧

自计算机问世以来&#xff0c;人类与计算机之间的交互方式已经经历过几个重要的阶段&#xff1a; 指令式交互&#xff08;Command-based Interaction&#xff09; 早期的计算机系统主要采用了指令式交互方式&#xff0c;用户需要输入特定的命令或代码来完成各种任务。这种交…

全网最全的ChatGPT提示词

全网最全最好用的ChatGPT调教指南(prompt) 什么是prompt 提示词&#xff08;Prompt&#xff09;是一种向人工智能系统&#xff08;如ChatGPT等&#xff09;提供的输入&#xff0c;用于引导和激发AI生成特定的回应或内容。在许多情况下&#xff0c;AI prompt可以是一个问题、一…

chat gpt的提示词汇总

提示词的存在让ChatGPT能够扮演特定的角色&#xff0c;对用户的回答更加专业对口 ChatGPT在日常的对话中&#xff0c;表现的非常的完美&#xff0c;当在其他的场景希望使用ChatGPT来解决问题的时候&#xff0c;通常需要给ChatGPT一些提示&#xff0c;或者说暗示&#xff0c;让其…

MySQL日常操作记录

1.查看MySQL版本 select version();2.快速复制表结构&#xff0c;不包含相关主键及约束 create table user_test as select * from user where 12;3.uuid select uuid(),uuid_short();4.替换uuid()里的’-‘为’’ select replace(uuid(),-,);5.md5摘要 select md5(uuid()…

Claude AI和ChatGPT的区别

Claude AI和ChatGPT都是基于人工智能技术的智能对话系统&#xff0c;但它们的设计和应用场景有一些不同。 Claude AI是一个基于语音识别、自然语言处理和机器学习等技术的智能客服平台。它能够像人一样进行对话&#xff0c;并根据用户提供的问题提供相应的答案&#xff0c;从而…

MOSS与ChatGPT,人工智能真的会取代人类吗?

MOSS与ChatGPT&#xff0c;人工智能真的会取代人类吗&#xff1f; 1 引言2 MOSS2.1 MOSS能力表现2.2 量子计算机2.3 MOSS实现的可能 3 ChatGPT3.1 ChatGPT的爆火3.2 ChatGPT能干什么3.3 ChatGPT带起的潮流3.4 ChatGPT具有自主意识吗&#xff1f; 4 结语 550W听起来不像是个名字…