Swarms Logo
指南工程

为 GitHub Pull Request 构建 AI 代码审查机器人

一个 GitHub Action:把每个 Pull Request 的 diff 发送给在 Swarms API 上并行运行的三个 AI 审查员(安全、逻辑和代码风格),发布一条合并后的审查评论,并在每次推送时更新它。附可直接复制的工作流 YAML 和一个无依赖的 Python 脚本。

Kye Gomez10 分钟阅读
为 GitHub Pull Request 构建 AI 代码审查机器人

让单个大模型“审查这个 diff”,得到的往往是一串代码风格上的挑剔,真正的 bug 被埋在中间。人类团队靠分工避免这种情况:有人看安全,有人看逻辑对不对,有人关心命名和测试。AI 审查机器人用同样的分工效果更好。

本指南构建的 GitHub Action 就是这样做的。每当有 Pull Request,它收集 diff,发送给在 Swarms API 上并行运行的三个审查智能体,再把它们的发现作为一条评论发布到 PR 上。推送新的提交时,更新的是同一条评论,不会越堆越多。

你只需要在仓库里添加两个文件和一个 secret。不需要服务器,不需要 Docker 镜像,也不需要安装任何 Python 包。

工作原理

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

三个审查员以 ConcurrentWorkflow 运行:每个都拿到同一份 diff 和各自的指令,同时运行,API 在一次响应中返回全部三个答案。每个智能体可以使用不同的模型,所以安全审查可以用更强的模型,代码风格审查用便宜的模型。

第一步:把 API 密钥添加为 secret

在 cloud.swarms.world/api-keys 创建一个密钥。在你的仓库中打开 Settings → Secrets and variables → Actions,点击 New repository secret,命名为 SWARMS_API_KEY,粘贴密钥。

第二步:工作流

保存为 .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

几个值得了解的设计选择:

  • fetch-depth: 0 会拉取基础分支,这样 git diff origin/main...HEAD 只显示这个 PR 改动的内容。
  • 排除了锁文件和压缩后的资源文件。 它们体积大,没人会手动审查,还会把真正的改动挤出模型的上下文。
  • concurrency 加 cancel-in-progress 意味着连续快速推送时,只审查最新的一次。
  • PR 标题和描述通过 env 传入,绝不直接写进 run: 脚本。把它们插值到 shell 里,是 Actions 工作流中一个经典的注入漏洞。
  • --edit-last --create-if-none 让机器人在每个 PR 上只保留一条评论,并在每次推送时更新。

第三步:审查脚本

保存为 .github/scripts/swarms_review.py。它只用 Python 标准库,CI 中不需要任何 pip install。

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()

这个脚本做三件事:把 PR 标题、描述和 diff 组装成一个任务;以 ConcurrentWorkflow 发送给三个智能体;再把 output 列表(每个智能体一条消息,role 是智能体名称)转换成 Markdown,每个审查员一节。

第四步:发起一个 Pull Request

在一个分支上提交这两个文件并发起 PR。工作流运行后,一两分钟内 PR 就会收到类似这样的评论(有删节):

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.

再推送一个提交,同一条评论会被改写为对整个 PR 的全新审查。

按你的需要定制

更换审查员。 REVIEWERS 列表就是全部配置。为热点路径加一个“性能审查员”,加一个只看 SQL 文件的“迁移审查员”,或者为公开 SDK 加一个“API 兼容性审查员”。智能体越多,同时运行的也越多,所以增加一个几乎不会延长审查时间。

为每个审查员选择模型。 model_name 接受平台列出的任何模型,每个模型按各自的 token 价格计费。常见的分配是:安全和逻辑用强模型,代码风格用小而快的模型。可以用 GET /v1/models/pricing 查询价格。

在出现严重问题时阻止合并。 如果希望安全审查员报告 critical 问题时检查失败,把下面的代码加到 main() 末尾,并把这个 job 设为必需的状态检查:

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

因为 review.md 在脚本退出前就已写好,给发布评论的步骤加上 if: always(),检查失败时审查结果依然会发布。

分块审查大型 PR。 对于超过上限的 diff,按文件拆分 pr.diff,用 tasks 为每组文件发送一个任务(/v1/swarm/completions 每个请求最多 50 个),整个审查团队会为每个任务各运行一次。

Fork、费用与隐私

  • Fork 仓库。 GitHub 不会把 secret 传给来自 fork 的 pull_request 运行,所以外部贡献的审查步骤会失败。保持这样就好,不要改用 pull_request_target:它带着 secret 运行,与检出不受信任的代码结合使用并不安全。维护者可以在自己推送的分支上重新运行审查。
  • 费用。 每次运行是三个智能体各读一遍同一份 diff。在 swarm 端点上,你为每个智能体支付 $0.01,加上各模型的 token 价格,每条评论的页脚都会显示响应中的确切 total_cost。排除锁文件和生成的代码是最大的节省。
  • 哪些内容会离开你的仓库。 发送给 API 的只有 diff、标题和描述。每个请求都会记录在你的 Swarms Cloud 账户中,你可以查看发送了什么、花了多少钱。

开始使用

  1. 在 cloud.swarms.world 创建 API 密钥,并添加为 SWARMS_API_KEY secret。
  2. 把上面的工作流和脚本复制到你的仓库。
  3. 发起一个 Pull Request。

Swarms API 文档 列出了该端点支持的所有集群类型,集群架构详解 介绍了什么时候该用流水线、评审小组或层级结构,而不是并行审查员。如果机器人需要同时审查很多仓库,Pro 方案 中的批处理端点可以在一个请求里运行多个集群。

更多文章

Swarms v18「Collective」:自组织 swarm、A2A、原生异步智能体、结构化输出,以及每个结构都能报告的 token 用量
工程

Swarms v18「Collective」:自组织 swarm、A2A、原生异步智能体、结构化输出,以及每个结构都能报告的 token 用量

Swarms v18(代号 Collective)的完整技术更新日志。SelfOrganizingSwarm 运行一支没有领导者、靠消息协调的团队;MessageBoard 给智能体一个通过工具来使用的论坛;A2AServer 和 A2AClient 让任何智能体接入 A2A 协议;Agent.arun 原生运行在事件循环上;output_schema 返回经过校验的 Pydantic 对象;每一个多智能体结构都会报告自己的 token 用量;七个结构强制要求它们所依赖的那次工具调用;图片终于真正送到了模型那里;遥测默认关闭;导入 swarms 并构建第一个 Agent 的时间减半。2026 年 11 月 2 日到 12 月 1 日之间的每一项新特性、改进、缺陷修复和删除,逐日记录。

无需服务器部署 AI 智能体:一次 API 调用实现定时与事件驱动的智能体
指南

无需服务器部署 AI 智能体:一次 API 调用实现定时与事件驱动的智能体

在 Vercel Cron、AWS Lambda 或 Cloudflare Workers 上按计划或响应 webhook 运行 AI 智能体,无需维护 Python 运行时、常驻 worker 或队列。每次智能体运行都只是对 Swarms API 的一次 HTTPS 请求。附三个平台的 TypeScript 代码。

OpenAI Assistants API 已经关停:如何把你的智能体迁移到 Swarms API
指南

OpenAI Assistants API 已经关停:如何把你的智能体迁移到 Swarms API

OpenAI 已于 2026 年 8 月 26 日停用 Assistants API。本指南把 assistant、thread、run、函数工具和文件检索逐一对应到 Swarms API,附 Python 迁移前后的对照代码、一个由你自己掌控的会话存储、用 MCP 替代函数调用,以及给已在使用 OpenAI SDK 的代码准备的一行改动方案。