ChatGPT for Code Review — Workflow and Best Practices 2026

Sanjeev SharmaSanjeev Sharma
6 min read

Advertisement

Introduction

Why This Matters

AI-assisted code review catches issues before human reviewers see the code, reduces review turnaround time, and provides consistent feedback on style and security patterns. Used correctly, it supplements — not replaces — human review by handling the mechanical checklist so engineers focus on architecture and business logic. This guide covers the prompts, workflows, and tooling to make AI code review genuinely useful.

What ChatGPT Catches Well

ChatGPT is reliable for:

  • Security vulnerabilities — SQL injection, hardcoded secrets, missing input validation, insecure deserialization
  • Error handling gaps — uncaught exceptions, missing null checks, unhandled promise rejections
  • Performance anti-patterns — N+1 queries, unnecessary loops, synchronous calls that should be async
  • Code style issues — naming conventions, function length, unnecessary complexity
  • Missing documentation — undocumented parameters, missing return type annotations

It is less reliable for:

  • Business logic correctness (it doesn't know your domain requirements)
  • Architectural decisions across many files it hasn't seen
  • Very recently introduced library APIs with post-April 2024 changes

Core Review Prompt Template

REVIEW_PROMPT = """
Act as a senior software engineer doing a thorough code review.
Review the following {language} code for:
 
1. Security vulnerabilities (severity: critical/medium/low)
2. Performance issues
3. Error handling gaps
4. Code clarity and maintainability
5. Missing or incorrect type annotations
6. Test coverage gaps
 
For each finding:
- Quote the specific line(s)
- Explain why it is a problem
- Provide a corrected version
 
Code to review:
[paste {language} code here]
 
{code}
"""
 
import openai
 
client = openai.OpenAI()
 
def review_code(code: str, language: str = "python") -> str:
    prompt = REVIEW_PROMPT.format(language=language, code=code)
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": prompt}],
        max_tokens=2048,
        temperature=0.1,
    )
    return response.choices[0].message.content

Security-Focused Review

For security audits, narrow the focus to get more thorough results:

SECURITY_PROMPT = """
You are a security engineer performing a security-focused code review.
Identify ALL potential security vulnerabilities in this code.
 
Check for:
- Injection vulnerabilities (SQL, command, LDAP, XPath)
- Authentication and authorization flaws
- Sensitive data exposure (hardcoded credentials, logged secrets)
- Missing input validation and sanitization
- Insecure dependencies or deprecated APIs
- Race conditions in concurrent code
- Path traversal or file inclusion issues
 
For each vulnerability:
- Assign a CVSS severity: Critical / High / Medium / Low
- Show the vulnerable code
- Explain the attack vector
- Provide a fixed version
 
Code:
{code}
"""

Example of what this catches:

# Submitted for review:
def get_user(username: str):
    query = f"SELECT * FROM users WHERE username = '{username}'"
    return db.execute(query)
 
# ChatGPT identifies:
# CRITICAL: SQL Injection — username is interpolated directly into the query.
# Attack: username = "' OR 1=1 --" returns all users.
# Fix:
 
def get_user(username: str):
    query = "SELECT * FROM users WHERE username = %s"
    return db.execute(query, (username,))

Refactoring Review

Use ChatGPT to identify refactoring opportunities in complex functions:

REFACTOR_PROMPT = """
Review this code for refactoring opportunities.
Focus on:
- Functions doing more than one thing (SRP violations)
- Duplicated logic that should be extracted
- Overly complex conditionals that should be simplified
- Magic numbers that should be named constants
- Long parameter lists that suggest a missing abstraction
 
Show the original and a refactored version with explanations.
"""
 
# Before:
def process_order(order_id, user_id, items, discount_code, shipping_method, notify):
    user = db.get(f"users:{user_id}")
    if not user or not user['active']:
        return None
    total = sum(i['price'] * i['qty'] for i in items)
    if discount_code == 'SUMMER10':
        total *= 0.9
    elif discount_code == 'WINTER20':
        total *= 0.8
    shipping = 5.99 if shipping_method == 'standard' else 14.99
    order = {'id': order_id, 'total': total + shipping}
    db.save(f"orders:{order_id}", order)
    if notify:
        email.send(user['email'], f"Order {order_id} confirmed")
    return order

CI/CD Integration

Automate code review on pull requests using the GitHub Actions pattern:

# .github/workflows/ai-review.yml
name: AI Code Review
 
on:
  pull_request:
    types: [opened, synchronize]
 
jobs:
  ai-review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
 
      - name: Get changed files
        id: diff
        run: |
          git diff origin/${{ github.base_ref }}...HEAD --name-only \
            --diff-filter=AM > changed_files.txt
          echo "files=$(cat changed_files.txt | tr '\n' ',')" >> $GITHUB_OUTPUT
 
      - name: Run AI Review
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: python scripts/ai_review.py
# scripts/ai_review.py
import os
import subprocess
from openai import OpenAI
 
client = OpenAI()
 
def get_diff():
    result = subprocess.run(
        ["git", "diff", "origin/main...HEAD", "--unified=5"],
        capture_output=True, text=True
    )
    return result.stdout
 
def review_diff(diff: str) -> str:
    if len(diff) > 60000:  # Truncate very large diffs
        diff = diff[:60000] + "\n... (truncated)"
 
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {
                "role": "system",
                "content": "Review this git diff for security issues and bugs. Be concise.",
            },
            {"role": "user", "content": f"Git diff:\n\n{diff}"},
        ],
        max_tokens=1024,
        temperature=0.1,
    )
    return response.choices[0].message.content
 
diff = get_diff()
if diff:
    review = review_diff(diff)
    print(review)

Common Mistakes

  • Submitting entire files for review instead of the changed diff — wastes tokens and dilutes feedback
  • Not specifying the review focus — a general "review this" prompt produces generic output
  • Accepting security findings without verifying them — ChatGPT occasionally flags false positives
  • Using AI review as a replacement for human review — it misses business logic and context-specific issues
  • Not limiting response length — verbose responses bury the most important findings

Best Practices

  • Break reviews into focused passes: one pass for security, one for performance, one for style
  • Use temperature=0.0-0.1 for code review to get consistent, deterministic output
  • Have AI review the git diff rather than full files to focus on what changed
  • Post AI review results as PR comments automatically to make them part of the workflow
  • Track which AI-identified issues developers accept vs reject to tune prompts over time

Key Takeaways

  • ChatGPT is reliable for catching SQL injection, hardcoded secrets, missing error handling, and N+1 query patterns
  • Security-focused prompts with specific vulnerability categories produce more thorough results than general "review this" prompts
  • Reviewing the git diff (not the full file) reduces token usage and focuses feedback on actual changes
  • CI/CD integration via GitHub Actions makes AI review automatic on every pull request
  • Low temperature (0.1) produces more consistent review output suitable for automated pipelines
  • AI review does not replace human review — it handles the checklist so engineers focus on architecture
  • False positives occur — require developer sign-off before treating AI findings as confirmed bugs
  • Structured output format (numbered list with severity labels) makes findings easier to triage

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro

Related reading