本文是《基于 ChatGPT 的 Prompt 工程》系列课程的第五讲,本文将介绍使用模型实施一些定制化任务,如给客户回复量身定制的邮件,个性化的聊天机器人。

量身定制的邮件

generate customer service emails that are tailored to each customer’s review.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 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.
"""

# 中文:因此,他们仍然有17件系统的季节性销售约49美元在11月,约半价,但出于某种原因(称之为价格欺诈)在12月的第二个星期左右,价格全部上升到大约70-89美元之间的任何地方为同一系统。而且11件系统的价格也比之前29美元的售价上涨了10美元左右。所以它看起来不错,但是如果你看看底部,刀片锁定到位的部分看起来不像前几年的版本那么好,但是我计划对它非常温和(例如,我先在搅拌机里碾碎非常硬的东西,像豆子,冰,大米等,然后在搅拌机里按照我想要的大小把它们碾碎,然后切换到搅拌刀片,得到更细的面粉,在做冰沙时先用横切刀片,如果我需要更细/更少的浆状,那么使用平刀片)。制作冰沙时的特别提示: 将水果和蔬菜切碎并冷冻(如果使用菠菜——略微炖一下使菠菜软化,然后冷冻直到可以使用——如果制作冰沙,使用一个中小型食品加工机) ,这样你就可以避免在制作冰沙时加入过多的冰块。大约一年后,发动机发出了奇怪的声音。我打电话给客服,但是保修期已经过了,所以我不得不再买一个。仅供参考: 这类产品的整体质量已经下降,所以他们需要依靠品牌知名度和消费者忠诚度来维持销售。大概两天后拿到的。

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)

提示词的中文是:

1
2
3
4
5
6
7
8
9
10
11
你是一个客户服务人工智能助理。您的任务是发送电子邮件回复到一个有价值的客户。

由于客户电子邮件由 ``` 分隔,生成一个回复来感谢客户的评审。

如果情绪是积极的或中性的,感谢他们他们的评论。

如果情绪是消极的,道歉并建议他们可以联系客户服务。

确保使用评审中的具体细节。用简洁专业的语气写作。

签署电子邮件为“人工智能客户代理”。

temperature

temperature 参数值是 0 到 1 之间的浮点数,默认值为 0,这表明模型是可靠的、可预测的;大于 0 则表示模型会更具备多样性。

如果把 response 换成 response = get_completion(prompt, temperature=0.7),模型的表现会更有创造性。

聊天机器人

准备工作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import os
import openai
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file

openai.api_key = os.getenv('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, # this is the degree of randomness of the model's output
)
return response.choices[0].message["content"]

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"]

聊天机器人

1
2
3
4
5
6
7
messages =  [  
# 系统对 model 说:你是个友好的机器人
{'role':'system', 'content':'You are friendly chatbot.'},
# 用户对 model 说:你好,我是 Isa。
{'role':'user', 'content':'Hi, my name is Isa'} ]
response = get_completion_from_messages(messages, temperature=1)
print(response)

模型回复:Hello!

点餐机器人

需要记住上下文。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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)
```

下面的代码中,系统对 model 说:你是个点餐机器人,要先对用户打招呼,然后点餐。
```py
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

上述代码可以进行多轮对话。

对话结束后,可以通过复制上下文的方式,总结对话的内容。

1
2
3
4
5
6
7
8
9
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)

总结

本文介绍了使用模型实施一些定制化任务,如给客户回复量身定制的邮件,个性化的聊天机器人。

简单的一个函数就可以构造一个个性化的聊天机器人,OpenAI 提供的 API 非常强大。

这些强大的应用让我们意识到,大部分简单的工作如发邮件、不太简单的工作如点餐等都可以被 ChatGPT 取代。

课程总结

本讲是最后一讲。《基于 ChatGPT 的 Prompt 工程》系列课程主要介绍了 Prompt 的两条方针,分别是:

  • 简洁且具体的指令,
  • 让模型有时间“思考”。

接着,课程通过两个示例解释了迭代式提示工程(iterative prompt engineering),并且展示了 ChatGPT 的四个能力:总结 summarization、推断 inferring、转换 transformation、拓展 expanding。

最后,课程介绍了使用模型实施一些定制化任务。

参考