├── LICENSE ├── README.md ├── deep_seek_auto_coder.py ├── deep_seek_auto_coder_executor.py ├── o1_auto_coder.py ├── o1_auto_coder_executor.py └── requirements.txt /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 Memo 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AI Auto Coder Collection 🚀 2 | 3 | 4 | ### DeepSeek R1 Versions: 5 | 6 | 1. `deep_seek_auto_coder.py` - Safe version that only generates code 7 | 2. `deep_seek_auto_coder_executor.py` - ⚠️**EXECUTES AI-GENERATED CODE ON YOUR MACHINE** 8 | 9 | ### OpenAI O1 Versions: 10 | 11 | 3. `o1_auto_coder.py` - Safe version that only generates code 12 | 4. `o1_auto_coder_executor.py` - ⚠️**EXECUTES AI-GENERATED CODE ON YOUR MACHINE** 13 | 14 | If you're not comfortable with code execution, use the safe versions (`deep_seek_auto_coder.py` or `o1_auto_coder.py`). 15 | 16 | An intelligent code generation and improvement system that automatically generates, iteratively improves, and enhances Python code based on your requirements, with a special focus on creating visually stunning applications without external dependencies. 17 | 18 | ## Model Options 🤖 19 | 20 | ### DeepSeek R1: 21 | 22 | - Available through OpenRouter 23 | - Specialized in code generation 24 | - Requires OpenRouter API key 25 | 26 | ### OpenAI O1: 27 | 28 | - Available through OpenAI 29 | - Can also use o1-mini or gpt-4o variants 30 | - Requires OpenAI API key 31 | - Generally faster response times 32 | 33 | ## Features ✨ 34 | 35 | - 🎨 Specialized in generating visually appealing applications 36 | - 🔄 Iterative code improvement system 37 | - 🛠️ Automatic code generation from text descriptions 38 | - 📝 Clean, documented, and well-structured code output 39 | - 🎮 Perfect for games, GUIs, and visual applications 40 | - 🔒 No external file dependencies - everything is generated programmatically 41 | - 🎯 Multiple iterations of improvements 42 | - 🌈 Colored terminal output for better visibility 43 | 44 | ## ❤️Join my AI Community & Get 400+ AI Projects & 1000x Cursor Course 45 | 46 | This is one of 400+ fascinating projects in my collection! [Support me on Patreon](https://www.patreon.com/c/echohive42/membership) to get: 47 | 48 | - 🎯 Access to 400+ AI projects (and growing daily!) 49 | - Including advanced projects like [2 Agent Real-time voice template with turn taking](https://www.patreon.com/posts/2-agent-real-you-118330397) 50 | - 📥 Full source code & detailed explanations 51 | - 📚 1000x Cursor Course 52 | - 🎓 Live coding sessions & AMAs 53 | - 💬 1-on-1 consultations (higher tiers) 54 | - 🎁 Exclusive discounts on AI tools & platforms (up to $180 value) 55 | 56 | ## Prerequisites 📋 57 | 58 | - Python 3.x 59 | - OpenRouter API key (for DeepSeek versions) 60 | - OpenAI API key (for O1 versions) 61 | 62 | ## Installation 🔧 63 | 64 | 1. Clone the repository: 65 | 66 | ```bash 67 | git clone 68 | cd 69 | ``` 70 | 71 | 2. Install required packages: 72 | 73 | ```bash 74 | pip install -r requirements.txt 75 | ``` 76 | 77 | 3. Set up your API key as an environment variable: 78 | 79 | ```bash 80 | # For DeepSeek versions (Windows) 81 | set OPENROUTER_API_KEY=your_api_key_here 82 | 83 | # For O1 versions (Windows) 84 | set OPENAI_API_KEY=your_api_key_here 85 | 86 | # For DeepSeek versions (Linux/Mac) 87 | export OPENROUTER_API_KEY=your_api_key_here 88 | 89 | # For O1 versions (Linux/Mac) 90 | export OPENAI_API_KEY=your_api_key_here 91 | ``` 92 | 93 | ## Usage 💻 94 | 95 | 1. Choose your preferred version and configure: 96 | 97 | ```python 98 | # User Configuration 99 | USER_PROMPT = "Your detailed Python program description" 100 | NUMBER_OF_ITERATIONS = 3 # Number of improvement iterations 101 | MODEL = "o1" # For O1 versions, can also use "o1-mini" or "gpt-4o" 102 | ``` 103 | 104 | 2. Run your chosen version: 105 | 106 | ```bash 107 | # DeepSeek versions 108 | python deep_seek_auto_coder.py 109 | python deep_seek_auto_coder_executor.py 110 | 111 | # O1 versions 112 | python o1_auto_coder.py 113 | python o1_auto_coder_executor.py 114 | ``` 115 | 116 | 3. Find your generated code in the `generated_code` folder: 117 | 118 | - `generated_code_v0.py`: Initial generation 119 | - `generated_code_v1.py` to `generated_code_vN.py`: Improved iterations 120 | 121 | ## Version Comparison 🔄 122 | 123 | ### Safe Versions (deep_seek_auto_coder.py & o1_auto_coder.py): 124 | 125 | - Generate and improve code without execution 126 | - Save all iterations to files 127 | - No system access or security risks 128 | - Best for initial development and exploration 129 | - Choose between DeepSeek R1 or OpenAI O1 models 130 | 131 | ### Executor Versions (deep_seek_auto_coder_executor.py & o1_auto_coder_executor.py): 132 | 133 | - **⚠️ EXECUTE CODE ON YOUR SYSTEM** 134 | - Automatically test generated code 135 | - Detect and fix runtime errors 136 | - 5-second timeout for each execution 137 | - Include error correction agent 138 | - Only save working versions 139 | - More efficient iteration process 140 | - Choose between DeepSeek R1 or OpenAI O1 models 141 | 142 | ## How It Works 🔄 143 | 144 | ### Safe Version: 145 | 146 | 1. **Initial Generation**: Creates base code from your prompt 147 | 2. **Iterative Improvement**: Enhances the code through multiple iterations 148 | 3. **Visual Focus**: Emphasizes beautiful, programmatically generated visuals 149 | 4. **Code Organization**: Maintains clean structure and documentation 150 | 5. **Progress Tracking**: Shows colored progress in the terminal 151 | 152 | ### Executor Version: 153 | 154 | 1. **Code Generation**: Creates initial code from prompt 155 | 2. **Execution Testing**: Runs code with 5-second timeout 156 | 3. **Error Detection**: Captures and analyzes runtime errors 157 | 4. **Automatic Fixing**: Uses AI to fix detected errors 158 | 5. **Verification**: Tests fixed code before proceeding 159 | 6. **Improvement**: Enhances working code 160 | 7. **Safety Features**: Process isolation, timeout, cleanup 161 | 162 | ## Example Prompts 📝 163 | 164 | ```python 165 | # Game Development 166 | USER_PROMPT = "create a beautiful tower defense game in pygame. do not use outside assets. all assets should be created within pygame" 167 | 168 | # GUI Application 169 | USER_PROMPT = "create a modern calculator with a beautiful dark theme using tkinter" 170 | 171 | # Data Visualization 172 | USER_PROMPT = "create an interactive bar chart race visualization using pygame" 173 | ``` 174 | 175 | ## Features of Generated Code 🎯 176 | 177 | - ✅ Complete error handling with descriptive messages 178 | - ✅ Defensive programming practices 179 | - ✅ Edge case handling 180 | - ✅ Resource cleanup and management 181 | - ✅ Proper documentation 182 | - ✅ Clean code structure 183 | - ✅ Programmatically generated assets 184 | - ✅ No external file dependencies 185 | - ✅ Beautiful visuals and animations 186 | - ✅ Performance optimizations 187 | 188 | ## Notes 📌 189 | 190 | - All visual assets are created programmatically - no external files needed 191 | - Each iteration builds upon the previous one 192 | - The system includes rate limiting to prevent API overload 193 | - Progress is saved after each iteration 194 | - Uses UTF-8 encoding for file operations 195 | - Comprehensive error detection and prevention 196 | - Defensive programming approach 197 | - Visual feedback for errors 198 | - Proper resource management 199 | 200 | ## Error Handling 🚨 201 | 202 | The script includes comprehensive error handling for: 203 | 204 | - Runtime errors and edge cases 205 | - Resource management and cleanup 206 | - State transitions and validation 207 | - User input and parameters 208 | - Visual elements and animations 209 | - Memory management 210 | - API connection issues 211 | - Code generation failures 212 | - File operations 213 | - Code extraction problems 214 | -------------------------------------------------------------------------------- /deep_seek_auto_coder.py: -------------------------------------------------------------------------------- 1 | import os 2 | from openai import OpenAI 3 | from termcolor import colored 4 | import time 5 | import re 6 | 7 | # User Configuration 8 | USER_PROMPT = "create a beautiful tower defense game in pygame. do not use outsiede assets. all assets should be created within pygame" 9 | NUMBER_OF_ITERATIONS = 20 10 | 11 | # Constants 12 | MODEL = "deepseek/deepseek-r1" 13 | OUTPUT_FOLDER = "generated_code" 14 | SYSTEM_PROMPT = """You are an expert Python programmer specializing in creating visually stunning and well-structured applications. Generate clean, efficient, and well-documented Python code based on the user's request. 15 | 16 | Follow these EXACT rules for code generation: 17 | 1. ALWAYS wrap your code response in tags 18 | 2. Include ALL necessary imports at the top 19 | 3. Include proper error handling with try/except blocks 20 | 4. Add descriptive comments and docstrings 21 | 5. Return ONLY the code within the tags, no explanations outside the tags 22 | 6. Make sure the code is complete and can run immediately 23 | 7. Use proper Python formatting and PEP 8 guidelines 24 | 8. NEVER use or reference external files (no loading images, sounds, or data files) 25 | 9. ALL assets (graphics, sounds, data) must be generated programmatically within the code 26 | 10. DO NOT include file operations (open, save, load) for external resources 27 | 28 | For visual applications (GUI, games, graphics): 29 | - Create beautiful, polished visuals using ONLY programmatic generation 30 | - All graphics must be drawn using the framework's primitives (shapes, lines, etc.) 31 | - Implement smooth animations and transitions 32 | - Use appealing color schemes and visual effects 33 | - Design intuitive and responsive UI/UX 34 | - Add visual feedback for user interactions 35 | - Include particle effects and visual polish where appropriate 36 | - ALL visual assets must be created within the code itself 37 | 38 | Example response format: 39 | 40 | import something 41 | 42 | def main(): 43 | # Your code here 44 | pass 45 | 46 | if __name__ == "__main__": 47 | main() 48 | """ 49 | 50 | # Initialize OpenAI client 51 | try: 52 | client = OpenAI( 53 | base_url="https://openrouter.ai/api/v1", 54 | api_key=os.getenv("OPENROUTER_API_KEY"), 55 | ) 56 | except Exception as e: 57 | print(colored(f"Error initializing OpenAI client: {str(e)}", "red")) 58 | exit(1) 59 | 60 | def extract_code(response_text): 61 | """Extract code from between tags.""" 62 | try: 63 | pattern = r"(.*?)" 64 | match = re.search(pattern, response_text, re.DOTALL) 65 | return match.group(1).strip() if match else None 66 | except Exception as e: 67 | print(colored(f"Error extracting code: {str(e)}", "red")) 68 | return None 69 | 70 | def generate_code(prompt, iteration=1): 71 | """Generate code using DeepSeek model.""" 72 | try: 73 | print(colored(f"\nGenerating code - Iteration {iteration}...", "cyan")) 74 | completion = client.chat.completions.create( 75 | model=MODEL, 76 | messages=[ 77 | {"role": "system", "content": SYSTEM_PROMPT}, 78 | {"role": "user", "content": f"Create a new Python program for: {prompt}"} 79 | ] 80 | ) 81 | return completion.choices[0].message.content 82 | except Exception as e: 83 | print(colored(f"Error generating code: {str(e)}", "red")) 84 | return None 85 | 86 | def improve_code(code, iteration): 87 | """Improve existing code.""" 88 | try: 89 | print(colored(f"\nImproving code - Iteration {iteration}...", "yellow")) 90 | improvement_prompt = """Improve this Python code with the following priorities: 91 | 92 | 1. Error Detection and Prevention: 93 | - Identify and fix any potential runtime errors 94 | - Check for edge cases and handle them 95 | - Validate all user inputs and parameters 96 | - Add defensive programming practices 97 | - Ensure proper resource cleanup 98 | - Verify all calculations and operations 99 | - Check for potential memory leaks 100 | - Validate game states and transitions 101 | - Handle window/screen edge cases 102 | - Prevent potential race conditions 103 | 104 | 2. If there are visual elements (GUI, game graphics, etc.): 105 | - Enhance visual aesthetics (colors, shapes, animations) 106 | - Add visual polish (particles, effects, transitions) 107 | - Improve UI/UX elements 108 | - Make the visuals more professional and engaging 109 | - ALL graphics must be generated programmatically (NO external files) 110 | - Use framework primitives to create all visual assets 111 | - Ensure smooth frame rates and performance 112 | - Handle window resizing gracefully 113 | - Add visual feedback for errors/exceptions 114 | 115 | 3. Add new features that make sense for this type of application: 116 | - Expand core functionality 117 | - Add quality-of-life improvements 118 | - Implement additional user interactions 119 | - Include more game mechanics/options if it's a game 120 | - ALL assets must be created within the code 121 | - Add proper state management 122 | - Implement undo/redo if applicable 123 | - Add pause/resume functionality if needed 124 | 125 | 4. Technical improvements: 126 | - Optimize performance 127 | - Enhance error handling with descriptive messages 128 | - Improve code organization 129 | - Add helpful comments and error documentation 130 | - NO external file operations or dependencies 131 | - Add logging for critical operations 132 | - Implement proper cleanup in finally blocks 133 | - Add type hints and validation 134 | - Use context managers where appropriate 135 | 136 | 5. Common Error Prevention: 137 | - Division by zero checks 138 | - None/null checks 139 | - Index out of bounds prevention 140 | - Type checking and conversion 141 | - Resource initialization verification 142 | - Event handler error catching 143 | - Timer/animation frame checks 144 | - Collision detection edge cases 145 | - Screen boundary checks 146 | - Memory management 147 | 148 | Keep the code complete and runnable. Return the improved code in tags. 149 | IMPORTANT: Do not use or reference any external files (images, sounds, data files, etc.). 150 | Make sure to handle ALL possible error cases with descriptive error messages.""" 151 | 152 | completion = client.chat.completions.create( 153 | model=MODEL, 154 | messages=[ 155 | {"role": "system", "content": SYSTEM_PROMPT}, 156 | {"role": "user", "content": f"{improvement_prompt}\n\nHere's the code to improve:\n{code}"} 157 | ] 158 | ) 159 | return completion.choices[0].message.content 160 | except Exception as e: 161 | print(colored(f"Error improving code: {str(e)}", "red")) 162 | return None 163 | 164 | def save_code(code, iteration): 165 | """Save generated code to file.""" 166 | try: 167 | if not os.path.exists(OUTPUT_FOLDER): 168 | os.makedirs(OUTPUT_FOLDER) 169 | 170 | filename = os.path.join(OUTPUT_FOLDER, f"generated_code_v{iteration}.py") 171 | with open(filename, "w", encoding="utf-8") as f: 172 | f.write(code) 173 | print(colored(f"Code saved to: {filename}", "green")) 174 | except Exception as e: 175 | print(colored(f"Error saving code: {str(e)}", "red")) 176 | 177 | def main(): 178 | print(colored(f"Starting code generation for prompt: {USER_PROMPT}", "cyan")) 179 | print(colored(f"Number of iterations: {NUMBER_OF_ITERATIONS}", "cyan")) 180 | 181 | code = None 182 | # Generate and improve code for all iterations 183 | for i in range(NUMBER_OF_ITERATIONS): 184 | if i == 0: 185 | # Initial generation 186 | response = generate_code(USER_PROMPT, i + 1) 187 | else: 188 | # Subsequent improvements 189 | response = improve_code(code, i + 1) 190 | 191 | if not response: 192 | continue 193 | 194 | code = extract_code(response) 195 | if not code: 196 | print(colored("No code found in the response", "red")) 197 | continue 198 | 199 | # Save code for this iteration 200 | save_code(code, i) 201 | time.sleep(1) # Rate limiting 202 | 203 | print(colored("\nCode generation and improvement completed!", "green")) 204 | 205 | if __name__ == "__main__": 206 | main() -------------------------------------------------------------------------------- /deep_seek_auto_coder_executor.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import subprocess 4 | import time 5 | from openai import OpenAI 6 | from termcolor import colored 7 | import re 8 | import tempfile 9 | 10 | # User Configuration 11 | USER_PROMPT = "create a beautiful tower defense game in pygame. do not use outside assets. all assets should be created within pygame" 12 | NUMBER_OF_ITERATIONS = 20 13 | 14 | # Constants 15 | MODEL = "deepseek/deepseek-r1" 16 | OUTPUT_FOLDER = "generated_code" 17 | MAX_ERROR_LENGTH = 500 # Maximum length of error message to send to model 18 | CODE_TIMEOUT = 5 # Maximum seconds to run code 19 | 20 | SYSTEM_PROMPT = """You are an expert Python programmer specializing in creating visually stunning and well-structured applications. Generate clean, efficient, and well-documented Python code based on the user's request. 21 | 22 | Follow these EXACT rules for code generation: 23 | 1. ALWAYS wrap your code response in tags 24 | 2. Include ALL necessary imports at the top 25 | 3. Add descriptive comments and docstrings 26 | 4. Return ONLY the code within the tags, no explanations outside the tags 27 | 5. Make sure the code is complete and can run immediately 28 | 6. Use proper Python formatting and PEP 8 guidelines 29 | 7. NEVER use or reference external files (no loading images, sounds, or data files) 30 | 8. ALL assets (graphics, sounds, data) must be generated programmatically within the code 31 | 32 | For visual applications (GUI, games, graphics): 33 | - Create beautiful, polished visuals using ONLY programmatic generation 34 | - All graphics must be drawn using the framework's primitives (shapes, lines, etc.) 35 | - Implement smooth animations and transitions 36 | - Use appealing color schemes and visual effects 37 | - Design intuitive and responsive UI/UX 38 | - Add visual feedback for user interactions 39 | - Include particle effects and visual polish where appropriate 40 | - ALL visual assets must be created within the code itself 41 | 42 | return the full code in tags""" 43 | 44 | ERROR_CORRECTION_PROMPT = """You are an expert Python debugging agent. Your task is to fix code that has runtime errors. 45 | Focus ONLY on fixing the specific error provided. Do not make unnecessary improvements or changes. 46 | 47 | Follow these rules EXACTLY: 48 | 1. Analyze the error message carefully 49 | 2. Make minimal changes needed to fix the error 50 | 3. Preserve the original functionality 51 | 4. Return the COMPLETE fixed code in tags 52 | 5. Do not add features or make improvements beyond error fixing 53 | 6. Keep all assets programmatically generated 54 | 7. NEVER return partial code or just the fixed section 55 | 8. Include ALL imports and ALL functions from the original code 56 | 9. Make sure to wrap the ENTIRE program in tags 57 | 10. The code between the tags must be immediately runnable 58 | 59 | Example format: 60 | 61 | import something 62 | 63 | # All original imports and code here 64 | # With minimal fixes applied 65 | # COMPLETE program, not just the fixed parts 66 | 67 | def main(): 68 | # Complete main function 69 | pass 70 | 71 | if __name__ == "__main__": 72 | main() 73 | """ 74 | 75 | IMPROVEMENT_PROMPT = """Improve this working Python code with the following priorities: 76 | 77 | 1. Visual Enhancement (for GUI/games): 78 | - Enhance visual aesthetics (colors, shapes, animations) 79 | - Add visual polish (particles, effects, transitions) 80 | - Improve UI/UX elements 81 | - Make the visuals more professional and engaging 82 | - ALL graphics must be generated programmatically 83 | - Use framework primitives for all visual assets 84 | 85 | 2. Feature Enhancement: 86 | - Expand core functionality 87 | - Add quality-of-life improvements 88 | - Implement additional user interactions 89 | - Include more game mechanics/options if it's a game 90 | - ALL assets must be created within the code 91 | 92 | 3. Technical Optimization: 93 | - Optimize performance 94 | - Improve code organization 95 | - Add helpful comments 96 | - NO external file operations 97 | 98 | Keep the code complete and runnable. Return the full improved code in its entirety in tags.""" 99 | 100 | # Initialize OpenAI client 101 | try: 102 | client = OpenAI( 103 | base_url="https://openrouter.ai/api/v1", 104 | api_key=os.getenv("OPENROUTER_API_KEY"), 105 | ) 106 | except Exception as e: 107 | print(colored(f"Error initializing OpenAI client: {str(e)}", "red")) 108 | exit(1) 109 | 110 | def run_code_with_timeout(code): 111 | """Run the code with a timeout and capture output/errors. 112 | A timeout usually indicates the program is running successfully in a continuous loop or long process.""" 113 | try: 114 | # Create a temporary file 115 | with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False, encoding='utf-8') as f: 116 | f.write(code) 117 | temp_path = f.name 118 | 119 | try: 120 | # Run the code in a separate process with timeout 121 | process = subprocess.run( 122 | [sys.executable, temp_path], 123 | capture_output=True, 124 | text=True, 125 | timeout=CODE_TIMEOUT 126 | ) 127 | # If we get here, the program exited before timeout 128 | if process.returncode != 0: 129 | return process.returncode, process.stdout, process.stderr 130 | return 0, process.stdout, process.stderr 131 | except subprocess.TimeoutExpired as e: 132 | print(colored(f"Program running (timeout reached after {CODE_TIMEOUT}s) - This is normal for continuous processes!", "green")) 133 | return 0, "", "" # Treat timeout as success 134 | finally: 135 | try: 136 | os.unlink(temp_path) # Clean up temp file 137 | except: 138 | pass 139 | except Exception as e: 140 | return -1, "", str(e) 141 | 142 | def extract_code(response_text): 143 | """Extract code from between tags.""" 144 | try: 145 | pattern = r"(.*?)" 146 | match = re.search(pattern, response_text, re.DOTALL) 147 | return match.group(1).strip() if match else None 148 | except Exception as e: 149 | print(colored(f"Error extracting code: {str(e)}", "red")) 150 | return None 151 | 152 | def generate_code(prompt, iteration=1): 153 | """Generate code using DeepSeek model.""" 154 | try: 155 | print(colored(f"\nGenerating code - Iteration {iteration}...", "cyan")) 156 | completion = client.chat.completions.create( 157 | model=MODEL, 158 | messages=[ 159 | {"role": "system", "content": SYSTEM_PROMPT}, 160 | {"role": "user", "content": f"Create a new Python program for: {prompt}"} 161 | ] 162 | ) 163 | return completion.choices[0].message.content 164 | except Exception as e: 165 | print(colored(f"Error generating code: {str(e)}", "red")) 166 | return None 167 | 168 | def fix_code(code, error_msg): 169 | """Fix code using the error correction agent.""" 170 | try: 171 | print(colored("\nAttempting to fix code errors...", "yellow")) 172 | # Get last MAX_ERROR_LENGTH characters of error 173 | error_msg = error_msg[-MAX_ERROR_LENGTH:] if len(error_msg) > MAX_ERROR_LENGTH else error_msg 174 | 175 | completion = client.chat.completions.create( 176 | model=MODEL, 177 | messages=[ 178 | {"role": "system", "content": ERROR_CORRECTION_PROMPT}, 179 | {"role": "user", "content": f"Fix this Python code that has the following error:\n{error_msg}\n\nHere's the code:\n{code}"} 180 | ] 181 | ) 182 | return completion.choices[0].message.content 183 | except Exception as e: 184 | print(colored(f"Error fixing code: {str(e)}", "red")) 185 | return None 186 | 187 | def improve_code(code, iteration): 188 | """Improve working code.""" 189 | try: 190 | print(colored(f"\nImproving code - Iteration {iteration}...", "yellow")) 191 | completion = client.chat.completions.create( 192 | model=MODEL, 193 | messages=[ 194 | {"role": "system", "content": SYSTEM_PROMPT}, 195 | {"role": "user", "content": f"{IMPROVEMENT_PROMPT}\n\nHere's the code to improve:\n{code}"} 196 | ] 197 | ) 198 | return completion.choices[0].message.content 199 | except Exception as e: 200 | print(colored(f"Error improving code: {str(e)}", "red")) 201 | return None 202 | 203 | def save_code(code, iteration): 204 | """Save generated code to file.""" 205 | try: 206 | if not os.path.exists(OUTPUT_FOLDER): 207 | os.makedirs(OUTPUT_FOLDER) 208 | 209 | filename = os.path.join(OUTPUT_FOLDER, f"generated_code_v{iteration}.py") 210 | with open(filename, "w", encoding="utf-8") as f: 211 | f.write(code) 212 | print(colored(f"Code saved to: {filename}", "green")) 213 | except Exception as e: 214 | print(colored(f"Error saving code: {str(e)}", "red")) 215 | 216 | def main(): 217 | print(colored(f"Starting code generation for prompt: {USER_PROMPT}", "cyan")) 218 | print(colored(f"Number of iterations: {NUMBER_OF_ITERATIONS}", "cyan")) 219 | print(colored(f"Note: Reaching the {CODE_TIMEOUT}s timeout means the program is running successfully!", "green")) 220 | 221 | code = None 222 | for i in range(NUMBER_OF_ITERATIONS): 223 | # Generate or improve code 224 | if i == 0: 225 | response = generate_code(USER_PROMPT, i + 1) 226 | else: 227 | response = improve_code(code, i + 1) 228 | 229 | if not response: 230 | continue 231 | 232 | code = extract_code(response) 233 | if not code: 234 | print(colored("No code found in the response", "red")) 235 | continue 236 | 237 | # Test the code 238 | print(colored("\nTesting code execution...", "cyan")) 239 | returncode, stdout, stderr = run_code_with_timeout(code) 240 | 241 | # Handle code execution results 242 | if returncode != 0 and stderr: 243 | print(colored(f"Code execution failed with error:\n{stderr}", "red")) 244 | # Try to fix the error 245 | fixed_response = fix_code(code, stderr) 246 | if not fixed_response: 247 | print(colored("Failed to fix the error, continuing to next iteration", "red")) 248 | continue 249 | 250 | code = extract_code(fixed_response) 251 | if not code: 252 | print(colored("No fixed code found in the response", "red")) 253 | continue 254 | 255 | # Test the fixed code 256 | print(colored("\nTesting fixed code...", "cyan")) 257 | returncode, stdout, stderr = run_code_with_timeout(code) 258 | if returncode != 0: 259 | print(colored("Fixed code still has errors, continuing to next iteration", "red")) 260 | continue 261 | else: 262 | if stdout: 263 | print(colored("Program output:", "cyan")) 264 | print(stdout) 265 | print(colored("Code execution successful!", "green")) 266 | 267 | # Save the working code 268 | save_code(code, i) 269 | time.sleep(1) # Rate limiting 270 | 271 | print(colored("\nCode generation and improvement completed!", "green")) 272 | 273 | if __name__ == "__main__": 274 | main() -------------------------------------------------------------------------------- /o1_auto_coder.py: -------------------------------------------------------------------------------- 1 | import os 2 | from openai import OpenAI 3 | from termcolor import colored 4 | import re 5 | import time 6 | 7 | # User Configuration 8 | USER_PROMPT = "create a beautiful tower defense game in pygame. do not use outside assets. all assets should be created within pygame" 9 | NUMBER_OF_ITERATIONS = 3 10 | 11 | # Constants 12 | MODEL = "o1" #you can also use o1-mini or gpt-4o 13 | OUTPUT_FOLDER = "generated_code" 14 | 15 | SYSTEM_PROMPT = """You are an expert Python programmer specializing in creating visually stunning and well-structured applications. Generate clean, efficient, and well-documented Python code based on the user's request. 16 | 17 | Follow these EXACT rules for code generation: 18 | 1. ALWAYS wrap your code response in tags 19 | 2. Include ALL necessary imports at the top 20 | 3. Add descriptive comments and docstrings 21 | 4. Return ONLY the code within the tags, no explanations outside the tags 22 | 5. Make sure the code is complete and can run immediately 23 | 6. Use proper Python formatting and PEP 8 guidelines 24 | 7. NEVER use or reference external files (no loading images, sounds, or data files) 25 | 8. ALL assets (graphics, sounds, data) must be generated programmatically within the code 26 | 27 | For visual applications (GUI, games, graphics): 28 | - Create beautiful, polished visuals using ONLY programmatic generation 29 | - All graphics must be drawn using the framework's primitives (shapes, lines, etc.) 30 | - Implement smooth animations and transitions 31 | - Use appealing color schemes and visual effects 32 | - Design intuitive and responsive UI/UX 33 | - Add visual feedback for user interactions 34 | - Include particle effects and visual polish where appropriate 35 | - ALL visual assets must be created within the code itself 36 | 37 | return the full code in tags""" 38 | 39 | IMPROVEMENT_PROMPT = """Improve this working Python code with the following priorities: 40 | 41 | 1. Visual Enhancement (for GUI/games): 42 | - Enhance visual aesthetics (colors, shapes, animations) 43 | - Add visual polish (particles, effects, transitions) 44 | - Improve UI/UX elements 45 | - Make the visuals more professional and engaging 46 | - ALL graphics must be generated programmatically 47 | - Use framework primitives for all visual assets 48 | 49 | 2. Feature Enhancement: 50 | - Expand core functionality 51 | - Add quality-of-life improvements 52 | - Implement additional user interactions 53 | - Include more game mechanics/options if it's a game 54 | - ALL assets must be created within the code 55 | 56 | 3. Technical Optimization: 57 | - Optimize performance 58 | - Improve code organization 59 | - Add helpful comments 60 | - NO external file operations 61 | 62 | Keep the code complete and runnable. Return the full improved code in its entirety in tags.""" 63 | 64 | # Initialize OpenAI client 65 | try: 66 | client = OpenAI( 67 | api_key=os.getenv("OPENAI_API_KEY"), 68 | ) 69 | except Exception as e: 70 | print(colored(f"Error initializing OpenAI client: {str(e)}", "red")) 71 | exit(1) 72 | 73 | def extract_code(response_text): 74 | """Extract code from between tags.""" 75 | try: 76 | pattern = r"(.*?)" 77 | match = re.search(pattern, response_text, re.DOTALL) 78 | return match.group(1).strip() if match else None 79 | except Exception as e: 80 | print(colored(f"Error extracting code: {str(e)}", "red")) 81 | return None 82 | 83 | def generate_code(prompt, iteration=1): 84 | """Generate code using o1 model.""" 85 | try: 86 | print(colored(f"\nGenerating code - Iteration {iteration}...", "cyan")) 87 | completion = client.chat.completions.create( 88 | model=MODEL, 89 | messages=[ 90 | {"role": "system", "content": SYSTEM_PROMPT}, 91 | {"role": "user", "content": f"Create a new Python program for: {prompt}"} 92 | ] 93 | ) 94 | return completion.choices[0].message.content 95 | except Exception as e: 96 | print(colored(f"Error generating code: {str(e)}", "red")) 97 | return None 98 | 99 | def improve_code(code, iteration): 100 | """Improve working code.""" 101 | try: 102 | print(colored(f"\nImproving code - Iteration {iteration}...", "yellow")) 103 | completion = client.chat.completions.create( 104 | model=MODEL, 105 | messages=[ 106 | {"role": "system", "content": SYSTEM_PROMPT}, 107 | {"role": "user", "content": f"{IMPROVEMENT_PROMPT}\n\nHere's the code to improve:\n{code}"} 108 | ] 109 | ) 110 | return completion.choices[0].message.content 111 | except Exception as e: 112 | print(colored(f"Error improving code: {str(e)}", "red")) 113 | return None 114 | 115 | def save_code(code, iteration): 116 | """Save generated code to file.""" 117 | try: 118 | if not os.path.exists(OUTPUT_FOLDER): 119 | os.makedirs(OUTPUT_FOLDER) 120 | 121 | filename = os.path.join(OUTPUT_FOLDER, f"generated_code_v{iteration}.py") 122 | with open(filename, "w", encoding="utf-8") as f: 123 | f.write(code) 124 | print(colored(f"Code saved to: {filename}", "green")) 125 | except Exception as e: 126 | print(colored(f"Error saving code: {str(e)}", "red")) 127 | 128 | def main(): 129 | print(colored(f"Starting code generation for prompt: {USER_PROMPT}", "cyan")) 130 | print(colored(f"Number of iterations: {NUMBER_OF_ITERATIONS}", "cyan")) 131 | 132 | code = None 133 | for i in range(NUMBER_OF_ITERATIONS): 134 | # Generate or improve code 135 | if i == 0: 136 | response = generate_code(USER_PROMPT, i + 1) 137 | else: 138 | response = improve_code(code, i + 1) 139 | 140 | if not response: 141 | continue 142 | 143 | code = extract_code(response) 144 | if not code: 145 | print(colored("No code found in the response", "red")) 146 | continue 147 | 148 | # Save the code 149 | save_code(code, i) 150 | time.sleep(1) # Rate limiting 151 | 152 | print(colored("\nCode generation and improvement completed!", "green")) 153 | 154 | if __name__ == "__main__": 155 | main() -------------------------------------------------------------------------------- /o1_auto_coder_executor.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import subprocess 4 | import time 5 | from openai import OpenAI 6 | from termcolor import colored 7 | import re 8 | import tempfile 9 | 10 | # User Configuration 11 | USER_PROMPT = "create a beautiful tower defense game in pygame. do not use outside assets. all assets should be created within pygame" 12 | NUMBER_OF_ITERATIONS = 3 13 | 14 | # Constants 15 | MODEL = "o1" #you can also use o1-mini or gpt-4o 16 | OUTPUT_FOLDER = "generated_code" 17 | MAX_ERROR_LENGTH = 500 # Maximum length of error message to send to model 18 | CODE_TIMEOUT = 5 # Maximum seconds to run code 19 | 20 | SYSTEM_PROMPT = """You are an expert Python programmer specializing in creating visually stunning and well-structured applications. Generate clean, efficient, and well-documented Python code based on the user's request. 21 | 22 | Follow these EXACT rules for code generation: 23 | 1. ALWAYS wrap your code response in tags 24 | 2. Include ALL necessary imports at the top 25 | 3. Add descriptive comments and docstrings 26 | 4. Return ONLY the code within the tags, no explanations outside the tags 27 | 5. Make sure the code is complete and can run immediately 28 | 6. Use proper Python formatting and PEP 8 guidelines 29 | 7. NEVER use or reference external files (no loading images, sounds, or data files) 30 | 8. ALL assets (graphics, sounds, data) must be generated programmatically within the code 31 | 32 | For visual applications (GUI, games, graphics): 33 | - Create beautiful, polished visuals using ONLY programmatic generation 34 | - All graphics must be drawn using the framework's primitives (shapes, lines, etc.) 35 | - Implement smooth animations and transitions 36 | - Use appealing color schemes and visual effects 37 | - Design intuitive and responsive UI/UX 38 | - Add visual feedback for user interactions 39 | - Include particle effects and visual polish where appropriate 40 | - ALL visual assets must be created within the code itself 41 | 42 | return the full code in tags""" 43 | 44 | ERROR_CORRECTION_PROMPT = """You are an expert Python debugging agent. Your task is to fix code that has runtime errors. 45 | Focus ONLY on fixing the specific error provided. Do not make unnecessary improvements or changes. 46 | 47 | Follow these rules EXACTLY: 48 | 1. Analyze the error message carefully 49 | 2. Make minimal changes needed to fix the error 50 | 3. Preserve the original functionality 51 | 4. Return the COMPLETE fixed code in tags 52 | 5. Do not add features or make improvements beyond error fixing 53 | 6. Keep all assets programmatically generated 54 | 7. NEVER return partial code or just the fixed section 55 | 8. Include ALL imports and ALL functions from the original code 56 | 9. Make sure to wrap the ENTIRE program in tags 57 | 10. The code between the tags must be immediately runnable 58 | 59 | Example format: 60 | 61 | import something 62 | 63 | # All original imports and code here 64 | # With minimal fixes applied 65 | # COMPLETE program, not just the fixed parts 66 | 67 | def main(): 68 | # Complete main function 69 | pass 70 | 71 | if __name__ == "__main__": 72 | main() 73 | """ 74 | 75 | IMPROVEMENT_PROMPT = """Improve this working Python code with the following priorities: 76 | 77 | 1. Visual Enhancement (for GUI/games): 78 | - Enhance visual aesthetics (colors, shapes, animations) 79 | - Add visual polish (particles, effects, transitions) 80 | - Improve UI/UX elements 81 | - Make the visuals more professional and engaging 82 | - ALL graphics must be generated programmatically 83 | - Use framework primitives for all visual assets 84 | 85 | 2. Feature Enhancement: 86 | - Expand core functionality 87 | - Add quality-of-life improvements 88 | - Implement additional user interactions 89 | - Include more game mechanics/options if it's a game 90 | - ALL assets must be created within the code 91 | 92 | 3. Technical Optimization: 93 | - Optimize performance 94 | - Improve code organization 95 | - Add helpful comments 96 | - NO external file operations 97 | 98 | Keep the code complete and runnable. Return the full improved code in its entirety in tags.""" 99 | 100 | # Initialize OpenAI client 101 | try: 102 | client = OpenAI( 103 | api_key=os.getenv("OPENAI_API_KEY"), 104 | ) 105 | except Exception as e: 106 | print(colored(f"Error initializing OpenAI client: {str(e)}", "red")) 107 | exit(1) 108 | 109 | def run_code_with_timeout(code): 110 | """Run the code with a timeout and capture output/errors. 111 | A timeout usually indicates the program is running successfully in a continuous loop or long process.""" 112 | try: 113 | # Create a temporary file 114 | with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False, encoding='utf-8') as f: 115 | f.write(code) 116 | temp_path = f.name 117 | 118 | try: 119 | # Run the code in a separate process with timeout 120 | process = subprocess.run( 121 | [sys.executable, temp_path], 122 | capture_output=True, 123 | text=True, 124 | timeout=CODE_TIMEOUT 125 | ) 126 | # If we get here, the program exited before timeout 127 | if process.returncode != 0: 128 | return process.returncode, process.stdout, process.stderr 129 | return 0, process.stdout, process.stderr 130 | except subprocess.TimeoutExpired as e: 131 | print(colored(f"Program running (timeout reached after {CODE_TIMEOUT}s) - This is normal for continuous processes!", "green")) 132 | return 0, "", "" # Treat timeout as success 133 | finally: 134 | try: 135 | os.unlink(temp_path) # Clean up temp file 136 | except: 137 | pass 138 | except Exception as e: 139 | return -1, "", str(e) 140 | 141 | def extract_code(response_text): 142 | """Extract code from between tags.""" 143 | try: 144 | pattern = r"(.*?)" 145 | match = re.search(pattern, response_text, re.DOTALL) 146 | return match.group(1).strip() if match else None 147 | except Exception as e: 148 | print(colored(f"Error extracting code: {str(e)}", "red")) 149 | return None 150 | 151 | def generate_code(prompt, iteration=1): 152 | """Generate code using o1 model.""" 153 | try: 154 | print(colored(f"\nGenerating code - Iteration {iteration}...", "cyan")) 155 | completion = client.chat.completions.create( 156 | model=MODEL, 157 | messages=[ 158 | {"role": "system", "content": SYSTEM_PROMPT}, 159 | {"role": "user", "content": f"Create a new Python program for: {prompt}"} 160 | ] 161 | ) 162 | return completion.choices[0].message.content 163 | except Exception as e: 164 | print(colored(f"Error generating code: {str(e)}", "red")) 165 | return None 166 | 167 | def fix_code(code, error_msg): 168 | """Fix code using the error correction agent.""" 169 | try: 170 | print(colored("\nAttempting to fix code errors...", "yellow")) 171 | # Get last MAX_ERROR_LENGTH characters of error 172 | error_msg = error_msg[-MAX_ERROR_LENGTH:] if len(error_msg) > MAX_ERROR_LENGTH else error_msg 173 | 174 | completion = client.chat.completions.create( 175 | model=MODEL, 176 | messages=[ 177 | {"role": "system", "content": ERROR_CORRECTION_PROMPT}, 178 | {"role": "user", "content": f"Fix this Python code that has the following error:\n{error_msg}\n\nHere's the code:\n{code}"} 179 | ] 180 | ) 181 | return completion.choices[0].message.content 182 | except Exception as e: 183 | print(colored(f"Error fixing code: {str(e)}", "red")) 184 | return None 185 | 186 | def improve_code(code, iteration): 187 | """Improve working code.""" 188 | try: 189 | print(colored(f"\nImproving code - Iteration {iteration}...", "yellow")) 190 | completion = client.chat.completions.create( 191 | model=MODEL, 192 | messages=[ 193 | {"role": "system", "content": SYSTEM_PROMPT}, 194 | {"role": "user", "content": f"{IMPROVEMENT_PROMPT}\n\nHere's the code to improve:\n{code}"} 195 | ] 196 | ) 197 | return completion.choices[0].message.content 198 | except Exception as e: 199 | print(colored(f"Error improving code: {str(e)}", "red")) 200 | return None 201 | 202 | def save_code(code, iteration): 203 | """Save generated code to file.""" 204 | try: 205 | if not os.path.exists(OUTPUT_FOLDER): 206 | os.makedirs(OUTPUT_FOLDER) 207 | 208 | filename = os.path.join(OUTPUT_FOLDER, f"generated_code_v{iteration}.py") 209 | with open(filename, "w", encoding="utf-8") as f: 210 | f.write(code) 211 | print(colored(f"Code saved to: {filename}", "green")) 212 | except Exception as e: 213 | print(colored(f"Error saving code: {str(e)}", "red")) 214 | 215 | def main(): 216 | print(colored(f"Starting code generation for prompt: {USER_PROMPT}", "cyan")) 217 | print(colored(f"Number of iterations: {NUMBER_OF_ITERATIONS}", "cyan")) 218 | print(colored(f"Note: Reaching the {CODE_TIMEOUT}s timeout means the program is running successfully!", "green")) 219 | 220 | code = None 221 | for i in range(NUMBER_OF_ITERATIONS): 222 | # Generate or improve code 223 | if i == 0: 224 | response = generate_code(USER_PROMPT, i + 1) 225 | else: 226 | response = improve_code(code, i + 1) 227 | 228 | if not response: 229 | continue 230 | 231 | code = extract_code(response) 232 | if not code: 233 | print(colored("No code found in the response", "red")) 234 | continue 235 | 236 | # Test the code 237 | print(colored("\nTesting code execution...", "cyan")) 238 | returncode, stdout, stderr = run_code_with_timeout(code) 239 | 240 | # Handle code execution results 241 | if returncode != 0 and stderr: 242 | print(colored(f"Code execution failed with error:\n{stderr}", "red")) 243 | # Try to fix the error 244 | fixed_response = fix_code(code, stderr) 245 | if not fixed_response: 246 | print(colored("Failed to fix the error, continuing to next iteration", "red")) 247 | continue 248 | 249 | code = extract_code(fixed_response) 250 | if not code: 251 | print(colored("No fixed code found in the response", "red")) 252 | continue 253 | 254 | # Test the fixed code 255 | print(colored("\nTesting fixed code...", "cyan")) 256 | returncode, stdout, stderr = run_code_with_timeout(code) 257 | if returncode != 0: 258 | print(colored("Fixed code still has errors, continuing to next iteration", "red")) 259 | continue 260 | else: 261 | if stdout: 262 | print(colored("Program output:", "cyan")) 263 | print(stdout) 264 | print(colored("Code execution successful!", "green")) 265 | 266 | # Save the working code 267 | save_code(code, i) 268 | time.sleep(1) # Rate limiting 269 | 270 | print(colored("\nCode generation and improvement completed!", "green")) 271 | 272 | if __name__ == "__main__": 273 | main() -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | openai 2 | termcolor --------------------------------------------------------------------------------