Spaces:
Sleeping
Sleeping
| 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) | |