Python uses PyQt5 to implement graphical software for chatting with DeepSeek
1. Import dependency library
import sys import requests import json from import QApplication, QWidget, QVBoxLayout, QTextEdit, QLineEdit, QPushButton, QLabel, QFileDialog from import QThread, pyqtSignal from import QPixmap
-
sys
: System-related functions used to handle Python, such as exiting the program. -
requests
: Used to send HTTP requests to communicate with the DeepSeek API. -
json
: Used to process data in JSON format. -
PyQt5
: Used to create a graphical user interface (GUI).-
QApplication
: Manage the application's control flow and main settings. -
QWidget
: Base class for all user interface objects. -
QVBoxLayout
: Vertical layout manager for arrangement of controls. -
QTextEdit
: Multi-line text input box to display chat history. -
QLineEdit
: Single-line text input box for user input messages. -
QPushButton
: Button control, used to trigger events. -
QLabel
: Tag control, used to display text or images. -
QFileDialog
: File selection dialog box for uploading images.
-
-
QThread
: Used to create multithreading to avoid blocking the main thread. -
pyqtSignal
: Used to pass signals between thread and main thread. -
QPixmap
: Used to load and display images.
2. DeepSeek API configuration
DEEPSEEK_API_URL = "/v1/chat/completions" DEEPSEEK_API_KEY = "your_deepseek_api_key" # Replace with your own DeepSeek API Key
-
DEEPSEEK_API_URL
: The endpoint URL of the DeepSeek API. -
DEEPSEEK_API_KEY
: DeepSeek API key for authentication.
3. ChatThread Class
class ChatThread(QThread): response_received = pyqtSignal(str) stream_response_received = pyqtSignal(str) def __init__(self, messages, stream=False): super().__init__() = messages = stream def run(self): headers = { "Authorization": f"Bearer {DEEPSEEK_API_KEY}", "Content-Type": "application/json" } data = { "model": "deepseek-chat", "messages": , "stream": } if : response = (DEEPSEEK_API_URL, headers=headers, json=data, stream=True) for line in response.iter_lines(): if line: decoded_line = ('utf-8') if decoded_line.startswith("data:"): json_data = (decoded_line[5:]) if "choices" in json_data: content = json_data["choices"][0]["delta"].get("content", "") self.stream_response_received.emit(content) else: response = (DEEPSEEK_API_URL, headers=headers, json=data) if response.status_code == 200: json_data = () content = json_data["choices"][0]["message"]["content"] self.response_received.emit(content) else: self.response_received.emit("Error: Cannot get a response from DeepSeekAPI.")
Function description
-
ChatThread
It is an inherited fromQThread
Class for communicating with the DeepSeek API in the background. -
response_received
andstream_response_received
: These two signals are used to pass the API's response back to the main thread. -
__init__
method:- accept
messages
(Chat history) andstream
(Whether streaming output is enabled) as a parameter.
- accept
-
run
method:- Send an HTTP POST request to the DeepSeek API.
- If streaming output is enabled (
stream=True
), then the response is read line by line and the signal is sent. - If streaming output is disabled, the signal is sent after waiting for the full response.
4. ChatApp class
class ChatApp(QWidget): def __init__(self): super().__init__() () = [] def initUI(self): ('DeepSeek Chat') (100, 100, 600, 400) layout = QVBoxLayout() self.chat_display = QTextEdit() self.chat_display.setReadOnly(True) (self.chat_display) self.input_box = QLineEdit() self.input_box.setPlaceholderText("Leave your thousands of words here...") (self.input_box) self.send_button = QPushButton('send') self.send_button.(self.send_message) (self.send_button) self.image_label = QLabel() (self.image_label) self.upload_image_button = QPushButton('Upload pictures') self.upload_image_button.(self.upload_image) (self.upload_image_button) (layout)
Function description
-
ChatApp
It is the main application class, inherited fromQWidget
。 -
__init__
method:- Initialize the interface and create an empty message list
。
- Initialize the interface and create an empty message list
-
initUI
method:- Set the window title and size.
- use
QVBoxLayout
Vertical arrangement of controls. -
chat_display
: Multi-line text box used to display chat history. -
input_box
: A single line text box for user input messages. -
send_button
: The button to send a message, triggered after clickingsend_message
method. -
image_label
: Used to display uploaded images. -
upload_image_button
: The button to upload the image, trigger after clickingupload_image
method.
5. Core functional methods
5.1 send_message method
def send_message(self): user_input = self.input_box.text() if user_input: ({"role": "user", "content": user_input}) self.chat_display.append(f"You: {user_input}") self.input_box.clear() self.chat_thread = ChatThread(, stream=True) self.chat_thread.stream_response_received.connect(self.update_chat_display_stream) self.chat_thread.start()
- Gets the message entered by the user.
- Add message to
in the list.
- Display user's message in the chat display area.
- Clear the input box.
- start up
ChatThread
Threads communicate with the DeepSeek API and enable streaming output.
5.2 update_chat_display_stream method
def update_chat_display_stream(self, content): self.chat_display.moveCursor(self.chat_display.textCursor().End) self.chat_display.insertPlainText(content) self.chat_display.moveCursor(self.chat_display.textCursor().End)
- Add the streaming response from the DeepSeek API verbatim to the chat display area.
- Make sure the cursor is always at the end of the text so that the user can see the latest content.
5.3 upload_image method
def upload_image(self): options = () file_name, _ = (self, "Upload pictures", "", "Images (*.png *.jpg *.jpeg)", options=options) if file_name: pixmap = QPixmap(file_name) self.image_label.setPixmap((200, 200)) ({"role": "user", "content": f"Image: {file_name}"})
- Opens the File Selection dialog box, allowing the user to select image files.
- Load the image and display it in
image_label
middle. - Add image path to
in the list.
6. Main program entry
if __name__ == '__main__': app = QApplication() chat_app = ChatApp() chat_app.show() (app.exec_())
- Create
QApplication
Example. - Create
ChatApp
Instance and display the window. - Enter the main event loop and wait for user interaction.
7. The complete code is as follows:
PyQt5 and requests are required to be installed
pip install PyQt5 requests
import sys import requests import json from import QApplication, QWidget, QVBoxLayout, QTextEdit, QLineEdit, QPushButton, QLabel, QFileDialog from import QThread, pyqtSignal from import QPixmap # DeepSeek API ConfigurationDEEPSEEK_API_URL = "/v1/chat/completions" DEEPSEEK_API_KEY = "your_deepseek_api_key" # Replace with your own DeepSeek API Key, go to DeepSeek to register and get it class ChatThread(QThread): response_received = pyqtSignal(str) stream_response_received = pyqtSignal(str) def __init__(self, messages, stream=False): super().__init__() = messages = stream def run(self): headers = { "Authorization": f"Bearer {DEEPSEEK_API_KEY}", "Content-Type": "application/json" } data = { "model": "deepseek-chat", "messages": , "stream": } if : response = (DEEPSEEK_API_URL, headers=headers, json=data, stream=True) for line in response.iter_lines(): if line: decoded_line = ('utf-8') if decoded_line.startswith("data:"): json_data = (decoded_line[5:]) if "choices" in json_data: content = json_data["choices"][0]["delta"].get("content", "") self.stream_response_received.emit(content) else: response = (DEEPSEEK_API_URL, headers=headers, json=data) if response.status_code == 200: json_data = () content = json_data["choices"][0]["message"]["content"] self.response_received.emit(content) else: self.response_received.emit("Error: Cannot get a response from DeepSeekAPI.") class ChatApp(QWidget): def __init__(self): super().__init__() () = [] def initUI(self): ('DeepSeek Chat') (100, 100, 600, 400) layout = QVBoxLayout() self.chat_display = QTextEdit() self.chat_display.setReadOnly(True) (self.chat_display) self.input_box = QLineEdit() self.input_box.setPlaceholderText("Leave your thousands of words here...") (self.input_box) self.send_button = QPushButton('send') self.send_button.(self.send_message) (self.send_button) self.image_label = QLabel() (self.image_label) self.upload_image_button = QPushButton('Upload pictures') self.upload_image_button.(self.upload_image) (self.upload_image_button) (layout) def send_message(self): user_input = self.input_box.text() if user_input: ({"role": "user", "content": user_input}) self.chat_display.append(f"You: {user_input}") self.input_box.clear() self.chat_thread = ChatThread(, stream=True) self.chat_thread.stream_response_received.connect(self.update_chat_display_stream) self.chat_thread.start() def update_chat_display_stream(self, content): self.chat_display.moveCursor(self.chat_display.textCursor().End) self.chat_display.insertPlainText(content) self.chat_display.moveCursor(self.chat_display.textCursor().End) def upload_image(self): options = () file_name, _ = (self, "Upload pictures", "", "Images (*.png *.jpg *.jpeg)", options=options) if file_name: pixmap = QPixmap(file_name) self.image_label.setPixmap((200, 200)) ({"role": "user", "content": f"Image: {file_name}"}) if __name__ == '__main__': app = QApplication() chat_app = ChatApp() chat_app.show() (app.exec_())
8. Summary
- Use PyQt5 to create a simple graphical chat interface.
- pass
ChatThread
It implements asynchronous communication with the DeepSeek API, supporting streaming and non-streaming outputs. - Supports multiple rounds of conversation and multi-modal input (such as image upload).
- The code is clear and easy to expand and optimize.
The above is the detailed content of Python's graphical software that uses PyQt5 to implement chat with DeepSeek. For more information about Python PyQt5 and DeepSeek chat software, please follow my other related articles!
Related Articles
Implementation steps for exporting environments in Anaconda
Exporting the environment in Anaconda is a common practice. You can export the current environment configuration into a file. This article mainly introduces the implementation steps of exporting the environment in Anaconda, which has certain reference value2024-05-05Preliminary creation and simple configuration of Django project
This article mainly introduces the preliminary creation and simple configuration of Django projects, and introduces in detail how to install and configure Django, including creating projects, database configuration, routing, etc. Through this article, you can learn how to use Django to create your own web application.2023-09-09Python implements automatic IP replacement method
This article mainly introduces the method of automatically replacing ip in Python, involving Python's related operation techniques for native network configuration. It is very practical. Friends who need it can refer to it.2015-05-05Python implements simple index sorting and search functions
This article mainly introduces Python to implement simple index sorting and search functions. This article introduces you very detailed through the example code, which has certain reference value for your study or work. Friends who need it can refer to it.2021-04-04Python uses large language models for chart visualization
There have always been two problems with Python's visualization using matplotlib. One is that the code is cumbersome, and the other is that the default template is ugly. In the era of big models, there is another solution to this problem. Let's take a look at how to use large language models to visualize charts.2025-04-04Python implements multi-layer perceptron MLP (based on bimonthly dataset)
This article mainly introduces the implementation of python multi-layer perceptron MLP, based on the bimonthly data set, the sample code in the article is introduced in detail and has certain reference value. Interested friends can refer to it.2019-01-01Sweepstakes script code that sets the weight of a drawer in Python
This article mainly introduces the lottery script that can set the weight of the lottery winners in Python. The lottery system includes different weights for different lottery winners. Start with the prize with high value. Those who have already won the prize will no longer participate in the subsequent lottery. This article introduces it to you in detail through the example code. Friends who need it can refer to it.2022-11-11Summary of the usage of Python's struct library
The struct module performs the conversion between Python values and C structures represented by Python bytes. This can be used to process binary data stored in files or from network connections and other sources. The following is an introduction to the usage of Python's struct library. Interested friends can take a look.2022-05-05How to convert aac to mp3 in python and maintain the original directory structure
Introduction to the method of using Python scripts to implement AAC format to MP3 format. Users need to enter the directory path where the AAC file is located and the MP3 output directory path. Format conversion is realized by calling the FFmpeg tool. This script is simple and easy to understand and is suitable for users who need to batch process audio files. Before using it, make sure that the FFmpeg environment is installed.2024-11-11Detailed explanation of the usage of Python range() function
range() is a built-in Python function. It can return a series of continuously increasing integers. Its working method is similar to sharding and can generate a list object. This article mainly introduces the usage of Python range() function. Friends who need it can refer to it.2023-03-03