【Prompting】ChatGPT Prompt Engineering开发指南(1)

ChatGPT Prompt Engineering开发指南1

  • Prompting指南
    • 设置
  • 提示原则
    • 策略1:使用分隔符清楚地指示输入的不同部分
    • 策略2:要求结构化输出
    • 策略3:让模型检查条件是否满足
    • 策略4: “Few-shot”提示
  • 原则2:给模型时间“思考”
    • 策略1:指定完成任务所需的步骤
    • 策略2:指导模型在匆忙得出结论之前制定自己的解决方案
  • 模型限制:幻觉
  • 补充内容
  • 参考资料

Prompting指南

在本课程中,您将练习两个提示原则及其相关策略,以便为大型语言模型编写有效的提示。本代码的编写基于Google colab notebook。

!pip install openai
!pip install -U python-dotenv

注:python-dotenv 可以用来修改 POSIX系统的环境变量.

设置

加载API密钥和相关的Python Libaries。

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

注意:上面是Deeplearning.AI给定的参考代码样例,这里不太适用,会报错,我们对其进行修改,如下:

import os
import openai# 注意,我们设置了本地代理
os.environ["http_proxy"] = "http://127.0.0.1:7890"
os.environ["https_proxy"] = "http://127.0.0.1:7890"# Set the OpenAI API key
os.environ['OPENAI_API_KEY'] = "sk-your open.api_key" # get api_key from openai official website
# openai.api_key = os.getenv("OPENAI_API_KEY")

辅助函数
在整个课程中使用OpenAI的GPT-3.5-Turbo模型Chat completions

curl https://api.openai.com/v1/chat/completions \-H "Content-Type: application/json" \-H "Authorization: Bearer $OPENAI_API_KEY" \-d '{"model": "gpt-3.5-turbo","messages": [{"role": "user", "content": "Hello!"}]}'

由于gpt-3.5-turbo的性能与text-davinci-003类似,但每个token的价格为10%,因此我们建议在大多数用例中使用gpt-3.5-turbo

此辅助函数将使使用提示更容易,并查看生成的输出:

def get_completion(prompt, model="gpt-3.5-turbo"):messages = [{'role': 'user', 'content': prompt}]response = openai.ChatCompletion.create(model=model,messages=messages,max_tokens=1024,n=1,temperature=0,  # this is the degree of randomness of the model's output# stop=None,# top_p=1,# frequency_penalty=0.0,# presence_penalty=0.6,)return response['choices'][0]['message']['content']

注意:使用什么样的temperature,介于0和2之间。值越高(如0.8),输出越随机,而值越低(如0.2),输出就越集中,确定性更强。其他参数详细解释见openai官方文档:https://platform.openai.com/docs/api-reference/completions/create

提示原则

  • 原则1:写清晰而具体的说明
  • 原则2:给模型时间“思考”

策略1:使用分隔符清楚地指示输入的不同部分

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

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)

策略1输出结果

策略2:要求结构化输出

  • 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:让模型检查条件是否满足

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”提示

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:指定完成任务所需的步骤

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
}

要求以指定格式输出:

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:指导模型在匆忙得出结论之前制定自己的解决方案

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)

执行结果:
执行结果

模型限制:幻觉

Boie是一家真正的公司,产品名称不是真实的。

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

执行结果

补充内容

错题小提示
关于反斜杠的注释:

  • 在本教程中,我们使用反斜杠使文本适合屏幕,而不插入换行符“\n”。
  • 无论是否插入换行符,GPT-3都不会真正受到影响。但是,在一般使用LLM时,您可能会考虑提示中的换行符是否会影响模型的性能。

参考资料

  1. DeepLearning.AI: ChatGPT Prompt Engineering for Developers
  2. python-dotenv的详细用法
  3. OpenAI调用API报错 time out:HTTPSConnectionPool(host=‘api.openai.com‘, port=443)

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

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【ChatGPT】Prompt Engineering入门

Prompt Engineering入门 一、什么是 Prompt Engineering&#xff1f;二、我们还需要学习 PE 吗&#xff1f;三、Prompt基础原则 一、什么是 Prompt Engineering&#xff1f; 简单的理解它是给 AI 模型的指令。它可以是一个问题、一段文字描述&#xff0c;甚至可以是带有一堆参数…

大型语言模型LLM的基础应用

ChatGPT是由人工智能研究实验室OpenAI在2022年11月30日发布的全新聊天机器人模型&#xff0c;一款人工智能技术驱动的自然语言处理工具。它能够通过学习和理解人类的语言来进行对话&#xff0c;还能根据聊天的上下文进行互动&#xff0c;真正像人类一样来聊天交流&#xff0c;甚…

【ChatGPT】怎样计算文本token数量?

ChatGPT 按 token 计费&#xff0c;当你把一段长文本发送给它时&#xff0c;你如何计算该文本消耗了多少 token&#xff1f; 在非流式访问的情况下&#xff0c;ChatGPT 的回复信息中包含有 token 消耗数量。但是在流式访问的情况下&#xff0c;回复信息里没有 token 数量&…

微软用 ChatGPT 改写 Bing、Edge,市值一夜飙涨 5450 亿元!

整理 | 屠敏 出品 | CSDN&#xff08;ID&#xff1a;CSDNnews&#xff09; 已经没有什么能够阻挡科技巨头追逐 ChatGPT 的步伐&#xff0c;前有 Google CEO 桑达尔皮查伊亲自下场官宣 Bard AI 对话式系统的到来&#xff0c;后有微软更快一步地推出了应用 ChatGPT 的 Bing 搜索引…

ChatGPT和DALLE-2级联后,输出效果震撼了…

源&#xff5c;机器之心 文&#xff5c;张倩、袁铭怿 生成式 AI 正在变革内容的生产方式。 在过去的一周&#xff0c;相信大家都被 ChatGPT 刷了屏。这个强大的对话 AI 仅用 5 天时间用户量就突破了 100 万。大家用各种方式测试着它的能力上限&#xff0c;其中一种测试方式就是…

ChatGPT 的能力上限将被突破

最近&#xff0c;一篇名为《Scaling Transformr to 1M tokens and beyond with RMT》的论文在 AI 界引起了广泛热议。 该论文提出一种名为 RMT 的新技术&#xff0c;如果能够成功应用&#xff0c;那将把 Transformer 的 Token 上限扩展至 100 万&#xff0c;甚至更多。 GitHub…

ChatGPT 的 10 种集成模式:从开源 AI 体验平台 ClickPrompt 中受到的启发

和国内外的很多公司一样&#xff0c;在 Open AI 公司开放了 ChatGPT API 接口之后&#xff0c;我们也在探索如何去结合到业务中。而在探索的过程中&#xff0c;我们发现了一个问题&#xff0c;大部分的业务人员并不了解 AI 的能力&#xff0c;所以我们开源构建了 ClickPrompt&a…

聊天新纪元:通过和ChatGPT聊天就能开发自己的Chrome插件

文章目录 1. 前言1.1 ChatGPT是什么1.2 ChatGPT能干什么1.3 我要让ChatGPT干什么 2. 环境准备3. 交互过程3.1 发送需求3.2 询问执行3.3 继续提问3.4 加载代码3.5 执行插件3.6 执行插件 4. 生成的代码4.1 manifest.json4.2 popup.css4.3 popup.js4.4 popup.html 5. 总结 1. 前言…

学术科研专用ChatGPT来了!

点击上方“小白学视觉”&#xff0c;选择加"星标"或“置顶” 重磅干货&#xff0c;第一时间送达 【导读】最近&#xff0c;一位开发者在GitHub上开源的「科研工作专用ChatGPT」项目大受好评。论文润色、语法检查、中英互译、代码解释等等一键搞定。 自从ChatGPT发布之…

今天,小呆呆第一次尝新ChatGPT,并小火了一把

前言 你盼世界&#xff0c;我盼望你无bug。Hello 大家好&#xff01;我是霖呆呆。 当我们遇到技术难题或生活困惑时&#xff0c;往往会寻求专业人士的帮助或者在网络上搜索相关问题。但你是否曾想过&#xff0c;如果有一种AI程序能够帮你解决问题&#xff0c;理解人类语言的含义…

ChatGPT真的有那么牛吗?

ChatGPT真的有那么牛吗&#xff1f;ChatGPT真的有那么牛吗&#xff1f; 作为一款大型语言模型&#xff0c;ChatGPT确实具有很高的自然语言处理和生成能力&#xff0c;可以生成流畅、准确和有逻辑性的语言&#xff0c;而且能够理解和回答广泛的问题。 它是目前最先进和最强大的…

大型语言模型用例和应用 Large Language Models Use Cases and Applications

目录 Large Language Models Use Cases and Applications大型语言模型用例和应用 What are large language models and how do they work什么是大型语言模型及其工作原理 Large language model examples 大型语言模型示例 Large language model use cases 大型语言模型用例…

WIKIBON:大模型炒作中,有哪些云与AI的新趋势?

进入2023年以来&#xff0c;以ChatGPT为代表的大模型喧嚣引发了AI的新一轮炒作热潮&#xff0c;堪比当年的加密货币。不同的是&#xff0c;以微软、NVIDIA、AWS、Google等为代表的云与芯片大厂纷纷实质性入局大模型&#xff0c;为大模型AI注入持续的生命力。因此ChatGPT可类比于…

chatGPT爆火让我们反思——人工智能是新的加密货币吗?

核冬天技术末日到来了&#xff0c;只有人工智能幸免于难。峰值 AI 指标无处不在。它能保持加密失去的信念吗&#xff1f; 作者&#xff1a;John Luttig 翻译: Chainwise 核冬天技术末日到来了&#xff1a;软件、SPAC、金融科技和加密货币都进入了深度冻结状态。AI 可能是唯一穿…

这AI二维码也太酷炫了!谷歌生成式AI学习路径;媒体的AI炒作套路报告;使用GPT-4自动化制作短视频 | ShowMeAI日报

&#x1f440;日报&周刊合集 | &#x1f3a1;生产力工具与行业应用大全 | &#x1f9e1; 点赞关注评论拜托啦&#xff01; &#x1f916; 新鲜出炉&#xff01;2023人工智能10大分类排行榜 这是根据2023年6月德本咨询、eNet研究院和互联网周刊联调的人工智能排行榜&#xf…

从“XML一统天下”聊聊我所经历的技术炒作

【编者按】身处技术圈我们&#xff0c;时常会听到“XX 已死&#xff0c;XXX 将一统天下”的论调&#xff0c;本文作者分享了自己入行以来&#xff0c;所经历的各种技术炒作。 原始链接&#xff1a;https://www.bitecode.dev/p/hype-cycles 未经允许&#xff0c;禁止转载&#x…

对话DataFocus创始人:大模型会颠覆ToB行业吗?

​编者按&#xff1a;年初ChatGPT引爆了AIGC&#xff0c;GPT几乎成了软件从业者最高频的话题了。如今时过半载&#xff0c;子弹仍然在飞舞&#xff0c;显然这波浪潮还远远没有到平息的时候。这是一次内部分享&#xff0c;我们有幸和DataFocus创始人JET畅聊了大模型的天南海北&a…

人工智能革命|是疯狂炒作还是大势所趋?

近期关于人工智能的话题与炒作激增。如果你看看过去五年“AI”一词的搜索量&#xff0c;就会发现它一直停滞&#xff0c;直到2022年11月30日&#xff0c;OpenAI 凭借 ChatGPT 引发了人工智能革命。 Google 趋势 — 过去 5 年“AI”搜索量 短短六个月内&#xff0c;究竟发生了…

被“错用”的开源软件许可!

大多数人习惯于忽视软件许可&#xff0c;就像在安装新程序或注册服务时一样。但在 AI 领域工作时&#xff0c;考虑这些因素很重要&#xff0c;因为我们使用的所有工具的默认设置都是开源的&#xff0c;而且通常我们会协作工作&#xff0c;在别人的劳动成果之上构建自己的产品&a…

ChatGPT 成功背后的技术原因及其对生命科学领域的启发

文章目录 一、前言二、主要内容三、总结 一、前言 2023 年 2 月 19 日看见一篇关于 ChatGPT 成功背后的技术原因及其对生命科学领域的启发的思考的优质文章&#xff0c;分享于此。 原文链接&#xff1a;DrugFlow | ChatGPT 成功背后的技术原因及其对生命科学领域的启发 作者…