
deepseek+pyqt简易界面
deepseek是国内目前非常好的问答大模型,结合pyqt设计自己的界面
界面效果:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLineEdit, QPushButton, QMessageBox
from openai import OpenAI
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QTextBrowser, QLineEdit, QPushButton, QScrollArea
from PyQt5.QtGui import QColor, QFont
client = OpenAI(api_key="自己的api", base_url="https://api.deepseek.com")
class ChatWindow(QWidget):
def __init__(self):
super().__init__()
# 初始化界面
self.setWindowTitle("小智问答")
self.setGeometry(100, 100, 600, 500)
self.setStyleSheet("background-color: #F5F5F5;")#
# 初始化 UI 组件
self.history_browser = QTextBrowser(self)
self.history_browser.setOpenExternalLinks(True) # 允许链接点击
self.history_browser.setStyleSheet("background-color: #FFFFFF; border-radius: 10px; padding: 10px; font-size: 14px;")
self.history_browser.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.input_text = QLineEdit(self)
self.input_text.setPlaceholderText("请输入消息...")
self.input_text.setStyleSheet("""
QLineEdit {
background-color: #FFFFFF;
border-radius: 5px;
padding: 10px;
font-size: 14px;
}
""")
self.send_button = QPushButton("发送", self)
self.send_button.setStyleSheet("""
QPushButton {
background-color: #4CAF50;
color: white;
border-radius: 5px;
padding: 10px;
font-size: 14px;
}
QPushButton:hover {
background-color: #45a049;
}
""")
self.send_button.clicked.connect(self.send_message)
# 布局设置
main_layout = QVBoxLayout()
chat_layout = QVBoxLayout()
# 创建历史记录区域
scroll_area = QScrollArea()
scroll_area.setWidgetResizable(True)
scroll_area.setWidget(self.history_browser)
# 输入和发送按钮
input_layout = QHBoxLayout()
input_layout.addWidget(self.input_text)
input_layout.addWidget(self.send_button)
# 添加控件到主布局
chat_layout.addWidget(scroll_area)
chat_layout.addLayout(input_layout)
main_layout.addLayout(chat_layout)
self.setLayout(main_layout)
def send_message(self):
message = self.input_text.text().strip()
if message:
# 显示用户输入的消息
self.history_browser.append(f'<div style="text-align: right; color: #007BFF; font-weight: bold;">用户: {message}</div>')
# 清空输入框
self.input_text.clear()
# 调用 DeepSeek API
try:
response = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "system", "content": "You are a helpful assistant"},
{"role": "user", "content": message},
],
stream=False
)
# 显示响应
reply = response.choices[0].message.content
# QMessageBox.information(self, "Response", reply)
except Exception as e:
QMessageBox.critical(self, "Error", f"An error occurred: {str(e)}")
# 模拟回复
self.history_browser.append(f'<div style="text-align: left; color: #000000;">小智:{reply}</div>')
# 滚动到底部
self.history_browser.moveCursor(Qt.TextCursor.End)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = ChatWindow()
window.show()
sys.exit(app.exec_())
更多推荐
所有评论(0)