Skip to main content

为 GitHub Actions 构建 PR 描述代理

🌐 Building a PR Description Agent for GitHub Actions

在本指南中,你将构建一个 GitHub Action,该操作使用 Mastra 代理读取拉取请求(PR)的差异,生成多语言摘要,并将其直接写入 GitHub 界面的 PR 描述中。该操作会在每次创建或更新拉取请求时运行,并根据差异的变化重新生成描述。

🌐 In this guide, you'll build a GitHub Action that uses a Mastra agent to read pull request diffs, generate multi-language summaries, and write them directly to the PR description in the GitHub UI. The action runs whenever a pull request is created or updated and regenerates the description as the diff changes.

这种方法类似于像 CodeRabbitGreptile 这样的 AI 驱动公关工具,但它是基于原生 GitHub Actions 工作流和 Mastra 代理构建的。

🌐 This approach is similar to AI-powered PR tools like CodeRabbit and Greptile, but built using native GitHub Actions workflows and Mastra agents.

该装置由三部分组成:

🌐 The setup consists of three parts:

  • 一个生成描述的 Mastra 代理
  • 一个在拉取请求时触发的 GitHub Actions 工作流
  • 一个将工作流连接到代理的 Node.js 脚本

完成的操作会用英语、西班牙语和日语写一段带有摘要的描述,每种语言都用标志表情符号标记,以便于快速浏览。例如:

🌐 The finished action writes a description with summaries in English, Spanish, and Japanese, each marked with a flag emoji for easy scanning. For example:

🇬🇧 English
This PR integrates Astro into the project, adding configuration files and updating scripts to support Astro development.

🇪🇸 Español
Este PR integra Astro en el proyecto, añadiendo archivos de configuración y actualizando scripts para soportar el desarrollo con Astro.

🇯🇵 日本語
このPRは、Astroをプロジェクトに統合し、Astro開発をサポートするための設定ファイルを追加し、スクリプトを更新します。

在你开始之前
Direct link to 在你开始之前

🌐 Before you begin

  • 一个 Mastra 项目(参见 快速开始
  • 来自支持的模型提供商的 API 密钥。如果你没有偏好,请使用OpenAI
  • Node.js v22.13.0 或更高版本

设置仓库密钥
Direct link to 设置仓库密钥

🌐 Set up repository secrets

该工作流需要访问你的模型提供商 API 密钥。请将其作为 GitHub 仓库的秘密添加:

🌐 The workflow needs access to your model provider API key. Add it as a repository secret in GitHub:

  1. 前往你在 GitHub 上的仓库

  2. 导航到 设置 > 机密和变量 > 操作

  3. 点击 新建仓库密钥

  4. 添加名称为 OPENAI_API_KEY 的 API 密钥(或你提供商的相应密钥)

    GitHub 用户界面中仓��库密钥的截图

工作流将此密钥引用为 ${{ secrets.OPENAI_API_KEY }},并在运行时将其提供给 Mastra 代理使用。

🌐 The workflow references this secret as ${{ secrets.OPENAI_API_KEY }} and makes it available to the Mastra agent at runtime.

创建描述代理
Direct link to 创建描述代理

🌐 Create the description agent

PR 描述代理负责将 Git 差异转换为清晰、便于审阅的拉取请求描述。

🌐 The PR description agent is responsible for turning a git diff into a clear, reviewer-friendly pull request description.

该代理接收来自拉取请求的原始差异。它会生成配置语言的描述,并使用表情符号标志格式化输出,使每个语言部分在拉取请求中易于浏览。

🌐 This agent receives the raw diff from a pull request. It generates descriptions in the configured languages and formats the output using emoji flags so each language section is easy to scan in the PR.

src/mastra/agents/description-agent.ts
import { Agent } from "@mastra/core/agent";

export const descriptionAgent = new Agent({
id: "description-agent",
name: "PR Description Agent",
instructions: `You are a helpful assistant that creates clear, concise PR descriptions.

When given a git diff of changed files, you will:
1. Analyze the changes to understand what was modified
2. Write a brief summary and list of changes
3. Output the same content in English, Spanish, and Japanese

Guidelines:
- Be concise but informative
- Focus on the "what" and "why" of changes
- Use technical terms appropriately
- Keep bullet points short and scannable
- Each language section should contain the same information, naturally translated

Output format:

### 🇬🇧 English

[1-2 sentence summary]

- [Change 1]
- [Change 2]
- [Change 3]

---

### 🇪🇸 Español

[Same summary in Spanish]

- [Same changes in Spanish]

---

### 🇯🇵 日本語

[Same summary in Japanese]

- [Same changes in Japanese]
`,
model: "openai/gpt-4o"
});

在本地测试代理
Direct link to 在本地测试代理

🌐 Test the agent locally

在部署工作流之前,你可以在 Mastra Studio 中测试代理,以验证其是否正确生成描述。

🌐 Before deploying the workflow, you can test the agent in Mastra Studio to verify it generates descriptions correctly.

  1. 通过在 PR URL 后添加 .diff,可以获取任何公开 GitHub PR 的差异:

    https://github.com/owner/repo/pull/123.diff
  2. 在 Studio 中打开 PR 描述代理,并使用此提示粘贴差异内容:

请为以下更改创建一个拉取请求描述。<paste the diff content here>

该代理将返回一个包含英文、西班牙文和日文部分的格式化描述。

🌐 The agent will return a formatted description with sections in English, Spanish, and Japanese.

GitHub 操作
Direct link to GitHub 操作

🌐 GitHub Actions

GitHub Actions 在 GitHub 的基础设施上以短期环境运行你的工作流。每次运行都从一个干净的虚拟机开始,检出你的代码,安装依赖,执行你的工作流步骤,然后关闭虚拟机。除非你明确将内容保存为工件或缓存,否则运行之间的内容不会被保留。

🌐 GitHub Actions run your workflows in short-lived environments on GitHub's infrastructure. Each run starts with a clean virtual machine, checks out your code, installs dependencies, runs your workflow steps, and then shuts down. Nothing persists between runs unless you explicitly save it as an artifact or cache.

创建工作流程
Direct link to 创建工作流程

🌐 Create the workflow

GitHub Actions 工作流位于 .github/workflows 目录中。在项目根目录下创建一个 .github 目录,然后在其内部创建一个 workflows 目录。添加一个名为 pr-description.yml 的文件。

🌐 GitHub Actions workflows live in the .github/workflows directory. Create a .github directory at the root of your project, then create a workflows directory inside it. Add a file named pr-description.yml.

每当拉取请求被创建或更新时,这个工作流就会运行。它会为拉取请求生成差异,调用 Mastra 代理来描述更改,并将描述直接写入 GitHub 界面的拉取请求中。

🌐 This workflow runs whenever a pull request is opened or updated. It generates a diff for the PR, calls the Mastra agent to describe the changes, and writes the description directly into the PR in the GitHub UI.

.github/workflows/pr-description.yml
name: PR Description Generator

on:
pull_request:
types: [opened, synchronize]

permissions:
contents: read
pull-requests: write

env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
PR_DIFF_FILE: /tmp/pr_diff.txt
PR_DESCRIPTION_FILE: /tmp/pr_description.md

jobs:
generate-description:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0

- uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'

- run: npm ci

- id: pr
run: |
BASE_REF=$(gh pr view ${{ github.event.pull_request.number }} --json baseRefName -q '.baseRefName')
git fetch origin $BASE_REF
git diff origin/$BASE_REF...HEAD -- . ':!package-lock.json' > $PR_DIFF_FILE

- run: npx tsx .github/scripts/generate-description.ts

- run: gh pr edit ${{ github.event.pull_request.number }} --body-file $PR_DESCRIPTION_FILE

工作流程说明
Direct link to 工作流程说明

🌐 The workflow explained

  • on: pull_request:在拉取请求被创建或更新时运行。
  • permissions: pull-requests: write:允许工作流更新 PR 描述。
  • env:定义在各步骤中使用的共享文件路径,并从仓库密钥中读取所需的值,包括 Mastra 代理使用的模型 API 密钥。
  • actions/checkout@v4 + git 命令:检出完整的仓库历史,获取 PR 的基础分支,并将 PR 的差异写入 /tmp/pr_diff.txt
  • actions/setup-node@v4:设置工作流使用的 Node.js 运行时。
  • npm ci:根据锁文件安装仓库的 Node.js 依赖。
  • generate-description.ts:读取 /tmp/pr_diff.txt,调用 Mastra 代理,并将生成的描述写入 /tmp/pr_description.md
  • gh pr edit:使用 /tmp/pr_description.md 的内容更新拉取请求描述。
note

在生成差异时,工作流会排除 package-lock.json。锁定文件通常很大且信息杂乱,包含它们可能会使代理的上下文窗口不堪重负,并使生成的描述更难理解。

🌐 The workflow excludes package-lock.json when generating the diff. Lockfiles are often large and noisy, and including them can overwhelm the agent's context window and make the resulting description harder to reason about.

创建工作流脚本
Direct link to 创建工作流脚本

🌐 Create the workflow script

.github 内创建一个 scripts 目录,并添加一个名为 generate-description.ts 的文件。

🌐 Create a scripts directory inside .github and add a file named generate-description.ts.

此脚本从 PR_DIFF_FILE 读取 PR 差异,使用 Mastra 代理生成描述,并将结果写入 PR_DESCRIPTION_FILE,供工作流发布到拉取请求。

🌐 This script reads the PR diff from PR_DIFF_FILE, generates a description using the Mastra agent, and writes the result to PR_DESCRIPTION_FILE for the workflow to publish to the pull request.

.github/scripts/generate-description.ts
import { readFileSync, writeFileSync } from "fs";
import { mastra } from "../../src/mastra";

const agent = mastra.getAgent("descriptionAgent");

await agent.generate(
`Please create a PR description for the following changes.

Git diff:
\`\`\`diff
${readFileSync(process.env.PR_DIFF_FILE!, "utf-8")}
\`\`\``,
{
onError: () => {
writeFileSync(
process.env.PR_DESCRIPTION_FILE!,
"This PR diff is too large to generate a description automatically."
);
},
onFinish: (result) => {
writeFileSync(process.env.PR_DESCRIPTION_FILE!, result.text);
}
}
);

工作流程脚本解释
Direct link to 工作流程脚本解释

🌐 The workflow script explained

  • mastra.getAgent("descriptionAgent"):获取生成 PR 描述的 Mastra 代理。
  • agent.generate(...):读取来自 PR_DIFF_FILE 的拉取请求差异,并要求代理撰写拉取请求描述。
  • onError 回调:当差异过大无法处理时,会向 PR_DESCRIPTION_FILE 写入备用消息。
  • onFinish 回调:将生成的 PR 描述写入 PR_DESCRIPTION_FILE

下一步
Direct link to 下一步

🌐 Next steps

你现在有一个使用 Mastra 代理生成多语言 PR 描述的 GitHub Action。一旦工作流和支持文件合并到你的主分支,当下一次创建或更新拉取请求时,该代理将自动运行。你可以在仓库的 Actions 标签中监控运行情况。

🌐 You now have a GitHub Action that generates multi-language PR descriptions using a Mastra agent. Once the workflow and supporting files are merged into your main branch, the agent will run automatically the next time a pull request is created or updated. You can monitor the run in the Actions tab of your repository.

在这里,你可以自定义代理指令、更改输出语言,或扩展工作流程以处理其他事件。

🌐 From here, you can customize the agent instructions, change the output languages, or extend the workflow to handle other events.

了解更多:

🌐 To learn more: