Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import io
|
| 3 |
+
import contextlib
|
| 4 |
+
import gradio as gr
|
| 5 |
+
from typing import TypedDict, List
|
| 6 |
+
from huggingface_hub import InferenceClient
|
| 7 |
+
from langgraph.graph import StateGraph, END
|
| 8 |
+
|
| 9 |
+
# 1. BRAIN CONFIGURATION
|
| 10 |
+
# It will look for the secret you added in Settings
|
| 11 |
+
client = InferenceClient(api_key=os.environ.get("HF_TOKEN"))
|
| 12 |
+
|
| 13 |
+
# 2. STATE DEFINITION
|
| 14 |
+
class AgentState(TypedDict):
|
| 15 |
+
task: str
|
| 16 |
+
code: str
|
| 17 |
+
error: str
|
| 18 |
+
logs: List[str]
|
| 19 |
+
iterations: int
|
| 20 |
+
|
| 21 |
+
# 3. GENERATE NODE
|
| 22 |
+
def generate_node(state: AgentState):
|
| 23 |
+
state['logs'].append(f"π§ [Attempt {state['iterations'] + 1}] Analyzing requirements...")
|
| 24 |
+
prompt = f"System: You are an expert Python engineer. Solve this task: {state['task']}."
|
| 25 |
+
|
| 26 |
+
if state['error']:
|
| 27 |
+
state['logs'].append(f"π [Self-Correction] Fixing previous error: {state['error']}")
|
| 28 |
+
prompt += f"\n\nCRITICAL: Your last code failed with this error: {state['error']}. Fix it."
|
| 29 |
+
|
| 30 |
+
response = client.chat.completions.create(
|
| 31 |
+
model="deepseek-ai/DeepSeek-R1",
|
| 32 |
+
messages=[{"role": "user", "content": prompt}],
|
| 33 |
+
max_tokens=2000
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
full_response = response.choices[0].message.content
|
| 37 |
+
# Simple extraction logic for markdown code blocks
|
| 38 |
+
code_only = full_response.split("```python")[-1].split("```")[0].strip() if "```python" in full_response else full_response.strip()
|
| 39 |
+
|
| 40 |
+
return {**state, "code": code_only, "iterations": state['iterations'] + 1}
|
| 41 |
+
|
| 42 |
+
# 4. EXECUTE NODE
|
| 43 |
+
def execute_node(state: AgentState):
|
| 44 |
+
state['logs'].append("π§ͺ Running verification tests...")
|
| 45 |
+
output_capture = io.StringIO()
|
| 46 |
+
try:
|
| 47 |
+
with contextlib.redirect_stdout(output_capture):
|
| 48 |
+
# Using a custom dict for globals/locals to keep it slightly cleaner
|
| 49 |
+
exec(state['code'], {"__name__": "__main__"})
|
| 50 |
+
result = output_capture.getvalue()
|
| 51 |
+
state['logs'].append(f"β
Success! Output:\n{result}")
|
| 52 |
+
return {**state, "error": ""}
|
| 53 |
+
except Exception as e:
|
| 54 |
+
error_msg = str(e)
|
| 55 |
+
state['logs'].append(f"β Failure: {error_msg}")
|
| 56 |
+
return {**state, "error": error_msg}
|
| 57 |
+
|
| 58 |
+
# 5. ROUTER
|
| 59 |
+
def router(state: AgentState):
|
| 60 |
+
# Stop if it works OR if we tried 3 times
|
| 61 |
+
if not state['error'] or state['iterations'] >= 3:
|
| 62 |
+
return "end"
|
| 63 |
+
return "generate"
|
| 64 |
+
|
| 65 |
+
# 6. BUILD THE GRAPH
|
| 66 |
+
builder = StateGraph(AgentState)
|
| 67 |
+
builder.add_node("generate", generate_node)
|
| 68 |
+
builder.add_node("execute", execute_node)
|
| 69 |
+
builder.set_entry_point("generate")
|
| 70 |
+
builder.add_edge("generate", "execute")
|
| 71 |
+
builder.add_conditional_edges("execute", router, {"generate": "generate", "end": END})
|
| 72 |
+
agent_app = builder.compile()
|
| 73 |
+
|
| 74 |
+
# 7. UI LOGIC
|
| 75 |
+
def run_ui_logic(user_task):
|
| 76 |
+
state = {"task": user_task, "code": "", "error": "", "logs": [], "iterations": 0}
|
| 77 |
+
final_state = agent_app.invoke(state)
|
| 78 |
+
return final_state['code'], "\n\n".join(final_state['logs'])
|
| 79 |
+
|
| 80 |
+
# 8. THE DASHBOARD
|
| 81 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 82 |
+
gr.Markdown("# π€ Auto-Debug Agent v2.0")
|
| 83 |
+
|
| 84 |
+
with gr.Row():
|
| 85 |
+
with gr.Column(scale=1):
|
| 86 |
+
gr.Markdown("### π Debug Monologue")
|
| 87 |
+
log_display = gr.Textbox(label="Agent Internal Logs", lines=20, interactive=False)
|
| 88 |
+
|
| 89 |
+
with gr.Column(scale=2):
|
| 90 |
+
task_input = gr.Textbox(label="Enter Coding Task", placeholder="Write a function to...", lines=3)
|
| 91 |
+
submit_btn = gr.Button("π Start Debug Cycle", variant="primary")
|
| 92 |
+
|
| 93 |
+
gr.Markdown("### π§ͺ Sandbox Presets")
|
| 94 |
+
with gr.Row():
|
| 95 |
+
btn_type = gr.Button("Type Mismatch")
|
| 96 |
+
btn_logic = gr.Button("Logic Error")
|
| 97 |
+
btn_api = gr.Button("Object Error")
|
| 98 |
+
|
| 99 |
+
output_code = gr.Code(label="Final Working Code", language="python", lines=10)
|
| 100 |
+
|
| 101 |
+
# Interactions
|
| 102 |
+
btn_type.click(lambda: "Fix this: data = ['10', 20]; print(sum(data))", outputs=task_input)
|
| 103 |
+
btn_logic.click(lambda: "Calculate 10% tax on $100, but I wrote: total = 100 - (100 * 0.1). Fix the logic.", outputs=task_input)
|
| 104 |
+
btn_api.click(lambda: "Fix this: x = {'vals': [1,2]}; print(sum(x))", outputs=task_input)
|
| 105 |
+
submit_btn.click(run_ui_logic, inputs=task_input, outputs=[output_code, log_display])
|
| 106 |
+
|
| 107 |
+
if __name__ == "__main__":
|
| 108 |
+
demo.launch()
|