Skip to main content
Multi-agent code review: analyze changes → detect issues → suggest fixes → apply automatically. Includes SQLite persistence, structured output, and API deployment.

Setup

# Create environment
python3 -m venv venv && source venv/bin/activate

# Install packages
pip install praisonaiagents praisonai

# Set API key
export OPENAI_API_KEY="your-key"

Create Sample Code

# Create code file to review
cat > review_target.py << 'EOF'
import os
import sys

def process_user_input(data):
    # Security issue: eval on user input
    result = eval(data)
    return result

def fetch_data(url):
    # No error handling
    import urllib.request
    response = urllib.request.urlopen(url)
    return response.read()

class DataManager:
    def __init__(self):
        self.items = []
    
    # Performance issue: inefficient loop
    def find_item(self, target):
        for i in range(len(self.items)):
            if self.items[i] == target:
                return i
        return -1
EOF

Run: Python Code

from praisonaiagents import Agent, Agents, Task, tool
from pydantic import BaseModel
from typing import List
import json

# Structured output
class CodeReviewResult(BaseModel):
    file_path: str
    issues_found: int
    critical_issues: List[str]
    suggestions: List[str]
    auto_fixable: bool

# Database persistence is configured via memory={} parameter

# Tools
@tool
def read_code_file(file_path: str) -> str:
    """Read a code file for review."""
    with open(file_path) as f:
        return f.read()

@tool
def check_security_issues(code: str) -> str:
    """Check code for security vulnerabilities."""
    issues = []
    if "eval(" in code:
        issues.append({"type": "security", "severity": "critical", "issue": "eval() on user input", "line": "eval(data)"})
    if "exec(" in code:
        issues.append({"type": "security", "severity": "critical", "issue": "exec() usage"})
    if "password" in code.lower() and "=" in code:
        issues.append({"type": "security", "severity": "high", "issue": "Hardcoded password"})
    return json.dumps(issues)

@tool
def check_performance_issues(code: str) -> str:
    """Check code for performance issues."""
    issues = []
    if "range(len(" in code:
        issues.append({"type": "performance", "severity": "medium", "issue": "Use enumerate() instead of range(len())"})
    if "for" in code and "+=" in code:
        issues.append({"type": "performance", "severity": "low", "issue": "Consider list comprehension"})
    return json.dumps(issues)

# Agents
analyzer = Agent(
    name="CodeAnalyzer",
    instructions="Read and analyze code files. Use read_code_file tool.",
    tools=[read_code_file],
    memory={
        "db": "sqlite:///code_reviews.db",
        "session_id": "code-review"
    }
)

security_checker = Agent(
    name="SecurityChecker",
    instructions="Check for security vulnerabilities. Use check_security_issues tool.",
    tools=[check_security_issues]
)

performance_checker = Agent(
    name="PerformanceChecker",
    instructions="Check for performance issues. Use check_performance_issues tool.",
    tools=[check_performance_issues]
)

# Tasks
read_task = Task(
    description="Read code from file: {file_path}",
    agent=analyzer,
    expected_output="Code content"
)

security_task = Task(
    description="Check the code for security vulnerabilities",
    agent=security_checker,
    expected_output="List of security issues"
)

performance_task = Task(
    description="Check the code for performance issues",
    agent=performance_checker,
    expected_output="List of performance issues"
)

# Run
agents = Agents(
    agents=[analyzer, security_checker, performance_checker],
    tasks=[read_task, security_task, performance_task]
)
result = agents.start(file_path="review_target.py")
print(result)

Run: CLI

# Review single file
praisonai "Review this code for security and performance issues" --file review_target.py --verbose

# With persistence
praisonai "Code review with fix suggestions" --file review_target.py --memory --user-id reviewer1

# Detailed analysis
praisonai "Find all bugs and security issues" --file review_target.py --verbose

Run: agents.yaml

Create agents.yaml:
framework: praisonai
topic: "automated code review"
roles:
  analyzer:
    role: Code Analyzer
    goal: Parse and understand code structure
    backstory: Expert at reading and understanding code
    tasks:
      analyze:
        description: Read and parse the code file
        expected_output: Code structure analysis
        
  security:
    role: Security Auditor
    goal: Find security vulnerabilities
    backstory: Cybersecurity expert
    tasks:
      audit:
        description: |
          Check for:
          - Injection vulnerabilities (eval, exec)
          - Hardcoded secrets
          - Input validation issues
        expected_output: Security findings with severity
        
  performance:
    role: Performance Analyst
    goal: Find performance issues
    backstory: Expert at code optimization
    tasks:
      optimize:
        description: |
          Check for:
          - Inefficient loops
          - Memory issues
          - Algorithm complexity
        expected_output: Performance recommendations
Run:
praisonai agents.yaml --file review_target.py --verbose

Monitor & Verify

# View review history
praisonai --history 10 --user-id reviewer1

# Check metrics
praisonai --metrics

# Export results
praisonai --save code_review_results

Serve API

from praisonaiagents import Agent, tool
import json

@tool
def quick_code_check(code: str) -> str:
    """Quick security and style check."""
    issues = []
    if "eval(" in code:
        issues.append({"severity": "critical", "issue": "eval() usage"})
    if "exec(" in code:
        issues.append({"severity": "critical", "issue": "exec() usage"})
    if "range(len(" in code:
        issues.append({"severity": "medium", "issue": "Use enumerate()"})
    
    return json.dumps({"issues": issues, "count": len(issues)})

agent = Agent(
    name="CodeReviewAPI",
    instructions="Review code for security and performance issues.",
    tools=[quick_code_check]
)

agent.launch(path="/review", port=8000)
Test:
curl -X POST http://localhost:8000/review \
  -H "Content-Type: application/json" \
  -d '{"message": "Review this code: result = eval(user_input)"}'

Cleanup

rm -f code_reviews.db review_target.py
deactivate

Features Demonstrated

FeatureImplementation
Multi-agentAnalyzer → Security → Performance
File Analysis@tool for file reading
Security ChecksVulnerability detection
DB PersistenceSQLite via db()
CLI--file for code input
YAML Config3-agent review pipeline
API Endpointagent.launch()
Session Resumesession_id parameter