0

0

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

心靈之曲

心靈之曲

发布时间:2024-12-17 14:33:10

|

656人浏览过

|

来源于dev.to

转载

使用 clientai 和 ollama 构建本地 ai 代码审查器 - 第 2 部分

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

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

系列索引

  • 第 1 部分:简介、设置、工具创建
  • 第 2 部分:构建助手和命令行界面(你在这里)

使用 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. 我们将工具分为两类:

    • “观察”工具(code_analyzer 和 style_checker)收集信息
    • “act”工具(docstring_generator)产生新内容

构建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
        """

第一个方法至关重要:

  • @observe 装饰器将其标记为观察步骤
  • stream=true 启用实时输出
  • 我们将代码存储在上下文中,以便在后续步骤中访问它
  • 返回字符串是指导ai使用我们的工具的提示

接下来,我们添加改进建议步骤:

    @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
        """

这个方法:

  • 使用@think来表明这是一个推理步骤
  • 将分析结果作为输入
  • 从上下文中检索原始代码
  • 创建改进建议的结构化提示

命令行界面

现在让我们创建一个用户友好的界面。我们将其分解为几个部分:

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客户端和助手:

sematic
sematic

一个开源的机器学习平台

下载
    # 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
        )

此设置的要点:

  • 上下文管理器(with)确保正确的服务器清理
  • 我们连接到本地 ollama 实例
  • 助手配置有:
    • 我们的定制工具
    • 工具使用的置信度阈值
    • 每个步骤的工具限制,以防止过度使用

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

        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("\n" + "=" * 50 + "\n")
                print("enter code:")

                # collect code input
                code_lines = []
                while true:
                    line = input()
                    if line == "###":
                        break
                    code_lines.append(line)

                code = "\n".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("\n")

            except exception as e:
                logger.error(f"unexpected error: {e}")
                print("\nan 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

小助手会多方面分析:

  • 结构问题(嵌套 if 语句增加复杂性、缺少类型提示、无输入验证)
  • 样式问题(变量命名不一致、逗号后缺少空格、缺少文档字符串)

扩展思路

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

  • 其他分析工具
  • 增强的样式检查
  • 文档改进
  • 自动修复功能

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

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

与我联系

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

  • github:igorbenav
  • x/twitter:@igorbenav
  • 领英:伊戈尔

相关专题

更多
json数据格式
json数据格式

JSON是一种轻量级的数据交换格式。本专题为大家带来json数据格式相关文章,帮助大家解决问题。

402

2023.08.07

json是什么
json是什么

JSON是一种轻量级的数据交换格式,具有简洁、易读、跨平台和语言的特点,JSON数据是通过键值对的方式进行组织,其中键是字符串,值可以是字符串、数值、布尔值、数组、对象或者null,在Web开发、数据交换和配置文件等方面得到广泛应用。本专题为大家提供json相关的文章、下载、课程内容,供大家免费下载体验。

528

2023.08.23

jquery怎么操作json
jquery怎么操作json

操作的方法有:1、“$.parseJSON(jsonString)”2、“$.getJSON(url, data, success)”;3、“$.each(obj, callback)”;4、“$.ajax()”。更多jquery怎么操作json的详细内容,可以访问本专题下面的文章。

306

2023.10.13

go语言处理json数据方法
go语言处理json数据方法

本专题整合了go语言中处理json数据方法,阅读专题下面的文章了解更多详细内容。

74

2025.09.10

if什么意思
if什么意思

if的意思是“如果”的条件。它是一个用于引导条件语句的关键词,用于根据特定条件的真假情况来执行不同的代码块。本专题提供if什么意思的相关文章,供大家免费阅读。

711

2023.08.22

mysql标识符无效错误怎么解决
mysql标识符无效错误怎么解决

mysql标识符无效错误的解决办法:1、检查标识符是否被其他表或数据库使用;2、检查标识符是否包含特殊字符;3、使用引号包裹标识符;4、使用反引号包裹标识符;5、检查MySQL的配置文件等等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

178

2023.12.04

Python标识符有哪些
Python标识符有哪些

Python标识符有变量标识符、函数标识符、类标识符、模块标识符、下划线开头的标识符、双下划线开头、双下划线结尾的标识符、整型标识符、浮点型标识符等等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

271

2024.02.23

java标识符合集
java标识符合集

本专题整合了java标识符相关内容,想了解更多详细内容,请阅读下面的文章。

250

2025.06.11

vlookup函数使用大全
vlookup函数使用大全

本专题整合了vlookup函数相关 教程,阅读专题下面的文章了解更多详细内容。

28

2025.12.30

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 0.6万人学习

Django 教程
Django 教程

共28课时 | 2.6万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.0万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号