File size: 2,005 Bytes
a2e04dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import google.generativeai as genai
import subprocess
import re

# πŸ”‘ Configure Gemini API
genai.configure(api_key="AIzaSyAdvERSmk7q02T2pLNPoERqDD-QPuW4RTs")

# Pick a model
model = genai.GenerativeModel("gemini-1.5-flash")

def extract_code(response_text):
    """Extracts Python code from Gemini's response (removes ``` fences)."""
    code_match = re.findall(r"```(?:python)?\n(.*?)```", response_text, re.DOTALL)
    if code_match:
        return code_match[0]
    return response_text.strip()

def run_code(code):
    """Executes code and returns output or error."""
    try:
        result = subprocess.run(
            ["python3", "-c", code],
            capture_output=True,
            text=True,
            timeout=10
        )
        return result.stdout if result.stdout else result.stderr
    except Exception as e:
        return str(e)

def recursive_ai_executor(task, depth=1):
    """Recursive AI Executor with auto-run + visible output."""
    print(f"\nπŸ”Ή Task (Level {depth}): {task}")
    
    # Ask Gemini to generate code + usage
    prompt = f"Write Python code to {task}. Always include a sample call (like print(...)) so output is shown."
    response = model.generate_content(prompt)
    code = extract_code(response.text)
    
    print("\nπŸ“œ Generated Code:\n", code)
    output = run_code(code)
    print("\nπŸ“Š Execution Output:\n", output)
    
    # If no useful output, refine recursively
    if "Traceback" in output or output.strip() == "":
        if depth < 3:
            print("\n⚑ Refining task...")
            return recursive_ai_executor(f"Fix the error: {output}", depth+1)
        else:
            print("\n❌ Stopping after 3 attempts.")
    return output


# πŸš€ Interactive loop
print("πŸ€– Recursive AI Executor (type 'exit' to quit)\n")
while True:
    user_task = input("Enter your Python task: ")
    if user_task.lower() in ["exit", "quit"]:
        print("πŸ‘‹ Exiting AI Executor.")
        break
    recursive_ai_executor(user_task)