AI代码审查自动化2026:GitHub Actions + GPT-4 实现拉取请求审查
通过AI驱动的代码审查,自动发现拉取请求中的错误和安全问题
AI代码审查自动化2026:GitHub Actions + GPT-4 实现拉取请求审查
通过AI驱动的代码审查,自动发现拉取请求中的错误和安全问题
使用GitHub Actions和GPT-4o构建AI代码审查机器人。分析每个PR的安全漏洞、逻辑错误和代码质量。在发现严重安全问题时阻止合并。
AI代码审查自动化2026:GitHub Actions + GPT-4
在人工审查之前自动审查拉取请求,捕获错误和安全问题。
AI代码审查能发现什么
GitHub Actions 工作流
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
审查脚本
python
scripts/ai_review.py
import os
from github import Github
from openai import OpenAIopenai_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()
安全模式(阻止严重问题)
python
import sysSECURITY_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()
智能模型路由
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
结论
AI代码审查创建了一个强大的自动化质量门。对于常规PR使用gpt-4o-mini,对于安全关键代码使用gpt-4o,并在检测到严重漏洞时阻止合并。
相关教程
利用AI自动分类、摘要和起草邮件回复
使用 Make (Integromat) 进行 AI 驱动自动化工作流的分步指南
从协作框架、路由调度到安全防御,全面覆盖多Agent系统的设计与落地
从 GeneBench-Pro 到 CJS 框架,系统梳理模型评测基准、安全攻击与对齐技术的全景与深度实践
AutoML与AI助手如何让数据科学大众化
使用 Modal 实现 AI 驱动的基础设施工作流的分步指南