Verwenden Sie große Sprachmodelle, um Ihren benutzerdefinierten Chatbot zu erstellen In diesem Video erfahren Sie, wie Sie mithilfe von Komponenten im OpenAI ChatCompletions-Format einen Bot erstellen.

Zunächst richten wir wie gewohnt das OpenAI-Python-Paket ein.

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

C3059587Bb03A94Bde098Fa16A60Eaa4

Ihre Nachricht ist eine Benutzernachricht chatgpt-Nachrichten sind Assistentennachrichten Systemnachrichten helfen dabei, das Verhalten und die Rolle des Assistenten festzulegen, und stellen eine Art allgemeine Anweisung für Gespräche dar. Man kann es sich also so vorstellen, als würde man dem Assistenten ins Ohr flüstern und so die Reaktion des Assistenten steuern, ohne dass der Benutzer die Systemmeldung bemerkt. Das Folgende ist ein Beispiel. Die Systemmeldung fordert Sie auf, ein Assistent zu sein, der wie Shakespeare spricht. Der Benutzer bittet Sie, einen Witz zu erzählen, und der Assistent fragt, warum das Huhn die Straße überqueren muss? Benutzerinformationen sind, ich weiß es nicht. Die Antwort nach dem Aufruf der Funktion lautet: „Auf die andere Seite gelangen, um fair zu sein, Ma’am, es ist ein alter Klassiker, der nie versagt.“

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, sire! 'Tis a classic jest, known by many a bard.
"""

Im folgenden Beispiel lautet die Assistentennachricht „Sie sind ein freundlicher Chatbot“ und die erste Benutzernachricht lautet „Hallo, mein Name ist Isa“. Wir wollen, ähm, die erste Benutzernachricht erhalten. Also, lasst uns das ausführen. Erste Assistentennachricht. Die erste Nachricht lautet also: Hallo Isa, schön dich kennenzulernen. Wie kann ich Ihnen heute helfen?

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'm sorry, but as a chatbot, I do not have access to information about your personal details such as your name. However, you can tell me your name and we can continue our conversation.
"""

Das Gespräch muss einen Kontext haben, sonst weiß das Modell es nicht. Beispielsweise kennt das Model Ihren Namen nicht.

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'm sorry, but as a chatbot, I do not have access to information about your personal details such as your name. However, you can tell me your name and we can continue our conversation.
"""

Wenn ein Kontext vorhanden ist, kann dieser extrahiert werden

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)
"""
Of course, your name is Isa.
"""

Sie müssen Ihren eigenen Chatbot-Bestellbot erstellen, um Benutzeraufforderungen und Assistentenantworten automatisch zu sammeln, d. h. Benutzerantworten automatisch zum Formularkontext hinzuzufügen.

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)

Konkreter Anfrageauftrag: Sie sind der Orderbot, ein automatisierter Dienst, der Bestellungen für ein Pizzarestaurant sammelt. Sie begrüßen zuerst den Kunden, holen dann die Bestellung ab und fragen dann, ob es sich um Abholung oder Lieferung handelt. Sie warten darauf, die gesamte Bestellung abzuholen, fassen sie dann zusammen und prüfen ein letztes Mal, ob der Kunde noch etwas hinzufügen möchte. Beim Versand können Sie eine Adresse anfordern. Schließlich kassieren Sie die Zahlung. Stellen Sie sicher, dass Sie alle Optionen, Zusatzkosten und Größen klären, um die Artikel auf Ihrer Speisekarte eindeutig identifizieren zu können. Sie antworten kurz, sehr gesprächig und freundlich. Das Menü beinhaltet und dann haben wir das Menü.

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
"""
[出现一个人机交互界面]
"""

727A6F4F41E06Ddf78316Fbc1Df7B80B

Wenn Sie das Modell befragen, wird eine JSON-Zusammenfassung erstellt, die wir basierend auf der Konversation an das Bestellsystem senden können.

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)

"""
Sure, here's a JSON summary of your order:

···
{
  "pizza": {
    "type": "意大利辣香肠披萨",
    "size": "中号",
    "price": 12.95
  },
  "toppings": [
    {
      "type": "加拿大培根",
      "price": 3.50
    },
    {
      "type": "蘑菇",
      "price": 1.50
    },
    {
      "type": "彩椒",
      "price": 1.00
    }
  ],
  "drinks": [
    {
      "type": "可乐",
      "size": "中杯",
      "price": 3.00
    }
  ],
  "sides": [],
  "total_price": 18.95
}
···
"""

Der Temperaturwert beträgt hier 0

Siehe auch  6 große ChatGPT-Updates wurden gerade veröffentlicht
5/5 - (217 votes)
Anzeige

Kommentieren Sie den Artikel

Bitte geben Sie Ihren Kommentar ein!
Bitte geben Sie hier Ihren Namen ein