这是一个基于 PyQt5 的聊天机器人程序,通过 API 接入硅基流动(Silicon Flow)或其他的聊天服务,支持用户与聊天机器人进行交互。
- API 设置:通过菜单栏的“设置”选项,用户可以修改 API 地址和 API 密钥。
- 设置对话框:提供输入框用于修改 API 地址和 API 密钥。
核心功能
- 发送消息:用户输入消息后,点击“发送”按钮或按回车键发送消息。
- 获取回复:通过 API 请求获取聊天机器人的回复。
- 显示对话:将用户消息和机器人回复显示在聊天记录区域。
API 集成
- API 地址:默认使用 https://api.siliconflow.com/v1/chat,支持通过设置对话框修改。
- API 密钥:需要提供有效的 API 密钥,支持通过设置对话框修改。
- 请求参数:包括用户消息、温度(temperature)和最大 token 数(max_tokens)。
交互流程
- 用户启动程序,界面显示聊天记录区域、输入框和发送按钮。
- 用户在输入框中输入消息,点击“发送”按钮或按回车键。
- 程序通过 API 请求获取聊天机器人的回复。
- 将用户消息和机器人回复显示在聊天记录区域。
import sys
import requests
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
QHBoxLayout, QPushButton, QTextEdit, QLabel, QLineEdit,
QDialog, QFormLayout, QDialogButtonBox)
from PyQt5.QtCore import Qt
class SettingsDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("API 设置")
# 创建表单布局
layout = QFormLayout(self)
# API 地址输入框
self.api_url_input = QLineEdit(self)
layout.addRow("API 地址:", self.api_url_input)
# API 密钥输入框
self.api_key_input = QLineEdit(self)
self.api_key_input.setEchoMode(QLineEdit.Password)
layout.addRow("API 密钥:", self.api_key_input)
# 按钮
buttons = QDialogButtonBox(
QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
Qt.Horizontal, self)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
layout.addRow(buttons)
def get_settings(self):
"""获取用户输入的设置"""
return {
'api_url': self.api_url_input.text().strip(),
'api_key': self.api_key_input.text().strip()
}
class ChatBotUI(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("硅基流动聊天机器人")
self.setGeometry(100, 100, 800, 600)
# 初始化UI
self.init_ui()
# 初始化 API 设置
self.api_url = "https://api.siliconflow.com/v1/chat"
self.api_key = "sk-gt**********mux" #请输入你的API秘钥
def init_ui(self):
"""初始化用户界面"""
# 创建主窗口部件和布局
central_widget = QWidget()
self.setCentralWidget(central_widget)
layout = QVBoxLayout(central_widget)
# 创建菜单栏
self.create_menu_bar()
# 创建聊天记录显示区域
self.chat_display = QTextEdit()
self.chat_display.setReadOnly(True)
self.chat_display.setStyleSheet("""
QTextEdit {
font-size: 14px;
margin: 10px;
padding: 10px;
background-color: #f0f0f0;
border-radius: 5px;
}
""")
layout.addWidget(self.chat_display)
# 创建输入区域
input_layout = QHBoxLayout()
# 用户输入框
self.user_input = QLineEdit()
self.user_input.setPlaceholderText("请输入您的问题...")
self.user_input.returnPressed.connect(self.send_message)
input_layout.addWidget(self.user_input)
# 发送按钮
self.btn_send = QPushButton("发送")
self.btn_send.clicked.connect(self.send_message)
input_layout.addWidget(self.btn_send)
layout.addLayout(input_layout)
# 状态栏
self.status_label = QLabel("准备就绪")
self.status_label.setAlignment(Qt.AlignCenter)
self.status_label.setStyleSheet("""
QLabel {
font-size: 12px;
color: #666;
margin: 5px;
}
""")
layout.addWidget(self.status_label)
def create_menu_bar(self):
"""创建菜单栏"""
menubar = self.menuBar()
# 添加设置菜单
settings_menu = menubar.addMenu('设置')
# 添加 API 设置选项
api_settings_action = settings_menu.addAction('API 设置')
api_settings_action.triggered.connect(self.show_api_settings)
def show_api_settings(self):
"""显示 API 设置对话框"""
dialog = SettingsDialog(self)
if dialog.exec_():
settings = dialog.get_settings()
self.api_url = settings['api_url']
self.api_key = settings['api_key']
self.status_label.setText("API 设置已更新")
def send_message(self):
"""发送消息并获取回复"""
user_message = self.user_input.text().strip()
if not user_message:
return
# 显示用户消息
self.append_message("用户", user_message)
self.user_input.clear()
# 获取机器人回复
self.status_label.setText("正在获取回复...")
try:
response = self.get_bot_response(user_message)
self.append_message("机器人", response)
self.status_label.setText("回复已接收")
except Exception as e:
self.append_message("系统", f"错误: {str(e)}")
self.status_label.setText("获取回复时出错")
def get_bot_response(self, message):
"""调用 API 获取机器人回复"""
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
data = {
"message": message,
"temperature": 0.7,
"max_tokens": 100
}
try:
response = requests.post(self.api_url, json=data, headers=headers)
response.raise_for_status()
# 打印原始响应内容用于调试
print("API 响应内容:", response.text)
# 尝试解析 JSON
json_response = response.json()
return json_response["choices"][0]["message"]["content"]
except requests.exceptions.RequestException as e:
print(f"API 请求错误: {str(e)}")
raise Exception(f"API 请求失败: {str(e)}")
except ValueError as e:
print(f"JSON 解析错误: {str(e)}")
print("原始响应内容:", response.text)
raise Exception("API 返回了无效的 JSON 数据")
except KeyError as e:
print(f"响应格式错误: {str(e)}")
print("完整响应:", json_response)
raise Exception("API 返回了意外的响应格式")
def append_message(self, sender, message):
"""在聊天记录中添加消息"""
self.chat_display.append(f"<b>{sender}:</b> {message}")
self.chat_display.ensureCursorVisible()
def main():
app = QApplication(sys.argv)
window = ChatBotUI()
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()