在第 1 部分中,我们为代码审查器构建了核心分析工具。现在我们将创建一个可以有效使用这些工具的人工智能助手。我们将逐步介绍每个组件,解释所有组件如何协同工作。
有关 clientai 的文档,请参阅此处;有关 github repo,请参阅此处。
系列索引- 第 1 部分:简介、设置、工具创建
- 第 2 部分:构建助手和命令行界面(你在这里)
首先,我们需要让我们的工具可供人工智能系统使用。以下是我们注册它们的方法:
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:
- 工具:实际调用的函数
- 名称:工具的唯一标识符
- 描述:该工具的用途以及它需要哪些参数
- 范围:工具何时可以使用(“观察”用于分析,“行动”用于生成)
-
我们将工具分为两类:
- “观察”工具(code_analyzer 和 style_checker)收集信息
- “act”工具(docstring_generator)产生新内容
现在让我们创建我们的人工智能助手。我们将其设计为分步骤工作,模仿人类代码审查者的想法:
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客户端和助手:
# 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("
" + "=" * 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
小助手会多方面分析:
- 结构问题(嵌套 if 语句增加复杂性、缺少类型提示、无输入验证)
- 样式问题(变量命名不一致、逗号后缺少空格、缺少文档字符串)
以下是增强助手的一些方法:
- 其他分析工具
- 增强的样式检查
- 文档改进
- 自动修复功能
通过创建新的工具函数,将其包装为适当的 json 格式,将其添加到 create_review_tools() 函数,然后更新助手的提示以使用新工具,可以添加其中的每一个。
要了解有关 clientai 的更多信息,请访问文档。
与我联系如果您有任何疑问,想要讨论技术相关主题或分享您的反馈,请随时在社交媒体上与我联系:
- github:igorbenav
- x/twitter:@igorbenav
- 领英:伊戈尔
以上就是使用 ClientAI 和 Ollama 构建本地 AI 代码审查器 - 第 2 部分的详细内容,更多请关注知识资源分享宝库其它相关文章!
版权声明
本站内容来源于互联网搬运,
仅限用于小范围内传播学习,请在下载后24小时内删除,
如果有侵权内容、不妥之处,请第一时间联系我们删除。敬请谅解!
E-mail:dpw1001@163.com
发表评论