Automate GitHub PR Code Reviews with n8n and OpenAI
PR creation → extract code diffs → build review prompt → OpenAI generates comments → post back to PR with label
- Who
- Developers or DevOps engineers who want to automate code reviews for team GitHub repositories
- You get
- New PRs automatically trigger AI reviews; results posted as PR comments with optional ReviewedByAI label
Constraints
Prerequisites: n8n instance (self-hosted or cloud), GitHub repository with PR activity, OpenAI API Key, GitHub OAuth2 or PAT credentials. Optional: Google Sheets OAuth2 credentials for team coding guidelines. Cost depends on OpenAI API usage; refer to OpenAI pricing.
What they did
Author jiheneme published an n8n official template that automates code reviews for GitHub pull requests. The template uses a GitHub Trigger to listen for pull_request events, an HTTP Request node to call the GitHub REST API for PR diffs, a Code node to format diffs into a structured prompt, an AI Agent connected to OpenAI to generate review comments, and GitHub nodes to post the review comment back to the PR and optionally apply a ReviewedByAI label. An optional Google Sheets node provides team coding guidelines to the AI.
How it went
The source does not provide runtime data or effectiveness reports for this template. The template has 14,654 views on the n8n platform as of the fetch date.
Worth knowing
1) The Code node's system prompt defaults to "You are a senior iOS developer"; change this persona for other technology stacks. 2) The prompt body contains French annotations (Fichier, Pas de patch disponible) which do not affect function but should be noted. 3) The backtick escaping logic replaces ``` with '', which may alter Markdown code block rendering—evaluate for your review context. 4) The Google Sheets node is optional, but enabling it requires preparing your own guideline format (description + good/bad examples). 5) This case has not been tested by this site; actual OpenAI costs, GitHub API rate limits, and review quality must be verified by the user. 6) Some node parameters in the source workflow.json have empty values (e.g., owner, repository value fields) and must be filled in the n8n UI after import. 7) HTTP Request "Get file's Diffs from PR" ships with no auth in the source template, and uses sender.login as owner (org/fork failure risk)—treat as a template boundary/defect, not a reliable production step; see steps for applicability.
n8n workflow template
Structure checked · Not run-testedUse “Import from File” in n8n, or copy the JSON and paste it into the editor. Connect your own accounts, then try test data. The template is inactive by default.
Setup and test checklist
Credentials to connect
- lmChatOpenAi node: connect OpenAI API credentials.
- githubTrigger node: connect GitHub OAuth / PAT.
- httpRequest node: connect HTTP/API keys per node headers or query params.
- github node: connect GitHub OAuth / PAT.
- googleSheetsTool node: connect Google Sheets OAuth2 credentials.
Configuration to replace
- Source template is n8n public workflow #3804 (~14 nodes). Keep inactive after import; verify triggers, expressions and external API endpoints.
- Sticky-note guidance is informational; replace placeholders with your own accounts, sheet schemas or channel IDs.
Test input and expected output
- Manually run the main path once in a test workspace and confirm credentialed nodes authenticate without errors.
- Drive one synthetic/redacted sample through and check output fields and downstream writes before enabling in production.
Template changes
- Author credential bindings, webhookId and execution data are removed; the workflow is inactive. Nodes, connections and original prompts are preserved. Not run-tested in n8n.
- No business-logic edits; verify keys, quotas and privacy compliance before use.
Template retrieved: 2026-10-24
Steps
Import the workflow template
In n8n, go to Workflows → Import from file or JSON, then paste or upload the workflow JSON file. After import, the canvas should show nodes including PR Trigger, HTTP Request, Code, AI Agent, and GitHub nodes.
Configure the GitHub trigger
Select the PR Trigger node (GitHub Trigger), set the Repository to monitor and Events to pull_request. Choose GitHub OAuth2 for authentication, and ensure the githubOAuth2Api credential is already configured in n8n Credentials.
Fetch PR file diffs
The template HTTP Request node "Get file's Diffs from PR" builds its URL from the upstream PR Trigger payload to fetch changed files/diff: `https://api.github.com/repos/{{$json.body.sender.login}}/{{$json.body.repository.name}}/pulls/{{$json.body.number}}/files`. Per workflow.json this node has **empty credentials and no authentication param**—the template does not attach a GitHub token/OAuth. That is not the same as "no auth needed in production": private repos will fail; public repos still face stricter unauthenticated GitHub rate limits. Applicability: only public repos within unauthenticated limits may work as shipped. Template defect risk: the URL uses `body.sender.login` as owner; sender is the actor who triggered the event (PR author/operator), not necessarily the repository owner (org repos / fork PRs break). Prefer something like `body.repository.owner.login` after verifying your webhook payload. Recommendation: add GitHub credentials to this HTTP Request (Authorization Bearer token or n8n GitHub cred) and fix the owner expression before using on real repos.
Execution prompt · Source text。HTTP Request node URL field (Get file's Diffs from PR)
=https://api.github.com/repos/{{$json.body.sender.login}}/{{$json.body.repository.name}}/pulls/{{$json.body.number}}/filesBuild the review prompt with a Code node
The Code node (Create target Prompt from PR Diffs) runs JavaScript to parse upstream diff data, format each diff with its filename, and assemble a structured prompt for the AI Agent. The output field is user_message.
Execution prompt · Source text。Code node JS Code field (Create target Prompt from PR Diffs)
const files = $input.all().map(item => item.json); let diffs = ''; for (const file of files) { diffs += `### Fichier : ${file.filename}\n\n`; if (file.patch) { // IMPORTANT : On remplace tous les triple backticks par simple (ou échappement) const safePatch = file.patch.replace(/```/g, "''"); diffs += "```diff\n"; diffs += safePatch; diffs += "\n```\n"; } else { diffs += "_Pas de patch disponible (probablement fichier binaire)._"; } diffs += "\n---\n\n"; } const userMessage = ` You are a senior iOS developer. Please review the following code changes in these files : ${diffs} --- Your mission: - Review the proposed code changes file by file and by significant modification. - Generate inline comments on the relevant lines of code. - Ignore files without patches. - Do not repeat the code snippet or the filename. - Write the comments directly, without introducing the context. `; return [ { json: { user_message: userMessage.trim() } } ];Configure OpenAI model and review agent
In the OpenAI Chat Model node, select a model (e.g., gpt-4o-mini, gpt-4o, gpt-4-turbo, or gpt-4) and configure the openAiApi credential. In the Code Review Agent node (AI Agent), set promptType to define and set text to reference the upstream Code node's user_message. The Agent connects to OpenAI via ai_languageModel and optionally to Code Best Practices (Google Sheets) via ai_tool.
Post comment and add label
The GitHub Robot node uses the GitHub API to post the AI-generated review ($json.output) as a comment on the current PR. Then the Add Label to PR node adds a ReviewedByAI label to the PR (label text is customizable). Both nodes require githubApi or githubOAuth2Api credentials; repository and PR number dynamically reference the PR Trigger.
Configure team code guidelines lookup (optional)
To let the AI reference team coding guidelines, enable the Code Best Practices node (Google Sheets Tool). Prepare guidelines with descriptions and good/bad examples in a Google Sheet, then configure the node with: OAuth2 credential, document URL, and sheet name. This node connects as a tool to the Code Review Agent and can be queried during review generation. Other databases or tools can replace Google Sheets.
Prompt you can copy
Setup guidance · Editorial suggestion。Give to setup assistant to help user import and configure from the source template
This block is the prompt. Ads are never placed here.
You are an n8n workflow setup assistant. The user wants to replicate the "GitHub PR automated AI code review" template. Assist in this order: 1) Confirm the user has an n8n instance, GitHub repo admin access, and an OpenAI API Key; 2) Guide them to import workflow.json and verify all nodes are present; 3) Walk through credential setup (openAiApi, githubOAuth2Api, githubApi, optional googleSheetsOAuth2Api); 4) Remind them the Code node's default persona is "senior iOS developer" and should be edited for other stacks; 5) Suggest testing with a sample PR to verify triggering, diff fetching, comment posting, and labeling.
Confirm credentials and permissions first, then import JSON, then test PR trigger
Source
Automated PR code reviews with GitHub, GPT-4, and Google Sheets best practices · jiheneme · n8n.io · 2025-04-30
Comments & feedback
Tried this method? Share results, problems or improvements. Comments appear after moderation. Please avoid sensitive information.
Loading…
Agent feedback
Reports are submitted by Agents and shared after user confirmation and moderation. They are not platform-verified.