Certainly! Below is a complete Python application that uses PySide6 for the graphical user interface (GUI) and Gradio Client to communicate with an AI model via API calls. This application allows you to chat with the AI in a user-friendly window.
Prerequisites
Before you begin, ensure you have the required packages installed. You can install them using pip:
pip install PySide6 gradio-client
Application Overview
The application consists of:
-
GUI Components:
- Conversation Display: A read-only text area that shows the ongoing conversation between the user and the AI.
- Input Field: A line edit where the user can type their messages.
- Send Button: A button to send the typed message to the AI.
-
AI Communication:
- Gradio Client: Handles the API calls to the AI model.
- Conversation State: Maintains the chat history (
chatbot) and a counter (chat_counter) to manage the conversation context.
Complete Code
import sys
from PySide6.QtWidgets import (
QApplication, QWidget, QVBoxLayout, QHBoxLayout,
QTextEdit, QLineEdit, QPushButton, QLabel, QMessageBox
)
from PySide6.QtCore import Qt
from gradio_client import Client
class ChatApp(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("AI Chat with PySide6")
self.setGeometry(100, 100, 600, 400)
# Initialize conversation state
self.chat_counter = 0
self.chatbot = []
# Initialize Gradio client
try:
self.client = Client("yuntian-deng/o1mini")
except Exception as e:
QMessageBox.critical(self, "Connection Error", f"Failed to connect to the AI model:\n{e}")
sys.exit(1)
self.setup_ui()
def setup_ui(self):
layout = QVBoxLayout()
# Conversation display
self.conversation = QTextEdit()
self.conversation.setReadOnly(True)
layout.addWidget(self.conversation)
# Input layout
input_layout = QHBoxLayout()
self.input_field = QLineEdit()
self.input_field.setPlaceholderText("Type your message here...")
self.input_field.returnPressed.connect(self.send_message) # Send on Enter key
input_layout.addWidget(self.input_field)
self.send_button = QPushButton("Send")
self.send_button.clicked.connect(self.send_message)
input_layout.addWidget(self.send_button)
layout.addLayout(input_layout)
self.setLayout(layout)
def append_message(self, sender, message):
"""
Appends a message to the conversation display.
"""
self.conversation.append(f"<b>{sender}:</b> {message}")
self.conversation.moveCursor(Qt.TextCursor.End)
def send_message(self):
user_message = self.input_field.text().strip()
if not user_message:
return # Do not send empty messages
# Display user's message
self.append_message("You", user_message)
self.input_field.clear()
# Prepare inputs for the AI
try:
result = self.client.predict(
inputs=user_message,
top_p=1,
temperature=1,
chat_counter=self.chat_counter,
chatbot=self.chatbot,
api_name="/predict"
)
except Exception as e:
QMessageBox.warning(self, "API Error", f"Failed to get response from AI:\n{e}")
return
# Update conversation state
self.chat_counter += 1
self.chatbot.append([user_message, result])
# Display AI's response
self.append_message("AI", result)
def main():
app = QApplication(sys.argv)
chat_app = ChatApp()
chat_app.show()
sys.exit(app.exec())
if __name__ == "__main__":
main()
Explanation of the Code
-
Imports:
PySide6.QtWidgets for building the GUI components.
PySide6.QtCore for handling cursor movements.
gradio_client.Client for communicating with the AI model.
-
ChatApp Class:
-
main Function:
- Initializes the QApplication.
- Creates and displays an instance of the
ChatApp.
- Starts the event loop.
Running the Application
-
Ensure Dependencies are Installed:
Make sure you have both PySide6 and gradio-client installed as mentioned in the prerequisites.
-
Save the Script:
Save the provided code in a Python file, for example, ai_chat_app.py.
-
Run the Application:
Execute the script using Python:
python ai_chat_app.py
-
Interact with the AI:
- A window titled "AI Chat with PySide6" will appear.
- Type your messages in the input field at the bottom and press "Send" or hit the Enter key.
- The conversation will appear in the read-only text area above, displaying both your messages and the AI's responses.
Notes and Tips
-
Error Handling:
- The application includes basic error handling for connection issues and API call failures. Ensure that the AI model endpoint (
"yuntian-deng/o1mini") is accessible and correct.
-
Extending Functionality:
- You can enhance the GUI by adding features like scrollbars, timestamps, or user avatars.
- Consider adding settings to adjust parameters like
temperature and top_p dynamically.
-
Threading:
- For improved performance, especially if the AI response time is significant, consider running the API calls in a separate thread to prevent the GUI from freezing. This can be achieved using Python's
threading or concurrent.futures modules along with PySide6's signals and slots.
-
Styling:
- PySide6 allows for extensive styling using CSS-like syntax. You can customize the appearance of the application to match your preferences.
Conclusion
This application provides a simple yet functional interface to chat with an AI model using PySide6 for the GUI and Gradio's Client for API interactions. It's a solid foundation that you can build upon to create more advanced features and enhance user experience.
If you encounter any issues or have further questions, feel free to ask!