Back to Hello Agents

CodeReviewAgent - 智能代码审查助手

Co-creation-projects/jjyaoao-CodeReviewAgent/main.ipynb

1.0.28.5 KB
Original Source

CodeReviewAgent - 智能代码审查助手

本项目演示如何使用HelloAgents框架构建一个智能代码审查助手。

📖 使用说明

  • 快速体验: 运行「第0部分」的快速演示
  • 完整功能: 依次运行第1-7部分,体验完整的代码审查流程

第0部分:快速演示 ⚡

如果你想快速了解项目功能,可以运行这个简化版本。

python
# 快速演示 - 导入库和配置
from hello_agents import SimpleAgent, HelloAgentsLLM
from hello_agents.tools import Tool, ToolParameter
from typing import Dict, Any, List
import ast
import os

# 配置LLM参数
os.environ["LLM_MODEL_ID"] = "Qwen/Qwen2.5-72B-Instruct"
os.environ["LLM_API_KEY"] = "your_api_key_here"
os.environ["LLM_BASE_URL"] = "https://api-inference.modelscope.cn/v1/"
os.environ["LLM_TIMEOUT"] = "60"

print("✅ 库导入和配置完成")
python
# 快速演示 - 定义简单的代码分析工具
class QuickAnalysisTool(Tool):
    def __init__(self):
        super().__init__(
            name="quick_analysis",
            description="快速分析Python代码结构"
        )
    
    def run(self, parameters: Dict[str, Any]) -> str:
        code = parameters.get("code", "")
        if not code:
            return "错误:代码不能为空"
        
        try:
            tree = ast.parse(code)
            functions = [n.name for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)]
            classes = [n.name for n in ast.walk(tree) if isinstance(n, ast.ClassDef)]
            return f"发现{len(classes)}个类、{len(functions)}个函数: {', '.join(functions)}"
        except Exception as e:
            return f"代码解析失败: {str(e)}"
    
    def get_parameters(self) -> List[ToolParameter]:
        return [
            ToolParameter(
                name="code",
                type="string",
                description="要分析的Python代码",
                required=True
            )
        ]

print("✅ 工具定义完成")
python
# 快速演示 - 创建工具注册表和智能体
from hello_agents import ToolRegistry

# 创建工具注册表
quick_registry = ToolRegistry()
quick_registry.register_tool(QuickAnalysisTool())

# 创建智能体
quick_agent = SimpleAgent(
    name="快速审查助手",
    llm=HelloAgentsLLM(),
    system_prompt="你是代码审查助手,使用工具分析代码并给出简要建议。",
    tool_registry=quick_registry
)

print("✅ 智能体创建完成")
print(f"✅ 可用工具: {list(quick_registry._tools.keys())}")
python
# 快速演示 - 测试代码
test_code = """
def hello():
    print("Hello")

def world():
    print("World")

class Greeter:
    def greet(self):
        hello()
        world()
"""

print("=== 快速演示:分析测试代码 ===")
result = quick_agent.run(f"请分析这段代码:\n{test_code}")
print(result)
print("\n✅ 快速演示完成!")
print("\n💡 提示:继续运行下面的单元格,体验完整功能")

完整版代码审查系统

下面是完整的代码审查系统,包含更强大的分析功能。

第1部分:环境配置

python
# 导入必要的库
from hello_agents import SimpleAgent, HelloAgentsLLM
from hello_agents.tools import Tool, ToolParameter
from typing import Dict, Any, List
import ast
import os

# 配置LLM参数
os.environ["LLM_MODEL_ID"] = "Qwen/Qwen2.5-72B-Instruct"
os.environ["LLM_API_KEY"] = "your_api_key_here"
os.environ["LLM_BASE_URL"] = "https://api-inference.modelscope.cn/v1/"
os.environ["LLM_TIMEOUT"] = "60"

print("✅ 环境配置完成")
print(f"✅ 使用模型: {os.getenv('LLM_MODEL_ID')}")
print(f"✅ API地址: {os.getenv('LLM_BASE_URL')}")

第2部分:定义代码分析工具

python
class CodeAnalysisTool(Tool):
    """代码静态分析工具"""

    def __init__(self):
        super().__init__(
            name="code_analysis",
            description="分析Python代码的结构、复杂度和潜在问题"
        )

    def run(self, parameters: Dict[str, Any]) -> str:
        """分析代码并返回结果"""
        code = parameters.get("code", "")
        if not code:
            return "错误:代码不能为空"
        
        try:
            tree = ast.parse(code)

            # 统计信息
            functions = [node for node in ast.walk(tree) if isinstance(node, ast.FunctionDef)]
            classes = [node for node in ast.walk(tree) if isinstance(node, ast.ClassDef)]

            result = {
                "函数数量": len(functions),
                "类数量": len(classes),
                "代码行数": len(code.split('\n')),
                "函数列表": [f.name for f in functions],
                "类列表": [c.name for c in classes]
            }

            return str(result)
        except SyntaxError as e:
            return f"语法错误:{str(e)}"
    
    def get_parameters(self) -> List[ToolParameter]:
        return [
            ToolParameter(
                name="code",
                type="string",
                description="要分析的Python代码",
                required=True
            )
        ]

print("✅ CodeAnalysisTool定义完成")
python
class StyleCheckTool(Tool):
    """代码风格检查工具"""

    def __init__(self):
        super().__init__(
            name="style_check",
            description="检查代码是否符合PEP 8规范"
        )

    def run(self, parameters: Dict[str, Any]) -> str:
        """检查代码风格"""
        code = parameters.get("code", "")
        if not code:
            return "错误:代码不能为空"
        
        issues = []

        lines = code.split('\n')
        for i, line in enumerate(lines, 1):
            # 检查行长度
            if len(line) > 79:
                issues.append(f"第{i}行:超过79个字符")

            # 检查缩进
            if line.startswith(' ') and not line.startswith('    '):
                if len(line) - len(line.lstrip()) not in [0, 4, 8, 12]:
                    issues.append(f"第{i}行:缩进不规范")

        if not issues:
            return "代码风格良好,符合PEP 8规范"
        return "发现以下问题:\n" + "\n".join(issues)
    
    def get_parameters(self) -> List[ToolParameter]:
        return [
            ToolParameter(
                name="code",
                type="string",
                description="要检查的Python代码",
                required=True
            )
        ]

print("✅ StyleCheckTool定义完成")

第3部分:创建智能体

python
# 导入工具注册表
from hello_agents import ToolRegistry

# 创建工具注册表
tool_registry = ToolRegistry()
tool_registry.register_tool(CodeAnalysisTool())
tool_registry.register_tool(StyleCheckTool())

# 初始化LLM
llm = HelloAgentsLLM()

# 定义系统提示词
system_prompt = """你是一位经验丰富的代码审查专家。你的任务是:

1. 使用code_analysis工具分析代码结构
2. 使用style_check工具检查代码风格
3. 基于分析结果,提供详细的审查报告

审查报告应包括:
- 代码结构分析
- 风格问题
- 潜在bug
- 性能优化建议
- 最佳实践建议

请以Markdown格式输出报告。"""

# 创建智能体
agent = SimpleAgent(
    name="代码审查助手",
    llm=llm,
    system_prompt=system_prompt,
    tool_registry=tool_registry
)

print("✅ 智能体创建完成")
print(f"智能体名称: {agent.name}")
print(f"可用工具: {list(tool_registry._tools.keys())}")

第4部分:读取示例代码

python
# 读取示例代码
with open("data/sample_code.py", "r", encoding="utf-8") as f:
    sample_code = f.read()

print("=== 待审查的代码 ===")
print(sample_code)
print("\n" + "="*50 + "\n")

第5部分:执行代码审查

python
# 执行代码审查
print("=== 开始代码审查 ===")
review_result = agent.run(f"请审查以下Python代码:\n\n```python\n{sample_code}\n```")

print(review_result)

第6部分:保存审查报告

python
# 保存审查报告
with open("outputs/review_report.md", "w", encoding="utf-8") as f:
    f.write(review_result)

print("\n✅ 审查报告已保存到 outputs/review_report.md")

第7部分:总结与展望

实现的功能

  • ✅ 代码结构分析
  • ✅ PEP 8风格检查
  • ✅ 智能审查报告生成

遇到的挑战

  • 如何准确解析Python代码结构
  • 如何设计合理的提示词让LLM生成高质量报告

未来改进方向

  • 支持更多编程语言
  • 添加安全漏洞检测
  • 集成更多静态分析工具
  • 支持批量文件审查