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

news2025/1/9 0:35:47

ChatGPT Prompt Engineering开发指南:Expanding/The Chat Format

  • Expanding
    • 自定义对客户电子邮件的自动回复
    • 提醒模型使用客户电子邮件中的详细信息
  • The Chat Format
  • 总结
  • 内容来源

在本教程中,第一部分学习生成客户服务电子邮件,这些电子邮件是根据每个客户的评论量身定制的。第二部分将探索如何利用聊天格式与针对特定任务或行为进行个性化或专门化的聊天机器人进行扩展对话。

注意:基本环境设置与前文保持一致,请参考设置。这里适当修改一下get_completion()函数:

@retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6))
def get_completion(prompt, model="gpt-3.5-turbo", temperature = 0):
    messages = [{'role': 'user', 'content': prompt}]
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        max_tokens=1024,
        n=1,
        temperature=temperature,  # 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']

Expanding

自定义对客户电子邮件的自动回复

# given the sentiment from the lesson on "inferring",
# and the original customer message, customize the email
sentiment = "negative"

# review for a blender
review = f"""
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.
"""

生成回复:

prompt = f"""
You are a customer service AI assistant.
Your task is to send an email reply to a valued customer.
Given the customer email delimited by ```, \
Generate a reply to thank the customer for their review.
If the sentiment is positive or neutral, thank them for \
their review.
If the sentiment is negative, apologize and suggest that \
they can reach out to customer service.
Make sure to use specific details from the review.
Write in a concise and professional tone.
Sign the email as `AI customer agent`.
Customer review: ```{review}```
Review sentiment: {sentiment}
"""
response = get_completion(prompt)
print(response)

回复结果

提醒模型使用客户电子邮件中的详细信息

prompt = f"""
You are a customer service AI assistant.
Your task is to send an email reply to a valued customer.
Given the customer email delimited by ```, \
Generate a reply to thank the customer for their review.
If the sentiment is positive or neutral, thank them for \
their review.
If the sentiment is negative, apologize and suggest that \
they can reach out to customer service. 
Make sure to use specific details from the review.
Write in a concise and professional tone.
Sign the email as `AI customer agent`.
Customer review: ```{review}```
Review sentiment: {sentiment}
"""
response = get_completion(prompt, temperature=0.7)
print(response)

生成回复

The Chat Format

新增一个函数,从回复的消息中补全信息:

@retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6))
def get_completion_from_messages(messages, model="gpt-3.5-turbo", temperature=0):
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=temperature, # this is the degree of randomness of the model's output
    )
#     print(str(response.choices[0].message))
    return response.choices[0]['message']['content']

开始聊天:

messages =  [
{'role':'system', 'content':'You are an assistant that speaks like Shakespeare.'},
{'role':'user', 'content':'tell me a joke'},
{'role':'assistant', 'content':'Why did the chicken cross the road'},
{'role':'user', 'content':'I don\'t know'}  ]

response = get_completion_from_messages(messages, temperature=1)
print(response)

回答:

To get to the other side, good sir!
messages =  [
{'role':'system', 'content':'You are friendly chatbot.'},
{'role':'user', 'content':'Hi, my name is Isa'}  ]
response = get_completion_from_messages(messages, temperature=1)
print(response)

回答:

Hi Isa! It's nice to meet you. How are you feeling today?
messages =  [
{'role':'system', 'content':'You are friendly chatbot.'},
{'role':'user', 'content':'Yes,  can you remind me, What is my name?'}  ]
response = get_completion_from_messages(messages, temperature=1)
print(response)

回答:

I apologize, but as a chatbot, I do not have access to your personal information such as your name. Can you please remind me?
messages =  [
{'role':'system', 'content':'You are friendly chatbot.'},
{'role':'user', 'content':'Hi, my name is Isa'},
{'role':'assistant', 'content': "Hi Isa! It's nice to meet you. \
Is there anything I can help you with today?"},
{'role':'user', 'content':'Yes, you can remind me, What is my name?'}  ]
response = get_completion_from_messages(messages, temperature=1)
print(response)

回答:

Your name is Isa.

订单机器人:我们可以自动化用户提示和助手响应的收集以构建订单机器人。Orderbot将在比萨餐厅接受订单。

def collect_messages(_):
    prompt = inp.value_input
    inp.value = ''
    context.append({'role':'user', 'content':f"{prompt}"})
    response = get_completion_from_messages(context)
    context.append({'role':'assistant', 'content':f"{response}"})
    panels.append(
        pn.Row('User:', pn.pane.Markdown(prompt, width=600)))
    panels.append(
        pn.Row('Assistant:', pn.pane.Markdown(response, width=600, style={'background-color': '#F6F6F6'})))

    return pn.Column(*panels)

绘制面板:

import panel as pn  # GUI
pn.extension()

panels = [] # collect display

context = [ {'role':'system', 'content':"""
You are OrderBot, an automated service to collect orders for a pizza restaurant. \
You first greet the customer, then collects the order, \
and then asks if it's a pickup or delivery. \
You wait to collect the entire order, then summarize it and check for a final \
time if the customer wants to add anything else. \
If it's a delivery, you ask for an address. \
Finally you collect the payment.\
Make sure to clarify all options, extras and sizes to uniquely \
identify the item from the menu.\
You respond in a short, very conversational friendly style. \
The menu includes \
pepperoni pizza  12.95, 10.00, 7.00 \
cheese pizza   10.95, 9.25, 6.50 \
eggplant pizza   11.95, 9.75, 6.75 \
fries 4.50, 3.50 \
greek salad 7.25 \
Toppings: \
extra cheese 2.00, \
mushrooms 1.50 \
sausage 3.00 \
canadian bacon 3.50 \
AI sauce 1.50 \
peppers 1.00 \
Drinks: \
coke 3.00, 2.00, 1.00 \
sprite 3.00, 2.00, 1.00 \
bottled water 5.00 \
"""} ]  # accumulate messages


inp = pn.widgets.TextInput(value="Hi", placeholder='Enter text here…')
button_conversation = pn.widgets.Button(name="Chat!")

interactive_conversation = pn.bind(collect_messages, button_conversation)

dashboard = pn.Column(
    inp,
    pn.Row(button_conversation),
    pn.panel(interactive_conversation, loading_indicator=True, height=300),
)

dashboard

面板

messages =  context.copy()
messages.append(
{'role':'system', 'content':'create a json summary of the previous food order. Itemize the price for each item\
 The fields should be 1) pizza, include size 2) list of toppings 3) list of drinks, include size   4) list of sides include size  5)total price '},
)
 #The fields should be 1) pizza, price 2) list of toppings 3) list of drinks, include size include price  4) list of sides include size include price, 5)total price '},

response = get_completion_from_messages(messages, temperature=0)
print(response)

执行结果

总结

  • Principles:
    • Write clear and specific instructions
    • Give the model time to “think”
  • Iterative prompt development
  • Capabilitis: Summarizing, Inferring, Transforming, Expanding
  • Building a ChatBot

内容来源

  1. DeepLearning.AI: 《ChatGPT Prompt Engineering for Developers》

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

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

相关文章

前端(HTML)

网络传输三大基石:URL,HTTP,HTML 前端使用URL利用HTTP协议去向服务器端发送请求某个资源,服务器端响应浏览器一个HTML页面,浏览器对HTML页面解析 HTML的标准结构: 【1】先用普通文本文档新建一个文本,将文本的后缀改为.html 或者 .htm 我…

chatgpt赋能Python-mac版的python怎么用

Mac版Python的使用指南 Python是一种高级编程语言,常用于Web开发、数据分析、机器学习等领域。在Mac系统上,Python的安装和使用非常方便。本文将介绍如何在Mac上安装和使用Python并演示几个常见的Python用例。 Python在Mac上的安装 Mac电脑自带Python…

springboot+jsp+javaweb学生信息管理系统 05hs

springboot是基于spring的快速开发框架, 相比于原生的spring而言, 它通过大量的java config来避免了大量的xml文件, 只需要简单的生成器便能生成一个可以运行的javaweb项目, 是目前最火热的java开发框架 (1)管理员模块:系统中的核心用户是管…

蓝牙耳机什么牌子的好用?发烧友实测2023年蓝牙耳机排名

从AirPods入坑蓝牙耳机开始,断断续续已经买过二十多款蓝牙耳机了,我每天都会逛逛数码板块,最近看到了2023年蓝牙耳机排名,为检验是否名副其实,我购入了排名前五的品牌进行了一个月的测试,接下来我就来分享一…

k8s系列(四)——资源对象

k8s系列四——资源对象 pod概念 思考:为什么k8s会引出pod这个概念,容器不能解决么? 我的理解:一组密切相关的服务使用容器的话,如果他们的镜像不在一个容器里的话,那么就需要配置反向代理进行通信&#xf…

Packet Tracer – 配置中继

Packet Tracer – 配置中继 地址分配表 设备 接口 IP 地址 子网掩码 交换机端口 VLAN PC1 NIC 172.17.10.21 255.255.255.0 S2 F0/11 10 PC2 NIC 172.17.20.22 255.255.255.0 S2 F0/18 20 PC3 NIC 172.17.30.23 255.255.255.0 S2 F0/6 30 PC4 NIC 1…

java 根据指定字段排序(mysql)

需求: 查询数据的时候,由前端指定字段和排序方式进行排序。 这时候要怎么做呢? 要定义一个相应的类,排序的时候,是动态拼接的。 要考虑多个字段,不同排序方式的情况。 处理 OrderField import io.swagge…

基于matlab的ADC输入动态范围测量代码

如图,本文主要分享基于matlab的ADC输入数据有效位分析的代码。 fidfopen(C:\Users\Administrator\Desktop\Test.txt,r); % numptinput(Data Record Size (Number of Points)? );% fclkinput(Sampling Frequency (MHz)? ); numpt16384; fclk50; numbit14; [v1]fs…

SDK案例记录

目前的极简配置 注意事项 默认的属性配置中,大多采用环境变量的形式,方便不同设备通用 比如“常规”->“输出目录”为 $(SolutionDir)..\bin\win_msvc2017$(Platform)\$(Configuration)\案例运行前的配置(除MwBatchSimPlugin&#xff0…

华丽家族股东大会21项议案全被否

5月17日晚间,A股上市公司华丽家族发布关于收到上海证券交易所监管工作函的公告,交易所对相关事项提出监管要求。 在此之前,华丽家族当天召开股东大会,21项股东大会议案全部未通过。历史上,股东大会议案全部被否的情形…

『python爬虫』24. selenium之无头浏览器-后台静默运行(保姆级图文)

目录 1. 无头浏览器2. 分析被爬取数据的网页结构3. 完整代码总结 欢迎关注 『python爬虫』 专栏,持续更新中 欢迎关注 『python爬虫』 专栏,持续更新中 1. 无头浏览器 一般性的selenium会打开浏览器页面,展示图形化页面给我们看,我…

Spring Boot注入Servlet、Filter、Listener 注解方式和使用RegistrationBean二种方式 加源码分析

目录 Spring Boot 注入Servlet、Filter、Listener 官方文档 基本介绍 应用实例1-使用注解方式注入 创建/Servlet_.java 修改Application.java , 加入ServletComponentScan 完成测试 创建Filter_.java 创建static/css/t.css, 作为测试文件 完成测试, 注意观察后台 注…

【数据结构】--- 博主拍了拍你并向你扔了一“棵”二叉树(概念+结构)

文章目录 前言🌟一、树概念及结构:🌏1.1树的概念:🌏1.2树的相关概念:🌏1.3树的表示:💫1.3.1左孩子右兄弟表示法:💫1.3.2双亲表示法: &…

Golang每日一练(leetDay0069) 数字范围按位与、快乐数

目录 201. 数字范围按位与 Bitwise-and-of-numbers-range 🌟🌟 202. 快乐数 Happy Number 🌟 🌟 每日一练刷题专栏 🌟 Rust每日一练 专栏 Golang每日一练 专栏 Python每日一练 专栏 C/C每日一练 专栏 Java每…

美团前高级测试工程师教你如何使用web自动化测试

一、自动化测试基本介绍 1 自动化测试概述: 什么是自动化测试?一般说来所有能替代人工测试的方式都属于自动化测试,即通过工具和脚本来模拟人执行用例的过程。 2 自动化测试的作用 减少软件测试时间与成本改进软件质量 通过扩大测试覆盖率…

python随机生成数据并用双y轴绘制两条带误差棒的折线图

python绘图系列文章目录 往期python绘图合集: python绘制简单的折线图 python读取excel中数据并绘制多子图多组图在一张画布上 python绘制带误差棒的柱状图 python绘制多子图并单独显示 python读取excel数据并绘制多y轴图像 python绘制柱状图并美化|不同颜色填充柱子 Python绘制…

IC验证学习笔记(AHB-RAM)08addr、bsize都随机,主要做地址偏移操作

rkv_ahbram_haddr_word_unaligned_virt_seq: 对addr和bsize都随机化操作 ifndef RKV_AHBRAM_HADDR_WORD_UNALIGNED_VIRT_SEQ_SV define RKV_AHBRAM_HADDR_WORD_UNALIGNED_VIRT_SEQ_SVclass rkv_ahbram_haddr_word_unaligned_virt_seq extends rkv_ahbram_base_virtual_sequenc…

深入探讨桥梁建筑中地质工程与仪器仪表应用

近期,随着桥梁建筑行业的不断发展,地质工程与仪器仪表应用成为了热议的话题。在桥梁、建筑、水利工程等领域,渗压计、MCU自动化测量单元、应变计、测缝计、固定测斜仪等各种先进的仪器仪表技术正在广泛应用,为工程施工和监测提供了…

什么是pytest自动化测试框架?如何安装和使用呢?赶快收藏起来

一、pytest是什么? pytest是一款强大的Python测试工具,可以胜任各种类型或级别的软件测试工作。实际上,越来越多的项目在使用pytest。因为pytest会提供更丰富的功能,包括assert重写、第三方插件,以及其他测试工具无法比…

116.【SpringBoot和Vue结合-图书馆管理系统】

前后端分离 (一)、SpringBootVue概述1.基本概述2.实现技术 (二)、Vue3.x搭建 (SpringBootVue)1.搭建Vue基本环境(1).搭建Vue项目框架(2).介绍Vue项目内容 2.搭建SpringBoot基本环境(1).创建SpringBootTest项目(2).初始化项目(3).测试SpringBoot的控制层 3.通过路由跳转访问组件…