Certainly! Below is the revised GUI application that incorporates the requested functionalities:
- Extracts Python code snippets enclosed within triple backticks (
```), removing the word python after the first set of backticks.
- Saves the extracted code to a uniquely named
.py file.
- Executes the
.py file and monitors for any errors.
- If errors are detected, it prompts the LLM to fix the errors and retries the process up to 5 times until the script runs successfully or the retry limit is reached.
Key Enhancements:
- Code Extraction: Utilizes regular expressions to parse the bot's response and extract Python code blocks.
- Unique File Naming: Generates unique filenames using UUID to prevent overwriting.
- Execution and Error Handling: Executes the Python script using the
subprocess module, captures errors, and manages retries.
- LLM Interaction for Error Fixing: Communicates with the LLM to obtain corrected code when errors are encountered.
Complete Revised Code:
import tkinter as tk
from tkinter import ttk, scrolledtext
from gradio_client import Client
import re
import uuid
import subprocess
import os
# Initialize client
client = Client("yuntian-deng/o1mini")
# Maximum number of retries for fixing errors
MAX_RETRIES = 5
def extract_code(response):
"""
Extracts Python code blocks from the response.
Removes the word 'python' after the first set of backticks.
Returns a list of code snippets.
"""
code_pattern = re.compile(r'```python\s*\n(.*?)```', re.DOTALL)
codes = code_pattern.findall(response)
return codes
def save_code(code):
"""
Saves the provided code to a uniquely named .py file.
Returns the filename.
"""
unique_id = uuid.uuid4().hex
filename = f"script_{unique_id}.py"
with open(filename, 'w', encoding='utf-8') as file:
file.write(code)
return filename
def execute_code(filename):
"""
Executes the Python script and captures any errors.
Returns a tuple (success: bool, error_message: str)
"""
try:
result = subprocess.run(
['python', filename],
capture_output=True,
text=True,
check=True
)
return True, result.stdout
except subprocess.CalledProcessError as e:
return False, e.stderr
def fix_code(original_code, error_message):
"""
Sends a prompt to the LLM to fix the provided code based on the error_message.
Returns the fixed code.
"""
prompt = (
f"An error occurred while executing the script:\n{error_message}\n\n"
f"Please fix this error and provide a fully revised version of the script written out in full."
)
fixed_code = client.predict(
inputs=prompt,
top_p=1.0,
temperature=1.0,
chat_counter=0.0,
chatbot=[],
api_name="/predict"
)
return fixed_code
def process_code(initial_code):
"""
Processes the code by executing it and handling errors by attempting fixes.
Retries up to MAX_RETRIES times.
"""
current_code = initial_code
for attempt in range(1, MAX_RETRIES + 1):
filename = save_code(current_code)
success, output = execute_code(filename)
os.remove(filename) # Clean up the script file after execution
if success:
chatbox.insert(tk.END, f"Script executed successfully:\n{output}\n")
return
else:
chatbox.insert(tk.END, f"Error on attempt {attempt}:\n{output}\n")
if attempt < MAX_RETRIES:
chatbox.insert(tk.END, "Attempting to fix the error...\n")
current_code = fix_code(current_code, output)
else:
chatbox.insert(tk.END, "Maximum retry attempts reached. Please check the script manually.\n")
return
def send_message():
user_input = input_text.get()
result = client.predict(
inputs=user_input,
top_p=1.0,
temperature=1.0,
chat_counter=0.0,
chatbot=[],
api_name="/predict"
)
display_result(result)
# Extract and process code snippets
bot_response = result[0] # Assuming the first element is the bot's text response
codes = extract_code(bot_response)
if codes:
for code in codes:
process_code(code)
else:
chatbox.insert(tk.END, "No Python code detected in the response.\n")
def reset_textbox():
result = client.predict(inputs="", chat_counter=0.0, chatbot=[], api_name="/reset_textbox")
input_text.set("")
chatbox.insert(tk.END, f"System: {result}\n")
def enable_inputs():
result = client.predict(inputs="", chat_counter=0.0, chatbot=[], api_name="/enable_inputs")
chatbox.insert(tk.END, "Inputs enabled\n")
def display_result(result):
"""
Displays the API response in the chatbox.
"""
# Unpack the tuple response for /predict API call
bot_response, chat_counter, status_code, textbox_response = result
chatbox.insert(tk.END, f"User: {input_text.get()}\n")
chatbox.insert(tk.END, f"Bot: {bot_response}\n")
chatbox.insert(tk.END, f"Status: {status_code}\n\n")
input_text.set("")
# Setting up the GUI with tkinter
root = tk.Tk()
root.title("Chatbot Interface with Python Script Executor")
# Chat display box with scrollbar
chatbox = scrolledtext.ScrolledText(root, wrap=tk.WORD, height=20, width=80, state='normal')
chatbox.pack(pady=10, padx=10)
# User input entry
input_text = tk.StringVar()
entry = tk.Entry(root, textvariable=input_text, width=80)
entry.pack(pady=5, padx=10)
# Button frame
button_frame = tk.Frame(root)
button_frame.pack(pady=5)
# Send button
send_button = ttk.Button(button_frame, text="Send", command=send_message)
send_button.grid(row=0, column=0, padx=5)
# Reset button
reset_button = ttk.Button(button_frame, text="Reset Textbox", command=reset_textbox)
reset_button.grid(row=0, column=1, padx=5)
# Enable Inputs button
enable_button = ttk.Button(button_frame, text="Enable Inputs", command=enable_inputs)
enable_button.grid(row=0, column=2, padx=5)
# Run the application
root.mainloop()
Detailed Explanation of Enhancements:
-
Code Extraction (extract_code Function):
- Utilizes a regular expression to identify Python code blocks enclosed within triple backticks followed by the word
python.
- Extracts and returns all such code snippets found in the bot's response.
-
Unique File Naming (save_code Function):
- Generates a unique filename for each script using
uuid.uuid4(), ensuring that each .py file is distinct.
- Saves the extracted code to this file.
-
Script Execution and Error Monitoring (execute_code Function):
- Executes the saved Python script using the
subprocess module.
- Captures standard output and errors.
- Returns a tuple indicating success status and either the output or error message.
-
Error Handling and Script Fixing (fix_code Function and process_code Function):
- If an error is detected during script execution, the
fix_code function sends a prompt to the LLM to rectify the error, including the error message.
- The
process_code function manages the retry mechanism, attempting to fix and execute the script up to MAX_RETRIES times.
- After each failed attempt, it updates the chatbox with the error and the attempt number.
- If the script executes successfully, it displays the output. Otherwise, it notifies the user after reaching the maximum number of retries.
-
GUI Enhancements:
- ScrolledText Widget: Replaced the standard
Text widget with ScrolledText to add vertical scrolling capabilities, enhancing readability for longer chat histories.
- Button Layout: Organized buttons within a
Frame for a cleaner and more structured layout.
- Enhanced Display: Updated
send_message to not only display the bot's response but also handle the code extraction and execution seamlessly.
-
Cleanup:
- After each script execution, whether successful or not, the corresponding
.py file is removed to prevent clutter and potential conflicts with future scripts.
Additional Considerations:
- Concurrency: For a production environment, consider handling script execution in a separate thread to prevent the GUI from freezing during long-running scripts.
- Security: Executing arbitrary code can be dangerous. Implement safety checks or restrictions to prevent malicious code execution.
- Feedback: Enhance user feedback by providing more detailed logs or outputs, especially for complex scripts.
This revised application should meet your requirements by automating the extraction, execution, and error handling of Python scripts generated by the LLM within the GUI.