Team Ai
Apppublic

Projecthack/Code_debugging

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py118 linesDownload Raw Back to root
1import os2import openai3import gradio as gr4import tempfile5import subprocess6import re7from dotenv import load_dotenv8 9# Load environment variables10load_dotenv()11openai_api_key = os.getenv("OPENAI_API_KEY")12if not openai_api_key:13    raise EnvironmentError("OPENAI_API_KEY not set in .env file.")14 15# Initialize OpenAI client16client = openai.OpenAI(api_key=openai_api_key)17 18# --- Tool 1: Ask GPT for Fixes ---19def ask_gpt_for_fixes(code):20    prompt = f"""21You are an expert Python debugger AI agent.22 231. Identify and explain any bugs in the code.242. Suggest up to 3 different fixed versions (wrap each in triple backticks).253. After each fix, provide a short explanation of what was corrected.26 27Code to debug:28```python29{code}30```"""31    try:32        response = client.chat.completions.create(33            model="gpt-4",34            messages=[35                {"role": "system", "content": "You debug Python code and suggest multiple fixes with explanations."},36                {"role": "user", "content": prompt}37            ],38            temperature=0.3,39            max_tokens=160040        )41        return response.choices[0].message.content.strip()42    except Exception as e:43        return f"Error contacting GPT-4: {e}"44 45# --- Tool 2: Code Execution ---46def run_code(code):47    with tempfile.NamedTemporaryFile(delete=False, suffix=".py", mode="w") as f:48        f.write(code)49        temp_path = f.name50    try:51        result = subprocess.run(52            ["python", temp_path],53            stdout=subprocess.PIPE,54            stderr=subprocess.PIPE,55            text=True,56            timeout=857        )58        return result.stdout.strip(), result.stderr.strip()59    except subprocess.TimeoutExpired:60        return "", "⏰ Execution timed out."61    except Exception as e:62        return "", f"⚠️ Runtime error: {e}"63    finally:64        os.remove(temp_path)65 66# --- Agentic Debugging Flow ---67def debug_code_interface(user_code):68    # Step 1: Run original code69    original_output, original_error = run_code(user_code)70 71    # Step 2: Ask GPT for suggestions72    suggestions = ask_gpt_for_fixes(user_code)73    74    # Step 3: Extract up to 3 code blocks75    code_blocks = re.findall(r"```python(.*?)```", suggestions, re.DOTALL)76    77    if not code_blocks:78        return suggestions, "", "❌ No fix suggestions found."79 80    # Step 4: Test first fix81    first_fix = code_blocks[0].strip()82    fixed_output, fixed_error = run_code(first_fix)83 84    # Step 5: Agentic Verdict85    if original_error and not fixed_error:86        verdict = "✅ Bug fixed successfully by Fix #1."87    elif fixed_error:88        verdict = f"❌ Fix #1 may still have issues: {fixed_error.splitlines()[-1]}"89    else:90        verdict = "⚠️ No clear verdict; manual inspection needed."91 92    # Step 6: Combine everything into AI analysis panel93    report = f"{suggestions}\n\n=== 🤖 Debugger Verdict ===\n{verdict}"94 95    return report, fixed_output, fixed_error96 97# --- Gradio UI ---98with gr.Blocks(title="Agentic GPT-4 Python Debugger") as demo:99    gr.Markdown("# 🐍 Real-Time GPT-4 Python Debugger with Agentic AI")100    gr.Markdown("Paste your code below. The agent will identify bugs, generate fixes, test them, and give a debugging verdict.")101 102    with gr.Row():103        code_input = gr.Textbox(lines=20, label="📝 Your Python Code", placeholder="Paste your buggy code here...")104 105    with gr.Row():106        suggestions_output = gr.Textbox(label="🤖 AI Suggestions & Fixes", lines=20)107    108    with gr.Row():109        output_box = gr.Textbox(label="✅ Output (from First Fix)")110        error_box = gr.Textbox(label="❌ Errors (from First Fix)")111 112    run_button = gr.Button("🧠 Debug My Code")113 114    run_button.click(fn=debug_code_interface, inputs=[code_input], outputs=[suggestions_output, output_box, error_box])115 116# Launch app117demo.launch()118