code_review.py
1 """ 2 Code review specialized agent. 3 """ 4 5 from langchain.agents import AgentExecutor, create_react_agent 6 from langchain_core.tools import Tool 7 from langchain_core.prompts import PromptTemplate 8 from langchain_core.language_models import BaseLLM 9 from typing import Optional 10 11 from kamaji.tools import read_file, execute_shell_command, list_directory 12 13 14 def check_python_syntax(file_path: str) -> str: 15 """Check Python file for syntax errors.""" 16 import subprocess 17 try: 18 result = subprocess.run( 19 ["python3", "-m", "py_compile", file_path], 20 capture_output=True, 21 text=True, 22 timeout=5 23 ) 24 if result.returncode == 0: 25 return f"✅ No syntax errors in {file_path}" 26 else: 27 return f"❌ Syntax errors:\n{result.stderr}" 28 except Exception as e: 29 return f"Error checking syntax: {str(e)}" 30 31 32 def count_lines_of_code(file_path: str) -> str: 33 """Count lines of code, comments, and blank lines.""" 34 try: 35 with open(file_path, 'r') as f: 36 lines = f.readlines() 37 38 total = len(lines) 39 blank = sum(1 for line in lines if line.strip() == '') 40 comments = sum(1 for line in lines if line.strip().startswith('#')) 41 code = total - blank - comments 42 43 return f""" 44 📊 Code Statistics for {file_path}: 45 • Total lines: {total} 46 • Code lines: {code} 47 • Comment lines: {comments} 48 • Blank lines: {blank} 49 • Code/Comment ratio: {code/max(comments, 1):.2f} 50 """ 51 except Exception as e: 52 return f"Error analyzing file: {str(e)}" 53 54 55 def create_code_review_agent(llm: BaseLLM, verbose: bool = False) -> AgentExecutor: 56 """ 57 Create a code review specialized agent. 58 59 This agent is optimized for reviewing code quality, finding issues, 60 and providing constructive feedback. 61 62 Args: 63 llm: The language model to use 64 verbose: Show detailed reasoning 65 66 Returns: 67 AgentExecutor configured for code review 68 """ 69 tools = [ 70 Tool( 71 name="read_file", 72 func=read_file, 73 description="Read contents of a source file to review. Input should be the file path." 74 ), 75 Tool( 76 name="check_syntax", 77 func=check_python_syntax, 78 description="Check Python file for syntax errors. Input should be the file path." 79 ), 80 Tool( 81 name="count_lines", 82 func=count_lines_of_code, 83 description="Count lines of code, comments, and blanks. Input should be the file path." 84 ), 85 Tool( 86 name="list_directory", 87 func=list_directory, 88 description="List files in a directory to find files to review. Input should be directory path." 89 ), 90 Tool( 91 name="run_tests", 92 func=execute_shell_command, 93 description="Run tests or linters on the code. Input should be a shell command." 94 ), 95 ] 96 97 prompt = PromptTemplate.from_template(""" 98 You are a senior software engineer specialized in code review. 99 100 Your responsibilities: 101 - Review code for bugs, security issues, and bad practices 102 - Check code style and readability 103 - Suggest improvements and refactoring opportunities 104 - Verify test coverage 105 106 Review criteria: 107 ✅ Code correctness and logic 108 ✅ Error handling 109 ✅ Security vulnerabilities 110 ✅ Code style and readability 111 ✅ Performance considerations 112 ✅ Test coverage 113 114 Available tools: {tools} 115 116 Use the following format: 117 118 Question: {input} 119 Thought: I should analyze the code systematically 120 Action: [one of: {tool_names}] 121 Action Input: [input for the tool] 122 Observation: [tool result] 123 ... (repeat Thought/Action/Observation as needed) 124 Thought: I have completed the code review 125 Final Answer: [comprehensive review with specific recommendations] 126 127 Begin! 128 129 Question: {input} 130 Thought:{agent_scratchpad} 131 """) 132 133 agent = create_react_agent(llm, tools, prompt) 134 135 return AgentExecutor( 136 agent=agent, 137 tools=tools, 138 verbose=verbose, 139 handle_parsing_errors=True, 140 max_iterations=30, # Increased for complex code review tasks 141 early_stopping_method="generate" # Generate answer even if not complete 142 )