Check that this gui is extracting the code correctly, redesign the GUI layout and see to it that once the llm's response is complete that the GUI saves the code to a temp file and executes it starting the debug loop.import sys
import re
import io
import contextlib
import logging
import time # For simulating delays
from PyQt6.QtCore import QObject, QThread, pyqtSignal, Qt
from PyQt6.QtWidgets import (
QApplication, QWidget, QVBoxLayout, QLabel, QLineEdit,
QPushButton, QSlider, QTextEdit, QProgressBar, QMessageBox, QGroupBox, QHBoxLayout
)
from gradio_client import Client
Configure logging
logging.basicConfig(filename='app_errors.log', level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s')
Constants
DEFAULT_TOP_P = 0.7
DEFAULT_TEMPERATURE = 0.7
MAX_RETRIES = 5
TOP_P_RANGE = (0, 100)
TEMPERATURE_RANGE = (0, 100)
class Worker(QObject):
finished = pyqtSignal()
result_ready = pyqtSignal(str, str)
execution_result = pyqtSignal(str)
save_code_finished = pyqtSignal(bool, str)
def __init__(self, client, inputs=None, top_p=DEFAULT_TOP_P, temperature=DEFAULT_TEMPERATURE, retries=MAX_RETRIES):
super().__init__()
self.client = client
self.inputs = inputs
self.top_p = top_p
self.temperature = temperature
self.retries = retries
self.api_call_count = 0
self.is_saving = False
def run(self):
if isinstance(self.inputs, tuple):
self.save_code()
else:
if self.inputs:
self.run_prediction()
else:
self.save_code()
def run_prediction(self):
current_input = self.inputs
for try_count in range(self.retries):
response_text, code, exec_output, last_error = self.make_prediction(current_input)
self.stream_response(response_text) # Streaming the response
if self.is_valid_code(code):
exec_output = self.execute_code(code)
self.execution_result.emit(exec_output)
if "Execution error" not in exec_output:
logging.info("Execution successful.")
break # Exit if the execution is successful
else:
last_error = exec_output.replace("Execution error: ", "")
current_input = self.autonomous_debugging(last_error, current_input)
else:
last_error = "No valid Python code found in the response."
logging.warning(last_error)
break
if "Execution error" in last_error:
self.execution_result.emit(f"Failed after {self.retries} attempts. Last error: {last_error}")
logging.error(f"Final Error: {last_error}")
self.finished.emit()
def make_prediction(self, current_input):
try:
self.api_call_count += 1
result = self.client.predict(
inputs=current_input,
top_p=self.top_p,
temperature=self.temperature,
chat_counter=self.api_call_count,
chatbot=[],
api_name="/predict"
)
response_text = result[0][0][1]
code = self.extract_code(response_text)
return response_text, code, "", ""
except Exception as e:
logging.error(f"API Call Error: {str(e)}")
return "", "", "", f"API Call Error: {str(e)}"
def stream_response(self, response_text):
"""
Streams the response by simulating delays.
In a real application, this might be replaced with actual streaming data.
"""
# Split the response into chunks; here we assume spaces for simplicity
for chunk in response_text.split('. '):
self.result_ready.emit(chunk.strip(), "") # Emit partial response
time.sleep(0.5) # Simulate delay for streaming effect (remove in production)
def autonomous_debugging(self, last_error, previous_input):
"""
Implement a logic for debugging based on the last error encountered.
Strategies can be defined for various types of errors.
"""
if "SyntaxError" in last_error:
return previous_input + "\n# Suggestion: Review your syntax for errors."
elif "IndentationError" in last_error:
return previous_input + "\n# Suggestion: Verify the indentation of your code."
elif "NameError" in last_error:
return previous_input + "\n# Suggestion: Check for undefined variable names."
elif "TypeError" in last_error:
return previous_input + "\n# Suggestion: Verify the types of variables used."
else:
return previous_input + "\n# Suggestion: Add print statements to inspect variable values."
def save_code(self):
filename, code = self.inputs # inputs contains filename and code tuple
try:
with open(filename, 'w') as f:
f.write(code)
self.save_code_finished.emit(True, "Code saved successfully.")
logging.info("Code saved successfully.")
except Exception as e:
logging.error(f"Failed to save code: {str(e)}")
self.save_code_finished.emit(False, f"Failed to save code: {str(e)}")
def extract_code(self, text):
pattern = r'```python\s*(.*?)\s*```'
matches = re.findall(pattern, text, re.DOTALL | re.IGNORECASE)
return "\n".join(match.strip() for match in matches) if matches else ""
def is_valid_code(self, code: str) -> bool:
return bool(code.strip()) and len(code.splitlines()) >= 2
def execute_code(self, code: str) -> str:
if not self.is_valid_code(code):
return "No valid code to execute."
try:
output = io.StringIO()
with contextlib.redirect_stdout(output):
exec(code, {})
exec_output = output.getvalue()
return exec_output if exec_output else "Code executed without output."
except Exception as e:
logging.error(f"Execution error: {str(e)}")
return f"Execution error: {str(e)}"
class ChatGPTApp(QWidget):
def init(self):
super().init()
self.setWindowTitle("ChatGPT API Interface")
self.resize(900, 700)
self.client = Client("yuntian-deng/ChatGPT")
self.initUI()
self.api_call_counter = 0
def initUI(self):
layout = QVBoxLayout()
# Input & Parameters Group
input_group = QGroupBox("Input & Parameters")
input_layout = QVBoxLayout()
self.input_field = QLineEdit(self)
self.input_field.setPlaceholderText("Type your message here...")
self.top_p_slider = QSlider(Qt.Orientation.Horizontal)
self.setup_slider(input_layout, self.top_p_slider, "Top-p:", self.update_top_p_label, 70)
self.temperature_slider = QSlider(Qt.Orientation.Horizontal)
self.setup_slider(input_layout, self.temperature_slider, "Temperature:", self.update_temperature_label, 70)
self.filename_field = QLineEdit(self)
self.filename_field.setPlaceholderText("Enter filename to save code (e.g., output.py)")
# Buttons
button_layout = QHBoxLayout()
self.predict_button = QPushButton("Predict", self)
self.predict_button.clicked.connect(self.start_prediction_thread)
self.save_execute_button = QPushButton("Save and Execute Code", self)
self.save_execute_button.clicked.connect(self.save_and_execute_code)
button_layout.addWidget(self.predict_button)
button_layout.addWidget(self.save_execute_button)
# Add to input layout
input_layout.addWidget(self.input_field)
input_layout.addLayout(button_layout)
input_group.setLayout(input_layout)
# Response Areas Group
response_group = QGroupBox("Response Areas")
response_layout = QVBoxLayout()
self.response_area = QTextEdit(self)
self.response_area.setReadOnly(True)
self.code_area = QTextEdit(self)
self.code_area.setReadOnly(True)
self.execution_area = QTextEdit(self)
self.execution_area.setReadOnly(True)
response_layout.addWidget(QLabel("Response:"))
response_layout.addWidget(self.response_area)
response_layout.addWidget(QLabel("Extracted Code:"))
response_layout.addWidget(self.code_area)
response_layout.addWidget(QLabel("Execution Result:"))
response_layout.addWidget(self.execution_area)
response_group.setLayout(response_layout)
# Progress Bar and Status Label
self.api_counter_label = QLabel("API Call Count: 0")
self.progress_bar = QProgressBar(self)
self.progress_bar.setVisible(False)
self.status_label = QLabel("Status: Idle")
layout.addWidget(input_group)
layout.addWidget(response_group)
layout.addWidget(self.api_counter_label)
layout.addWidget(self.progress_bar)
layout.addWidget(self.status_label)
self.setLayout(layout)
def setup_slider(self, layout, slider: QSlider, label_text, update_function, default_value):
slider.setRange(*TOP_P_RANGE)
slider.setValue(default_value)
slider.valueChanged.connect(update_function)
label = QLabel(f"{label_text} {slider.value() / 100:.2f}")
slider_layout = QHBoxLayout()
slider_layout.addWidget(QLabel(label_text))
slider_layout.addWidget(slider)
slider_layout.addWidget(label)
layout.addLayout(slider_layout)
def update_top_p_label(self, value):
self.top_p_label.setText(f"Top-p: {value / 100:.2f}")
def update_temperature_label(self, value):
self.temperature_label.setText(f"Temperature: {value / 100:.2f}")
def start_prediction_thread(self):
inputs = self.input_field.text().strip()
if not inputs:
QMessageBox.warning(self, "Warning", "Please enter a message before predicting.")
return
top_p = self.top_p_slider.value() / 100.0
temperature = self.temperature_slider.value() / 100.0
self.toggle_buttons(False)
self.clear_response_areas()
self.progress_bar.setVisible(True)
self.progress_bar.setRange(0, 0) # Indeterminate
self.status_label.setText("Status: Processing...")
self.thread = QThread()
self.worker = Worker(client=self.client, inputs=inputs, top_p=top_p, temperature=temperature)
self.setup_thread(self.thread, self.worker)
self.api_call_counter += 1
self.api_counter_label.setText(f"API Call Count: {self.api_call_counter}")
self.thread.start()
def clear_response_areas(self):
self.response_area.clear()
self.code_area.clear()
self.execution_area.clear()
def save_and_execute_code(self):
code = self.code_area.toPlainText().strip()
filename = self.filename_field.text().strip()
if not filename:
QMessageBox.warning(self, "Warning", "Please enter a filename to save the code.")
return
if not code:
QMessageBox.warning(self, "Warning", "There is no code to save.")
return
self.toggle_buttons(False)
self.status_label.setText("Status: Saving code...")
self.save_thread = QThread()
self.save_worker = Worker(client=self.client, inputs=(filename, code))
self.save_worker.is_saving = True
self.setup_thread(self.save_thread, self.save_worker)
self.save_thread.start()
def setup_thread(self, thread, worker):
worker.moveToThread(thread)
thread.started.connect(worker.run)
worker.finished.connect(thread.quit)
worker.finished.connect(worker.deleteLater)
thread.finished.connect(thread.deleteLater)
if worker.is_saving:
worker.save_code_finished.connect(self.on_code_saved)
else:
worker.result_ready.connect(self.update_ui)
worker.execution_result.connect(self.update_execution_result)
worker.finished.connect(self.on_prediction_finished)
def toggle_buttons(self, enable):
self.predict_button.setEnabled(enable)
self.save_execute_button.setEnabled(enable)
def on_code_saved(self, success, message):
if success:
QMessageBox.information(self, "Success", message)
logging.info(message)
else:
QMessageBox.warning(self, "Error", message)
self.toggle_buttons(True)
self.status_label.setText("Status: Idle")
def on_prediction_finished(self):
self.progress_bar.setVisible(False)
self.toggle_buttons(True)
status_message = "Status: Completed with errors." if "Execution error" in self.execution_area.toPlainText() else "Status: Completed successfully."
self.status_label.setText(status_message)
def update_ui(self, response_text, code):
self.response_area.append(response_text) # Append new text for streaming effect
self.code_area.setPlainText(code)
def update_execution_result(self, execution_result):
self.execution_area.setPlainText(execution_result)
if name == "main":
try:
app = QApplication(sys.argv)
window = ChatGPTApp()
window.show()
sys.exit(app.exec())
except Exception as e:
logging.error(f"Application failed with unexpected error: {str(e)}")
QMessageBox.critical(None, "Critical Error", f"Application could not start: {str(e)}")