Swarms Logo
GuidesEngineering

Build an AI Code Review Bot for GitHub Pull Requests

A GitHub Action that sends every pull request diff to three AI reviewers (security, logic and style) running in parallel on the Swarms API, then posts one combined review comment and updates it on every push. Copy-paste workflow YAML and a dependency-free Python script.

Kye Gomez10 min read
Build an AI Code Review Bot for GitHub Pull Requests

A single LLM asked to "review this diff" tends to produce a list of style nitpicks with the one real bug buried in the middle. Human teams avoid that by splitting the work: someone checks security, someone checks whether the logic is right, someone cares about naming and tests. An AI review bot works better the same way.

This guide builds a GitHub Action that does exactly that. On every pull request it collects the diff, sends it to three reviewer agents running in parallel on the Swarms API, and posts their findings as one comment on the PR. When you push more commits, the same comment is updated instead of a new one piling up.

You need two files in your repository and one secret. No servers, no Docker image, and no Python packages to install.

How it works

pull_request event │ ▼ git diff base...head ──► swarms_review.py ──► POST /v1/swarm/completions (ConcurrentWorkflow) ├─ Security Reviewer ├─ Logic Reviewer └─ Style Reviewer │ gh pr comment --edit-last ◄── review.md

The three reviewers run as a ConcurrentWorkflow: each gets the same diff and its own instructions, they run at the same time, and the API returns all three answers in one response. Each agent can use a different model, so the security pass can use a stronger model while the style pass uses a cheap one.

Step 1: add your API key as a secret

Create a key at cloud.swarms.world/api-keys. In your repository, open Settings → Secrets and variables → Actions, click New repository secret, name it SWARMS_API_KEY and paste the key.

Step 2: the workflow

Save this as .github/workflows/ai-review.yml:

YAML
name: AI code review

on:
  pull_request:
    types: [opened, synchronize, reopened, ready_for_review]

permissions:
  contents: read
  pull-requests: write

concurrency:
  group: ai-review-${{ github.event.pull_request.number }}
  cancel-in-progress: true

jobs:
  review:
    if: github.event.pull_request.draft == false
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Collect the diff
        run: |
          git diff --unified=3 "origin/${{ github.base_ref }}...HEAD" -- . \
            ':(exclude)*.lock' ':(exclude)package-lock.json' ':(exclude)pnpm-lock.yaml' \
            ':(exclude)*.min.js' ':(exclude)*.svg' > pr.diff
          echo "Diff size: $(wc -c < pr.diff) bytes"

      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      - name: Review with three agents
        env:
          SWARMS_API_KEY: ${{ secrets.SWARMS_API_KEY }}
          PR_TITLE: ${{ github.event.pull_request.title }}
          PR_BODY: ${{ github.event.pull_request.body }}
        run: python .github/scripts/swarms_review.py pr.diff > review.md

      - name: Post or update the review comment
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          gh pr comment ${{ github.event.pull_request.number }} \
            --body-file review.md --edit-last --create-if-none

A few choices worth knowing about:

  • fetch-depth: 0 fetches the base branch so git diff origin/main...HEAD shows only what the PR changes.
  • Lock files and minified assets are excluded. They are large, nobody reviews them by hand, and they would push the real changes out of the model's context.
  • concurrency with cancel-in-progress means a quick series of pushes only reviews the latest one.
  • The PR title and body go through env, never straight into the run: script. Interpolating them into shell is a classic injection hole in Actions workflows.
  • --edit-last --create-if-none makes the bot keep a single comment per PR and update it on each push.

Step 3: the review script

Save this as .github/scripts/swarms_review.py. It uses only the Python standard library, so there is nothing to pip install in CI.

Python
#!/usr/bin/env python3
"""Send a PR diff to three reviewer agents on the Swarms API and print a Markdown review."""
import json
import os
import sys
import urllib.error
import urllib.request

API_URL = "https://api.swarms.world/v1/swarm/completions"
MAX_DIFF_CHARS = 60_000  # roughly 15k tokens; larger diffs are truncated

FORMAT_RULES = (
    "Review only the lines added or changed in the diff. "
    "Report each finding as a Markdown bullet: `path/to/file:line` **severity** (critical, high, medium or low), "
    "then one or two sentences on the problem and how to fix it. "
    "Order findings from most to least severe. Do not repeat the diff back. "
    "If you find nothing in your area, reply with exactly: No issues found."
)

REVIEWERS = [
    {
        "agent_name": "Security Reviewer",
        "model_name": "claude-sonnet-5",
        "system_prompt": (
            "You are an application security engineer reviewing a pull request. Look for injection "
            "(SQL, shell, template), missing authentication or authorization checks, secrets in code, "
            "unsafe deserialization, path traversal, SSRF, insecure defaults and data exposure in logs "
            "or API responses. Ignore style. " + FORMAT_RULES
        ),
    },
    {
        "agent_name": "Logic Reviewer",
        "model_name": "gpt-5.4",
        "system_prompt": (
            "You are a senior engineer checking whether a pull request does what it claims. Look for "
            "off-by-one errors, unhandled None or empty cases, wrong conditions, race conditions, "
            "resources that are never closed, swallowed exceptions, and behavior changes the PR "
            "description does not mention. Ignore formatting. " + FORMAT_RULES
        ),
    },
    {
        "agent_name": "Style Reviewer",
        "model_name": "gpt-5.4-mini",
        "system_prompt": (
            "You review readability and maintainability. Look for unclear names, functions doing "
            "too much, dead code, duplicated logic, missing or misleading comments, and new code "
            "paths without tests. Keep it to the five most useful points. " + FORMAT_RULES
        ),
    },
]


def build_task(diff: str) -> str:
    title = os.environ.get("PR_TITLE", "")
    body = (os.environ.get("PR_BODY") or "")[:2000]
    note = ""
    if len(diff) > MAX_DIFF_CHARS:
        diff = diff[:MAX_DIFF_CHARS]
        note = "\n(The diff was truncated; review what is shown.)"
    return f"Pull request: {title}\n\nDescription:\n{body}\n\nDiff:{note}\n```diff\n{diff}\n```"


def run_swarm(task: str) -> dict:
    payload = {
        "name": "PR Review",
        "description": "Security, logic and style review of a pull request",
        "swarm_type": "ConcurrentWorkflow",
        "task": task,
        "agents": [
            {**r, "max_loops": 1, "max_tokens": 3000, "temperature": 0.2} for r in REVIEWERS
        ],
    }
    req = urllib.request.Request(
        API_URL,
        data=json.dumps(payload).encode(),
        headers={"x-api-key": os.environ["SWARMS_API_KEY"], "Content-Type": "application/json"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=300) as resp:
            return json.load(resp)
    except urllib.error.HTTPError as e:
        sys.exit(f"Swarms API returned {e.code}: {e.read().decode()[:500]}")


def main() -> None:
    diff = open(sys.argv[1], encoding="utf-8", errors="replace").read()
    if not diff.strip():
        print("### AI review\n\nNo reviewable changes in this pull request.")
        return

    result = run_swarm(build_task(diff))

    # `output` is a list of {role, content} messages; role is the agent's name.
    answers = {}
    for message in result.get("output", []):
        if message.get("role") in {r["agent_name"] for r in REVIEWERS}:
            answers[message["role"]] = str(message["content"]).strip()

    lines = ["### AI review", ""]
    for r in REVIEWERS:
        lines += [f"#### {r['agent_name']} ({r['model_name']})", "", answers.get(r["agent_name"], "_No response._"), ""]
    cost = result.get("usage", {}).get("total_cost")
    footer = f"Reviewed by three agents on the [Swarms API](https://swarms.ai) in {result.get('execution_time', 0):.0f}s"
    if cost is not None:
        footer += f" for ${cost:.4f}"
    lines.append(f"<sub>{footer}. Findings are suggestions; a human approves the merge.</sub>")
    print("\n".join(lines))


if __name__ == "__main__":
    main()

The script does three things: builds one task containing the PR title, description and diff; sends it to the three agents as a ConcurrentWorkflow; and turns the output list (one message per agent, with the agent's name as role) into Markdown with a section per reviewer.

Step 4: open a pull request

Commit both files on a branch and open a PR. The workflow runs, and within a minute or two the PR gets a comment like this (abridged):

Markdown
### AI review

#### Security Reviewer (claude-sonnet-5)

- `api/export.py:42` **high**: `filename` comes from the query string and is joined into a path
  without normalization, so `../../etc/passwd` reads outside the export directory. Resolve the path
  and check it stays under `EXPORT_DIR`.

#### Logic Reviewer (gpt-5.4)

- `api/export.py:57` **medium**: when `rows` is empty the function returns `None`, but the caller
  calls `.encode()` on the result. Return an empty CSV with headers instead.

#### Style Reviewer (gpt-5.4-mini)

- `api/export.py:30` **low**: `do_export` builds the query, formats CSV and writes the file.
  Splitting the CSV formatting into its own function would make it testable.

Push another commit and the same comment is rewritten with a fresh review of the whole PR.

Make it yours

Change the reviewers. The REVIEWERS list is the whole configuration. Add a "Performance Reviewer" for a hot path, a "Migration Reviewer" that only looks at SQL files, or an "API Compatibility Reviewer" for a public SDK. More agents run at the same time, so adding one barely changes how long the review takes.

Pick models per reviewer. model_name accepts any model the platform lists, and each one is billed at its own token price. A common split is a strong model on security and logic and a small, fast one on style. Check prices with GET /v1/models/pricing.

Block merges on critical findings. If you want the check to fail when the security reviewer reports something critical, add this to the end of main() and make the job a required status check:

Python
    if "**critical**" in answers.get("Security Reviewer", "").lower():
        sys.exit("Critical security finding; see the review comment.")

Because review.md is written before the script exits, add if: always() to the comment step so the review is still posted when the check fails.

Review large PRs in pieces. For diffs over the limit, split pr.diff by file and send one task per file group with tasks (up to 50 per request on /v1/swarm/completions), which runs the whole team once per task.

Forks, cost and privacy

  • Forked repositories. GitHub does not pass secrets to pull_request runs from forks, so the review step fails on outside contributions. Leave it that way rather than switching to pull_request_target, which runs with secrets and is unsafe to combine with checking out untrusted code. Maintainers can rerun the review on a branch they push themselves.
  • Cost. Each run is three agents reading the same diff once. You pay $0.01 per agent on swarm endpoints plus each model's token price, and the footer of every comment shows the exact total_cost from the response. Excluding lock files and generated code is the biggest saving.
  • What leaves your repository. Only the diff, title and description are sent to the API. Every request is logged in your Swarms Cloud account, where you can review what was sent and what it cost.

Get started

  1. Create an API key at cloud.swarms.world and add it as the SWARMS_API_KEY secret.
  2. Copy the workflow and script above into your repository.
  3. Open a pull request.

The Swarms API docs list every swarm type the endpoint supports, and Swarm Architectures Explained shows when to use a pipeline, a panel or a hierarchy instead of reviewers in parallel. If the bot needs to review many repositories at once, the batch endpoints on the Pro plan run many swarms in one request.

More from the blog

Swarms v18 'Collective': Self-Organizing Swarms, A2A, Native Async Agents, Structured Output, and Token Usage on Every Structure
Engineering

Swarms v18 'Collective': Self-Organizing Swarms, A2A, Native Async Agents, Structured Output, and Token Usage on Every Structure

The complete technical changelog for Swarms v18, code-named Collective. SelfOrganizingSwarm runs a leaderless team that coordinates by message, MessageBoard gives agents a forum they work through tools, A2AServer and A2AClient put any agent on the A2A protocol, Agent.arun runs natively on the event loop, output_schema returns a validated Pydantic object, every multi-agent structure reports its token usage, seven structures force the tool call they depend on, images actually reach the model, telemetry is off by default, and importing swarms and building the first Agent takes half the time. Every new feature, improvement, bug fix and removal from November 2 to December 1, 2026, day by day.

Deploy AI Agents Without Servers: Scheduled and Event-Driven Agents With One API Call
Guides

Deploy AI Agents Without Servers: Scheduled and Event-Driven Agents With One API Call

Run AI agents on a schedule or in response to webhooks from Vercel Cron, AWS Lambda or Cloudflare Workers, with no Python runtime, worker process or queue to maintain. Each agent run is one HTTPS request to the Swarms API. TypeScript code for all three platforms.

The OpenAI Assistants API Has Shut Down: How to Migrate Your Agents to the Swarms API
Guides

The OpenAI Assistants API Has Shut Down: How to Migrate Your Agents to the Swarms API

OpenAI sunset the Assistants API on August 26, 2026. This guide maps assistants, threads, runs, function tools and file search to the Swarms API, with before-and-after Python code, a thread store you own, MCP in place of function calling, and a one-line route for code that already uses the OpenAI SDK.