Skip to main content

AI-powered code reviewer using OpenRouter LLMs

Project description

Iara - AI Code Reviewer 🧜‍♀️

Iara é uma ferramenta de revisão de código automatizada, agnóstica a projetos e configurável, projetada para rodar em pipelines de CI/CD ou localmente via CLI. Ela utiliza a API OpenRouter para acessar diversos modelos de LLM (Llama 3, Gemini 2.0, etc.) gratuitamente ou em planos pagos.

🚀 Funcionalidades

  • Agnóstica: Configure o contexto do seu projeto (Tech Stack, Regras) via JSON.
  • Multi-Modelo: Suporte a múltiplos provedores via OpenRouter.
  • Fallback Inteligente: Tenta modelos gratuitos automaticamente se o preferido falhar.
  • Rules-Based (Estático): Identifica padrões perigosos instantaneamente sem gastar tokens (ex: GetComponent em loops no Unity).
  • LLM-Based (Inteligente): Usa IA para entender a lógica, segurança e contexto, indo além da sintaxe.
  • GitHub + GitLab: Integração nativa com ambas as plataformas, com comentários automáticos em PRs/MRs.

🧠 Capacidades

A Iara combina diferentes tipos de análise para uma revisão completa:

Tipo O que faz? A Iara cobre? Como?
Análise Estática Caça bugs lendo o código (rápido). Sim Via Extensões (Regex) e LLM.
Linting Corrige estilo e formatação. Sim LLM pode sugerir Clean Code.
SAST Caça falhas de segurança no código. Sim Foco primário na busca por vulnerabilidades.
Análise Dinâmica Caça bugs rodando o app (lento). ❌ Não Foco em CI/CD rápido (Code Review).

O que ela detecta?

  1. Unity / Game Dev:

    • Uso de APIs lentas (Find, GetComponent) em loops críticos (Update).
    • Alocação excessiva de memória (Garbage Collection).
    • Excesso de logs (Debug.Log) em builds finais.
  2. Segurança (Geral):

    • Credenciais hardcoded (Senhas, API Keys).
    • Vulnerabilidades de Injeção (SQL, Command).
    • Falta de validação de inputs.
  3. Qualidade de Código:

    • Lógica complexa ou confusa.
    • Erros de tratamento de exceções.
    • Sugestões de refatoração para legibilidade.

📦 Instalação e Setup

1. Instalar

pip install iara-reviewer

2. Configurar (Setup Interativo)

iara init

O wizard vai guiar você em 3 passos:

  • API Key — Pede sua chave OpenRouter (gratuita em openrouter.ai/keys), valida e salva
  • Projeto — Nome, tech stack, descrição
  • Preferências — Áreas de foco (Security, Performance, etc.)

Pronto! A API key fica salva em ~/.iara/config.json e o projeto em .iara.json.

3. Usar

git diff main | iara

Verificar autenticação

iara auth status

Setup alternativo (sem wizard)

Se preferir configurar manualmente:

# Linux/Mac
export OPENROUTER_API_KEY="sk-or-..."

# Windows (PowerShell)
$env:OPENROUTER_API_KEY="sk-or-..."

A prioridade de resolução da API key é: variável de ambiente > config global (~/.iara/config.json).

Via clone (Desenvolvimento)

git clone https://github.com/felipefernandes/iara.git
cd iara
pip install -e .

⚙️ Configuração do Projeto

O iara init cria automaticamente o .iara.json. Você também pode criá-lo manualmente:

{
  "project": {
    "name": "Meu Projeto",
    "description": "Descrição do projeto.",
    "tech_stack": ["Python"]
  },
  "review": {
    "focus_areas": ["Performance", "Security"],
    "ignore_patterns": []
  },
  "model": {
    "preferred": "google/gemini-2.0-flash-exp:free",
    "fallback_enabled": true
  }
}

Exemplo pronto disponível em iara-example.json.


🏃 Como Usar

Via Pipe (Git Diff)

git diff main | iara

Via Variável de Ambiente

export PR_DIFF=$(git diff main)
iara

Modo Scan (Análise Estática)

iara --scan ./caminho/do/projeto

Forçando um Modelo

export IARA_MODEL="meta-llama/llama-3.2-3b-instruct:free"
git diff | iara

🐙 Integração GitHub

Adicione a Iara ao seu repositório GitHub em 2 passos:

1. Configurar o secret

Vá em Settings > Secrets and variables > Actions > New repository secret e adicione:

  • Nome: OPENROUTER_API_KEY
  • Valor: sua chave da API OpenRouter

2. Criar o workflow

Crie o arquivo .github/workflows/iara-review.yml:

name: Iara Code Review

on:
  pull_request:
    types: [opened, synchronize]

permissions:
  pull-requests: write
  contents: read

jobs:
  review:
    runs-on: ubuntu-latest
    name: AI Code Review
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Run Iara Code Review
        uses: felipefernandes/iara@v1
        with:
          openrouter_api_key: ${{ secrets.OPENROUTER_API_KEY }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

A Iara vai automaticamente:

  • Revisar o diff do Pull Request
  • Postar um comentário com o resultado da review

Opções adicionais

- uses: felipefernandes/iara@v1
  with:
    openrouter_api_key: ${{ secrets.OPENROUTER_API_KEY }}
    model: 'google/gemini-2.0-flash-exp:free'   # Forçar modelo
    config_path: '.iara.json'                     # Caminho do config
    post_comment: 'true'                          # Postar comentário (default: true)

🦊 Integração GitLab

1. Configurar variáveis

Vá em Settings > CI/CD > Variables e adicione:

  • OPENROUTER_API_KEY: Chave da API OpenRouter
  • GITLAB_TOKEN: Personal/Project Access Token com scope api (necessário para comentários no MR)

2. Adicionar ao .gitlab-ci.yml

stages:
  - review

iara_code_review:
  stage: review
  image: python:3.11-slim
  script:
    - apt-get update && apt-get install -y --no-install-recommends git curl
    - pip install iara-reviewer
    - git fetch origin $CI_MERGE_REQUEST_TARGET_BRANCH_NAME
    - export PR_DIFF=$(git diff origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME...$CI_COMMIT_SHA)
    - REVIEW=$(iara 2>/tmp/iara_stderr.txt) || true
    - echo "$REVIEW"
    - |
      if [ -n "$REVIEW" ] && [ -n "$GITLAB_TOKEN" ]; then
        PAYLOAD=$(python3 -c "
      import sys, json
      review = '''$REVIEW'''
      body = '## 🧜‍♀️ Iara Code Review\n\n' + review + '\n\n---\n*Reviewed by Iara - AI Code Reviewer*'
      print(json.dumps({'body': body}))
      ")
        curl -s -X POST \
          -H "PRIVATE-TOKEN: $GITLAB_TOKEN" \
          -H "Content-Type: application/json" \
          -d "$PAYLOAD" \
          "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/merge_requests/${CI_MERGE_REQUEST_IID}/notes"
      fi
  allow_failure: true
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"

A Iara vai automaticamente:

  • Revisar o diff do Merge Request
  • Postar um comentário com o resultado da review no MR

Um template completo está disponível em gitlab-ci.yml.


🔧 Qualquer CI (Jenkins, CircleCI, etc.)

pip install iara-reviewer
export OPENROUTER_API_KEY="sk-or-..."
git diff main...HEAD | iara

🧪 Testes

python -m unittest discover tests

📜 Licença

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

iara_reviewer-1.1.0.tar.gz (20.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

iara_reviewer-1.1.0-py3-none-any.whl (18.5 kB view details)

Uploaded Python 3

File details

Details for the file iara_reviewer-1.1.0.tar.gz.

File metadata

  • Download URL: iara_reviewer-1.1.0.tar.gz
  • Upload date:
  • Size: 20.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.11

File hashes

Hashes for iara_reviewer-1.1.0.tar.gz
Algorithm Hash digest
SHA256 5e345584c46000fb5720967915e551d3b2613a0a3ed1e89db5609904825c8ae4
MD5 eccfc056a11f28b952e5d13833e86056
BLAKE2b-256 eccca78729ee0a8972d7b6e2dc6c0cbc3a980de5fa375953b76060e9795a1330

See more details on using hashes here.

File details

Details for the file iara_reviewer-1.1.0-py3-none-any.whl.

File metadata

  • Download URL: iara_reviewer-1.1.0-py3-none-any.whl
  • Upload date:
  • Size: 18.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.11

File hashes

Hashes for iara_reviewer-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8c141196b33d3be1922e4431086d1cfb8048e7cd4e38f3b9f8840056f38869d5
MD5 427afddc21cdcc1ae29441b377f62eb6
BLAKE2b-256 b5d5636173c9f2c5dd49c5356e2297e2c352d18f81daa8e3518fe2786398efcd

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page