Published on

【備忘録】pizza order bot

Authors
  • Name
    Twitter

Contents

チャット形式を利用して、特定のタスクや行動にパーソナライズまたは特化したチャットボットと長時間会話する方法

初期手順

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


従来の方法

1回目。引数を各種messagesのhashmmapに格納

def get_completion_from_messages定義

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)

output:

Verily, to get to the other side! Hahaha!

2回目のchat

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)

output:

I'm sorry, but I don't have access to that information. As a chatbot, I do not have the capability to retrieve individual user details. Is there anything else I can assist you with?
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)

オーダーボットの作成

ピザ屋さんで注文を受ける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}"})
    # ユーザーの入力とアシスタントの応答を表示 pn.Rowで2つのパネルを水平に並べる
    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)

chatbotの作成

GUIを生成して、contextを保存しながら、プロンプトを実行

import panel as pn  # GUI
# Panelライブラリの拡張機能を有効
pn.extension()

# panelsリストは、表示するすべての行を収集するために使用
panels = [] # collect display 

# contextリストは、OrderBotの振る舞いに関する説明を含むメッセージを収集するために使用
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!")

# collect_messages関数をボタンにバインドするために使用
# collect_messages関数は、入力フィールドに入力されたテキストを受け取り、それに基づいてアシスタントが応答する対話型のパネルを生成
# collect_messages関数とbutton_conversationウィジェットをバインドして、ボタンがクリックされたときにcollect_messages関数が呼び出される
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

前回の注文に関するJSONの要約を生成

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)

output json:

Here's a JSON summary of the previous food order:

{
  "pizza": {
    "size": "10-inch",
    "type": "Cheese Pizza",
    "price": 9.25
  },
  "toppings": [
    {
      "name": "Mushrooms",
      "price": 1.50
    }
  ],
  "drinks": [
    {
      "name": "Coke",
      "size": "20 oz",
      "price": 3.00
    }
  ],
  "sides": [],
  "total_price": 13.75
}

Let me know if you need any further assistance!