Team Ai
Apppublic

chandrasekhar560/coding-agent

sourceHugging Faceupdated 10mo agoView on Hugging Face
0likes
agent_functions.py449 linesDownload Raw Back to root
1"""2Agent definitions for the multi-agent code analysis system.3Each agent is defined as an async function that creates and runs an Agent instance.4"""5 6from agents import Agent, Runner  # OpenAI Agents SDK7from models import (8    ClassificationResult,9    CodeInput,10    ErrorAnalysisResult,11    CodeWithErrors,12    ImprovedCodeResult,13    ImprovedCodeInput,14    AlternativesResult,15    TextInput,16    GeneratedCodeResult,17    FinalOutput,18    MarkdownReport19)20 21import json 22 23# ============================================24# CLASSIFIER AGENT25# ============================================26 27async def classify_input(user_input: str) -> ClassificationResult:28    """29    Classify whether the input is code or plain text using Runner.30    31    Args:32        user_input (str): Raw user input (code or text)33    34    Returns:35        ClassificationResult: Pydantic model with type field36    """37    classifier_agent = Agent(38        name="Classifier Agent",39        model="gpt-4o-mini",40        instructions="""You are an expert AI that accurately classifies user input as either CODE or PLAIN TEXT.41 42        Task:43        - Analyze the given input carefully.44        - Determine whether it contains **actual executable code** or is **natural language** (requests, questions, instructions).45 46        Classification Rules:47 48        **Classify as CODE only if:**49        - Input contains ACTUAL programming syntax that can be executed50        - Has real code elements: variables, functions, operators, control flow51        - Examples of CODE:52            ```python53            def hello():54                print("Hi")55            ```56            57            ```javascript58            const x = 10;59            let arr = [1, 2, 3];60            ```61            62            ```java63            public class Main {64                public static void main(String[] args) {65                    System.out.println("Hello");66                }67            }68            ```69 70        **Classify as TEXT if:**71        - Input is a REQUEST, QUESTION, or INSTRUCTION about code72        - Contains natural language with words like "write", "create", "generate", "could you", "please", etc.73        - Mentions programming concepts but has NO executable syntax74        - Examples of TEXT:75            - "write a function to reverse an array"76            - "could you write 2 sum code in java"77            - "generate a binary search algorithm"78            - "create a function for palindrome check"79            - "how to implement quicksort in python"80            - "write code to find duplicates"81 82        Critical Distinction:83        WRONG: "write 2 sum code" → CODE (this is a REQUEST, not code!)84        CORRECT: "write 2 sum code" → TEXT (natural language request)85        86        CORRECT: "def two_sum(nums, target): ..." → CODE (actual executable code)87 88        Requirements:89        - If input ASKS for code or DESCRIBES what code should do → TEXT90        - If input IS actual code with syntax → CODE91        - Natural language questions/requests are ALWAYS TEXT, even if they mention "code", "function", "java", etc.""",92        output_type=ClassificationResult,93    )94   95    result = await Runner.run(96        classifier_agent,97        input=user_input98    )99    100    return result101 102 103# ============================================104# ERROR ANALYZER AGENT105# ============================================106 107async def analyze_code_errors(code_input: CodeInput) -> ErrorAnalysisResult:108    """109    Analyze code for errors, bugs, and anti-patterns.110    111    Args:112        code_input: CodeInput with raw code113    114    Returns:115        ErrorAnalysisResult: List of errors with descriptions, locations, and fixes116    """117    error_analysis_agent = Agent(118        name="Code Error Analyzer",119        model="gpt-4o-mini",120        instructions="""You are an expert code analyzer specializing in comprehensive error detection. 121 122        Your task:123        - Analyze the provided code thoroughly.124        - Identify **all types of errors**, including:125 126        1. **Syntax Errors**: Missing brackets, incorrect indentation, invalid syntax127        2. **Compilation Issues**: Import errors, undefined variables, type mismatches128        3. **Logical Errors**: Incorrect logic, infinite loops, wrong conditions129        4. **Anti-patterns**: Bad practices, code smells, inefficient patterns130        5. **Runtime Errors**: Potential null references, division by zero, out-of-bounds access131 132        For **each error**, provide:133 134        - **description**: Clear and concise explanation of the issue135        - **location**: Specific line number, function name, or code block136        - **suggestedFix**: Concrete fix or corrected code example if applicable137 138        Requirements:139        - Be **thorough and precise**.140        - Detect all possible errors without skipping edge cases.141        - Focus strictly on **actual code issues**, not style preferences unless they constitute an anti-pattern.142        143 144        Structured Output Format:145        {146        "errors": [147            {148            "description": "string",149            "location": "string",150            "suggestedFix": "string"151            }152        ]153        }154        """,155        output_type=ErrorAnalysisResult,156    )157    158    result = await Runner.run(159        error_analysis_agent,160        input=code_input.code161    )162    163    return result164 165 166# ============================================167# BUG FIX AGENT168# ============================================169 170async def fix_code_bugs(code_with_errors: CodeWithErrors) -> ImprovedCodeResult:171    """172    Fix bugs and improve code quality with inline comments.173    174    Args:175        code_with_errors: CodeWithErrors with raw code and error list176    177    Returns:178        ImprovedCodeResult: Improved code with inline comments explaining fixes179    """180    bug_fix_agent = Agent(181        name="Code Bug Fixer & Improver",182        model="gpt-4o",183        instructions="""You are a senior AI engineer specializing in code optimization and refactoring. 184 185Your task:186- Take the provided raw code and its associated list of errors.187- Generate an **improved version of the code** that:188  1. Fixes all errors provided in the input.189  2. Adds **clear, concise inline comments** explaining each change.190  3. Preserves the original functionality while ensuring the code runs correctly without errors.191  4.specify time and space complexity of the code in the comments.192 193Requirements:194- Do not introduce new errors.195- Focus on **practical, executable improvements**.196- Explain changes **inline as comments**, not in separate text.197- Return **only the improved code** in the structured output format.198 199The improved code should be production-ready and follow best practices.""",200        output_type=ImprovedCodeResult,201    )202    203    # Format input for the agent204    errors_text = "\n".join([205        f"- {err.location}: {err.description} (Fix: {err.suggestedFix})"206        for err in code_with_errors.errors207    ])208    209    input_text = f"""Original Code:210```211{code_with_errors.code}212```213 214Errors to Fix:215{errors_text if errors_text else "No specific errors listed - perform general code improvement."}216"""217    218    result = await Runner.run(219        bug_fix_agent,220        input=input_text221    )222    223    return result224 225 226# ============================================227# ALTERNATIVE SOLUTIONS AGENT228# ====================================================================================229 230async def generate_alternative_solutions(code_input: ImprovedCodeInput) -> AlternativesResult:231    """232    Generate 2-3 alternative implementations of the given code.233    234    Args:235        code_input: ImprovedCodeInput with the improved code236    237    Returns:238        AlternativesResult: List of alternative solutions with explanations and trade-offs239    """240    alternative_code_agent = Agent(241        name="Alternative Code Generator",242        model="gpt-4o-mini",243        instructions="""You are a senior AI engineer specializing in generating multiple high-quality solutions for a given piece of code.244 245Your task:246- Take the provided improved code as input.247- Generate **alternative implementations like brute force and better and optimized** of the same functionality.248- For each alternative:249   1. Provide solution name/title of the approach including  brute force/better/optimized250  2. provide clean, executable code with inline comments.251  3. Provide a brief **explanation** of the approach.252  4. Describe  time complexity and space complexity253Requirements:254- Maintain the original functionality in all alternatives.255- Explore different paradigms, algorithms, or coding styles where appropriate (e.g., iterative vs recursive, functional vs OOP).256- Avoid introducing errors.257 258Each alternative should offer a genuinely different approach, not just minor variations.""",259        output_type=AlternativesResult,260    )261    262    input_text = f"""Generate alternative implementations for this code:263 264```265{code_input.improvedCode}266```267 268Provide different approaches like brute force and better and optimized with explanations and trade-offs."""269    270    result = await Runner.run(271        alternative_code_agent,272        input=input_text273    )274    275    return result276 277 278# ============================================279# CODE GENERATOR AGENT280# ============================================281 282async def generate_code_from_text(text_input: TextInput) -> GeneratedCodeResult:283    """284    Generate code implementations from natural language description.285    286    Args:287        text_input: TextInput with natural language description288    289    Returns:290        GeneratedCodeResult: Multiple implementations with explanations and complexity analysis291    """292    code_generator_agent = Agent(293        name="Code Generator from Text",294        model="gpt-4o",295        instructions="""You are a senior AI engineer specializing in generating multiple high-quality code solutions from natural language descriptions.296 297Your task:298- Take the provided text description as input.299- Generate **multiple implementations** following a strict efficiency progression:300  1. **Brute Force**: Naive approach (Highest Time/Space Complexity)301  2. **Better Approach**: Improved logic (Intermediate Complexity)302  3. **Optimized Solution**: Best possible algorithm (Lowest Time/Space Complexity)303- For each implementation:304  1. Provide solution name/title of the approach (e.g., "Brute Force", "Better Approach", "Optimized Solution") 305  2. Provide clean, executable code.306  3. Include **clear inline comments** explaining the logic.307  4. Provide a brief **explanation** of the approach.308  5. Describe **time complexity and space complexity**.309 310Requirements:311- Generate working, executable code in the appropriate language.312- Explore different algorithms and approaches (e.g., brute force, hash table, two pointers, etc.).313- Avoid introducing errors.314- Each alternative should offer a genuinely different approach with different complexity characteristics.315 316Ensure all code is production-ready and follows best practices.""",317        output_type=GeneratedCodeResult,318    )319    320    input_text = f"""Generate code implementations for the following request:321 322"{text_input.text}"323 324Provide multiple approaches (brute force, better, optimized) with explanations and complexity analysis."""325    326    result = await Runner.run(327        code_generator_agent,328        input=input_text329    )330    331    return result332 333 334 335 336async def generate_markdown_report(final_output: FinalOutput) -> MarkdownReport:337    """338    Generate a clean Markdown technical report from FinalOutput.339    340    Args:341        final_output: FinalOutput from the orchestrator with all agent results342    343    Returns:344        MarkdownReport: Clean, structured Markdown document345    """346    markdown_agent = Agent(347        name="Markdown Report Generator",348        model="gpt-4o-mini",349        instructions="""You are a senior technical documentation expert who specializes in generating **clean, structured, and highly readable Markdown** reports.350 351You will receive a `FinalOutput` object defined by the following Pydantic model:352 353FinalOutput {354    inputType: str355    errors: List[ErrorDetail]356    improvedCode: str357    alternatives: List[AlternativeSolution]358    generatedCode: List[GeneratedSolution]359}360 361Your task is to convert this FinalOutput object into a polished, **user-friendly Markdown report** that is easy to read and visually appealing.362 363---------------------------------364### **Formatting Rules**365---------------------------------366 3671. **Only include sections that have actual content.**368   - If a field is empty (`""`, `None`, or `[]`), *do NOT display that field or section.*369 3702. **Section Order (when applicable):**371   1. **Errors**  372   2. **Improved Code**  373   3. **Alternative Solutions**  374   4. **Generated Code**375 3763. **Errors Section (only if errors list is NOT empty)**  377   - Create a subsection for each error:  378     - **Description:** …  379     - **location:** …  380     - **Suggested Fix:** Wrap in `backticks` for inline code or code block for longer fixes  381   - Use **bullet points** or subheadings  382   - Add a subtle horizontal separator (`---`) between errors for readability  383 3845. **Improved Code Section (only if improvedCode is not empty)**  385   - Use header: `## Improved Code`386   - Wrap code in fenced triple-backtick blocks  387   - Detect language if possible (e.g., ```python)  388   - Do NOT add a second bold line saying "Improved Code"  389 3906. **Alternatives Section (only if alternatives list is NOT empty)**  391   - For each alternative:  392     - `### Approach: *solutionName*` (bold & slightly larger heading)  393     - Code block with proper syntax highlighting  394     - **Explanation:** …  395     - **Tradeoffs:** …  396   - Add spacing between alternative solutions for clarity  397 3987. **Generated Code Section (only if generatedCode list is NOT empty)**  399   - For each solution:  400     - `### Approach: *solutionName*`  401     - Code block  402     - **Explanation:** …  403     - **Tradeoffs:** …  404   - Use consistent spacing and headings  405 4068. **General Markdown Styling**  407   - Use clear headings (##, ###, ####)  408   - Maintain consistent line breaks and spacing between sections  409   - Use **bold** for key labels like Description, Explanation, Tradeoffs  410   - Add subtle horizontal lines (`---`) to separate main sections for readability  411   - Ensure the report is visually scannable for users  412 413---------------------------------414### **Do NOT**415---------------------------------416- Do not show empty fields  417- Do not add content not present in FinalOutput  418- Do not rewrite or correct the data  419- Do not add reasoning, commentary, or explanations outside Markdown  420- Do NOT include an "Input Type" section or header421 422---------------------------------423### **Goal**424Produce a clean, professional, visually attractive Markdown report that is **easy to read and highlights key information**.  425- Users should quickly understand:  426  - What errors exist (if any)  427  - How the code was improved  428  - Alternative solutions  429  - Generated code (for text input)430 431        """,432        output_type=MarkdownReport,433    )434    435    # Convert FinalOutput to JSON for the agent436    final_output_dict = final_output.model_dump()437    438    input_text = f"""Generate a Markdown technical report from this FinalOutput:439 440{json.dumps(final_output_dict, indent=2)}441 442Remember: Only include sections with actual content. Skip empty fields."""443    444    result = await Runner.run(445        markdown_agent,446        input=input_text447    )448    449    return result