在第 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中文網其他相關文章!