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

news2025/1/22 21:56:28

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 os

from 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.coloradmin.cn/o/522050.html

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

相关文章

idea新建springboot项目并提交码云仓库

新建springboot项目 平常我们在使用联网方式新建springboot项目时总是会遇到连接失败等这种情况 IDEA创建项目&#xff0c;本质是从官网创建并下载项目&#xff0c;然后导入本地。 创建项目连接失败&#xff0c;一般是外国网站的原因导致连接超时&#xff0c;解决方式很简单&a…

C++linux高并发服务器项目实践 day11

Clinux高并发服务器项目实践 day11 线程同步互斥锁死锁读写锁读写锁相关操作函数 生产者消费者模型条件变量信号量 线程同步 线程的主要优势在于&#xff0c;能够通过全局变量来共享信息。不过&#xff0c;这种便捷的共享是有代价的:必须确保多个线程不会同时修改同一变量&…

LabVIEWCompactRIO 开发指南17 网络流

LabVIEWCompactRIO 开发指南17 网络流 网络流类似于队列函数&#xff0c;因为它们是基于FIFO的&#xff0c;但与队列函数不同的是&#xff0c;网络流具有网络作用域。它们是为通过以太网进行无损、高吞吐量数据通信而设计和优化的&#xff0c;并且它们具有增强的连接管理功能…

Springboot +Flowable,各种历史信息如何查询(三)

一.简介 正在执行的流程信息是保存在以 ACT_RU_ 为前缀的表中&#xff0c;执行完毕的流程信息则保存在以 ACT_HI_ 为前缀的表中&#xff0c;也就是流程历史信息表。 假设有一个流程&#xff0c;流程图如下&#xff1a; 当这个流程执行完毕后&#xff0c;以 ACT_RU_ 为前缀的…

学习新技术,争做新青年:请ChatGPT帮我写一篇计算机视觉分类算法论文

文章目录 学习新技术&#xff0c;争做新青年&#xff1a;你不会还不用 ChatGPT 吧&#xff1f;学习新技术请告诉我最好的图像分类模型是哪个请推荐最新的分类模型是哪个请详细介绍一下 Swin Transformer请给出Swin Transformer的论文链接请帮我分析一下Swin Transformer 的创新…

Java实现多线程操作多账户

前言 某公司一个面试题&#xff1a; 1.有二十个账户&#xff0c;每个账户初始余额10000元。 2.有十个转账线程&#xff0c;对二十个账户中的两个随机选取账户进行转账&#xff0c;转账额度100以内正整数随机数。 3.每个线程执行100次转账操作。 4.最后请打印出二十个账户的…

西门子PLC控制步进电机方法与接线(全)

一、步进驱动系统 步进驱动系统包含步进电动机和步进驱动器&#xff0c;前端由PLC发脉冲。 步进电机是将电脉冲信号转变为角位移或线位移以控制转子转动的开环控制电机&#xff08;可以通过安装编码器形成闭环系统&#xff09;。 它旋转是以固定的角度&#xff08;步距角&…

ThinkPHP6的控制器定义及控制器初使用

ThinkPHP6的控制器定义及控制器初使用 控制器定义 控制器文件通常放在controller下面&#xff0c;类名和文件名保持大小写一致&#xff0c;并采用驼峰命名&#xff08;首字母大写&#xff09;。 如果要改变controller目录名&#xff0c;需要在route.php(config/route.php)配…

redis从零开始(1)----五种基本类型:string/hash

认识redis NoSQL Nosql not only sql&#xff0c;泛指非关系型数据库&#xff0c;与之相对的是RDBMS(Relational Database Management System)&#xff0c;即关系型数据库 关系型数据库&#xff1a;列行&#xff0c;同一个表下数据的结构是一样的。 非关系型数据库&#xff…

原生js手动实现一个多级菜单效果(高度可过渡变化)

文章目录 学习链接效果图代码要点 学习链接 vue实现折叠展开收缩动画 - 自己的链接 elment-ui/plus不定高度容器收缩折叠动画组件 - 自己的链接 Vue transition 折叠类动画自动获取隐藏层高度以及手风琴效果实现 vue transition动画钩子- vue官网 vue transition 过渡动画…

vue基础入门

1. vue简介 1.1 什么是vue 官方概念&#xff1a;Vue&#xff08;读音/vju:/&#xff0c;类似于view&#xff09;是一套用于构建用户界面的前端框架 1.2 vue 的特性 vue 框架的特性&#xff0c;主要体现在如下两方面&#xff1a; ① 数据驱动视图 ② 双向数据绑定 数据驱动…

IMS补充业务场景介绍

呼叫保持流程 通话主动Hold的一方,发INVITE消息,媒体流从sendrecv变为sendonly,对方返回200 ok,媒体流从sendrecv变为recvonly,双方ACK后,进入呼叫保持状态,没有通话的RTP包。 大致流程如下 UE A发送INVITE(Sendonly)到网络 网络发送INVITE(Sendonly)到UE B UE发…

Linux文件属性修改

关于我们的文件属性如何修改呢&#xff1f; 我们今天来看一下 chmod chmod u(拥有者)/g(所属组)/o(其他人)(-)r/w/x(t) 文件名 就是这样&#xff0c;我们演示几个 我们想给拥有者去掉file1的读权限 我们file1的拥有者已经没有读权限了&#xff0c;那么我们还想加回来呢…

asp.net+C#基于web的旅游网站自驾游网站

&#xff08;1&#xff09;登录注册模块&#xff1a;输入账号密码&#xff0c;数据库进行验证&#xff0c;正确通过后&#xff0c;根据不同的账户信息&#xff0c;不同角色&#xff0c;获取不同的功能。 &#xff08;2&#xff09;自驾游模块&#xff1a;此模块可以分享自己自…

《计算机网络—自顶向下方法》 第五章Wireshark实验:UDP 协议分析

用户数据报(UDP)协议是运输层提供的一种最低限度的复用/分解服务&#xff0c;可以在网络层和正确的用户即进程间传输数据。UDP 是一种不提供不必要服务的轻量级运输协议&#xff0c;除了复用/分用功能和简单的差错检测之外&#xff0c;几乎就是 IP 协议了&#xff0c;也可以说它…

Python操作Redis常见类型详解

1、windows 上安装 Redis 便于测试&#xff0c;笔者在 windows 上安装 Redis Redis 官方不建议在 windows 下使用 Redis&#xff0c;所以官网没有 windows 版本可以下载。微软团队维护了开源的 windows 版本&#xff0c;对于普通测试使用足够了。 1.1、安装包方式安装 Redis…

万字收藏:《2023网络工程师年度必看书单》

晚上好&#xff0c;我是老杨。 这周是总结周&#xff0c;更新的第三篇内容&#xff0c;还是关于总结的。很多人让我推荐网工适合看的书&#xff0c;其实我推荐过好多次了。 趁着年底&#xff0c;一起把我认为网工适合看的、推荐你看的、值得看的书整理一下&#xff0c;供新老…

视觉SLAM ch13 设计SLAM系统

目录 一、SLAM系统 二、工程框架 三、框架流程 四、具体实现 五、VO整体流程 六、显示整体建图效果 一、SLAM系统 实现一个精简版的双目视觉里程计&#xff0c;前端使用光流法&#xff0c;局部使用局部BA优化。 二、工程框架 app中 run_kitti_stereo.cpp是代码的运行入口…

国内免费可用 ChatGPT 网页版

ChatGPT是一个神奇的机器人&#xff0c;它可以回答任何问题&#xff0c;解决任何问题。它的名字来源于“Chat”和“GPT”&#xff0c;前者代表聊天&#xff0c;后者代表生成预测文本。它被设计成一个智能助手&#xff0c;可以帮助人们解决各种问题。 有一天&#xff0c;一个名…

【Python 爬虫之requests库】零基础也能轻松掌握的学习路线与参考资料

文章目录 一、概述二、Requests 库基本用法三、爬虫中的优秀实践四、参考资料 一、概述 Python 爬虫中&#xff0c;常用来请求网页的库有 urllib、urllib2、httplib等&#xff0c;但是这些库用起来比较麻烦&#xff0c;需要写很多代码。Requests 库正是为了解决这个问题而生的…