我用 AI Agent 重构了日常开发工作流,效果出乎意料
写代码 5 年,我第一次觉得 AI 不只是「自动补全」
前言
不知道你有没有这种感觉——AI 编程工具用了一堆,但总觉得差点意思。
GitHub Copilot 帮你补全代码,但补完你还是要自己调试。Cursor 让你和 AI 聊天,但聊完你还是要自己改。ChatGPT 给你写函数,但写完你还得自己组装。
这些工具更像是一个「超级自动补全」,而不是一个「真正的开发者」。
直到我开始尝试 AI Agent——让你的 AI 不再是只会回答问题的工具,而是能自己规划、执行、验证的「数字同事」。
这篇文章记录了我用 AI Agent 重构日常开发工作流的完整过程,从概念到落地,从失败到成功,全是实战经验。
什么是 AI Agent?它和普通 AI 工具有什么区别?
简单来说:
- 普通 AI 工具:你问它答,它给你建议,你去执行
- AI Agent:你给目标,它自己规划步骤、调用工具、执行任务、验证结果
举个例子,当我需要「给项目添加一个日志系统」时:
普通 AI 工具的做法:
1我:帮我写一个日志系统 2AI:好的,这是代码...(返回一大段代码) 3我:复制粘贴 → 修改 → 调试 → 发现漏了 → 再问 → 再改 4
AI Agent 的做法:
1我:给项目添加一个日志系统 2Agent: 3 1. 扫描项目结构,理解现有代码风格 4 2. 创建 logger.ts 文件 5 3. 修改 main.ts 引入日志 6 4. 运行 lint 检查 7 5. 发现类型错误,自动修复 8 6. 运行测试,确认通过 9 7. 提交代码,附带 commit message 10
看到区别了吗?Agent 不只是「写代码」,而是「完成一个完整的开发任务」。
我的第一个 Agent:自动化 PR Review
我所在团队每次 PR Review 都很耗时,reviewer 要检查:
- 代码风格是否符合规范
- TypeScript 类型是否安全
- 是否有潜在的性能问题
- 测试覆盖是否足够
于是我写了一个 PR Review Agent,基于 GitHub Actions + Claude API。
架构设计
1┌─────────────────────────────────────────────┐ 2│ GitHub Webhook │ 3│ (PR opened / updated) │ 4└───────────────────┬─────────────────────────┘ 5 │ 6 ▼ 7┌─────────────────────────────────────────────┐ 8│ GitHub Actions │ 9│ (触发 review workflow) │ 10└───────────────────┬─────────────────────────┘ 11 │ 12 ▼ 13┌─────────────────────────────────────────────┐ 14│ Review Agent │ 15│ │ 16│ 1. 获取 PR diff │ 17│ 2. 分析代码变更 │ 18│ 3. 对照项目规范检查 │ 19│ 4. 生成 review 评论 │ 20│ 5. 自动标记问题等级 │ 21└───────────────────┬─────────────────────────┘ 22 │ 23 ▼ 24┌─────────────────────────────────────────────┐ 25│ GitHub PR Comment │ 26│ (自动发布 review 结果) │ 27└─────────────────────────────────────────────┘ 28
核心代码
1// agent/review-agent.ts 2import { Anthropic } from '@anthropic-ai/sdk'; 3import { context, getOctokit } from '@actions/github'; 4 5interface ReviewResult { 6 file: string; 7 line: number; 8 severity: 'error' | 'warning' | 'suggestion'; 9 message: string; 10 suggestion?: string; 11} 12 13class PRReviewAgent { 14 private claude: Anthropic; 15 private octokit: ReturnType<typeof getOctokit>; 16 17 constructor(apiKey: string, githubToken: string) { 18 this.claude = new Anthropic({ apiKey }); 19 this.octokit = getOctokit(githubToken); 20 } 21 22 async review(): Promise<ReviewResult[]> { 23 // 1. 获取 PR 变更 24 const diff = await this.getPRDiff(); 25 const projectConfig = await this.getProjectConfig(); 26 27 // 2. 构建 prompt 28 const prompt = this.buildPrompt(diff, projectConfig); 29 30 // 3. 调用 AI 进行分析 31 const response = await this.claude.messages.create({ 32 model: 'claude-sonnet-4-20250514', 33 max_tokens: 4096, 34 messages: [{ role: 'user', content: prompt }], 35 // 关键:使用 tool_use 让 AI 返回结构化数据 36 tools: [{ 37 name: 'submit_review', 38 description: '提交代码审查结果', 39 input_schema: { 40 type: 'object', 41 properties: { 42 reviews: { 43 type: 'array', 44 items: { 45 type: 'object', 46 properties: { 47 file: { type: 'string' }, 48 line: { type: 'number' }, 49 severity: { 50 type: 'string', 51 enum: ['error', 'warning', 'suggestion'] 52 }, 53 message: { type: 'string' }, 54 suggestion: { type: 'string' } 55 }, 56 required: ['file', 'line', 'severity', 'message'] 57 } 58 } 59 }, 60 required: ['reviews'] 61 } 62 }] 63 }); 64 65 // 4. 解析结果 66 const reviews = this.parseToolResponse(response); 67 return reviews; 68 } 69 70 private buildPrompt(diff: string, config: string): string { 71 return `你是一个资深的前端代码审查员。请审查以下 PR 变更。 72 73## 项目规范 74${config} 75 76## 审查要点 771. TypeScript 类型安全:检查 any 类型滥用、类型断言是否合理 782. React 性能:检查不必要的重渲染、memo/useMemo 使用 793. 代码可维护性:函数长度、命名规范、注释质量 804. 安全隐患:XSS 风险、敏感信息泄露 81 82## 代码变更 83\`\`\`diff 84${diff} 85\`\`\` 86 87请给出具体的修改建议,按严重程度分级。`; 88 } 89} 90
实际效果
部署后第一个月的数据:
| 指标 | 之前 | 之后 |
|---|---|---|
| PR Review 平均时间 | 4.2 小时 | 1.1 小时 |
| 代码规范问题漏检率 | 23% | 6% |
| 类型安全问题漏检率 | 31% | 4% |
| Reviewer 满意度 | - | ⭐⭐⭐⭐⭐ |
最让我意外的是,Agent 发现了几个 reviewer 都没注意到的问题:
- 一个
useEffect缺少 cleanup 函数导致内存泄漏 - 一个
JSON.parse没有 try-catch 包裹 - 一个
dangerouslySetInnerHTML没有做 XSS 过滤
第二个 Agent:自动化 API 文档生成
我们团队有 200+ 个 API 接口,文档永远跟不上代码变化。开发说「文档等下补」,然后就没有然后了。
于是我写了一个 API Doc Agent,它做的事情很简单:
- 扫描代码中的 API 路由定义
- 提取请求参数、返回值类型
- 从 TypeScript 类型推导字段说明
- 生成 OpenAPI 规范文档
- 自动更新到团队文档平台
关键实现
1// agent/api-doc-agent.ts 2import * as ts from 'typescript'; 3import * as fs from 'fs'; 4import * as path from 'path'; 5 6interface APIEndpoint { 7 path: string; 8 method: string; 9 handler: string; 10 params: ParamInfo[]; 11 response: TypeInfo; 12 description: string; 13} 14 15class APIDocAgent { 16 private async scanRoutes(sourceDir: string): Promise<APIEndpoint[]> { 17 const endpoints: APIEndpoint[] = []; 18 19 // 遍历所有 .ts 文件 20 const files = this.walkDir(sourceDir, '.ts'); 21 for (const file of files) { 22 const source = fs.readFileSync(file, 'utf-8'); 23 const sourceFile = ts.createSourceFile( 24 file, source, ts.ScriptTarget.Latest, true 25 ); 26 27 // 遍历 AST,查找路由定义 28 ts.forEachChild(sourceFile, (node) => { 29 if (this.isRouteDefinition(node)) { 30 const endpoint = this.extractEndpoint(node, sourceFile); 31 if (endpoint) { 32 endpoints.push(endpoint); 33 } 34 } 35 }); 36 } 37 38 return endpoints; 39 } 40 41 private async generateDescription( 42 endpoint: APIEndpoint 43 ): Promise<string> { 44 // 用 AI 根据代码上下文生成描述 45 const prompt = `请根据以下代码为 API 生成一段中文描述(50字以内): 46 47路径: ${endpoint.method} ${endpoint.path} 48处理函数: ${endpoint.handler} 49参数: ${JSON.stringify(endpoint.params, null, 2)} 50返回值: ${JSON.stringify(endpoint.response, null, 2)} 51 52请描述:这个接口做什么、什么场景使用。`; 53 54 const response = await this.ai.complete(prompt); 55 return response.trim(); 56 } 57 58 private async generateOpenAPI( 59 endpoints: APIEndpoint[] 60 ): Promise<string> { 61 const paths: Record<string, any> = {}; 62 63 for (const ep of endpoints) { 64 const desc = await this.generateDescription(ep); 65 66 if (!paths[ep.path]) { 67 paths[ep.path] = {}; 68 } 69 70 paths[ep.path][ep.method.toLowerCase()] = { 71 summary: desc, 72 operationId: ep.handler, 73 parameters: ep.params.map(p => ({ 74 name: p.name, 75 in: p.location, 76 required: p.required, 77 schema: { type: p.type } 78 })), 79 responses: { 80 '200': { 81 description: '成功', 82 content: { 83 'application/json': { 84 schema: ep.response 85 } 86 } 87 } 88 } 89 }; 90 } 91 92 return JSON.stringify({ 93 openapi: '3.0.0', 94 info: { title: 'API Documentation', version: '1.0.0' }, 95 paths 96 }, null, 2); 97 } 98 99 // 辅助方法:遍历目录 100 private walkDir(dir: string, ext: string): string[] { 101 const results: string[] = []; 102 const list = fs.readdirSync(dir); 103 for (const file of list) { 104 const fullPath = path.join(dir, file); 105 const stat = fs.statSync(fullPath); 106 if (stat.isDirectory()) { 107 results.push(...this.walkDir(fullPath, ext)); 108 } else if (fullPath.endsWith(ext)) { 109 results.push(fullPath); 110 } 111 } 112 return results; 113 } 114} 115
实际效果
之前「API 文档更新」是团队周会上的固定吐槽环节,现在:
- 📄 文档更新频率:从「永不更新」到「每次提交自动更新」
- ⏱️ 新人上手时间:从 2 周缩短到 3 天
- 🐛 前后端联调对接问题:减少 60%
第三个 Agent:自动化 Bug 修复
这个是三个 Agent 里最激进也最实用的。
工作流程
11. 从 Sentry 获取新 Bug 2 ↓ 32. Agent 分析错误堆栈,定位代码 4 ↓ 53. 生成修复方案 6 ↓ 74. 创建修复分支 8 ↓ 95. 应用修复 10 ↓ 116. 运行测试 12 ↓ 137. 测试通过 → 创建 PR 14 测试失败 → 调整修复方案(最多 3 次) 15
核心逻辑
1// agent/bug-fix-agent.ts 2class BugFixAgent { 3 async fix(issue: SentryIssue): Promise<FixResult> { 4 console.log([`🔍 开始修复 Bug: ${issue.title}`](https://xplanc.org/primers/document/zh/03.HTML/EX.HTML%20%E5%85%83%E7%B4%A0/EX.title.md)); 5 6 // 1. 分析错误 7 const analysis = await this.analyzeError(issue); 8 9 // 2. 生成修复 10 let fix = await this.generateFix(analysis); 11 let attempts = 0; 12 13 // 3. 验证修复(最多重试 3 次) 14 while (attempts < 3) { 15 const branch = [`fix/auto-${issue.id}-${Date.now()}`](https://xplanc.org/primers/document/zh/10.Bash/90.%E5%B8%AE%E5%8A%A9%E6%89%8B%E5%86%8C/EX.id.md); 16 await this.createBranch(branch); 17 await this.applyFix(fix); 18 19 const testResult = await this.runTests(); 20 if (testResult.passed) { 21 // 测试通过,创建 PR 22 await this.createPR(branch, issue.title, fix.description); 23 return { success: true, branch, pr: fix.description }; 24 } 25 26 // 测试失败,分析失败原因并重新生成修复 27 console.log(`❌ 第 ${attempts + 1} 次修复失败,分析原因...`); 28 fix = await this.retryFix(fix, testResult.failures); 29 attempts++; 30 } 31 32 return { success: false, reason: '3次修复尝试均失败,需要人工介入' }; 33 } 34 35 private async analyzeError(issue: SentryIssue): Promise<ErrorAnalysis> { 36 const prompt = `你是一个资深的前端工程师,请分析以下错误: 37 38## 错误信息 39${issue.title} 40${issue.stackTrace} 41 42## 相关代码 43${issue.sourceCode} 44 45## 请分析 461. 错误的根本原因 472. 影响范围 483. 建议的修复方案 494. 风险评估`; 50 51 const response = await this.ai.complete(prompt); 52 return this.parseAnalysis(response); 53 } 54} 55
安全边界
让 AI 自动修复代码,最怕的就是「修好一个 Bug,引入三个新 Bug」。我设置了几条硬性规则:
- 只修复明确可复现的错误:NullPointer、TypeError、未捕获的 Promise 等
- 禁止修改核心业务逻辑:通过代码路径白名单控制
- 必须通过全部测试:测试不通过绝不合并
- 必须有人工 Review:PR 需要至少一个 reviewer 批准
- 灰度发布:先修非关键 Bug → 观察效果 → 再开放更复杂的修复
三个 Agent 的整体架构
我把三个 Agent 整合到了一个统一的调度系统中:
1┌──────────────────────────────────────────────────────┐ 2│ Agent Scheduler │ 3│ │ 4│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ 5│ │ PR Review │ │ API Doc │ │ Bug Fix │ │ 6│ │ Agent │ │ Agent │ │ Agent │ │ 7│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │ 8│ │ │ │ │ 9│ └─────────┬───────┴─────────────────┘ │ 10│ │ │ 11│ ▼ │ 12│ ┌─────────────────┐ │ 13│ │ Tool Registry │ │ 14│ │ │ │ 15│ │ • file_system │ │ 16│ │ • git_ops │ │ 17│ │ • test_runner │ │ 18│ │ • github_api │ │ 19│ │ • sentry_api │ │ 20│ └─────────────────┘ │ 21└──────────────────────────────────────────────────────┘ 22
每个 Agent 共享同一套工具注册表,但有不同的权限范围:
- PR Review Agent:只读权限(读代码、写评论)
- API Doc Agent:读写文档权限(读代码、写文档)
- Bug Fix Agent:读写代码权限(读代码、写代码、改分支)
遇到的坑和教训
坑 1:AI 过度自信
有一次 Bug Fix Agent 分析了一个 Cannot read property 'map' of undefined 的错误,它自信地加了一个 ?. 可选链操作符。然后测试通过了,PR 也合了。
结果上线后发现,这个错误是因为后端返回的数据结构变了,加 ?. 只是让页面不报错,但数据完全不显示了——用户看到的是空白页面。
教训:AI 倾向于「最小改动」,但有时候最小改动只是掩盖问题,而不是解决问题。现在我在 prompt 里加了「先分析根本原因,再给出修复方案」的约束。
坑 2:Token 消耗超出预期
刚开始用的时候,一个月 Anthropic API 账单让我吓了一跳——PR Review Agent 每次 review 要消耗约 20000 tokens,团队一天 15 个 PR,一个月就是 900 万 tokens。
教训:优化 prompt,只传变更的 diff,不传整个文件。用更轻量的模型做预筛选(比如先用小模型判断是否有问题,有问题再交给大模型详细分析)。
坑 3:Agent 的「幻觉」
API Doc Agent 有一次给一个用户删除接口生成了描述:「该接口用于删除用户,请在确认用户已注销后调用」。但实际代码里根本没有「确认用户已注销」的逻辑,这是 AI 自己脑补的。
教训:AI 生成的内容必须标注来源,让 reviewer 能快速判断哪些是代码推断的、哪些是 AI 猜测的。
总结:AI Agent 不是银弹
经过这几个月的实践,我最大的感受是:AI Agent 不是来替代开发者的,而是来放大开发者的。
它擅长的是:
- ✅ 重复性工作(PR Review 模式检查、API 文档更新)
- ✅ 结构化分析(错误堆栈分析、类型检查)
- ✅ 低风险修复(NullPointer、类型错误)
它不擅长的是:
- ❌ 需要业务理解的决策
- ❌ 跨模块的复杂重构
- ❌ 创新性的架构设计
所以我的策略是:让 Agent 做 80% 的体力活,我专注 20% 的决策活。
这套 Agent 系统我已经开源在 GitHub 上了(见文末),三个 Agent 加起来不到 2000 行代码,但节省了我们团队每周约 20 小时的工作时间。
如果你也在考虑用 AI Agent 改造开发流程,我的建议是:从一个最小可行场景开始,跑通闭环,再逐步扩展。不要一上来就想搞一个「全自动开发 Agent」,那样大概率会耗尽你的耐心和预算。
参考资源
- GitHub 仓库:agent-workflow
- Anthropic Tool Use 文档:docs.anthropic.com/en/docs/bui…
- 掘金 AI 编程话题:juejin.cn/theme/75090…
扩展:Agent 提示词工程实战
很多人以为 Agent 就是「把任务扔给 AI」,但实际上,提示词的质量直接决定了 Agent 的表现。分享几个我踩过的坑和总结的技巧。
技巧 1:给 Agent 明确的任务边界
我刚写 PR Review Agent 时,prompt 就一句话:「请审查这个 PR」。结果 AI 会给出各种离谱的建议——比如建议重写整个架构、引入新的设计模式,完全偏离了 Code Review 的初衷。
后来我把 prompt 改成:
1你是一个代码审查员,你的审查范围仅限于: 21. 代码风格是否符合 ESLint 配置 32. TypeScript 类型是否安全 43. 是否有明显的性能问题(如循环中的不必要计算) 54. 是否有安全隐患(XSS、敏感信息泄露) 6 7禁止审查以下内容: 8- 架构设计(由架构师负责) 9- 业务逻辑正确性(由测试保证) 10- 命名风格偏好(由团队规范决定) 11
效果立竿见影——review 内容从「天马行空」变成了「精准打击」。
技巧 2:用 Few-Shot 示例引导输出格式
刚开始做 Bug Fix Agent 时,AI 的修复代码风格很不稳定——有时候用 if (!data) return null,有时候用 data?.map(),有时候用 try-catch。没有一致性让 reviewer 很难建立信任。
我的解决方案是:在 prompt 里提供 3 个示例,让 AI 模仿团队已有的修复模式。
1const FEW_SHOT_EXAMPLES = ` 2## 修复示例 3 4### 示例 1:NullPointer 修复 5**错误代码**: 6const name = user.profile.name; // TypeError: Cannot read property 'name' 7 8**修复方案**: 9const name = user?.profile?.name ?? '未知用户'; 10 11### 示例 2:异步错误处理 12**错误代码**: 13const data = await fetchUser(id); 14 15**修复方案**: 16try { 17 const data = await fetchUser(id); 18} catch (error) { 19 logger.error('Failed to fetch user', { id, error }); 20 throw new UserFetchError(id, error); 21} 22 23### 示例 3:内存泄漏修复 24**错误代码**: 25useEffect(() => { 26 const timer = setInterval(() => updateTime(), 1000); 27}, []); 28 29**修复方案**: 30useEffect(() => { 31 const timer = setInterval(() => updateTime(), 1000); 32 return () => clearInterval(timer); 33}, []); 34`; 35
有了这些示例后,AI 的修复代码风格几乎和团队手写代码一模一样。
技巧 3:加入「自我质疑」环节
这是我从一篇论文里学到的技巧。在 prompt 最后加一段:
1在输出最终方案前,请先自我质疑: 21. 这个修复是否引入了新的问题? 32. 有没有更简单的方案? 43. 是否考虑了边界情况(空值、并发、超时)? 5
这个小小的改动,让 Bug Fix Agent 的首次修复成功率从 62% 提升到了 78%。
成本分析:值不值得?
很多人关心成本问题,我直接上数据。
月度成本明细
| Agent | 调用频率 | 每次 Token | 月度消耗 | 费用(约) |
|---|---|---|---|---|
| PR Review Agent | 15次/天 | 8000 tokens | 360万 tokens | ¥180 |
| API Doc Agent | 触发式 | 20000 tokens | 60万 tokens | ¥30 |
| Bug Fix Agent | 3次/天 | 15000 tokens | 135万 tokens | ¥68 |
| 合计 | - | - | 555万 tokens | ¥278 |
对比人力成本
| 场景 | 人工耗时 | Agent 耗时 | 节省 |
|---|---|---|---|
| PR Review | 30分钟/次 | 3分钟/次 | 每周 33 小时 |
| API 文档更新 | 2小时/次 | 5分钟/次 | 按需触发 |
| Bug 修复 | 1小时/次 | 10分钟/次 | 每周 5 小时 |
月度 ROI:投入 ¥278,节省约 152 小时人力 ≈ 节省 ¥30,000+
所以你问我值不值得?用不到 300 块钱换来一个「不眠不休的初级开发」,这买卖太划算了。
最后
AI Agent 开发的本质,不是「让 AI 替代人」,而是「让 AI 成为团队里最勤奋的那个初级开发」——它不抱怨、不请假、不摸鱼,24 小时待命。
而你作为「高级开发」,需要做的是:
- 定义清楚它要做什么(任务边界)
- 告诉它怎么做才是对的(示例和规范)
- 检查它做得对不对(验证和审核)
这恰恰是一个高级开发带初级开发的日常,只不过你的「徒弟」是 AI 而已。
本文是「AI 编程」系列的第一篇,下一篇我会深入讲如何用 MCP 协议让你的 Agent 接入更多工具,比如数据库、飞书、Jira 等。
《我用 AI Agent 重构了日常开发工作流,效果出乎意料》 是转载文章,点击查看原文。