走进任何一家现代披萨店,你可能会发现一个有趣的现象:越来越多的订单不再通过传统电话或柜台完成,而是由智能系统处理。这种转变不仅提高了效率,还带来了更个性化的顾客体验。本文将带你从零开始,用Python和GPT-3.5 API构建一个完整的披萨店订单机器人系统,包含GUI界面和订单结构化处理功能。
在开始编码前,我们需要明确整个系统的技术栈和架构设计。这个订单机器人将采用三层架构:表现层使用panel库构建轻量级GUI,逻辑层处理与GPT-3.5 API的交互,数据层负责订单信息的结构化存储。
首先确保你的Python环境是3.8或更高版本。我们需要安装以下关键依赖:
bash复制pip install openai panel pandas
创建项目配置文件config.py存储API密钥:
python复制# config.py
OPENAI_API_KEY = "你的实际API密钥" # 请替换为真实密钥
MENU_ITEMS = {
"pizzas": {
"pepperoni": [12.95, 10.00, 7.00],
"cheese": [10.95, 9.25, 6.50],
"eggplant": [11.95, 9.75, 6.75]
},
"toppings": {
"extra cheese": 2.00,
"mushrooms": 1.50
}
}
与GPT-3.5 API交互的核心函数需要精心设计,以支持多轮对话和上下文保持:
python复制import openai
from config import OPENAI_API_KEY
openai.api_key = OPENAI_API_KEY
def get_chat_response(messages, temperature=0.7):
"""
获取GPT-3.5的聊天响应
:param messages: 对话消息列表
:param temperature: 响应随机性(0-1)
:return: 助手回复内容
"""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages,
temperature=temperature
)
return response.choices[0].message["content"]
except Exception as e:
return f"API请求出错: {str(e)}"
一个高效的订单机器人需要精心设计的对话流程和系统提示词,这直接决定了用户体验和订单准确率。
系统提示词(system prompt)是指导AI行为的关键。以下是针对披萨店场景优化的提示词:
python复制system_prompt = """
你是一个名为PizzaBot的智能订餐助手,专门为Mario披萨店服务。你的职责是以友好、专业的语气引导顾客完成订餐流程。请遵循以下规则:
1. 问候后首先询问顾客姓名,并在后续对话中使用
2. 分步骤收集以下信息:
- 披萨类型(必选):pepperoni/cheese/eggplant
- 尺寸(必选):large/medium/small
- 配料(可选):extra cheese/mushrooms等
- 饮品和小食(可选)
- 取餐方式:delivery(需地址)/pickup
- 支付方式:cash/card
3. 菜单价格:
- 披萨:
• Pepperoni: 大12.95/中10.00/小7.00
• Cheese: 大10.95/中9.25/小6.50
• Eggplant: 大11.95/中9.75/小6.75
- 配料:每份+1.0-3.0
- 饮品:3.0-5.0
4. 确认订单前总结所有选择,并询问是否需要修改
5. 最终以JSON格式输出完整订单
"""
实现多轮对话需要维护完整的对话历史上下文:
python复制class ConversationManager:
def __init__(self, system_prompt):
self.messages = [{"role": "system", "content": system_prompt}]
self.current_order = {}
def add_user_message(self, content):
self.messages.append({"role": "user", "content": content})
def add_assistant_message(self, content):
self.messages.append({"role": "assistant", "content": content})
def get_response(self):
response = get_chat_response(self.messages)
self.add_assistant_message(response)
return response
def extract_order_details(self):
"""从对话历史中提取订单信息"""
order_prompt = """
请将以下对话内容中的订单信息提取为JSON格式,包含:
- customer_name
- items (list)
- total_price
- delivery_type
- payment_method
"""
extract_messages = self.messages.copy()
extract_messages.append({
"role": "user",
"content": order_prompt
})
return get_chat_response(extract_messages, temperature=0)
使用panel库可以快速构建交互式界面,让订单机器人更加用户友好。
python复制import panel as pn
from conversation import ConversationManager
pn.extension() # 初始化panel扩展
class PizzaOrderApp:
def __init__(self):
self.conversation = ConversationManager(system_prompt)
self.chat_history = []
self.setup_ui()
def setup_ui(self):
"""初始化UI组件"""
self.input_widget = pn.widgets.TextInput(
placeholder="输入你的消息...",
width=600
)
self.send_button = pn.widgets.Button(
name="发送",
button_type="primary"
)
self.send_button.on_click(self.process_message)
self.chat_log = pn.Column(
*self.chat_history,
scroll=True,
height=400
)
self.dashboard = pn.Column(
"## Mario披萨店订餐助手",
self.chat_log,
pn.Row(self.input_widget, self.send_button),
width=700
)
def process_message(self, event):
"""处理用户发送的消息"""
user_input = self.input_widget.value
if not user_input.strip():
return
self.conversation.add_user_message(user_input)
response = self.conversation.get_response()
# 更新聊天记录显示
self.chat_history.extend([
pn.Row("👤 顾客:", pn.pane.Markdown(user_input)),
pn.Row("🤖 助手:", pn.pane.Markdown(response,
styles={"background": "#f5f5f5"}))
])
self.chat_log.objects = self.chat_history
self.input_widget.value = ""
增强GUI功能,添加订单确认和导出按钮:
python复制def setup_ui(self):
# ...原有代码...
self.confirm_button = pn.widgets.Button(
name="确认订单",
button_type="success",
disabled=True
)
self.confirm_button.on_click(self.finalize_order)
self.export_button = pn.widgets.Button(
name="导出订单JSON",
button_type="warning",
disabled=True
)
self.export_button.on_click(self.export_order)
self.order_summary = pn.pane.JSON(
{},
name="订单摘要",
height=200
)
self.dashboard.extend([
pn.Row(self.confirm_button, self.export_button),
"## 订单摘要",
self.order_summary
])
def finalize_order(self, event):
"""确认最终订单"""
order_json = self.conversation.extract_order_details()
self.order_summary.object = json.loads(order_json)
self.export_button.disabled = False
完整的订单机器人需要将对话转化为结构化数据,便于后续处理。
定义标准的订单数据结构:
python复制{
"order_id": "自动生成的唯一ID",
"customer_info": {
"name": "顾客姓名",
"phone": "联系电话(可选)"
},
"items": [
{
"type": "pizza",
"name": "pepperoni",
"size": "large",
"quantity": 1,
"price": 12.95,
"toppings": ["mushrooms"]
}
],
"delivery": {
"type": "pickup/delivery",
"address": "仅配送需要",
"estimated_time": "预计时间"
},
"payment": {
"method": "cash/card",
"amount": 15.95,
"status": "pending"
},
"timestamp": "订单创建时间"
}
实现订单保存和处理的逻辑:
python复制import json
from datetime import datetime
import uuid
class OrderManager:
def __init__(self):
self.orders = {}
def create_order(self, order_data):
"""创建新订单"""
order_id = str(uuid.uuid4())[:8]
order_data["order_id"] = order_id
order_data["timestamp"] = datetime.now().isoformat()
self.orders[order_id] = order_data
# 实际应用中这里可以添加数据库存储逻辑
with open(f"orders/{order_id}.json", "w") as f:
json.dump(order_data, f, indent=2)
return order_id
def process_payment(self, order_id, payment_info):
"""处理支付"""
if order_id not in self.orders:
return False
self.orders[order_id]["payment"] = {
**payment_info,
"status": "completed",
"processed_at": datetime.now().isoformat()
}
return True
完成开发后,我们需要考虑如何部署这个订单机器人并优化其性能。
在正式部署前,进行充分测试:
python复制def test_order_flow():
"""测试完整的订餐流程"""
manager = ConversationManager(system_prompt)
# 模拟用户对话
test_messages = [
"你好",
"我叫张三",
"我想要订一个大份的pepperoni披萨",
"加mushrooms配料",
"再要一杯可乐",
"我要外带",
"用现金支付"
]
for msg in test_messages:
print(f"用户: {msg}")
manager.add_user_message(msg)
response = manager.get_response()
print(f"助手: {response}")
order_json = manager.extract_order_details()
print("\n生成的订单JSON:")
print(order_json)
if __name__ == "__main__":
test_order_flow()
根据使用场景选择适合的部署方式:
| 部署方式 | 适用场景 | 优点 | 缺点 |
|---|---|---|---|
| 本地运行 | 小型披萨店单机使用 | 简单快速,无需网络 | 难以多设备访问 |
| Web应用 | 多门店集中管理 | 随时随地访问 | 需要服务器资源 |
| 桌面应用 | 店内收银台集成 | 稳定可靠 | 安装部署复杂 |
对于大多数场景,推荐使用Panel的Web部署功能:
python复制# 在app.py中添加
if __name__ == "__main__":
app = PizzaOrderApp()
app.dashboard.servable()
然后通过命令启动服务:
bash复制panel serve app.py --show
基础功能实现后,可以考虑添加以下增强功能提升用户体验:
通过修改系统提示词实现多语言切换:
python复制multilingual_prompt = """
You are PizzaBot, capable of handling orders in multiple languages.
Respond in the same language as the customer uses.
Start by asking: "In which language would you like to place your order?"
Then continue the conversation in that language.
"""
基于订单历史实现智能推荐:
python复制def get_recommendations(order_history):
"""根据历史订单生成推荐"""
prompt = f"""
根据以下订单历史,为顾客生成个性化推荐:
{order_history}
考虑:
1. 经常点的品类
2. 搭配组合(如披萨+饮品)
3. 新品或促销
返回3条推荐,格式为:
- 推荐1: 理由
- 推荐2: 理由
"""
return get_chat_response([{"role": "user", "content": prompt}])
使用语音识别API实现语音输入:
python复制import speech_recognition as sr
def voice_input():
r = sr.Recognizer()
with sr.Microphone() as source:
print("请说话...")
audio = r.listen(source)
try:
text = r.recognize_google(audio, language="zh-CN")
return text
except Exception as e:
return f"语音识别错误: {e}"