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

wufei123 2025-01-05 阅读:41 评论:0
在第 1 部分中,我们为代码审查器构建了核心分析工具。现在我们将创建一个可以有效使用这些工具的人工智能助手。我们将逐步介绍每个组件,解释所有组件如何协同工作。 有关 clientai 的文档,请参阅此处;有关 github repo,请...

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

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

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

系列索引
  • 第 1 部分:简介、设置、工具创建
  • 第 2 部分:构建助手和命令行界面(你在这里)
使用 clientai 注册我们的工具

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

PHP
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助手类

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

PHP
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使用我们的工具的提示

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

PHP
    @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来表明这是一个推理步骤
  • 将分析结果作为输入
  • 从上下文中检索原始代码
  • 创建改进建议的结构化提示
命令行界面

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

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

PHP
    # 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 实例
  • 助手配置有:
    • 我们的定制工具
    • 工具使用的置信度阈值
    • 每个步骤的工具限制,以防止过度使用

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

PHP
        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.")

此界面:

  • 收集多行代码输入,直到看到“###”
  • 处理流式和非流式输出
  • 提供干净的错误处理
  • 允许通过“退出”轻松退出

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

PHP
if __name__ == "__main__":
    main()
使用助手

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

PHP
python code_analyzer.py

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

PHP
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
  • 领英:伊戈尔

以上就是使用 ClientAI 和 Ollama 构建本地 AI 代码审查器 - 第 2 部分的详细内容,更多请关注知识资源分享宝库其它相关文章!

版权声明

本站内容来源于互联网搬运,
仅限用于小范围内传播学习,请在下载后24小时内删除,
如果有侵权内容、不妥之处,请第一时间联系我们删除。敬请谅解!
E-mail:dpw1001@163.com

分享:

扫一扫在手机阅读、分享本文

发表评论
热门文章
  • BioWare埃德蒙顿工作室面临关闭危机,龙腾世纪制作总监辞职引关注(龙腾.总监.辞职.危机.面临.....)

    BioWare埃德蒙顿工作室面临关闭危机,龙腾世纪制作总监辞职引关注(龙腾.总监.辞职.危机.面临.....)
    知名变性人制作总监corrine busche离职bioware,引发业界震荡!外媒“smash jt”独家报道称,《龙腾世纪:影幢守护者》制作总监corrine busche已离开bioware,此举不仅引发了关于个人职业发展方向的讨论,更因其可能预示着bioware埃德蒙顿工作室即将关闭而备受关注。本文将深入分析busche离职的原因及其对bioware及游戏行业的影响。 Busche的告别信:挑战与感激并存 据“Smash JT”获得的内部邮件显示,Busche离职原...
  • 闪耀暖暖靡城永恒怎么样-闪耀暖暖靡城永恒套装介绍(闪耀.暖暖.套装.介绍.....)

    闪耀暖暖靡城永恒怎么样-闪耀暖暖靡城永恒套装介绍(闪耀.暖暖.套装.介绍.....)
    闪耀暖暖钻石竞技场第十七赛季“华梦泡影”即将开启!全新闪耀性感套装【靡城永恒】震撼来袭!想知道如何获得这套精美套装吗?快来看看吧! 【靡城永恒】套装设计理念抢先看: 设计灵感源于夜色中的孤星,象征着淡然、漠视一切的灰色瞳眸。设计师希望通过这套服装,展现出在虚幻与真实交织的夜幕下,一种独特的魅力。 服装细节考究,从面料的光泽、鞋跟声响到裙摆的弧度,都力求完美还原设计初衷。 【靡城永恒】套装设计亮点: 闪耀的绸缎与金丝交织,轻盈的羽毛增添华贵感。 这套服装仿佛是从无尽的黑...
  • python怎么调用其他文件函数

    python怎么调用其他文件函数
    在 python 中调用其他文件中的函数,有两种方式:1. 使用 import 语句导入模块,然后调用 [模块名].[函数名]();2. 使用 from ... import 语句从模块导入特定函数,然后调用 [函数名]()。 如何在 Python 中调用其他文件中的函数 在 Python 中,您可以通过以下两种方式调用其他文件中的函数: 1. 使用 import 语句 优点:简单且易于使用。 缺点:会将整个模块导入到当前作用域中,可能会导致命名空间混乱。 步骤:...
  • 斗魔骑士哪个角色强势-斗魔骑士角色推荐与实力解析(骑士.角色.强势.解析.实力.....)

    斗魔骑士哪个角色强势-斗魔骑士角色推荐与实力解析(骑士.角色.强势.解析.实力.....)
    斗魔骑士角色选择及战斗策略指南 斗魔骑士游戏中,众多角色各具特色,选择适合自己的角色才能在战斗中占据优势。本文将为您详细解读如何选择强力角色,并提供团队协作及角色培养策略。 如何选择强力角色? 斗魔骑士的角色大致分为近战和远程两种类型。近战角色通常拥有高攻击力和防御力,适合冲锋陷阵;远程角色则擅长后方输出,并依靠灵活走位躲避攻击。 选择角色时,需根据个人游戏风格和喜好决定。喜欢正面硬刚的玩家可以选择战士型角色,其高生命值和防御力能承受更多伤害;偏好策略性玩法的玩家则可以选择法...
  • 奇迹暖暖诸星梦眠怎么样-奇迹暖暖诸星梦眠套装介绍(星梦.暖暖.奇迹.套装.介绍.....)

    奇迹暖暖诸星梦眠怎么样-奇迹暖暖诸星梦眠套装介绍(星梦.暖暖.奇迹.套装.介绍.....)
    奇迹暖暖全新活动“失序之圜”即将开启,参与活动即可获得精美套装——诸星梦眠!想知道这套套装的细节吗?一起来看看吧! 奇迹暖暖诸星梦眠套装详解 “失序之圜”活动主打套装——诸星梦眠,高清海报震撼公开!少女在无垠梦境中,接受星辰的邀请,馥郁芬芳,预示着命运之花即将绽放。 诸星梦眠套装包含:全新妆容“隽永之梦”、星光面饰“熠烁星光”、动态特姿连衣裙“诸星梦眠”、动态特姿发型“金色绮想”、精美特效皇冠“繁星加冕”,以及动态摆件“芳馨酣眠”、“沉云余音”、“流星低语”、“葳蕤诗篇”。...