All writing
ai-code-review ci-cd llm-engineering devops

AI Generated Code Review Pipeline That Catches Real Bugs

Ayush Kaushik 7 min read
AI Generated Code Review Pipeline That Catches Real Bugs

You built your product with AI. It shipped fast. Now you are staring at a dashboard full of errors you did not write and cannot explain. An ai generated code review pipeline catches the hallucinations before they hit production by layering deterministic checks first and LLM reasoning second. I run this in production for a FastAPI monorepo processing millions of requests daily. Here is what actually works.

What Should Run Before an LLM Even Sees the Code

Start with tools that never lie. Ruff for Python. ESLint for TypeScript. Bandit or Semgrep for security patterns. These run in milliseconds and catch the obvious stuff: unused imports, SQL injection patterns, hardcoded secrets, missing awaits.

.github/workflows/ai-review.yml
name: AI Code Review
on:
pull_request:
types: [opened, synchronize, reopened]
jobs:
deterministic-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run Ruff
run: ruff check . --output-format=github
- name: Run Bandit
run: bandit -r . -f json -o bandit.json || true
- name: Run Semgrep
uses: returntocorp/semgrep-action@v1

This job must pass before the LLM stage runs. If Ruff fails, the PR author fixes lint errors first. No reason to burn tokens on code that does not parse.

How Do I Design a Multi-Stage AI Review Architecture

Run three stages in sequence. Each stage has a different job and a different model.

Stage one: static analysis. Fast, cheap, deterministic. Ruff, Bandit, Semgrep, your custom regex rules for internal patterns like “no direct database calls in route handlers.”

Stage two: security-focused LLM pass. Use a smaller model like gpt-4o-mini or claude-3-haiku. Prompt it with a system message that encodes your threat model. Feed it only the changed files plus the security findings from stage one.

review_agents/security_reviewer.py
import os
from openai import OpenAI
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
SECURITY_SYSTEM_PROMPT = """
You are a security engineer reviewing a pull request.
Focus on: authentication bypass, authorization gaps, injection risks,
secret exposure, and insecure defaults.
Output ONLY a JSON array of findings:
[{"file": "path.py", "line": 42, "severity": "high|medium|low",
"issue": "description", "fix": "suggested code change"}]
"""
def review_security(diff: str, bandit_findings: list) -> list:
context = f"Bandit findings: {bandit_findings}\n\nDiff:\n{diff}"
resp = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": SECURITY_SYSTEM_PROMPT},
{"role": "user", "content": context}
],
temperature=0,
response_format={"type": "json_object"}
)
return resp.choices[0].message.content

Stage three: architecture and style review. This is where you use the expensive model. Claude 3.5 Sonnet or GPT-4o. Prompt it with your actual architecture docs: layer boundaries, naming conventions, error handling patterns. Feed it the full PR context, not just the diff.

Integrating AI Reviewers Into GitHub Actions Without Slowing CI

The naive approach posts a comment per finding. That creates noise. Instead, aggregate findings into a single review object and post one review per stage.

llm-security-review:
needs: deterministic-checks
runs-on: ubuntu-latest
if: github.event.pull_request.draft == false
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get diff
id: diff
run: |
git diff origin/${{ github.base_ref }}...HEAD > pr.diff
echo "diff<<EOF" >> $GITHUB_OUTPUT
cat pr.diff >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
- name: Run security reviewer
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
python -m review_agents.security_reviewer \
--diff "${{ steps.diff.outputs.diff }}" \
--bandit bandit.json \
--output security_findings.json
- name: Post review
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const findings = JSON.parse(fs.readFileSync('security_findings.json'));
const comments = findings.map(f => ({
path: f.file,
line: f.line,
body: `**${f.severity.toUpperCase()}**: ${f.issue}\n\n\`\`\`suggestion\n${f.fix}\n\`\`\``
}));
await github.rest.pulls.createReview({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.payload.pull_request.number,
event: comments.length ? 'REQUEST_CHANGES' : 'APPROVE',
body: `Security review: ${comments.length} findings`,
comments
});

Key detail: fetch-depth: 0 so the diff works on forced pushes. The if: github.event.pull_request.draft == false prevents reviews on WIP branches.

How Do I Handle False Positives Without Ignoring Real Issues

You will get false positives. The LLM will flag a test file for “hardcoded password” because the test uses password = "test123". Do not add // ai-ignore comments everywhere. That rots the signal.

Instead, tune the prompt with few-shot examples. Show the model what a false positive looks like and what a real finding looks like.

FEW_SHOT_EXAMPLES = """
Example 1 (FALSE POSITIVE):
File: tests/test_auth.py
Line: 12
Code: api_key = "test-key-123"
Reason: Test fixture. Not production code.
Example 2 (REAL FINDING):
File: app/config.py
Line: 8
Code: api_key = os.getenv("API_KEY") or "sk-live-abc123"
Reason: Fallback secret in source code. High severity.
"""

Add this to your system prompt. Update it weekly when you see new false positive patterns. I keep a prompts/security_reviewer.md file in the repo so the team can PR improvements to the prompt itself.

Another lever: temperature zero and structured output. Force JSON. If the model hallucinates a field, the parser fails and you catch it in the workflow.

Cost Optimization for Large Monorepos

Do not send the whole repo to an LLM. Ever.

Send only changed files. Use git diff --name-only to filter. If a PR touches 500 files, split it. Set a hard limit: if changed files > 50, skip LLM review and require human review instead.

Terminal window
# In your workflow
CHANGED_FILES=$(git diff --name-only origin/${{ github.base_ref }}...HEAD | wc -l)
if [ "$CHANGED_FILES" -gt 50 ]; then
echo "PR too large for AI review. Requiring human review."
exit 0
fi

Cache aggressively. Semgrep and Ruff results can be cached by GitHub Actions cache keyed on requirements.txt hash. LLM calls cannot be cached easily, but you can cache the prompt template and few-shot examples.

Model routing saves 80% of cost. Route simple security patterns (hardcoded secrets, SQL concatenation) to a fine-tuned small model or even a regex. Only send ambiguous cases to the big model. I wrote about this pattern in Fixing AI Generated Code Quality Issues in Production where a team cut review costs from $400/month to $40/month by adding a regex pre-filter.

Measuring ROI: Defect Escape Rate vs Review Latency

You need two metrics. Defect escape rate: bugs found in production that the pipeline should have caught. Review latency: time from PR open to merge.

Track escape rate by tagging production incidents with “missed-by-ai-review” when post-mortem shows the pipeline had context. Aim for zero critical escapes. Medium and low are acceptable if latency stays low.

Latency target: deterministic checks under 2 minutes. LLM stages under 5 minutes total. If your pipeline takes 20 minutes, developers will bypass it.

-- Sample query for your metrics dashboard
SELECT
DATE_TRUNC('week', pr.created_at) AS week,
COUNT(*) AS total_prs,
AVG(EXTRACT(EPOCH FROM (pr.merged_at - pr.created_at))/3600) AS avg_hours_to_merge,
SUM(CASE WHEN incident.severity = 'critical' THEN 1 ELSE 0 END) AS critical_escapes
FROM pull_requests pr
LEFT JOIN incidents ON incidents.related_pr = pr.number
GROUP BY week
ORDER BY week DESC;

When escape rate rises, audit the prompts. When latency rises, check file count limits and model routing. I covered a real incident where a missing auth check escaped review in Fixing an AI Generated Code Vulnerabilities Report - the prompt lacked context about the new permission system.

When Not to Use This Approach

Skip the LLM stages if:

  • Your team is under five people and reviews are fast already
  • You ship fewer than ten PRs per week
  • Your codebase has no tests (fix tests first)
  • You cannot afford the API spend (use local models via Ollama instead)

Do not replace human review for security-critical paths: auth, payments, data deletion. The pipeline is a net, not the fisherman.

FAQ

How much does an AI code review pipeline cost per month?

For a team of 8 engineers merging 60 PRs per week with 20 changed files each, expect $50-150/month on GPT-4o-mini and Claude Haiku. GPT-4o or Sonnet pushes that to $300-600. Local models on GPU instances can run under $50 fixed cost.

Can I run this on GitLab CI instead of GitHub Actions?

Yes. The review logic lives in Python scripts. GitLab CI uses rules:if instead of if: and posts notes via the GitLab API. The prompt engineering and model routing stay identical.

What if the LLM misses a vulnerability the static analyzer caught?

Static analyzers catch patterns. LLMs catch logic. They are complementary. If Bandit flags SQL injection but the LLM misses it, your Bandit rule worked. If the LLM catches an auth bypass Bandit cannot see, your prompt worked. Track both.

Should I use a local model like CodeLlama or DeepSeek Coder?

For stage one and two, yes. They handle “is this a hardcoded secret” well. For architecture review (stage three), they still hallucinate layer violations. I use local models for the cheap stages and cloud for the reasoning stage.

Key Takeaways

  • Run deterministic tools first. They are free, fast, and never hallucinate.
  • Split LLM review into security, architecture, and style stages with different models.
  • Post one aggregated review per stage, not one comment per finding.
  • Tune prompts with few-shot examples from your actual false positives.
  • Cap file count per PR. Large PRs get human review only.
  • Measure escape rate and latency weekly. Adjust prompts when escapes rise.
  • Keep humans on auth, payments, and data deletion paths.

Working on something similar?

If you're building backend or AI systems and want a second set of senior eyes, let's talk.

Keep reading

Related articles