大型语言模(LLM) : 提示词工程(一)

news2024/10/7 14:30:54

今天我学习了DeepLearning.AI的 Prompt Engineering 的在线课程,我想和大家一起分享一下该门课程的一些主要内容。

下面是我们访问大型语言模(LLM)的主要代码:

import openai

openai.api_key  ='XXXXXXXXX'

def get_completion(prompt, model="gpt-3.5-turbo"):
    messages = [{"role": "user", "content": prompt}]
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=0, 
    )
    return response.choices[0].message["content"]

提示词原则(Prompting Principles)

  • 原则1:写出清晰和具体的说明(Write clear and specific instructions)

  • 原则2:给模型时间“思考”(Give the model time to “think”)

策略

策略 1:使用分隔符清楚地指示输入的不同部分
分隔符可以是:```, """, < >, <tag> </tag>, :

对策略1的说明:

策略1的意思是:如果我们需要chatgpt完成某个特定任务,那么我们要在prompt里面明确的告诉ChatGPT需要做的事情是什么以及所需要的素材的位置。比如我们要chatGPT对一段文本内容做一个总结或摘要,那么我们就需要在prompt中指明:1.需要gpt完成的任务是什么, 2. 任务所需的素材在哪里。

下面的代码演示的是让gpt对一段特定文本内容做摘要, 在定义prompt时我们需要用特定的分隔符来分隔需要做摘要的文本内容,这样做的目的是让gpt知道文本内容所在位置。

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)

 策略 2:可以要求GPT给出一个结果化的结果

  • 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)

 策略3:要求模型检查条件是否满足

这里我们要求gpt去检查一段文本的内容是否满足特定的条件(步骤),如果满足则按条件输出符合条件的内容,如果不满足条件则输出:不符合条件。

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_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)

 上述两个prompt中第一个prompt的内容符合特定的条件,所以结果按条件输出结果,第二个prompt不符合条件,所以输出: 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)

上述的prompt要求ChatGPT以一致的风格来回答问题,在prompt中给出来child和grandparent的一轮对话内容作为一个例子,这样做的目的是让ChatGPT明白所谓的“consistent style”是怎么一回事,prompt的最后是child的一个问题,但是没有grandparent的回答。这是让ChatGPT明白要做的事情是:充当grandparent角色来回答child的最后一个问题,并且风格要和前面的grandparent的风格保存一致。

下面是ChatGPT返回的结果:

 原则 2:给模型时间“思考”

策略 1:指定完成任务所需的步骤

这里我们会给模型一段文本,然后要求模型按指定的步骤来完成一个任务:

执行以下操作:
1 - 用 1 个句子总结以下用三重反引号分隔的文本。
2 - 将摘要翻译成法语。
3 - 在法语摘要中列出每个名字。
4 - 输出包含以下键的 json 对象:french_summary、num_names。

用换行符分隔你的答案。

ext = 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)

 要求指定格式的输出

这里我们要求ChatGPT按指定的格式来输出内容,在prompt中的内容分成了2部分,上半部分告诉ChatGPT需要做哪几件事情,下半部分输出的格式:

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)

 策略 2:在匆忙下结论之前指示模型自己制定解决方案

这里在prompt中给ChatGPT出了一道学生做的简单的数学应用题,希望ChatGPT来判断学生的答案是否正确。对于ChatGPT给出的答案我们发现,它并没有仔细的去亲自去做这道题目,结果给出了一个错误的答案。从中我们发现,当prompt中的问题的逻辑比较复杂的时候,我们直接了当的要求ChatGPT给出一个答案时候,ChatGPT也会像人类一样经常犯错误。下面我们先将prompt翻译一下:

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)

 

请注意,该学生的答案实际上是不正确的。

我们可以通过指示ChatGPT首先计算出自己的答案再来判断学生的答案是否正确。因此需要改写一下prompt,我们需要把求解这道应用题的详细步骤告诉ChatGPT:

接下来给出实现这些步骤的具体格式:

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)

 这里我们可以发现ChatGPT的实际输出是从“Use the following format:” 的“Actual solution:”开始的,并没有将“Question:”和“Student's solution:”这两部分内容输出。这表明ChatGPT能够理解人类的意图,因为“Question:”和“Student's solution:”部分在题目中已经出现,无需在重复输出,只需输出“Actual solution:”部分以后的内容即可。最后ChatGPT通过比对自己的答案和学生的答案后给出了正确的答案。

模型局限性:幻觉(Hallucinations)

当ChatGPT不知道问题答案时候,ChatGPT往往不会承认自己不知道,因此GPT往往会在不知道正确答案的时候会给出一个貌似正确的错误答案。

下面我们在prompt中要求ChatGPT给出Boie这家公司的电动牙刷的相关信息,这里的 Boie 是一家真实的公司,产品名称不是真实的。

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

 这里我们发现ChatGPT对一个Boie公司不存在的产品说了一大堆的内容,好像这个产品是真实存在似的。

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

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

相关文章

高性能分布式API网关Kong

目录 1 kong网关简介2 为什么需要 API 网关2.1 和Spring Cloud Gateway区别 3 为什么要使用kong3.1 kong的组成部分3.2 Kong网关的特性 4 kong网关架构4.1 Kong网关请求流程 5 kong 部署5.1 搭建网络5.2 搭建数据库环境5.3 kong网关部署5.3.1 初始化kong数据5.3.2 启动Kong容器…

【项目】树莓派4B镜像安装

本文主要记录下如何使用Raspberry Pi image 软件进行树莓派镜像进行安装。 官网&#xff1a;Raspberry Pi OS – Raspberry Pi 百度网盘&#xff1a; 链接&#xff1a;https://pan.baidu.com/s/1G7z1Fdvk5Chmhj894WPU3A 提取码&#xff1a;xnzw 一、格式化SD卡 若SD卡存在…

释放潜能——解读新时代OEM竞争规则,打造精雕细琢的用户体验

从消费零售全领域的实践观察来看&#xff0c;仅仅凭借产品赢得竞争的时代已经过去&#xff0c;商业模式创新体现在越来越多企业向“产品服务”转变&#xff0c;向用户全生命周期需求挖掘转变。企业与消费者之间的关系从过去的一次性、断点式产品交易&#xff0c;转向持续性、覆…

读写ini配置文件(C++)

文章目录 1、为什么要使用ini或者其它(例如xml,json)配置文件&#xff1f;2、ini文件基本介绍3、ini配置文件的格式4、C读写ini配置文件5、 代码示例6、 配置文件的解析库 文章转载于&#xff1a;https://blog.csdn.net/weixin_44517656/article/details/109014236 1、为什么要…

基于 Web 和 Deep Zoom 的高分辨率大图查看器的实践

基于 Web 和 Deep Zoom 的高分辨率大图查看器的实践 高分辨率大图像在 Web 中查看可以使用 Deep Zoom 技术&#xff0c;这是一种用于查看和浏览大型高分辨率图像的技术&#xff0c;它可以让用户以交互方式浏览高分辨率大图像&#xff0c;并且能够在不影响图像质量的情况下进行…

搭建个人网站 保姆级教程(四)Navicat链接mySql 失败

长时间没有折腾云服务器上的mysql了&#xff0c;今天再次使用Navicat连接云服务器上的mysql时&#xff0c;输入密码报错&#xff01; 1130 - Host ‘119.130.212.168’ is not allowed to connect to this MySQL server 1.于是Royal TSX 远程服务器查看mysql的状态 systemctl …

通达信标记文字中可能用到的特殊符号大全

特殊符号是难以直接输入的符号&#xff0c;特殊符号是符号的一种&#xff0c;比如说圆圈&#xff08;〇&#xff09;、叉号&#xff08;✕、✖、✘&#xff09;、五角星&#xff08;★、☆&#xff09;、勾号&#xff08;✓、✔&#xff09; 。 01.特殊符号简表 ♠♣♧♡♥❤…

chatgpt赋能python:Python强制取整:如何在Python中正确进行取整操作

Python强制取整&#xff1a;如何在Python中正确进行取整操作 Python是一种广泛使用的编程语言&#xff0c;有许多不同的用途&#xff0c;包括数据分析、web开发、机器学习、科学计算等等。Python语言非常容易学习和使用&#xff0c;但有时候它的行为可能会出人意料&#xff0c…

alpa概览

文章目录 背景alpa简介DeviceMesh跨 DeviceMeshes 的 GPU Buffer管理Ray CollectivePipeline parallelism runtime orchestration运行时 背景 LLM训练有3D并行的需求&#xff08;alpa将数据并行视为张量并行&#xff0c;即张量沿batch切分&#xff09; 算子间并行的通信成本小…

【Vue】父子组件传参 孙子调用爷爷的方法 provide inject

一. 父传子 父组件先在data中定义要传给子组件的属性名父组件在中引入子组件在components中注册使用步骤 3 中注册好的子组件在 3 中&#xff0c;父传子 &#xff08;1&#xff09;利用 : 将父组件的对象、数组、字符串等传给子组件&#xff0c;供子组件使用 &#xff08;2&am…

Rocky Linux9安装教程

序言 Centos废了&#xff0c;最近在考虑将服务器迁移至Rockylinux系统&#xff0c;在这里记录下安装过程 当前安装版本RockyLinux9.2&#xff08;minimal版本&#xff09;&#xff0c;VMware Fusion专业版13.0.2 创建虚拟机 第一步&#xff1a; 先下载好ISO文件&#xff0c…

python-高级特性

文章目录 1.生成式2.生成器3.闭包4.装饰器&#xff08;1&#xff09;万能装饰器的实现&#xff08;2&#xff09;含参数的装饰器&#xff08;3&#xff09;多装饰器 5.内置高阶函数 1.生成式 列表生成式就是一个用来生成列表的特定语法形式的表达式。是Python提供的一种生成列表…

2023.6.7小记——什么是FPGA?

最近打算开始继续做一些个人分享&#xff0c;已经太久时间没有写文章了&#xff0c;感觉这样下去肯定不是个好事&#xff0c;当程序员当然是要保持分享~ 标题就暂时先以每天我认为最重要的一点来取&#xff0c;内容不仅限于此。 1. 什么是FPGA&#xff1f; 全称是Field-Progra…

PCL 点云均值漂移算法(MeanShift)

文章目录 一、简介二、实现代码三、实现效果参考资料一、简介 均值漂移算法是一种非常经典的层次聚类方式,已在二维图像中得到了广泛的应用。这里我们也已二维图像为例来阐述其整个计算过程: 算法基本思想:如下图所示,左侧为实际的图像特征的分布,右侧为基于图像特征分布计…

Linux操作系统——第二章 进程控制

目录 进程创建 fork函数初识 fork函数返回值 写时拷贝 fork常规用法 fork调用失败的原因 进程终止 进程退出场景 进程常见退出方法 _exit函数 exit函数 return退出 进程等待 进程等待必要性 进程等待的方法 wait方法 waitpid方法 获取子进程status 进程程序…

接口测试框架实战 | 通用 API 封装实战

接口测试仅仅掌握 Requests 或者其他一些功能强大的库的用法&#xff0c;是远远不够的&#xff0c;还需要具备能根据公司的业务流程以及需求去定制化一个接口自动化测试框架的能力。所以&#xff0c;接下来&#xff0c;我们主要介绍下接口测试用例分析以及通用的流程封装是如何…

火龙果MM32F3273G8P开发板MindSDK开发教程3 - Sysclk的配置

Sysclk的配置 1、时钟初始化流程 一般流程为startup_mm32f3273g.s中调用system_mm32f3273g.c中的SystemInit函数完成系统时钟的初始&#xff0c;而system_mm32f3273g.c中函数是空的。 原来MindSdk时钟初始化的流程放到了clock_init.c中。 2、采用外部高速时钟源 先弄清几个…

Effective第三版 中英 | 第二章 创建和销毁对象 | 通过私有构造器强化不可实例化的能力

文章目录 Effective第三版前言第二章 创建和销毁对象通过私有构造器强化不可实例化的能力 Effective第三版 前言 大家好&#xff0c;这里是 Rocky 编程日记 &#xff0c;喜欢后端架构及中间件源码&#xff0c;目前正在阅读 effective-java 书籍。同时也把自己学习该书时的笔记…

文本三剑客 之 grep

目录 一.grep 1.grep常用选项命令选项 2.grep 命令选项 3.简单的正则表达式 二.sort 命令 三.uniq 去重 四 .语法格式&#xff1a; tr 选项 参数 五.快速裁剪命令——cut: 六.split 文件拆分 七.文件合并——paste 一.grep 文本三剑客了之一&#xff0c;对文本内容进行…

网络通信 --- HTTP 协议初识

目录 &#x1f332;一、HTTP 协议是什么 &#x1f333;二、HTTP协议格式 &#x1f9aa;1.抓包工具的使用(以 Fiddler 为例) &#x1f363;2. 抓包工具的原理 (以 Fiddler 为例) &#x1f364;3. 抓包结果 &#x1f365;① HTTP 请求(request) &#x1f96e;②HTTP响应(re…