Code Analysis Agent

Automated code review with structured output, persistence, and API deployment

Diagram

Code Repository

Code Analyzer

Analysis Report

Analyze GitHub repos or local code: quality scoring, security review, architecture assessment. Includes SQLite persistence, structured Pydantic output, and API deployment.

Setup

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

# Install packages
pip install praisonaiagents praisonai gitingest

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

Create Sample Code

bash
# Create test directory with sample code
mkdir -p sample_project/src
cat > sample_project/src/main.py << 'EOF'
import os
from typing import List, Optional

class DataProcessor:
    def __init__(self, config: dict):
        self.config = config
        self.data = []

    def load_data(self, path: str) -> List[dict]:
        # TODO: Add error handling
        with open(path) as f:
            return eval(f.read())  # Security issue: eval

    def process(self, items: List[dict]) -> List[dict]:
        results = []
        for item in items:
            results.append(self._transform(item))
        return results

    def _transform(self, item: dict) -> dict:
        return {k: str(v).upper() for k, v in item.items()}

if __name__ == "__main__":
    dp = DataProcessor({})
    data = dp.load_data("data.json")
    print(dp.process(data))
EOF

Run: Python Code

python
from praisonaiagents import Agent, Task, AgentTeam, tool
from praisonaiagents.db import db
from pydantic import BaseModel
from typing import List, Dict
from gitingest import ingest
import json

# Structured output schema
class CodeAnalysisReport(BaseModel):
    overall_quality: int
    architecture_score: int
    maintainability_score: int
    security_score: int
    key_strengths: List[str]
    security_issues: List[str]
    recommendations: List[str]

# Database persistence is configured via memory={} parameter

# Code analyzer agent
analyzer = Agent(
    name="CodeAnalyzer",
    instructions="""Analyze code for quality, security, and best practices.
    Provide scores 0-100 and specific findings.""",
    memory={
        "db": "sqlite:///code_analysis.db",
        "session_id": "code-review-session"
    }
)

# Analysis task with structured output
analysis_task = Task(
    description="""Analyze this code repository:

{code_content}

Provide:
1. Overall quality score (0-100)
2. Architecture score
3. Maintainability score  
4. Security score
5. Key strengths (list)
6. Security issues found (list)
7. Recommendations (list)""",
    agent=analyzer,
    expected_output="Structured code analysis report",
    output_pydantic=CodeAnalysisReport
)

def analyze_code(source: str) -> CodeAnalysisReport:
    """Analyze code from path or GitHub URL."""
    summary, tree, content = ingest(source)
    code_content = f"STRUCTURE:\n{tree}\n\nCODE:\n{content[:10000]}"

    agents = AgentTeam(agents=[analyzer], tasks=[analysis_task])
    result = agents.start(code_content=code_content)
    return result

if __name__ == "__main__":
    # Analyze local directory
    report = analyze_code("./sample_project")
    print(json.dumps(report.model_dump() if hasattr(report, 'model_dump') else str(report), indent=2))

Run: CLI

bash
# Analyze with file input
praisonai "Analyze this code for security issues" --file ./sample_project/src/main.py

# With memory persistence
praisonai "Review code quality" --file ./sample_project --memory --user-id reviewer1

# With verbose output
praisonai "Find security vulnerabilities in this code" --file ./sample_project --verbose

Run: agents.yaml

Create agents.yaml:

yaml
framework: praisonai
topic: "code quality analysis"
roles:
  code_analyzer:
    role: Senior Code Reviewer
    goal: Analyze code for quality, security, and best practices
    backstory: Expert in code review with 15 years experience
    tasks:
      analyze_code:
        description: |
          Analyze the provided code for:
          - Code quality (0-100 score)
          - Security vulnerabilities
          - Best practices adherence
          - Recommendations for improvement
        expected_output: |
          JSON report with scores and findings

  security_auditor:
    role: Security Auditor
    goal: Find security vulnerabilities
    backstory: Cybersecurity expert specializing in code audits
    tasks:
      security_audit:
        description: |
          Perform security audit:
          - Injection vulnerabilities
          - Authentication issues
          - Data exposure risks
        expected_output: Security findings with severity levels

Run:

bash
praisonai agents.yaml --file ./sample_project --verbose

Monitor & Verify

bash
# View analysis history
praisonai --history 5 --user-id reviewer1

# Check metrics
praisonai --metrics

# Save results
praisonai --save code_review_results

Serve API

python
from praisonaiagents import Agent
from gitingest import ingest

agent = Agent(
    name="CodeReviewAPI",
    instructions="Analyze code for quality and security issues. Return structured JSON."
)

agent.launch(path="/analyze", port=8000)

Test:

bash
# Start server (in background)
python code_api.py &

# Test endpoint
curl -X POST http://localhost:8000/analyze \
  -H "Content-Type: application/json" \
  -d '{"message": "Analyze this Python code: def foo(): return eval(input())"}'

Cleanup

bash
rm -rf sample_project code_analysis.db
deactivate

Features Demonstrated

FeatureImplementation
Structured OutputPydantic CodeAnalysisReport
DB PersistenceSQLite via db()
External Toolgitingest for repo parsing
CLI--file flag for code input
YAML ConfigMulti-agent security audit
API Endpointagent.launch()
Session Resumesession_id parameter