PHP前端开发

使用 ClientAI 和 Ollama 构建本地 AI 代码审查器 - 第 2 部分

百变鹏仔 5天前 #Python
文章标签 代码

在第 1 部分中,我们为代码审查器构建了核心分析工具。现在我们将创建一个可以有效使用这些工具的人工智能助手。我们将逐步介绍每个组件,解释所有组件如何协同工作。

有关 clientai 的文档,请参阅此处;有关 github repo,请参阅此处。

系列索引

使用 clientai 注册我们的工具

首先,我们需要让我们的工具可供人工智能系统使用。以下是我们注册它们的方法:

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"],        ),    ]

让我们来分解一下这里发生的事情:

  1. 每个工具都包装在一个 toolconfig 对象中,该对象告诉 clientai:

  2. 我们将工具分为两类:

构建ai助手类

现在让我们创建我们的人工智能助手。我们将其设计为分步骤工作,模仿人类代码审查者的想法:

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        )

此设置的要点:

最后,我们创建交互式循环:

        print("code review assistant (local ai)")        print("enter python code to review, or 'quit' to exit.")        print("end input with '###' on a new line.")        while true:            try:                print("" + "=" * 50 + "")                print("enter code:")                # collect code input                code_lines = []                while true:                    line = input()                    if line == "###":                        break                    code_lines.append(line)                code = "".join(code_lines)                if code.lower() == "quit":                    break                # process the code                result = assistant.run(code, stream=true)                # handle both streaming and non-streaming results                if isinstance(result, str):                    print(result)                else:                    for chunk in result:                        print(chunk, end="", flush=true)                print("")            except exception as e:                logger.error(f"unexpected error: {e}")                print("an unexpected error occurred. please try again.")

此界面:

让我们将其设为我们能够运行的脚本:

if __name__ == "__main__":    main()

使用助手

让我们看看助手如何处理真实的代码。让我们运行一下:

python code_analyzer.py

这是一个需要查找问题的示例:

def calculate_total(values,tax_rate):    Total = 0    for Val in values:        if Val > 0:            if tax_rate > 0:                Total += Val + (Val * tax_rate)            else:                Total += Val    return Total

小助手会多方面分析:

扩展思路

以下是增强助手的一些方法:

通过创建新的工具函数,将其包装为适当的 json 格式,将其添加到 create_review_tools() 函数,然后更新助手的提示以使用新工具,可以添加其中的每一个。

要了解有关 clientai 的更多信息,请访问文档。

与我联系

如果您有任何疑问,想要讨论技术相关主题或分享您的反馈,请随时在社交媒体上与我联系: