Dalam Bahagian 1, kami membina alat analisis teras untuk penyemak kod kami. Kini kami akan mencipta pembantu AI yang boleh menggunakan alatan ini dengan berkesan. Kami akan meneliti setiap komponen langkah demi langkah, menerangkan cara semuanya berfungsi bersama.
Untuk dokumen ClientAI lihat di sini dan untuk Github Repo, di sini.
Pertama, kita perlu menyediakan alatan kita kepada sistem AI. Begini cara kami mendaftarkan mereka:
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"], ), ]
Mari kita pecahkan apa yang berlaku di sini:
Setiap alat dibalut dengan objek ToolConfig yang memberitahu ClientAI:
Kami mengelaskan alatan kami kepada dua kategori:
Sekarang mari buat pembantu AI kami. Kami akan mereka bentuknya supaya berfungsi mengikut langkah, meniru cara penilai kod manusia berfikir:
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 """
Kaedah pertama ini penting:
Seterusnya, kami menambah langkah cadangan penambahbaikan:
@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 """
Kaedah ini:
Sekarang mari buat antara muka yang mesra pengguna. Kami akan memecahkan ini kepada beberapa bahagian:
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 )
Bahagian pertama ini menyediakan pengelogan ralat, mengkonfigurasi pelayan Ollama dengan lalai yang wajar dan membenarkan penyesuaian penggunaan GPU dan CPU.
Seterusnya, kami mencipta klien dan pembantu 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 )
Perkara penting tentang persediaan ini:
Akhir sekali, kami mencipta gelung interaktif:
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"], ), ]
Antara muka ini:
Dan mari kita jadikan skrip yang boleh kita jalankan:
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 """
Mari lihat cara pembantu mengendalikan kod sebenar. Jom jalankan:
@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 """
Berikut ialah contoh dengan isu yang perlu dicari:
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 )
Pembantu akan menganalisis pelbagai aspek:
Berikut ialah beberapa cara untuk meningkatkan pembantu:
Setiap satu ini boleh ditambah dengan mencipta fungsi alat baharu, membungkusnya dalam pemformatan JSON yang sesuai, menambahkannya pada fungsi create_review_tools() dan kemudian mengemas kini gesaan pembantu untuk menggunakan alat baharu.
Untuk melihat lebih lanjut tentang ClientAI, pergi ke dokumen.
Jika anda mempunyai sebarang soalan, ingin membincangkan topik berkaitan teknologi atau berkongsi maklum balas anda, sila hubungi saya di media sosial:
Atas ialah kandungan terperinci Membina Penyemak Kod AI Tempatan dengan ClientAI dan Ollama - Bahagian 2. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!