在第 1 部分中,我们为代码审查器构建了核心分析工具。现在我们将创建一个可以有效使用这些工具的人工智能助手。我们将逐步介绍每个组件,解释所有组件如何协同工作。
有关 ClientAI 的文档,请参阅此处;有关 Github Repo,请参阅此处。
首先,我们需要让我们的工具可供人工智能系统使用。以下是我们注册它们的方法:
def create_review_tools() -> List[ToolConfig]: """Create the tool configurations for code review.""" return [ ToolConfig( tool=analyze_python_code, name="code_analyzer", description=( "Analyze Python code structure and complexity. " "Expects a 'code' parameter with the Python code as a string." ), scopes=["observe"], ), ToolConfig( tool=check_style_issues, name="style_checker", description=( "Check Python code style issues. " "Expects a 'code' parameter with the Python code as a string." ), scopes=["observe"], ), ToolConfig( tool=generate_docstring, name="docstring_generator", description=( "Generate docstring suggestions for Python code. " "Expects a 'code' parameter with the Python code as a string." ), scopes=["act"], ), ]
让我们来分解一下这里发生的事情:
每个工具都包装在一个 ToolConfig 对象中,该对象告诉 ClientAI:
我们将工具分为两类:
现在让我们创建我们的人工智能助手。我们将其设计为分步骤工作,模仿人类代码审查者的想法:
class CodeReviewAssistant(Agent): """An agent that performs comprehensive Python code review.""" @observe( name="analyze_structure", description="Analyze code structure and style", stream=True, ) def analyze_structure(self, code: str) -> str: """Analyze the code structure, complexity, and style issues.""" self.context.state["code_to_analyze"] = code return """ Please analyze this Python code structure and style: The code to analyze has been provided in the context as 'code_to_analyze'. Use the code_analyzer and style_checker tools to evaluate: 1. Code complexity and structure metrics 2. Style compliance issues 3. Function and class organization 4. Import usage patterns """
第一个方法至关重要:
接下来,我们添加改进建议步骤:
@think( name="suggest_improvements", description="Suggest code improvements based on analysis", stream=True, ) def suggest_improvements(self, analysis_result: str) -> str: """Generate improvement suggestions based on the analysis results.""" current_code = self.context.state.get("current_code", "") return f""" Based on the code analysis of: ``` {% endraw %} python {current_code} {% raw %} ``` And the analysis results: {analysis_result} Please suggest specific improvements for: 1. Reducing complexity where identified 2. Fixing style issues 3. Improving code organization 4. Optimizing import usage 5. Enhancing readability 6. Enhancing explicitness """
这个方法:
现在让我们创建一个用户友好的界面。我们将其分解为几个部分:
def main(): # 1. Set up logging logger = logging.getLogger(__name__) # 2. Configure Ollama server config = OllamaServerConfig( host="127.0.0.1", # Local machine port=11434, # Default Ollama port gpu_layers=35, # Adjust based on your GPU cpu_threads=8, # Adjust based on your CPU )
第一部分设置错误日志记录,使用合理的默认值配置 Ollama 服务器,并允许自定义 GPU 和 CPU 使用情况。
接下来,我们创建AI客户端和助手:
# Use context manager for Ollama server with OllamaManager(config) as manager: # Initialize ClientAI with Ollama client = ClientAI( "ollama", host=f"http://{config.host}:{config.port}" ) # Create code review assistant with tools assistant = CodeReviewAssistant( client=client, default_model="llama3", tools=create_review_tools(), tool_confidence=0.8, # How confident the AI should be before using tools max_tools_per_step=2, # Maximum tools to use per step )
此设置的要点:
最后,我们创建交互式循环:
def create_review_tools() -> List[ToolConfig]: """Create the tool configurations for code review.""" return [ ToolConfig( tool=analyze_python_code, name="code_analyzer", description=( "Analyze Python code structure and complexity. " "Expects a 'code' parameter with the Python code as a string." ), scopes=["observe"], ), ToolConfig( tool=check_style_issues, name="style_checker", description=( "Check Python code style issues. " "Expects a 'code' parameter with the Python code as a string." ), scopes=["observe"], ), ToolConfig( tool=generate_docstring, name="docstring_generator", description=( "Generate docstring suggestions for Python code. " "Expects a 'code' parameter with the Python code as a string." ), scopes=["act"], ), ]
此界面:
让我们将其设为我们能够运行的脚本:
class CodeReviewAssistant(Agent): """An agent that performs comprehensive Python code review.""" @observe( name="analyze_structure", description="Analyze code structure and style", stream=True, ) def analyze_structure(self, code: str) -> str: """Analyze the code structure, complexity, and style issues.""" self.context.state["code_to_analyze"] = code return """ Please analyze this Python code structure and style: The code to analyze has been provided in the context as 'code_to_analyze'. Use the code_analyzer and style_checker tools to evaluate: 1. Code complexity and structure metrics 2. Style compliance issues 3. Function and class organization 4. Import usage patterns """
让我们看看助手如何处理真实的代码。让我们运行一下:
@think( name="suggest_improvements", description="Suggest code improvements based on analysis", stream=True, ) def suggest_improvements(self, analysis_result: str) -> str: """Generate improvement suggestions based on the analysis results.""" current_code = self.context.state.get("current_code", "") return f""" Based on the code analysis of: ``` {% endraw %} python {current_code} {% raw %} ``` And the analysis results: {analysis_result} Please suggest specific improvements for: 1. Reducing complexity where identified 2. Fixing style issues 3. Improving code organization 4. Optimizing import usage 5. Enhancing readability 6. Enhancing explicitness """
这是一个需要查找问题的示例:
def main(): # 1. Set up logging logger = logging.getLogger(__name__) # 2. Configure Ollama server config = OllamaServerConfig( host="127.0.0.1", # Local machine port=11434, # Default Ollama port gpu_layers=35, # Adjust based on your GPU cpu_threads=8, # Adjust based on your CPU )
小助手会多方面分析:
以下是增强助手的一些方法:
通过创建新的工具函数,将其包装为适当的 JSON 格式,将其添加到 create_review_tools() 函数,然后更新助手的提示以使用新工具,可以添加其中的每一个。
要了解有关 ClientAI 的更多信息,请访问文档。
如果您有任何疑问,想要讨论技术相关主题或分享您的反馈,请随时在社交媒体上与我联系:
以上是使用 ClientAI 和 Ollama 构建本地 AI 代码审查器 - 第 2 部分的详细内容。更多信息请关注PHP中文网其他相关文章!