Projecthack's picture
Update app.py
feffe72 verified
Raw
History Blame Contribute Delete
2.82 kB
# Code Debugger Agent - Web Version with Memory and Fix Options
# - Built with Gradio UI
# - Accepts user code input
# - Uses OpenAI GPT-4 to identify and fix bugs
# - Suggests multiple fix options
# - Remembers previous inputs during session
import openai
import gradio as gr
import tempfile
import subprocess
import os
import os
openai.api_key = os.getenv("OPENAI_API_KEY")
# Replace with your OpenAI API key
if not openai.api_key:
raise EnvironmentError("OPENAI_API_KEY is not set in environment variables.")
# Simple in-session memory
code_history = []
# Ask GPT-4 to fix code and return multiple versions
def ask_gpt_for_fixes(code):
prompt = f"""
You are an expert Python debugger. Analyze the code below and suggest 3 different corrected versions if bugs are found. Each version should be well-formatted and wrapped in triple backticks.
```python
{code}
```
"""
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a helpful Python debugging assistant."},
{"role": "user", "content": prompt}
],
temperature=0.4,
max_tokens=1500
)
return response.choices[0].message.content.strip()
# Run code in a temporary file
def run_code(code):
with tempfile.NamedTemporaryFile(delete=False, suffix=".py", mode="w") as f:
f.write(code)
path = f.name
try:
result = subprocess.run(
["python", path],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=10
)
return result.stdout or "", result.stderr or ""
finally:
os.remove(path)
# Gradio interface logic
def debug_code_interface(user_code):
code_history.append(user_code)
suggestions = ask_gpt_for_fixes(user_code)
# Extract the first fixed code block for execution (basic example)
fixed_code = suggestions.split("```python")
if len(fixed_code) > 1:
first_fix = fixed_code[1].split("```")[0]
else:
first_fix = user_code # fallback
output, error = run_code(first_fix)
return suggestions, output, error, "\n--- Session History ---\n" + "\n\n".join(code_history)
# Gradio app
demo = gr.Interface(
fn=debug_code_interface,
inputs=gr.Textbox(lines=20, placeholder="Paste your Python code here...", label="Your Code"),
outputs=[
gr.Textbox(label="Fix Suggestions (Multiple Options)"),
gr.Textbox(label="Output from First Fix"),
gr.Textbox(label="Errors from First Fix"),
gr.Textbox(label="Session Memory")
],
title="AI Code Debugger Agent",
description="Paste Python code. The agent will fix bugs, show multiple versions, run the first one, and maintain memory for the session."
)
demo.launch()