Chand11 commited on
Commit
a2e04dd
Β·
verified Β·
1 Parent(s): ff5a0fd

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -0
app.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import google.generativeai as genai
2
+ import subprocess
3
+ import re
4
+
5
+ # πŸ”‘ Configure Gemini API
6
+ genai.configure(api_key="AIzaSyAdvERSmk7q02T2pLNPoERqDD-QPuW4RTs")
7
+
8
+ # Pick a model
9
+ model = genai.GenerativeModel("gemini-1.5-flash")
10
+
11
+ def extract_code(response_text):
12
+ """Extracts Python code from Gemini's response (removes ``` fences)."""
13
+ code_match = re.findall(r"```(?:python)?\n(.*?)```", response_text, re.DOTALL)
14
+ if code_match:
15
+ return code_match[0]
16
+ return response_text.strip()
17
+
18
+ def run_code(code):
19
+ """Executes code and returns output or error."""
20
+ try:
21
+ result = subprocess.run(
22
+ ["python3", "-c", code],
23
+ capture_output=True,
24
+ text=True,
25
+ timeout=10
26
+ )
27
+ return result.stdout if result.stdout else result.stderr
28
+ except Exception as e:
29
+ return str(e)
30
+
31
+ def recursive_ai_executor(task, depth=1):
32
+ """Recursive AI Executor with auto-run + visible output."""
33
+ print(f"\nπŸ”Ή Task (Level {depth}): {task}")
34
+
35
+ # Ask Gemini to generate code + usage
36
+ prompt = f"Write Python code to {task}. Always include a sample call (like print(...)) so output is shown."
37
+ response = model.generate_content(prompt)
38
+ code = extract_code(response.text)
39
+
40
+ print("\nπŸ“œ Generated Code:\n", code)
41
+ output = run_code(code)
42
+ print("\nπŸ“Š Execution Output:\n", output)
43
+
44
+ # If no useful output, refine recursively
45
+ if "Traceback" in output or output.strip() == "":
46
+ if depth < 3:
47
+ print("\n⚑ Refining task...")
48
+ return recursive_ai_executor(f"Fix the error: {output}", depth+1)
49
+ else:
50
+ print("\n❌ Stopping after 3 attempts.")
51
+ return output
52
+
53
+
54
+ # πŸš€ Interactive loop
55
+ print("πŸ€– Recursive AI Executor (type 'exit' to quit)\n")
56
+ while True:
57
+ user_task = input("Enter your Python task: ")
58
+ if user_task.lower() in ["exit", "quit"]:
59
+ print("πŸ‘‹ Exiting AI Executor.")
60
+ break
61
+ recursive_ai_executor(user_task)