【プロンプト】ChatGPT プロンプトエンジニアリング開発ガイド (6)


このチュートリアルの最初の部分では、各顧客のレビューに基づいてカスタマイズされたカスタマー サービス メールを作成する方法を学びます。2 番目のパートでは、特定のタスクや動作に合わせてパーソナライズまたは特化したチャットボットとの長時間の会話にチャット形式を活用する方法を検討します。

注: 基本的な環境設定は以前のものと一致しています。設定を参照してください。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']

拡大する

顧客メールへの自動応答をカスタマイズする

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

返信を生成する

チャット形式

応答メッセージから情報を完成させる関数を追加します。

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

の結果

要約する

  • 原則:
    • 明確かつ具体的な指示を書く
    • モデルに「考える」時間を与えます
  • 反復的な迅速な開発
  • 能力: 要約、推論、変換、拡張
  • チャットボットの構築

コンテンツソース

  1. DeepLearning.AI: 《開発者向け ChatGPT プロンプト エンジニアリング》

おすすめ

転載: blog.csdn.net/ARPOSPF/article/details/130664133