• Openai+Coursera: ChatGPT Prompt Engineering(二)


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

    ChatGPT Prompt Engineerin(一)

    Summarizing(总结/摘要)


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

    设置参数

    1. import openai
    2. openai.api_key ='YOUR_OPENAI_API_KEY'
    1. def get_completion(prompt, model="gpt-3.5-turbo"):
    2. messages = [{"role": "user", "content": prompt}]
    3. response = openai.ChatCompletion.create(
    4. model=model,
    5. messages=messages,
    6. temperature=0,
    7. )
    8. return response.choices[0].message["content"]

    文本总结

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

    1. prod_review = """
    2. Got this panda plush toy for my daughter's birthday, \
    3. who loves it and takes it everywhere. It's soft and \
    4. super cute, and its face has a friendly look. It's \
    5. a bit small for what I paid though. I think there \
    6. might be other options that are bigger for the \
    7. same price. It arrived a day earlier than expected, \
    8. so I got to play with it myself before I gave it \
    9. to her.
    10. """
    11. prod_review1="""
    12. 这个熊猫毛绒玩具是我女儿生日的礼物,她很喜欢,走到哪里都带着它。
    13. 它很柔软,超级可爱,它的脸看起来很友好。不过相对于我付的钱来说有点小了。
    14. 我想同样的价格可能还有其他更大的选择。它比预期提前了一天到达,所以我在给她之前自己玩了一下。
    15. """

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

    1. prompt = f"""
    2. Your task is to generate a short summary of a product \
    3. review from an ecommerce site.
    4. Summarize the review below, delimited by triple
    5. backticks, in at most 30 words.
    6. Review: ```{prod_review}```
    7. """
    8. response = get_completion(prompt)
    9. print(response)

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

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

    1. prompt = f"""
    2. Your task is to generate a short summary of a product \
    3. review from an ecommerce site to give feedback to the \
    4. Shipping deparmtment.
    5. Summarize the review below, delimited by triple
    6. backticks, in at most 30 words, and focusing on any aspects \
    7. that mention shipping and delivery of the product.
    8. Review: ```{prod_review}```
    9. """
    10. response = get_completion(prompt)
    11. print(response)

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

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

    1. prompt = f"""
    2. Your task is to generate a short summary of a product \
    3. review from an ecommerce site to give feedback to the \
    4. pricing deparmtment, responsible for determining the \
    5. price of the product.
    6. Summarize the review below, delimited by triple
    7. backticks, in at most 30 words, and focusing on any aspects \
    8. that are relevant to the price and perceived value.
    9. Review: ```{prod_review}```
    10. """
    11. response = get_completion(prompt)
    12. print(response)

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

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

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

    1. prompt = f"""
    2. Your task is to extract relevant information from \
    3. a product review from an ecommerce site to give \
    4. feedback to the Shipping department.
    5. From the review below, delimited by triple quotes \
    6. extract the information relevant to shipping and \
    7. delivery. Limit to 30 words.
    8. Review: ```{prod_review}```
    9. """
    10. response = get_completion(prompt)
    11. print(response)

     总结多个产品评论

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

    1. review_1 = prod_review
    2. # review for a standing lamp
    3. review_2 = """
    4. Needed a nice lamp for my bedroom, and this one \
    5. had additional storage and not too high of a price \
    6. point. Got it fast - arrived in 2 days. The string \
    7. to the lamp broke during the transit and the company \
    8. happily sent over a new one. Came within a few days \
    9. as well. It was easy to put together. Then I had a \
    10. missing part, so I contacted their support and they \
    11. very quickly got me the missing piece! Seems to me \
    12. to be a great company that cares about their customers \
    13. and products.
    14. """
    15. # review for an electric toothbrush
    16. review_3 = """
    17. My dental hygienist recommended an electric toothbrush, \
    18. which is why I got this. The battery life seems to be \
    19. pretty impressive so far. After initial charging and \
    20. leaving the charger plugged in for the first week to \
    21. condition the battery, I've unplugged the charger and \
    22. been using it for twice daily brushing for the last \
    23. 3 weeks all on the same charge. But the toothbrush head \
    24. is too small. I’ve seen baby toothbrushes bigger than \
    25. this one. I wish the head was bigger with different \
    26. length bristles to get between teeth better because \
    27. this one doesn’t. Overall if you can get this one \
    28. around the $50 mark, it's a good deal. The manufactuer's \
    29. replacements heads are pretty expensive, but you can \
    30. get generic ones that're more reasonably priced. This \
    31. toothbrush makes me feel like I've been to the dentist \
    32. every day. My teeth feel sparkly clean!
    33. """
    34. # review for a blender
    35. review_4 = """
    36. So, they still had the 17 piece system on seasonal \
    37. sale for around $49 in the month of November, about \
    38. half off, but for some reason (call it price gouging) \
    39. around the second week of December the prices all went \
    40. up to about anywhere from between $70-$89 for the same \
    41. system. And the 11 piece system went up around $10 or \
    42. so in price also from the earlier sale price of $29. \
    43. So it looks okay, but if you look at the base, the part \
    44. where the blade locks into place doesn’t look as good \
    45. as in previous editions from a few years ago, but I \
    46. plan to be very gentle with it (example, I crush \
    47. very hard items like beans, ice, rice, etc. in the \
    48. blender first then pulverize them in the serving size \
    49. I want in the blender then switch to the whipping \
    50. blade for a finer flour, and use the cross cutting blade \
    51. first when making smoothies, then use the flat blade \
    52. if I need them finer/less pulpy). Special tip when making \
    53. smoothies, finely cut and freeze the fruits and \
    54. vegetables (if using spinach-lightly stew soften the \
    55. spinach then freeze until ready for use-and if making \
    56. sorbet, use a small to medium sized food processor) \
    57. that you plan to use that way you can avoid adding so \
    58. much ice if at all-when making your smoothie. \
    59. After about a year, the motor was making a funny noise. \
    60. I called customer service but the warranty expired \
    61. already, so I had to buy another one. FYI: The overall \
    62. quality has gone done in these types of products, so \
    63. they are kind of counting on brand recognition and \
    64. consumer loyalty to maintain sales. Got it in about \
    65. two days.
    66. """
    67. reviews = [review_1, review_2, review_3, review_4]
    1. for i in range(len(reviews)):
    2. prompt = f"""
    3. Your task is to generate a short summary of a product \
    4. review from an ecommerce site.
    5. Summarize the review below, delimited by triple \
    6. backticks in at most 20 words.
    7. Review: ```{reviews[i]}```
    8. """
    9. response = get_completion(prompt)
    10. 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。

    1. # pip install backoff
    2. import backoff
    3. @backoff.on_exception(backoff.expo, openai.error.RateLimitError)
    4. def get_completion(prompt, model="gpt-3.5-turbo"):
    5. messages = [{"role": "user", "content": prompt}]
    6. response = openai.ChatCompletion.create(
    7. model=model,
    8. messages=messages,
    9. temperature=0,
    10. )
    11. return response.choices[0].message["content"]

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

    请帮我买杯咖啡

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

  • 相关阅读:
    C Primer Plus(6) 中文版 第12章 存储类别、链接和内存管理 12.5 ANSI C类型限定符 12.6 关键概念 12.7 本章小结
    操作系统 | 内存文件映射 —— 文件到内存的映射
    蒙提霍尔问题(The Monty Hall Problem)解析(含python仿真)
    Java多线程(6):锁与AQS(下)
    cesium 设置默认视图
    【MindSpore】【TFRecordDataset】无法正确处理tfrecord文件
    Mysql和ES、Redis数据同步方案汇总
    计算机网络 传输层 TCP协议总结
    Nodejs基于Vue的音乐播放器的设计与实现7z140
    OpenShift 4 - 部署 RHODS 环境,运行 AI/ML 应用(视频)
  • 原文地址:https://blog.csdn.net/weixin_42608414/article/details/130767175