AI Code Review Automation 2026: GitHub Actions + GPT-4 for Pull Requests

Automatically catch bugs and security issues in PRs with AI-powered code review

返回教程列表
进阶30 分钟

AI Code Review Automation 2026: GitHub Actions + GPT-4 for Pull Requests

Automatically catch bugs and security issues in PRs with AI-powered code review

Build an AI code review bot with GitHub Actions and GPT-4o. Analyzes every PR for security vulnerabilities, logic errors, and code quality. Block merges on critical security issues.

code reviewgithub actionsgpt-4automationdevopssecurity

AI Code Review Automation 2026: GitHub Actions + GPT-4

Automatically review pull requests to catch bugs and security issues before human review.

What AI Code Review Catches

  • Security: SQL injection, hardcoded secrets, path traversal
  • Bugs: logic errors, missing null checks, wrong conditions
  • Performance: N+1 queries, unnecessary computation
  • Quality: missing error handling, unclear code
  • GitHub Actions Workflow

    yaml
    name: AI Code Review
    on:
      pull_request:
        types: [opened, synchronize]
    jobs:
      review:
        runs-on: ubuntu-latest
        permissions:
          pull-requests: write
          contents: read
        steps:
          - uses: actions/checkout@v4
          - uses: actions/setup-python@v5
            with: {python-version: '3.12'}
          - run: pip install openai PyGithub
          - name: AI Review
            env:
              OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
              GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
              PR_NUMBER: ${{ github.event.pull_request.number }}
              REPO_NAME: ${{ github.repository }}
            run: python scripts/ai_review.py
    

    Review Script

    python
    

    scripts/ai_review.py

    import os from github import Github from openai import OpenAI

    openai_client = OpenAI(api_key=os.environ['OPENAI_API_KEY']) gh = Github(os.environ['GITHUB_TOKEN']) repo = gh.get_repo(os.environ['REPO_NAME']) pr = repo.get_pull(int(os.environ['PR_NUMBER']))

    PROMPT = ( 'You are an expert code reviewer. Analyze this diff for:\n' '1. Security: SQL injection, XSS, hardcoded secrets\n' '2. Bugs: logic errors, null pointer risks\n' '3. Performance: N+1 queries, inefficiencies\n' '4. Quality: missing error handling\n' 'For each issue: file+line, explain problem, suggest fix.\n' 'Be concise. Focus on significant issues only.\n\nDiff:\n{diff}' )

    def get_diff(): parts = [] total = 0 for f in pr.get_files(): if not f.patch or f.status == 'removed': continue part = f'\n## {f.filename}\n

    \n{f.patch[:5000]}\n
    '
            total += len(part)
            if total > 80000: break
            parts.append(part)
        return '\n'.join(parts)

    def run_review(): diff = get_diff() if not diff.strip(): return r = openai_client.chat.completions.create( model='gpt-4o', messages=[{'role': 'user', 'content': PROMPT.format(diff=diff)}], temperature=0.1, max_tokens=2000 ) pr.create_issue_comment( f'## AI Code Review\n\n{r.choices[0].message.content}\n\n*by GPT-4o*' ) print('Review posted!')

    run_review()

    Security Mode (Blocks Critical Issues)

    python
    import sys

    SECURITY_CHECK = ( 'Scan for security vulnerabilities only.\n' 'Check: SQL injection, command injection, path traversal, hardcoded secrets, missing auth.\n' 'Rate each: CRITICAL/HIGH/MEDIUM/LOW\n' 'If none: respond exactly: No security issues found.' )

    def security_review(): r = openai_client.chat.completions.create( model='gpt-4o', messages=[{'role': 'user', 'content': SECURITY_CHECK + '\n\nDiff:\n' + get_diff()}], temperature=0 ) review = r.choices[0].message.content if 'CRITICAL' in review: pr.create_review(body=f'## Critical Security Issues!\n\n{review}', event='REQUEST_CHANGES') sys.exit(1) # Fail CI, block merge else: pr.create_issue_comment(f'## Security Review\n\n{review}')

    security_review()

    Smart Model Routing

    python
    def select_model(pr) -> str:
        critical_patterns = ['auth', 'payment', 'crypto', 'password', 'token', 'secret']
        for f in pr.get_files():
            if any(p in f.filename.lower() for p in critical_patterns):
                return 'gpt-4o'  # Security-critical: use best model
        return 'gpt-4o-mini'  # Routine: use cheaper model
    

    Conclusion

    AI code review creates a powerful automated quality gate. Use gpt-4o-mini for routine PRs, gpt-4o for security-critical code, and block merges when critical vulnerabilities are detected.

    相关工具

    openaigithubpython