ChatGPT プロンプトワードプロジェクト (7): Chatbot チャットロボット

1. 説明

これは、Wu Enda の「開発者のための ChatGPT プロンプト エンジニアリング」のコース ノート シリーズですこの記事は第8回「チャットボット」
の内容です

2. 設置環境

参考: ChatGPT プロンプトワードプロジェクト (1):ガイドライン第 2 節

その中で、補助機能が変更されました。

1. 補助関数: get_completion

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

ここに画像の説明を挿入

2. 補助関数: 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"]

ここに画像の説明を挿入

ここで、メッセージをカスタマイズできます: : ユーザーには不明なシステム補助モデルの役割; : モデルと対話する役割は私たちです; message:モデルを参照しますrolesystemuserassistant
system
user
assistant

https://blog.csdn.net/Jay_Xio/article/details/130463604



3. チャットボット

1. 一般的なチャットボット

システムの役割はモデルにそれがどのような役割であるかを伝えます

1.1 簡単な例

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)

message:
キャラクター システム: モデルにシェイクスピアのように話すアシスタントであると伝えます;
キャラクター ユーザー: モデルにジョークを言ってください
キャラクター アシスタント: モデルがジョークを言いました: なぜ鶏は道路を横切るのですか?
ロール ユーザー: モデルに伝えます。わかりません。
その後、コードの実行結果 (つまり、モデルの出力):
ここに画像の説明を挿入


1.2 複数回の対話

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)

message:
ロール システム: あなたがフレンドリーなロボットであることをモデルに伝えます;
ロール ユーザー: モデルに「こんにちは、私の名前は Isa です」と伝えます
。 次に、コードの実行結果 (つまり、モデルの出力):
ここに画像の説明を挿入

次に会話を続けます

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)

まずは実行結果を見てみましょう。
ここに画像の説明を挿入
最後の対話ラウンドで、モデルに私の名前は Isa であると伝え、ロボットはフレンドリーに挨拶してくれましたが、今度は「私の名前を覚えていますか?」と尋ねると、ロボットはもうわかりません。
どうやって解決すればいいでしょうか?
以前の対話を継続するには、対話を再度開始するときに、モデルが対話のコンテキストを認識できるように、前の対話の内容をまとめなければなりません。

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)

コードでは、メッセージには前回のダイアログで尋ねた質問とその回答の結果が含まれており、その後に今回尋ねる質問が続きます

ここに画像の説明を挿入

2. 注文ボット

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

コードでは、GUI がインポートされ、ダイアログを表示するためにインターフェイスが使用されます。関数はcollect_messages各ラウンドでダイアログを収集し、マシン モデルについて質問したいときに前のダイアログをモデルに送信します。
結果:
ここに画像の説明を挿入

ここに画像の説明を挿入

注文後、注文ロボットは注文内容を 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)

ここに画像の説明を挿入

https://blog.csdn.net/Jay_Xio/article/details/130463604



おすすめ

転載: blog.csdn.net/Jay_Xio/article/details/130463604