本节介绍如何使用 OpenAI 创建您的第一个聊天机器人
这只是一个简单的示例,用于开始了解 OpenAI API 的工作原理以及如何创建提示。它远非一个完整的解决方案,但我们将介绍一些有趣的点:
1.对话中的角色。
2.对话的记忆是如何保存的?
1.安装必要库 #
#First install the necesary libraries
!pip install -q openai==1.1.1
!pip install -q panel
2.设置API密钥 #
#if you need a API Key from OpenAI
#https://platform.openai.com/account/api-keys
import openai
import panel as pn
openai.api_key="your-openai-key"
#model = "gpt-3.5-turbo"
model = "gpt-4o-mini"
3.定义对话函数 #
#This function will receive the different messages in the conversation,
#and call OpenAI passing the full conversartion.
def continue_conversation(messages, temperature=0):
response = openai.chat.completions.create(
model=model,
messages=messages,
temperature=temperature,
)
return response.choices[0].message.content
4.添加对话提示prompt #
def add_prompts_conversation(_):
#Get the value introduced by the user
prompt = client_prompt.value_input
client_prompt.value = ''
#Append to the context the User promnopt.
context.append({'role':'user', 'content':f"{prompt}"})
#Get the response.
response = continue_conversation(context)
#Add the response to the context.
context.append({'role':'assistant', 'content':f"{response}"})
#Update the panels to show the conversation.
panels.append(
pn.Row('User:', pn.pane.Markdown(prompt, width=600)))
panels.append(
pn.Row('Assistant:', pn.pane.Markdown(response, width=600)))
return pn.Column(*panels)
5.定义system提示词 #
#Creating the system part of the prompt
#Read and understand it.
context = [ {'role':'system', 'content':"""
You work collecting orders in a delivery IceCream shop called
I'm freezed.
First welcome the customer, in a very friedly way, then collects the order.
Your instuctions are:
-Collect the entire order, only from options in our menu, toppings included.
-Summarize it
-check for a final time if everithing is ok or the customer wants to add anything else.
-collect the payment, be sure to include topings and the size of the ice cream.
-Make sure to clarify all options, extras and sizes to uniquely
identify the item from the menu.
-Your answer should be short in a very friendly style.
Our Menu:
The IceCream menu includes only the flavors:
-Vainilla.
-Chocolate.
-Lemon.
-Strawberry.
-Coffe.
The IceCreams are available in two sizes:
-Big: 3$
-Medium: 2$
Toppings:
-Caramel sausage
-White chocolate
-melted peanut butter
Each topping cost 0.5$
"""} ]
#Creating the panel.
pn.extension()
panels = []
client_prompt = pn.widgets.TextInput(value="Hi", placeholder='Enter text here…')
button_conversation = pn.widgets.Button(name="talk")
interactive_conversation = pn.bind(add_prompts_conversation, button_conversation)
dashboard = pn.Column(
client_prompt,
pn.Row(button_conversation),
pn.panel(interactive_conversation, loading_indicator=True),
)
#To talk with the chat push the botton: 'talk' after your sentence.
dashboard