๐Ÿ’ป Project: AI Code Generator

Build an intelligent programming assistant

Project Overview

Create a powerful AI code generation tool that helps developers write, debug, test, and refactor code across multiple programming languages. This assistant understands context and generates production-ready code.

Features We'll Build:

  • Code generation: Natural language to code in 10+ languages
  • Debugging assistant: Find and fix bugs automatically
  • Test generation: Create unit and integration tests
  • Code refactoring: Improve code quality and structure
  • Documentation: Generate comments and docs
  • Code explanation: Understand complex code

๐Ÿ› ๏ธ Setup and Dependencies

# Install required packages
pip install streamlit openai anthropic gradio
pip install black autopep8 pylint  # Code formatters
pip install pytest  # Testing framework

# Required imports
import streamlit as st
from openai import OpenAI
import anthropic
import subprocess
import tempfile
import os
from typing import List, Dict
import json

print("โœ“ Dependencies installed!")
print("\nSupported Languages:")
languages = [
    'Python', 'JavaScript', 'TypeScript', 'Java', 'C++',
    'Go', 'Rust', 'C#', 'PHP', 'Ruby', 'Swift', 'Kotlin'
]
for lang in languages:
    print(f"  โ€ข {lang}")

๐Ÿค– Code Generation Engine

class CodeGenerator:
    """AI-powered code generation engine"""
    
    def __init__(self, api_key=None, model="gpt-4"):
        self.client = OpenAI(api_key=api_key or os.getenv('OPENAI_API_KEY'))
        self.model = model
        
        # Language-specific configurations
        self.language_configs = {
            'python': {
                'extension': '.py',
                'test_framework': 'pytest',
                'formatter': 'black',
            },
            'javascript': {
                'extension': '.js',
                'test_framework': 'jest',
                'formatter': 'prettier',
            },
            'typescript': {
                'extension': '.ts',
                'test_framework': 'jest',
                'formatter': 'prettier',
            },
            'java': {
                'extension': '.java',
                'test_framework': 'junit',
                'formatter': 'google-java-format',
            },
        }
    
    def generate_code(self, 
                     description: str,
                     language: str = 'python',
                     style: str = 'clean',
                     include_comments: bool = True,
                     include_error_handling: bool = True) -> str:
        """
        Generate code from natural language description
        
        Args:
            description: What the code should do
            language: Programming language
            style: Code style (clean, concise, verbose)
            include_comments: Add explanatory comments
            include_error_handling: Add try-catch blocks
        """
        
        system_prompt = f"""You are an expert {language} programmer.
Generate clean, efficient, production-ready code.

Requirements:
- Write idiomatic {language} code
- Follow best practices and conventions
- {('Include helpful comments' if include_comments else 'Minimal comments')}
- {('Include error handling' if include_error_handling else 'Basic implementation')}
- Style: {style}
- Make code maintainable and testable

Return ONLY the code, no explanations unless requested."""
        
        response = self.client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": f"Generate code for: {description}"}
            ],
            temperature=0.3,  # Lower for more deterministic code
        )
        
        code = response.choices[0].message.content
        
        # Clean markdown code blocks
        code = self._clean_code_blocks(code)
        
        return code
    
    def _clean_code_blocks(self, code: str) -> str:
        """Remove markdown code block markers"""
        lines = code.split('\n')
        
        # Remove first line if it's a language marker
        if lines and lines[0].strip().startswith('```'):
            lines = lines[1:]
        
        # Remove last line if it's closing marker
        if lines and lines[-1].strip() == '```':
            lines = lines[:-1]
        
        return '\n'.join(lines)

# Initialize generator
generator = CodeGenerator(model="gpt-4")

# Example: Generate function
code = generator.generate_code(
    description="Create a function that validates email addresses using regex",
    language="python",
    style="clean",
    include_comments=True,
    include_error_handling=True
)

print("Generated Code:")
print(code)

๐Ÿ› Debugging Assistant

class DebugAssistant:
    """AI-powered debugging assistant"""
    
    def __init__(self, api_key=None):
        self.client = OpenAI(api_key=api_key or os.getenv('OPENAI_API_KEY'))
    
    def debug_code(self, 
                   code: str,
                   error_message: str = None,
                   language: str = 'python') -> Dict:
        """
        Debug code and suggest fixes
        
        Returns:
            Dict with 'explanation', 'issues', 'fixed_code', 'suggestions'
        """
        
        prompt = f"""Analyze this {language} code and help debug it.

Code:
```{language}
{code}
```
"""
        
        if error_message:
            prompt += f"\nError Message:\n{error_message}\n"
        
        prompt += """
Provide:
1. Explanation of what's wrong
2. List of specific issues
3. Fixed version of the code
4. Additional suggestions for improvement

Format as JSON:
{
    "explanation": "...",
    "issues": ["issue1", "issue2"],
    "fixed_code": "...",
    "suggestions": ["suggestion1", "suggestion2"]
}"""
        
        response = self.client.chat.completions.create(
            model="gpt-4",
            messages=[
                {"role": "system", "content": "You are an expert debugger."},
                {"role": "user", "content": prompt}
            ],
            temperature=0.3,
        )
        
        result = response.choices[0].message.content
        
        # Parse JSON response
        try:
            debug_info = json.loads(result)
        except:
            # Fallback if not proper JSON
            debug_info = {
                'explanation': result,
                'issues': [],
                'fixed_code': '',
                'suggestions': []
            }
        
        return debug_info
    
    def explain_error(self, error_message: str) -> str:
        """Explain error message in simple terms"""
        
        response = self.client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "Explain programming errors in simple terms."},
                {"role": "user", "content": f"Explain this error:\n{error_message}"}
            ],
            temperature=0.5,
        )
        
        return response.choices[0].message.content

# Example usage
debugger = DebugAssistant()

buggy_code = """
def calculate_average(numbers):
    total = 0
    for num in numbers:
        total += num
    return total / len(numbers)

# This will crash
result = calculate_average([])
print(result)
"""

error_msg = "ZeroDivisionError: division by zero"

debug_result = debugger.debug_code(buggy_code, error_msg, language='python')

print("Debug Analysis:")
print(f"\nExplanation: {debug_result['explanation']}")
print(f"\nIssues:")
for issue in debug_result['issues']:
    print(f"  โ€ข {issue}")
print(f"\nFixed Code:\n{debug_result['fixed_code']}")
print(f"\nSuggestions:")
for suggestion in debug_result['suggestions']:
    print(f"  โ€ข {suggestion}")

๐Ÿงช Test Generator

class TestGenerator:
    """Generate unit tests for code"""
    
    def __init__(self, api_key=None):
        self.client = OpenAI(api_key=api_key or os.getenv('OPENAI_API_KEY'))
    
    def generate_tests(self,
                      code: str,
                      language: str = 'python',
                      test_framework: str = 'pytest',
                      coverage: str = 'comprehensive') -> str:
        """
        Generate unit tests for given code
        
        Args:
            code: Code to test
            language: Programming language
            test_framework: Test framework (pytest, jest, junit, etc.)
            coverage: Level of coverage (basic, standard, comprehensive)
        """
        
        coverage_descriptions = {
            'basic': 'Basic happy path tests',
            'standard': 'Happy path and common edge cases',
            'comprehensive': 'Happy path, edge cases, error cases, boundary conditions'
        }
        
        system_prompt = f"""You are an expert at writing {test_framework} tests.

Generate {coverage_descriptions[coverage]} for the provided code.

Requirements:
- Use {test_framework} syntax and conventions
- Test all public functions/methods
- Include test cases for edge cases and error conditions
- Use descriptive test names
- Add assertions for expected behavior
- Mock external dependencies if needed

Return ONLY the test code."""
        
        user_prompt = f"""Generate {test_framework} tests for this {language} code:

```{language}
{code}
```

Create {coverage} test coverage."""
        
        response = self.client.chat.completions.create(
            model="gpt-4",
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_prompt}
            ],
            temperature=0.3,
        )
        
        tests = response.choices[0].message.content
        return self._clean_code_blocks(tests)
    
    def _clean_code_blocks(self, code: str) -> str:
        """Remove markdown code blocks"""
        lines = code.split('\n')
        if lines and lines[0].strip().startswith('```'):
            lines = lines[1:]
        if lines and lines[-1].strip() == '```':
            lines = lines[:-1]
        return '\n'.join(lines)
    
    def run_tests(self, test_code: str, language: str = 'python') -> Dict:
        """
        Run generated tests and return results
        
        Returns:
            Dict with 'success', 'output', 'errors'
        """
        
        if language == 'python':
            # Create temporary test file
            with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
                f.write(test_code)
                test_file = f.name
            
            try:
                # Run pytest
                result = subprocess.run(
                    ['pytest', test_file, '-v'],
                    capture_output=True,
                    text=True,
                    timeout=30
                )
                
                return {
                    'success': result.returncode == 0,
                    'output': result.stdout,
                    'errors': result.stderr
                }
            finally:
                os.unlink(test_file)
        
        return {'success': False, 'output': '', 'errors': 'Language not supported'}

# Example usage
test_gen = TestGenerator()

# Code to test
code_to_test = """
def calculate_average(numbers):
    if not numbers:
        raise ValueError("Cannot calculate average of empty list")
    return sum(numbers) / len(numbers)

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True
"""

# Generate tests
tests = test_gen.generate_tests(
    code=code_to_test,
    language='python',
    test_framework='pytest',
    coverage='comprehensive'
)

print("Generated Tests:")
print(tests)

# Run tests
# test_results = test_gen.run_tests(tests)
# print(f"\nTest Results: {'โœ“ Passed' if test_results['success'] else 'โœ— Failed'}")

โ™ป๏ธ Code Refactoring

class CodeRefactorer:
    """Refactor and improve code quality"""
    
    def __init__(self, api_key=None):
        self.client = OpenAI(api_key=api_key or os.getenv('OPENAI_API_KEY'))
    
    def refactor_code(self,
                     code: str,
                     language: str = 'python',
                     focus: str = 'general') -> Dict:
        """
        Refactor code for better quality
        
        Args:
            code: Code to refactor
            language: Programming language
            focus: What to focus on (general, performance, readability, maintainability)
        
        Returns:
            Dict with 'refactored_code', 'changes', 'improvements'
        """
        
        focus_descriptions = {
            'general': 'overall code quality and best practices',
            'performance': 'execution speed and efficiency',
            'readability': 'code clarity and understandability',
            'maintainability': 'ease of maintenance and extensibility'
        }
        
        prompt = f"""Refactor this {language} code focusing on {focus_descriptions[focus]}.

Original Code:
```{language}
{code}
```

Provide:
1. Refactored code with improvements
2. List of changes made
3. Explanation of improvements

Format as JSON:
{{
    "refactored_code": "...",
    "changes": ["change1", "change2"],
    "improvements": "explanation of improvements"
}}"""
        
        response = self.client.chat.completions.create(
            model="gpt-4",
            messages=[
                {"role": "system", "content": f"You are an expert {language} developer focused on code quality."},
                {"role": "user", "content": prompt}
            ],
            temperature=0.3,
        )
        
        result = response.choices[0].message.content
        
        try:
            refactor_info = json.loads(result)
        except:
            refactor_info = {
                'refactored_code': result,
                'changes': [],
                'improvements': 'See refactored code'
            }
        
        return refactor_info
    
    def add_documentation(self, code: str, language: str = 'python') -> str:
        """Add comprehensive documentation to code"""
        
        prompt = f"""Add comprehensive documentation to this {language} code.

Code:
```{language}
{code}
```

Add:
- Module/file docstring
- Function/method docstrings with parameters and returns
- Inline comments for complex logic
- Type hints (if applicable)
- Usage examples in docstrings

Return the fully documented code."""
        
        response = self.client.chat.completions.create(
            model="gpt-4",
            messages=[
                {"role": "system", "content": "You are an expert at writing clear documentation."},
                {"role": "user", "content": prompt}
            ],
            temperature=0.3,
        )
        
        documented_code = response.choices[0].message.content
        return self._clean_code_blocks(documented_code)
    
    def _clean_code_blocks(self, code: str) -> str:
        """Remove markdown code blocks"""
        lines = code.split('\n')
        if lines and lines[0].strip().startswith('```'):
            lines = lines[1:]
        if lines and lines[-1].strip() == '```':
            lines = lines[:-1]
        return '\n'.join(lines)

# Example usage
refactorer = CodeRefactorer()

messy_code = """
def calc(x, y, z):
    if z == 'add':
        return x + y
    elif z == 'sub':
        return x - y
    elif z == 'mul':
        return x * y
    elif z == 'div':
        return x / y
    else:
        return None

result = calc(10, 5, 'add')
print(result)
"""

# Refactor for readability
refactor_result = refactorer.refactor_code(
    code=messy_code,
    language='python',
    focus='readability'
)

print("Refactoring Results:")
print(f"\nChanges Made:")
for change in refactor_result['changes']:
    print(f"  โ€ข {change}")

print(f"\nImprovements:\n{refactor_result['improvements']}")
print(f"\nRefactored Code:\n{refactor_result['refactored_code']}")

๐ŸŽจ Streamlit Interface

# app.py - Main application

import streamlit as st

def main():
    st.set_page_config(
        page_title="AI Code Generator",
        page_icon="๐Ÿ’ป",
        layout="wide"
    )
    
    st.title("๐Ÿ’ป AI Code Generator")
    st.markdown("Your intelligent programming assistant")
    
    # Sidebar
    with st.sidebar:
        st.header("โš™๏ธ Configuration")
        
        api_key = st.text_input("OpenAI API Key", type="password")
        
        mode = st.selectbox(
            "Mode",
            ['Generate Code', 'Debug Code', 'Generate Tests', 
             'Refactor Code', 'Explain Code']
        )
        
        language = st.selectbox(
            "Language",
            ['Python', 'JavaScript', 'TypeScript', 'Java', 
             'C++', 'Go', 'Rust']
        )
    
    # Main content based on mode
    if mode == 'Generate Code':
        show_generate_mode(api_key, language)
    elif mode == 'Debug Code':
        show_debug_mode(api_key, language)
    elif mode == 'Generate Tests':
        show_test_mode(api_key, language)
    elif mode == 'Refactor Code':
        show_refactor_mode(api_key, language)
    elif mode == 'Explain Code':
        show_explain_mode(api_key, language)

def show_generate_mode(api_key, language):
    """Code generation interface"""
    st.header("๐Ÿš€ Generate Code")
    
    description = st.text_area(
        "Describe what you want to build:",
        placeholder="e.g., Create a REST API endpoint that handles user authentication...",
        height=150
    )
    
    col1, col2 = st.columns(2)
    with col1:
        style = st.selectbox("Style", ['clean', 'concise', 'verbose'])
    with col2:
        include_comments = st.checkbox("Include comments", value=True)
    
    if st.button("Generate Code", type="primary"):
        if not api_key or not description:
            st.error("Please provide API key and description")
        else:
            with st.spinner("Generating code..."):
                generator = CodeGenerator(api_key=api_key)
                code = generator.generate_code(
                    description=description,
                    language=language.lower(),
                    style=style,
                    include_comments=include_comments
                )
                
                st.code(code, language=language.lower())
                
                # Copy button
                st.download_button(
                    "Download Code",
                    data=code,
                    file_name=f"generated_code.{language.lower()}",
                    mime="text/plain"
                )

def show_debug_mode(api_key, language):
    """Debugging interface"""
    st.header("๐Ÿ› Debug Code")
    
    code_input = st.text_area(
        "Paste your code:",
        height=200
    )
    
    error_msg = st.text_area(
        "Error message (optional):",
        height=100
    )
    
    if st.button("Debug", type="primary"):
        if not api_key or not code_input:
            st.error("Please provide API key and code")
        else:
            with st.spinner("Analyzing code..."):
                debugger = DebugAssistant(api_key=api_key)
                result = debugger.debug_code(
                    code=code_input,
                    error_message=error_msg,
                    language=language.lower()
                )
                
                st.subheader("Analysis")
                st.write(result['explanation'])
                
                if result['issues']:
                    st.subheader("Issues Found")
                    for issue in result['issues']:
                        st.error(f"โ€ข {issue}")
                
                st.subheader("Fixed Code")
                st.code(result['fixed_code'], language=language.lower())
                
                if result['suggestions']:
                    st.subheader("Suggestions")
                    for suggestion in result['suggestions']:
                        st.info(f"โ€ข {suggestion}")

def show_test_mode(api_key, language):
    """Test generation interface"""
    st.header("๐Ÿงช Generate Tests")
    
    code_input = st.text_area(
        "Paste code to test:",
        height=200
    )
    
    col1, col2 = st.columns(2)
    with col1:
        framework = st.selectbox(
            "Test Framework",
            ['pytest', 'unittest', 'jest', 'mocha', 'junit']
        )
    with col2:
        coverage = st.select_slider(
            "Coverage Level",
            options=['basic', 'standard', 'comprehensive']
        )
    
    if st.button("Generate Tests", type="primary"):
        if not api_key or not code_input:
            st.error("Please provide API key and code")
        else:
            with st.spinner("Generating tests..."):
                test_gen = TestGenerator(api_key=api_key)
                tests = test_gen.generate_tests(
                    code=code_input,
                    language=language.lower(),
                    test_framework=framework,
                    coverage=coverage
                )
                
                st.code(tests, language=language.lower())
                
                st.download_button(
                    "Download Tests",
                    data=tests,
                    file_name=f"test_{language.lower()}.{language.lower()}",
                    mime="text/plain"
                )

def show_refactor_mode(api_key, language):
    """Refactoring interface"""
    st.header("โ™ป๏ธ Refactor Code")
    
    code_input = st.text_area(
        "Paste code to refactor:",
        height=200
    )
    
    focus = st.selectbox(
        "Focus Area",
        ['general', 'performance', 'readability', 'maintainability']
    )
    
    if st.button("Refactor", type="primary"):
        if not api_key or not code_input:
            st.error("Please provide API key and code")
        else:
            with st.spinner("Refactoring code..."):
                refactorer = CodeRefactorer(api_key=api_key)
                result = refactorer.refactor_code(
                    code=code_input,
                    language=language.lower(),
                    focus=focus
                )
                
                col1, col2 = st.columns(2)
                
                with col1:
                    st.subheader("Original")
                    st.code(code_input, language=language.lower())
                
                with col2:
                    st.subheader("Refactored")
                    st.code(result['refactored_code'], language=language.lower())
                
                st.subheader("Changes Made")
                for change in result['changes']:
                    st.write(f"โœ“ {change}")
                
                st.info(result['improvements'])

def show_explain_mode(api_key, language):
    """Code explanation interface"""
    st.header("๐Ÿ“– Explain Code")
    
    code_input = st.text_area(
        "Paste code to explain:",
        height=200
    )
    
    if st.button("Explain", type="primary"):
        if not api_key or not code_input:
            st.error("Please provide API key and code")
        else:
            with st.spinner("Analyzing code..."):
                client = OpenAI(api_key=api_key)
                response = client.chat.completions.create(
                    model="gpt-4",
                    messages=[
                        {"role": "system", "content": "Explain code clearly and thoroughly."},
                        {"role": "user", "content": f"Explain this {language} code:\n\n{code_input}"}
                    ]
                )
                
                explanation = response.choices[0].message.content
                st.markdown(explanation)

if __name__ == "__main__":
    main()

# Run with: streamlit run app.py

๐ŸŽฏ Key Features Summary

๐Ÿš€ Enhancements