Openai+Coursera: ChatGPT Prompt Engineering(二)

news2024/9/22 11:35:51

这是我写的ChatGPT Prompt Engineerin的第二篇博客,如何还没看过第一篇的请先看我写的第一篇博客:

ChatGPT Prompt Engineerin(一)

Summarizing(总结/摘要)


今天我们的重点关注按特定主题来总结文本。

设置参数

import openai
openai.api_key ='YOUR_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, 
    )
    return response.choices[0].message["content"]

文本总结

下面我们来定义一段文本,该文本来自于一个电商网站的客户评论,我们要让ChatGPT来对这段文本进行总结,由于原文本内容是英文的,我将它的中文翻译文也罗列出来,这样便于大家理解原文的意思:

prod_review = """
Got this panda plush toy for my daughter's birthday, \
who loves it and takes it everywhere. It's soft and \ 
super cute, and its face has a friendly look. It's \ 
a bit small for what I paid though. I think there \ 
might be other options that are bigger for the \ 
same price. It arrived a day earlier than expected, \ 
so I got to play with it myself before I gave it \ 
to her.
"""

prod_review1="""
这个熊猫毛绒玩具是我女儿生日的礼物,她很喜欢,走到哪里都带着它。
它很柔软,超级可爱,它的脸看起来很友好。不过相对于我付的钱来说有点小了。
我想同样的价格可能还有其他更大的选择。它比预期提前了一天到达,所以我在给她之前自己玩了一下。
"""

指定用一个单词/句子/字符的限制来总结文本

prompt = f"""
Your task is to generate a short summary of a product \
review from an ecommerce site. 

Summarize the review below, delimited by triple 
backticks, in at most 30 words. 

Review: ```{prod_review}```
"""

response = get_completion(prompt)
print(response)

这里我们要ChatGPT使用不超过30个词语来总结前面给的文档,ChatGPT用非常简短的一句话对原文做出了总结。

将总结的重点放在配送和交付方面

prompt = f"""
Your task is to generate a short summary of a product \
review from an ecommerce site to give feedback to the \
Shipping deparmtment. 

Summarize the review below, delimited by triple 
backticks, in at most 30 words, and focusing on any aspects \
that mention shipping and delivery of the product. 

Review: ```{prod_review}```
"""

response = get_completion(prompt)
print(response)

之前的总结我们只是要求了一个字数限制(最多30个词语),没有其他别的要求了,所以ChatGPT在总结是把重点放在了玩具质量和价格方面,配送方面只是简略的提了一下: Arrived early 。现在我们要求ChatGPT将总结的重点放在配送和交付方面,从结果上看ChatGPT的总结非常符合我们的要求。

以价格和价值为重点进行总结

prompt = f"""
Your task is to generate a short summary of a product \
review from an ecommerce site to give feedback to the \
pricing deparmtment, responsible for determining the \
price of the product.  

Summarize the review below, delimited by triple 
backticks, in at most 30 words, and focusing on any aspects \
that are relevant to the price and perceived value. 

Review: ```{prod_review}```
"""

response = get_completion(prompt)
print(response)

 从ChatGPT答复的内容上来看也符合我们的要求。

尝试用“内容抽取”来替代“总结”

除了总结以外我们还可以让ChatGPT从文章“抽取”相关内容,可以用这种方式来替代“总结”。

prompt = f"""
Your task is to extract relevant information from \ 
a product review from an ecommerce site to give \
feedback to the Shipping department. 

From the review below, delimited by triple quotes \
extract the information relevant to shipping and \ 
delivery. Limit to 30 words. 

Review: ```{prod_review}```
"""

response = get_completion(prompt)
print(response)

 总结多个产品评论

接下来我们要让ChatGPT总结多个产品的评论:

review_1 = prod_review 

# review for a standing lamp
review_2 = """
Needed a nice lamp for my bedroom, and this one \
had additional storage and not too high of a price \
point. Got it fast - arrived in 2 days. The string \
to the lamp broke during the transit and the company \
happily sent over a new one. Came within a few days \
as well. It was easy to put together. Then I had a \
missing part, so I contacted their support and they \
very quickly got me the missing piece! Seems to me \
to be a great company that cares about their customers \
and products. 
"""

# review for an electric toothbrush
review_3 = """
My dental hygienist recommended an electric toothbrush, \
which is why I got this. The battery life seems to be \
pretty impressive so far. After initial charging and \
leaving the charger plugged in for the first week to \
condition the battery, I've unplugged the charger and \
been using it for twice daily brushing for the last \
3 weeks all on the same charge. But the toothbrush head \
is too small. I’ve seen baby toothbrushes bigger than \
this one. I wish the head was bigger with different \
length bristles to get between teeth better because \
this one doesn’t.  Overall if you can get this one \
around the $50 mark, it's a good deal. The manufactuer's \
replacements heads are pretty expensive, but you can \
get generic ones that're more reasonably priced. This \
toothbrush makes me feel like I've been to the dentist \
every day. My teeth feel sparkly clean! 
"""

# review for a blender
review_4 = """
So, they still had the 17 piece system on seasonal \
sale for around $49 in the month of November, about \
half off, but for some reason (call it price gouging) \
around the second week of December the prices all went \
up to about anywhere from between $70-$89 for the same \
system. And the 11 piece system went up around $10 or \
so in price also from the earlier sale price of $29. \
So it looks okay, but if you look at the base, the part \
where the blade locks into place doesn’t look as good \
as in previous editions from a few years ago, but I \
plan to be very gentle with it (example, I crush \
very hard items like beans, ice, rice, etc. in the \ 
blender first then pulverize them in the serving size \
I want in the blender then switch to the whipping \
blade for a finer flour, and use the cross cutting blade \
first when making smoothies, then use the flat blade \
if I need them finer/less pulpy). Special tip when making \
smoothies, finely cut and freeze the fruits and \
vegetables (if using spinach-lightly stew soften the \ 
spinach then freeze until ready for use-and if making \
sorbet, use a small to medium sized food processor) \ 
that you plan to use that way you can avoid adding so \
much ice if at all-when making your smoothie. \
After about a year, the motor was making a funny noise. \
I called customer service but the warranty expired \
already, so I had to buy another one. FYI: The overall \
quality has gone done in these types of products, so \
they are kind of counting on brand recognition and \
consumer loyalty to maintain sales. Got it in about \
two days.
"""

reviews = [review_1, review_2, review_3, review_4]
for i in range(len(reviews)):
    prompt = f"""
    Your task is to generate a short summary of a product \ 
    review from an ecommerce site. 

    Summarize the review below, delimited by triple \
    backticks in at most 20 words. 

    Review: ```{reviews[i]}```
    """

    response = get_completion(prompt)
    print(i, response, "\n")

 当我们通过循环遍历的方式来调用ChatGPT的API时,我们会收到一个异常的报错信息:"Rate limit", 从这里我们可以发现OpenAI似乎对API调用做了频率上的限制,即每分钟不能超过3次的api调用,这里我们的文档数量是4篇,因此在第4次循环调用API时超过了次数限制因此抛出了异常错误信息。

解决Rate limit的方法

由于openai官方对api的调用有着严格的限制,对于免费用户每分钟调用API次数不能超过3次,大家可以参考官方对 Rate limits的官方说明:

 同事官方也给出了三种针对Rate limit 解决方案,经过我的验证其中的第二种可行,第一种方案可能是由于我参数设置不当导致没有成功。以下是第二种方案:需要安装一个为回退和重试提供函数装饰器的库 backoff。

# pip install backoff
import backoff  

@backoff.on_exception(backoff.expo, openai.error.RateLimitError)
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"]

在 给get_completion函数附加了一个回退和重试的装饰器backoff后,我们再循环调用get_completion函后就不再报错,只是需要等待一定的时候后才能得到所有的答案。

请帮我买杯咖啡

如果你觉得我的文章对你有用,请帮我买杯咖啡,这样会使我时刻保持写出优秀博文的欲望和动力,谢谢!

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

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

相关文章

【备战秋招】每日一题:3月18日美团春招第二题:题面+题目思路 + C++/python/js/Go/java 带注释

2023大厂笔试模拟练习网站(含题解) www.codefun2000.com 最近我们一直在将收集到的各种大厂笔试的解题思路还原成题目并制作数据,挂载到我们的OJ上,供大家学习交流,体会笔试难度。现已录入200道互联网大厂模拟练习题&…

深入理解递归算法

文章目录 概述单路递归 Single RecursionE01. 阶乘E02. 反向打印字符串E03. 二分查找 多路递归 Multi RecursionE01. 斐波那契数列 递归优化-记忆法递归优化-尾递归递归时间复杂度-Master theorem递归时间复杂度-展开求解 概述 定义 计算机科学中,递归是一种解决计…

Unity UI -- (5)增加基础按钮功能

分析分析一些常见UI 良好的UI设计会清晰地和用户沟通。用户知道他们能和屏幕上哪些东西交互,哪些不能。如果他们进行了交互,他们也要清楚地知道交互是否成功。换句话说,UI要提供给用户很多反馈。 我们可以来看看在Unity里或者在计算机上的任何…

一款适合国内多场景的免费ChatGPT镜像网站【建议收藏】

随着人工智能技术的不断进步,智能问答系统正逐渐成为我们生活中必不可少的助手。而在这个领域中,ChatGPT中文版-知否AI问答凭借其出色的性能和广泛的应用场景,成为了引领智能问答新时代的重要代表。本文将带您深入了解ChatGPT中文版-知否AI问…

LabVIEWCompactRIO 开发指南25 实施LabVIEW FPGA代码的方法

LabVIEWCompactRIO 开发指南25 实施LabVIEW FPGA代码的方法 开始开发时,应在LabVIEW项目的FPGA目标下创建VI,以便使用LabVIEW FPGA选板进行编程,该选板是LabVIEW选板的子集,包括一些LabVIEW FPGA特定函数。 应该在仿真模式下开…

每日一个MySQL知识点:主从表大小相差巨大和一个BUG

一、主从相同表空间相差巨大 1.1 问题描述 我们知道MySQL主从基本上是逻辑的复制,那么有少量的空间差异没有问题,但是本案例主库表只有10G,但是从库表有100G,这么大的差距比较少见,需要分析原因。 1.2 问题分析 实…

ResNet (深度残差网络)

ResNet 算法概述 解决的核心问题:网络的退化现象 网络层数在变深之后,性能不如浅层时候的性能 。注意:网络退化既不是梯度消失也不是梯度爆炸。 那是如何解决退化现象的呢?引入残差模块 把模型的输入分成两条路:右边…

SQL 大全(四)|数据库迁移升级时常用 SQL 语句

作者 | JiekeXu 来源 |公众号 JiekeXu DBA之路(ID: JiekeXu_IT) 如需转载请联系授权 | (个人微信 ID:JiekeXu_DBA) 大家好,我是 JiekeXu,很高兴又和大家见面了,今天和大家一起来看看SQL 大全(四)|数据库迁移…

由浅入深了解 深度神经网络优化算法

CV - 计算机视觉 | ML - 机器学习 | RL - 强化学习 | NLP 自然语言处理 导言 优化是从一组可用的备选方案中选择最佳方案。优化无疑是深度学习的核心。基于梯度下降的方法已经成为训练深度神经网络的既定方法。 在最简单的情况下,优化问题包括通过系统地从允许集合中…

Jenkins+GitLab+Docker搭建前端自动化构建镜像容器部署

前言 🚀 需提前安装环境及知识点: 1、Docker搭建及基础操作 2、DockerFile文件描述 3、Jenkins搭建及基础点 🚀 目的: 将我们的前端项目打包成一个镜像容器并自动发布部署,可供随时pull访问 一、手动部署镜像及容器 1…

6-《网络面试》

6-《网络面试》 1.http是什么?http的工作机制?http报文?1.1 http工作机制:1.2 URL和http报文 2. HTTP请求方法和状态码3.Get和Post的区别4.HTTP的Header解析1.text/html2.x-www-form-urlencoded3.multipart/form-data4.applicatio…

中断相关概念并利用中断实现按键点亮LED灯

一.中断相关概念 什么是中断? 中断是指计算机运行过程中,出现某些意外情况需主机干预时,机器能自动停止正在运行的 程序并转入处理新情况的程序,处理完毕后又返回原被暂停的程序继续运行。 什么是EXTI? 外部…

【vue上传文件——hash】

vue上传文件 要求:只能上传视频,先计算文件的hash值,hash值一样则不需要上传,不一样在执行上传 分析:因为el-upload没有找到合适的属性,本次用的是原生的input的type属性为file上传 代码: html: 通过点击选取文件按钮调用input上传 js 第一步:点击上传文件先效验是否…

windows下免U盘安装manjaro

建议 建议先看这个https://www.bilibili.com/read/cv23161386/ 背景 新到了一块硬盘,想把这台主机做成双系统的,windowsmanjaro系统。 为什么选择manjaro? win中的虚拟机已经有了日常使用的ubuntu。体验一下manjaro。ubuntu用来开发办公要…

python 之 logging的使用

一、日志模块 import logginglogging.debug("调试日志") logging.info(消息日志) logging.warning("告警日志") logging.error(错误日志) logging.critical(严重错误日志)debug(调试)级别用于输出调试信息,这些信息主…

JDK源码阅读环境搭建

本次针对jdk8u版本的搭建 1.新建项目 新建java项目JavaSourceLearn ,这里我创建的是maven 2.获取JDK源码 打开Project Structure 找到本地JDK安装位置将src.zip解压到项目java包中 整理下项目结构,删除用不到的目录 提示: 添加源码到项目之后首次运行…

【BBQ: A Hand-Built Bias Benchmark for Question Answering 论文精读】

BBQ: A Hand-Built Bias Benchmark for Question Answering 论文精读 InformationAbstract1 Introduction2 Related Work3 The Dataset3.1 Coverage3.2 Template Construction3.3 Vocabulary4 Validation5 Evaluation6 Results7 Discussion8 Conclusion9 Ethical Consideration…

keepalived+nginx搭建高可用kubeadm1.25

实验环境 系统都是centos 7 IP地址主机名称192.168.0.1k8s-master01192.168.0.2k8s-master02192.168.0.3k8s-master03192.168.0.230k8s-vip192.168.0.4k8s-node01192.168.0.5k8s-node02 所有节点修改主机名称 cat <<EOF >> /etc/hosts 192.168.0.1 k8s-master0…

python 容器

容器 Python中&#xff0c;可包含其他对象的对象&#xff0c;称之为“容器”。容器是一种数据结构。 常用的容器主要划分为两种&#xff1a;序列&#xff08;如&#xff1a;列表、元祖等&#xff09;和映射&#xff08;如&#xff1a;字典&#xff09;。序列中&#xff0c;每个…

国考省考行测:百分点和百分数,相对量和绝对量的比较

国考省考行测&#xff1a;百分点和百分数 2022找工作是学历、能力和运气的超强结合体! 公务员特招重点就是专业技能&#xff0c;附带行测和申论&#xff0c;而常规国考省考最重要的还是申论和行测&#xff0c;所以大家认真准备吧&#xff0c;我讲一起屡屡申论和行测的重要知识…