赞
踩
MVP(最简可行产品)版本的客服机器人应该聚焦于核心功能,以快速上线和测试用户反馈为目标。以下是一个简化的版本:
这个MVP版本的客服机器人可以快速上线,并根据用户反馈逐步增加更多功能和改进。它能够解决用户的一些基本需求,同时保持开发和维护的简洁性。
实现这些MVP功能的客服机器人需要一个清晰的技术架构,确保其高效、稳定地运行。以下是推荐的技术架构:
通过以上架构和步骤,可以有效地实现一个功能完备的MVP客服机器人。
优先级:
npm install -g @vue/cli
vue create chat-bot
报错vue:无法加载,因为在此系统上禁止运行脚本
分析原因,权限不足
1. 以管理员身份运行powerShell
2.输入命令: set-ExecutionPolicy RemoteSigned
3. 输入Y
问题解决
继续第二步
在 src
目录下创建一个新的组件文件 ChatBot.vue
,并添加以下代码:
<template> <div class="chat-container"> <div class="messages"> <div v-for="(message, index) in messages" :key="index" class="message"> <div :class="message.sender">{{ message.text }}</div> </div> </div> <div class="input-container"> <input v-model="userInput" @keyup.enter="sendMessage" type="text" placeholder="Type a message..." /> <button @click="sendMessage">Send</button> </div> </div> </template> <script> export default { data() { return { userInput: '', messages: [ { text: 'Hello! How can I help you today?', sender: 'bot' }, ], }; }, methods: { sendMessage() { if (this.userInput.trim() !== '') { this.messages.push({ text: this.userInput, sender: 'user' }); this.userInput = ''; // Simulate bot response setTimeout(() => { this.messages.push({ text: 'I am still learning. Please ask something else!', sender: 'bot' }); }, 1000); } }, }, }; </script> <style scoped> .chat-container { width: 100%; max-width: 600px; margin: 0 auto; border: 1px solid #ccc; border-radius: 5px; display: flex; flex-direction: column; height: 400px; } .messages { flex: 1; padding: 10px; overflow-y: auto; border-bottom: 1px solid #ccc; } .message { margin: 5px 0; } .user { text-align: right; color: blue; } .bot { text-align: left; color: green; } .input-container { display: flex; border-top: 1px solid #ccc; } input { flex: 1; border: none; padding: 10px; font-size: 16px; border-top-left-radius: 5px; border-bottom-left-radius: 5px; } button { padding: 10px; font-size: 16px; border: none; background-color: #007bff; color: white; cursor: pointer; border-top-right-radius: 5px; border-bottom-right-radius: 5px; } button:hover { background-color: #0056b3; } </style>
在 src/App.vue
中注册并使用 ChatBot
组件:
<template> <div id="app"> <ChatBot /> </div> </template> <script> import ChatBot from './components/ChatBot.vue'; export default { name: 'App', components: { ChatBot, }, }; </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
确保你在项目目录下,然后运行以下命令启动应用:
npm run serve
支持简单输出和回复
在D盘创建flaskproject
mkdir flask-chat-bot
cd flask-chat-bot
python -m venv venv
venv\Scripts\activate
安装Flask和Flask-CORS:
pip install Flask Flask-CORS
用PyCharm里面,在项目根目录下创建一个 app.py
文件,并添加以下代码:
# app.py from flask import Flask, request, jsonify from flask_cors import CORS import random app = Flask(__name__) CORS(app) # 模拟的机器人回复 bot_responses = [ "I'm still learning. Please ask something else!", "Can you please elaborate?", "I'm here to help you. What do you need?", ] def get_bot_response(): return random.choice(bot_responses) @app.route('/api/chat/message', methods=['POST']) def chat(): user_message = request.json.get('message') if not user_message: return jsonify({'error': 'Message is required'}), 400 # 模拟处理用户消息并生成回复 bot_message = get_bot_response() return jsonify({ 'userMessage': user_message, 'botMessage': bot_message, }) if __name__ == '__main__': app.run(debug=True)
报错ModuleNotFoundError: No module named ‘flask_cors’,flask_cors下载失败
分析问题:python312版本和pycharm的310版本间出现冲突
解决问题:
删除310版本,更改pycharm的本地配置解释器为312版本
C:\Users\Administrator\AppData\Local\Programs\Python\Python312
问题解决。
在终端中运行以下命令启动Flask服务器:
python app.py
Flask服务器将在 http://localhost:5000
上运行。
基于Windows系统的Flask后端和Vue.js前端的REST API消息传递功能
<template> <div class="chat-container"> <div class="messages"> <div v-for="(message, index) in messages" :key="index" class="message"> <div :class="message.sender">{{ message.text }}</div> </div> </div> <div class="input-container"> <input v-model="userInput" @keyup.enter="sendMessage" type="text" placeholder="Type a message..." /> <button @click="sendMessage">Send</button> </div> </div> </template> <script> export default { data() { return { userInput: '', messages: [ { text: 'Hello! How can I help you today?', sender: 'bot' }, ], }; }, methods: { async sendMessage() { if (this.userInput.trim() !== '') { this.messages.push({ text: this.userInput, sender: 'user' }); // 保存用户输入 const userMessage = this.userInput; this.userInput = ''; try { // 发送请求到后端API const response = await fetch('http://localhost:5000/api/chat/message', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ message: userMessage }), }); const data = await response.json(); // 显示机器人的回复 this.messages.push({ text: data.botMessage, sender: 'bot' }); } catch (error) { console.error('Error:', error); } } }, }, }; </script> <style scoped> .chat-container { width: 100%; max-width: 600px; margin: 0 auto; border: 1px solid #ccc; border-radius: 5px; display: flex; flex-direction: column; height: 400px; } .messages { flex: 1; padding: 10px; overflow-y: auto; border-bottom: 1px solid #ccc; } .message { margin: 5px 0; } .user { text-align: right; color: blue; } .bot { text-align: left; color: green; } .input-container { display: flex; border-top: 1px solid #ccc; } input { flex: 1; border: none; padding: 10px; font-size: 16px; border-top-left-radius: 5px; border-bottom-left-radius: 5px; } button { padding: 10px; font-size: 16px; border: none; background-color: #007bff; color: white; cursor: pointer; border-top-right-radius: 5px; border-bottom-right-radius: 5px; } button:hover { background-color: #0056b3; } </style>
效果
技术栈:Vue.js
功能
:
技术栈:Flask(Python)
功能
:
OpenAI API
:
|-------------| HTTP |--------------| HTTP |---------------|
| Frontend | <-----------------> | Backend | <--------------> | OpenAI API |
| Vue.js | REST API | Flask | API Request | |
|-------------| |--------------| |---------------|
| | | |
User input Process request
| | | |
Send message ---> Receive message ---> Call OpenAI
| | | |
Display reply <--- Return reply <--- Get reply
# app.py from flask_cors import CORS from flask import Flask, request, jsonify from openai import OpenAI from dotenv import load_dotenv, find_dotenv app = Flask(__name__) CORS(app) _ = load_dotenv(find_dotenv()) client = OpenAI() @app.route('/api/chat/message', methods=['POST']) def chat(): user_message = request.json.get('message') if not user_message: return jsonify({'error': 'Message is required'}), 400 messages = [ {"role": "system", "content": "你是一个客服机器人"}, {"role": "user", "content": user_message} ] print(messages) try: # 调用OpenAI API获取回复 response = client.chat.completions.create( model="gpt-3.5-turbo", messages=messages ) bot_message = response.choices[0].message.content print(bot_message) except Exception as e: return jsonify({'error': str(e)}), 500 return jsonify({ 'userMessage': user_message, 'botMessage': bot_message, }) if __name__ == '__main__': app.run(debug=True)
<template> <div class="chat-container"> <div class="messages"> <div v-for="(message, index) in messages" :key="index" class="message"> <div :class="message.sender">{{ message.text }}</div> </div> </div> <div class="input-container"> <input v-model="userInput" @keyup.enter="sendMessage" type="text" placeholder="Type a message..." /> <button @click="sendMessage">Send</button> </div> </div> </template> <script> export default { data() { return { userInput: '', messages: [ { text: 'Hello! How can I help you today?', sender: 'bot' }, ], }; }, methods: { async sendMessage() { if (this.userInput.trim() !== '') { this.messages.push({ text: this.userInput, sender: 'user' }); // 保存用户输入 const userMessage = this.userInput; this.userInput = ''; try { // 发送请求到后端API const response = await fetch('http://localhost:5000/api/chat/message', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ message: userMessage }), }); const data = await response.json(); // 显示机器人的回复 this.messages.push({ text: data.botMessage, sender: 'bot' }); } catch (error) { console.error('Error:', error); } } }, }, }; </script> <style scoped> .chat-container { width: 100%; max-width: 600px; margin: 0 auto; border: 1px solid #ccc; border-radius: 5px; display: flex; flex-direction: column; height: 400px; } .messages { flex: 1; padding: 10px; overflow-y: auto; border-bottom: 1px solid #ccc; } .message { margin: 5px 0; } .user { text-align: right; color: blue; } .bot { text-align: left; color: green; } .input-container { display: flex; border-top: 1px solid #ccc; } input { flex: 1; border: none; padding: 10px; font-size: 16px; border-top-left-radius: 5px; border-bottom-left-radius: 5px; } button { padding: 10px; font-size: 16px; border: none; background-color: #007bff; color: white; cursor: pointer; border-top-right-radius: 5px; border-bottom-right-radius: 5px; } button:hover { background-color: #0056b3; } </style>
更改后的效果如下
使用mysql数据库接入,通过OpenAI API查询本地数据库以获取真实的订单信息
采用DBeaver创建zh数据库并建立order表,插入数据
CREATE DATABASE order_db; USE order_db; CREATE TABLE orders ( id INT AUTO_INCREMENT PRIMARY KEY, order_number VARCHAR(50) NOT NULL, customer_name VARCHAR(100), product VARCHAR(100), quantity INT, status VARCHAR(50) ); -- 插入一些示例数据 INSERT INTO orders (order_number, customer_name, product, quantity, status) VALUES ('ORD001', 'Alice', 'Laptop', 1, 'Shipped'), ('ORD002', 'Bob', 'Smartphone', 2, 'Processing'), ('ORD003', 'Charlie', 'Tablet', 1, 'Delivered');
添加app.py连接数据库
# 数据库配置
db_config = {
'user': 'root',
'password': 'your_mysql_password', # 在此处替换为你的MySQL密码
'host': '127.0.0.1',
'database': 'order_db',
'raise_on_warnings': True
}
查询订单信息
# 查询订单信息 def get_order_info(order_number): try: cnx = mysql.connector.connect(**db_config) cursor = cnx.cursor(dictionary=True) query = "SELECT * FROM orders WHERE order_number = %s" cursor.execute(query, (order_number,)) result = cursor.fetchone() cursor.close() cnx.close() return result except mysql.connector.Error as err: return {'error': str(err)}
添加chatgpt访问数据库
def get_completion(messages): # 调用OpenAI API获取回复 response = client.chat.completions.create( model="gpt-3.5-turbo", messages=messages, temperature=0, tools=[{ "type": "function", "function": { "name": "get_order_id", "description": "Get the current order id", "parameters": { "type": "object", "properties": { "order_id": { "type": "string", "description": "订单号格式为ORD开头", } }, "required": ["order_id"], }, } }], ) return response.choices[0].message @app.route('/api/chat/message', methods=['POST']) def chat(): user_message = request.json.get('message') if not user_message: return jsonify({'error': 'Message is required'}), 400 messages = [ {"role": "system", "content": "你是一个客服机器人"}, {"role": "user", "content": user_message} ] print(messages) try: # 调用OpenAI API获取回复 response = get_completion(messages) bot_content = response.content print(f'bot_content:', bot_content) if bot_content: return jsonify({ 'userMessage': user_message, 'botMessage': bot_content, }) bot_message = response print(f'bot_message:', bot_message) messages.append(bot_message) if (response.tool_calls is not None): tool_call = response.tool_calls[0] print(f'tool_call:', tool_call) if (tool_call.function.name == 'get_order_id'): print(f'get_order_id:') args = json.loads(tool_call.function.arguments) order_id = get_order_info(**args) print(f'order_id:', order_id) messages.append( { "role": "tool", "content": "Order ID: " + str(order_id), "tool_call_id": tool_call.id } ) print(f'messages:', messages) response = get_completion(messages) print(f'response:', response) return jsonify({ 'userMessage': user_message, 'botMessage': response.content, }) except Exception as e: return jsonify({'error': str(e)}), 500 return jsonify({ 'userMessage': user_message, 'botMessage': bot_message, })
重新启动服务器
效果如下,可以看到成功查询到本地数据库订单号为ORD001的订单状态信息,并且成功返回客户端界面:
数据库中创建一个名为 faqs
的表,存储常见问题和答案
CREATE TABLE faqs (
id INT AUTO_INCREMENT PRIMARY KEY,
question TEXT NOT NULL,
answer TEXT NOT NULL
);
插入数据
INSERT INTO faqs (question, answer) VALUES
('如何重置密码?', '要重置密码,请转到登录页面并点击“忘记密码”链接。按照说明重置您的密码。'),
('退货政策是什么?', '我们的退货政策允许您在购买后30天内退货。请确保产品处于原始状态。'),
('如何跟踪我的订单?', '要跟踪订单,请登录您的账户并转到“订单”部分。点击您想要跟踪的订单以查看最新状态。'),
('我可以更改收货地址吗?', '是的,您可以在订单发货前更改收货地址。请联系客户服务以获取帮助。'),
('你们接受哪些付款方式?', '我们接受多种付款方式,包括信用卡、借记卡、PayPal和银行转账。'),
('如何联系客户支持?', '您可以通过电子邮件support@example.com联系我们的客户支持,或拨打1-800-123-4567。'),
('你们的工作时间是什么时候?', '我们的客户支持时间为周一至周五,上午9点到下午5点。'),
('如何取消我的订单?', '要取消订单,请登录您的账户,转到“订单”部分,然后选择您要取消的订单。如果订单尚未发货,您将看到“取消订单”选项。'),
('你们提供国际运输吗?', '是的,我们提供大多数国家的国际运输。运费和交货时间因目的地而异。'),
('如何使用折扣码?', '要使用折扣码,请在结账时在“折扣码”字段中输入代码并点击“应用”。折扣将应用到您的订单总额。');
数据库显示及如下:
接下来,我们需要调整Flask应用以支持FAQ查询。我们将实现一个新的API端点,用于从数据库中检索常见问题和答案。
# 查询FAQ def get_faq(question): try: cnx = mysql.connector.connect(**db_config) cursor = cnx.cursor(dictionary=True) query = "SELECT answer FROM faqs WHERE question LIKE %s" cursor.execute(query, ("%"+question+"%",)) result = cursor.fetchone() cursor.close() cnx.close() return result except mysql.connector.Error as err: return {'error': str(err)}
添加chatgpt功能部分代码
{ "type": "function", "function": { "name": "get_faq", "description": "Get the current question id", "parameters": { "type": "object", "properties": { "question": { "type": "string", "description": "question should be a question in table", } }, "required": ["question"], }, }
增加返回值判断
elif (tool_call.function.name == 'get_faq'): print(f'get_faq:') args = json.loads(tool_call.function.arguments) answer = get_faq(**args) print(f'question_id:', answer) messages.append( { "role": "tool", "content": "answer: " + str(answer), "tool_call_id": tool_call.id } ) print(f'messages:', messages) response = get_completion(messages) print(f'response:', response) return jsonify({ 'userMessage': user_message, 'botMessage': response.content, })
效果如下:
https://chatgpt.com/share/cd990a21-86d5-4a6c-ac0b-b3a775738d5a
为了使用RabbitMQ消息队列系统来管理和转发用户请求给人工客服,我们需要设置RabbitMQ服务器,并且在Flask后端实现发送消息到RabbitMQ的功能。在接收端,可以实现一个消费者程序,实时监听队列并将请求分配给人工客服。
首先,你需要在你的系统上安装RabbitMQ。可以参考RabbitMQ官方文档进行安装。
由于本机的docker和vm虚拟器冲突无法使用docker,按照传统方式安装rabbitMQ
以下是具体的命令和下载链接: 下载Erlang: 访问Erlang Solutions的官方网站下载最新版本的Erlang:https://www.erlang.org/downloads 安装Erlang: 双击下载的exe文件,按提示进行安装。 设置环境变量,将Erlang的安装目录和bin目录添加到系统的PATH变量中。 下载RabbitMQ: 访问RabbitMQ官方网站下载最新版本的RabbitMQ:https://www.rabbitmq.com/download.html 安装RabbitMQ: 双击下载的exe文件,按提示进行安装。 可以使用RabbitMQ Plugin来管理和扩展RabbitMQ的功能,通过命令行运行以下命令来启用管理界面: rabbitmq-plugins enable rabbitmq_management 访问RabbitMQ管理界面: 打开浏览器,访问 http://localhost:15672 ,使用默认用户guest和密码guest登录RabbitMQ管理界面。 注意:如果在安装过程中遇到问题,请确保你的Windows系统支持RabbitMQ,并查看官方文档以获取更多信息和解决方案。
安装完RabbitMQ后,启动RabbitMQ服务:
sudo service rabbitmq-server start
Pika是Python的RabbitMQ客户端库。可以通过pip安装:
pip install pika
我们将在Flask后端添加一个新的路由,将用户请求发送到RabbitMQ队列中。
# 发送消息到RabbitMQ def send_to_rabbitmq(message): try: connection = pika.BlockingConnection(pika.ConnectionParameters(host=rabbitmq_host)) channel = connection.channel() channel.queue_declare(queue=queue_name, durable=True) channel.basic_publish( exchange='', routing_key=queue_name, body=message, properties=pika.BasicProperties( delivery_mode=2, # make message persistent )) connection.close() except Exception as e: print(f"Failed to send message to RabbitMQ: {e}") # 将用户消息发送到RabbitMQ队列 send_to_rabbitmq(user_message)
接下来,我们创建一个消费者程序,它会监听RabbitMQ队列,并将用户请求分配给人工客服。
# consumer.py import pika rabbitmq_host = 'localhost' queue_name = 'customer_requests' def callback(ch, method, properties, body): print(f"Received {body}") # 在此处处理消息,将其分配给人工客服 # 比如通过邮件、通知系统等方式 ch.basic_ack(delivery_tag=method.delivery_tag) def main(): connection = pika.BlockingConnection(pika.ConnectionParameters(host=rabbitmq_host)) channel = connection.channel() channel.queue_declare(queue=queue_name, durable=True) channel.basic_qos(prefetch_count=1) channel.basic_consume(queue=queue_name, on_message_callback=callback) print('Waiting for messages. To exit press CTRL+C') channel.start_consuming() if __name__ == '__main__': main()
启动RabbitMQ服务器
sudo service rabbitmq-server start
启动Flask应用:
python app.py
3., 启动RabbitMQ消费者
python consumer.py
4; 测试应用:
在浏览器中访问 http://localhost:8080
,输入消息发送到后端,确认消息被成功发送到RabbitMQ,并在消费者端被接收和处理。
通过这些步骤,你就可以实现使用RabbitMQ消息队列系统管理和转发用户请求给人工客服的功能。
效果如下:
为了通过Email告知客服有用户需要帮助,我们需要在消费者程序中添加发送电子邮件的功能。我们可以使用Python的smtplib
库来实现发送邮件。下面是更新后的消费者代码,添加了通过电子邮件通知客服的功能。
首先,确保你有一个SMTP服务器和有效的电子邮件账户来发送通知邮件。下面是一个使用Gmail SMTP服务器的示例。
# consumer.py import pika import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart rabbitmq_host = 'localhost' queue_name = 'customer_requests' smtp_server = 'smtp.gmail.com' smtp_port = 587 smtp_user = 'your_email@gmail.com' # 在此处替换为你的电子邮件 smtp_password = 'your_email_password' # 在此处替换为你的电子邮件密码 customer_support_email = 'support@example.com' # 在此处替换为客服的电子邮件 def send_email(user_message): subject = "New Customer Request" body = f"You have a new customer request:\n\n{user_message}" msg = MIMEMultipart() msg['From'] = smtp_user msg['To'] = customer_support_email msg['Subject'] = subject msg.attach(MIMEText(body, 'plain')) try: server = smtplib.SMTP(smtp_server, smtp_port) server.starttls() server.login(smtp_user, smtp_password) text = msg.as_string() server.sendmail(smtp_user, customer_support_email, text) server.quit() print(f"Email sent to {customer_support_email}") except Exception as e: print(f"Failed to send email: {e}") def callback(ch, method, properties, body): user_message = body.decode() print(f"Received {user_message}") # 发送邮件通知客服 send_email(user_message) ch.basic_ack(delivery_tag=method.delivery_tag) def main(): connection = pika.BlockingConnection(pika.ConnectionParameters(host=rabbitmq_host)) channel = connection.channel() channel.queue_declare(queue=queue_name, durable=True) channel.basic_qos(prefetch_count=1) channel.basic_consume(queue=queue_name, on_message_callback=callback) print('Waiting for messages. To exit press CTRL+C') channel.start_consuming() if __name__ == '__main__': main()
确保安装了pika和smtplib库,如果没有安装,可以使用pip安装:
pip install pika
smtplib是Python标准库的一部分,因此不需要额外安装。
在代码中,替换以下变量为你自己的SMTP服务器信息和邮件账户信息:
smtp_server = 'smtp.gmail.com'
smtp_port = 587
smtp_user = 'your_email@gmail.com'
smtp_password = 'your_email_password'
customer_support_email = 'support@example.com'
python consumer.py
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。