File size: 2,823 Bytes
9fd5566
 
 
 
 
 
 
 
b4b8890
9fd5566
 
 
b4b8890
46efdb9
 
 
feffe72
 
9fd5566
 
 
b4b8890
9fd5566
 
 
 
b4b8890
9fd5566
 
 
 
 
 
 
 
 
 
 
 
 
 
b4b8890
9fd5566
 
 
 
 
b4b8890
9fd5566
 
 
 
 
 
 
 
 
 
 
b4b8890
9fd5566
 
 
 
b4b8890
9fd5566
 
 
 
 
 
b4b8890
9fd5566
b4b8890
9fd5566
b4b8890
9fd5566
 
 
 
 
 
 
 
 
b4b8890
9fd5566
 
b4b8890
 
9fd5566
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# 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()