简介
本指南介绍如何将OpenAI推理模型集成到您的GitHub拉取请求(PR)工作流中,以自动审查代码质量、安全性和企业标准合规性。通过在开发流程早期利用AI驱动的洞察,您可以更早发现问题,减少人工工作量,并在整个代码库中保持统一的最佳实践。
为什么要在PR中集成OpenAI推理模型?
• 通过自动检测代码异味、安全漏洞和风格不一致,节省代码审查时间。
• 在全组织范围内强制执行编码标准,确保代码一致可靠。
• 为开发人员提供及时的AI指导反馈,帮助改进潜在问题。
示例用例
• 审阅者希望在合并前获得关于新代码变更安全性的反馈。
• 团队希望强制执行标准编码规范,确保整个组织内代码质量的一致性。
先决条件
1. 生成一个OpenAI“项目密钥”
- 前往 platform.openai.com/api-keys 并点击创建新的密钥。
- 将令牌安全存储在您的GitHub仓库机密中,命名为OPENAI_API_KEY。
2. 选择您的OpenAI模型
使用OpenAI Reasoning Models对代码变更进行深入分析。从最先进的模型开始,根据需要优化您的提示词。
3. 选择拉取请求
- 确认您的代码仓库已启用GitHub Actions功能。
- 确保您拥有配置仓库密钥或变量的权限(例如,针对您的PROMPT、MODELNAME和BEST_PRACTICES变量)。
4. 定义企业编码标准
将您的标准存储为仓库变量(BEST_PRACTICES)。这些标准可能包括:
• 代码风格与格式
• 可读性与可维护性
• 安全性与合规性
• 错误处理与日志记录
• 性能与可扩展性
• 测试与质量保证
• 文档管理与版本控制
• 可访问性与国际化
5. 定义提示内容
构建一个元提示来引导OpenAI进行安全性、质量和最佳实践检查。包括:
- 代码质量与标准
- 安全性与漏洞分析
- 容错与错误处理
- 性能与资源管理
- 逐步验证
鼓励OpenAI提供详尽、逐行的审查,并给出明确的建议。
创建您的GitHub Actions工作流
该GitHub Actions工作流会在每次针对主分支的拉取请求时触发,包含两个任务。第一个任务收集所有变更文件的差异(排除.json和.png文件),并将这些变更发送至OpenAI进行分析。OpenAI提供的任何修复建议会以评论形式显示在PR中。第二个任务根据您定义的企业标准评估PR,并返回一个总结代码符合这些标准情况的Markdown表格。您可以通过更新提示词、模型名称和最佳实践等变量,轻松调整或优化此工作流。
name: PR Quality and Security Check
on:
pull_request:
branches: [main]
permissions:
contents: read
pull-requests: write
jobs:
quality-security-analysis:
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v3
with:
fetch-depth: 0 # Ensure full history for proper diff
- name: Gather Full Code From Changed Files
run: |
CHANGED_FILES=$(git diff --name-only origin/main...HEAD)
echo '{"original files": [' > original_files_temp.json
for file in $CHANGED_FILES; do
if [[ $file == *.json ]] || [[ $file == *.png ]]; then
continue
fi
if [ -f "$file" ]; then
CONTENT=$(jq -Rs . < "$file")
echo "{\"filename\": \"$file\", \"content\": $CONTENT}," >> original_files_temp.json
fi
done
sed -i '$ s/,$//' original_files_temp.json
echo "]}" >> original_files_temp.json
- name: Display Processed Diff (Debug)
run: cat original_files_temp.json
- name: Get Diff
run: |
git diff origin/main...HEAD \
| grep '^[+-]' \
| grep -Ev '^(---|\+\+\+)' > code_changes_only.txt
jq -Rs '{diff: .}' code_changes_only.txt > diff.json
if [ -f original_files_temp.json ]; then
jq -s '.[0] * .[1]' diff.json original_files_temp.json > combined.json
mv combined.json diff.json
- name: Display Processed Diff (Debug)
run: cat diff.json
- name: Analyze with OpenAI
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
DIFF_CONTENT=$(jq -r '.diff' diff.json)
ORIGINAL_FILES=$(jq -r '."original files"' diff.json)
PROMPT="Please review the following code changes for any obvious quality or security issues. Provide a brief report in markdown format:\n\nDIFF:\n${DIFF_CONTENT}\n\nORIGINAL FILES:\n${ORIGINAL_FILES}"
jq -n --arg prompt "$PROMPT" '{
"model": "gpt-4",
"messages": [
{ "role": "system", "content": "You are a code reviewer." },
{ "role": "user", "content": $prompt }
]
}' > request.json
curl -sS https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${OPENAI_API_KEY}" \
-d @request.json > response.json
- name: Extract Review Message
id: extract_message
run: |
ASSISTANT_MSG=$(jq -r '.choices[0].message.content' response.json)
{
echo "message<<EOF"
echo "$ASSISTANT_MSG"
echo "EOF"
} >> $GITHUB_OUTPUT
- name: Post Comment to PR
env:
COMMENT: ${{ steps.extract_message.outputs.message }}
GH_TOKEN: ${{ github.token }}
run: |
gh api \
repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments \
-f body="$COMMENT"
enterprise-standard-check:
runs-on: ubuntu-latest
needs: [quality-security-analysis]
steps:
- name: Checkout code
uses: actions/checkout@v3
with:
fetch-depth: 0 # ensures we get both PR base and head
- name: Gather Full Code From Changed Files
run: |
# Identify changed files from the base (origin/main) to the pull request HEAD
CHANGED_FILES=$(git diff --name-only origin/main...HEAD)
# Build a JSON array containing filenames and their content
echo '{"original files": [' > original_files_temp.json
for file in $CHANGED_FILES; do
# Skip .json and .txt files
if [[ $file == *.json ]] || [[ $file == *.txt ]]; then
continue
fi
# If the file still exists (i.e., wasn't deleted)
if [ -f "$file" ]; then
CONTENT=$(jq -Rs . < "$file")
echo "{\"filename\": \"$file\", \"content\": $CONTENT}," >> original_files_temp.json
fi
done
# Remove trailing comma on the last file entry and close JSON
sed -i '$ s/,$//' original_files_temp.json
echo "]}" >> original_files_temp.json
- name: Analyze Code Against Best Practices
id: validate
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
set -e
# Read captured code
ORIGINAL_FILES=$(cat original_files_temp.json)
# Construct the prompt:
# - Summarize each best-practice category
# - Provide a rating for each category: 'extraordinary', 'acceptable', or 'poor'
# - Return a Markdown table titled 'Enterprise Standards'
PROMPT="You are an Enterprise Code Assistant. Review each code snippet below for its adherence to the following categories:
1) Code Style & Formatting
2) Security & Compliance
3) Error Handling & Logging
4) Readability & Maintainability
5) Performance & Scalability
6) Testing & Quality Assurance
7) Documentation & Version Control
8) Accessibility & Internationalization
Using \${{ vars.BEST_PRACTICES }} as a reference, assign a rating of 'extraordinary', 'acceptable', or 'poor' for each category. Return a markdown table titled 'Enterprise Standards' with rows for each category and columns for 'Category' and 'Rating'.
Here are the changed file contents to analyze:
$ORIGINAL_FILES"
# Create JSON request for OpenAI
jq -n --arg system_content "You are an Enterprise Code Assistant ensuring the code follows best practices." \
--arg user_content "$PROMPT" \
'{
"model": "${{ vars.MODELNAME }}",
"messages": [
{
"role": "system",
"content": $system_content
},
{
"role": "user",
"content": $user_content
}
]
}' > request.json
# Make the API call
curl -sS https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d @request.json > response.json
# Extract the model's message
ASSISTANT_MSG=$(jq -r '.choices[0].message.content' response.json)
# Store for next step
{
echo "review<<EOF"
echo "$ASSISTANT_MSG"
echo "EOF"
} >> $GITHUB_OUTPUT
- name: Post Table Comment
env:
COMMENT: ${{ steps.validate.outputs.review }}
GH_TOKEN: ${{ github.token }}
run: |
# If COMMENT is empty or null, skip posting
if [ -z "$COMMENT" ] || [ "$COMMENT" = "null" ]; then
echo "No comment to post."
exit 0
fi
gh api \
repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments \
-f body="$COMMENT"测试工作流程
将此工作流程提交到您的代码仓库,然后开启一个新的拉取请求(PR)。该工作流程将自动运行,并将AI生成的反馈作为PR评论发布。
公开示例可参考OpenAI-Forum代码库的工作流文件:pr_quality_and_security_check.yml。

