Skip to content
看累了听个音乐吧

9.5 构建 AI Agent 团队

9.5 构建 AI Agent 团队

一个 Claude 不够用?那就多来几个,各司其职。

为什么需要多个 Agent?

单个 Claude Code 会话有一个根本限制:context window。当项目足够大,任务足够复杂,一个 agent 的上下文会很快装满——它既要记住整个对话历史,又要读代码、分析问题、生成输出。

子 agent(Sub-agent)的核心思想是分治

  • 把大任务拆成小任务
  • 每个子 agent 在自己独立的 context window 里处理一个小任务
  • 主 agent 负责协调、汇总

这样既保持了每个 agent 的专注度,也避免了 context 爆炸。

内置子 Agent

Claude Code 自带几个内置子 agent,会在合适的时机自动调用:

Agent模型作用
ExploreHaiku(快速低延迟)搜索、探索代码库,只读
Plan继承主会话Plan Mode 下做背景调研,只读
General-purpose继承主会话复杂多步骤任务,可读写

比如当你问 Claude "帮我分析整个 src 目录的结构",它可能会把探索任务委托给 Explore agent——结果注入回主会话,但不占用主 context 太多空间。

这些内置 agent 不需要你手动配置,Claude 会自动决定什么时候用它们。

创建自定义子 Agent

子 agent 是一个 Markdown 文件,头部是 YAML 配置(frontmatter),正文是 system prompt。

文件格式

markdown
---
name: security-reviewer
description: Reviews code changes for security vulnerabilities. Use when asked to audit code security, check for injection risks, or review auth implementations.
model: claude-haiku-4-5
tools:
  - Read
  - Bash
allowed_tools:
  - Read
  - "Bash(grep *)"
  - "Bash(find *)"
---

You are a security-focused code reviewer specializing in web application security.

When reviewing code, always check for:
1. SQL injection vulnerabilities
2. XSS attack vectors
3. Hardcoded secrets or credentials
4. Insecure authentication patterns
5. Missing input validation

Be concise but thorough. Report each issue with: severity (critical/warning/info), location, and a specific fix suggestion.

存放位置

位置作用范围适合
.claude/agents/your-agent.md当前项目项目专属 agent,可提交 Git
~/.claude/agents/your-agent.md所有项目个人通用 agent

/agents 命令管理

在 Claude Code 里输入 /agents,打开交互式管理界面:

  • 查看所有可用 agent(内置 + 用户自定义 + 项目级)
  • 创建新 agent(可以让 Claude 帮你生成 system prompt)
  • 编辑、删除现有 agent
bash
# 从命令行列出所有 agent(不进入交互式界面)
claude agents

调用自定义 Agent

配置好后,直接在对话里描述任务,Claude 会根据 agent 的 description 字段自动判断是否委托:

You: Review the auth module for security vulnerabilities
Claude: [delegates to security-reviewer agent]
       → security-reviewer: Found 2 issues...

或者明确指定:

You: Use the security-reviewer agent to check src/auth.js

Orchestrator + Worker 模式

最常用的多 agent 架构:一个**主 agent(Orchestrator)负责规划和协调,多个工作 agent(Worker)**负责执行具体任务。

场景:大型项目全面审查

markdown
---
name: code-auditor
description: Comprehensive code audit coordinator. Use when asked to audit an entire codebase or run a multi-faceted review.
model: claude-sonnet-4-5
tools:
  - Bash
  - Read
---

You are a code audit coordinator. When asked to audit a codebase:

1. First, explore the project structure to understand what's there
2. Then delegate specialized reviews to appropriate sub-agents:
   - Security review → use the security-reviewer agent
   - Performance analysis → use the performance-analyzer agent  
   - Test coverage → use the test-coverage agent
3. Collect all results and compile a unified report

Always present findings organized by severity: Critical → Warning → Info.

配套的专业 worker:

markdown
---
name: performance-analyzer  
description: Analyzes code for performance bottlenecks, N+1 queries, memory leaks, and inefficient algorithms.
model: claude-haiku-4-5
tools:
  - Read
  - "Bash(grep *)"
---

You are a performance specialist. Analyze code for:
- N+1 database query patterns
- Synchronous I/O in async code
- Memory leaks (event listeners not cleaned up, circular refs)
- O(n²) or worse algorithms where O(n) is possible
- Missing caching opportunities

Report each issue with estimated performance impact (high/medium/low).

使用时,你只需要告诉 Orchestrator:

You: Run a comprehensive audit of the entire src/ directory

它会自动协调各个 worker,最终汇总一份完整报告。

注意事项

子 agent 不能再生 agent

为了防止无限递归,子 agent 不能再委托给其他子 agent。这是设计上的限制。如果你需要多层嵌套,用 SDK 的编程式调用来实现。

权限继承

子 agent 继承父会话的权限,再加上自己的限制。也就是说,子 agent 只能做父 agent 允许的事情的子集。

markdown
# agent 配置里的 tools 进一步限制权限
tools:
  - Read          # 只能读文件
  # 不加 Edit/Write/Bash,就不能写文件或执行命令

模型选择与成本

不同 agent 可以用不同模型——用 Haiku 做轻量探索,用 Sonnet 做复杂分析:

markdown
---
name: quick-explorer
model: claude-haiku-4-5  # 快、便宜,适合只读探索
---

---
name: deep-refactor
model: claude-sonnet-4-5  # 更强,适合复杂重构
---

这样可以在成本和能力之间取得平衡。

description 写好是关键

Claude 根据 description 字段决定什么时候委托给子 agent。描述要具体、有场景

markdown
# ❌ 太模糊
description: Helps with code

# ✅ 清晰有场景
description: Reviews TypeScript code for type safety issues, incorrect generics usage, and missing type annotations. Use when asked to check types, fix TypeScript errors, or improve type coverage.

完整示例:CI 里的多 Agent 流水线

结合 SDK + 多个子 agent,在 CI 里实现并行审查:

python
# multi-agent-review.py
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def run_security_review():
    """委托给 security-reviewer agent"""
    async for message in query(
        prompt="Use the security-reviewer agent to audit src/ for vulnerabilities",
        options=ClaudeAgentOptions(allowed_tools=["Read", "Bash"])
    ):
        if hasattr(message, "result"):
            return message.result
    return ""

async def run_performance_review():
    """委托给 performance-analyzer agent"""
    async for message in query(
        prompt="Use the performance-analyzer agent to check src/ for performance issues",
        options=ClaudeAgentOptions(allowed_tools=["Read", "Bash"])
    ):
        if hasattr(message, "result"):
            return message.result
    return ""

async def main():
    # 并行运行两个 agent
    security, performance = await asyncio.gather(
        run_security_review(),
        run_performance_review()
    )
    
    print("## Security Review\n", security)
    print("## Performance Review\n", performance)

asyncio.run(main())

到这里,你已经掌握了 Claude Code 从基础到高阶的完整体系:

  • -p 把 Claude 变成脚本工具
  • --output-format json 拿结构化输出
  • 接进 CI/CD 流水线做自动审查
  • 用 SDK 构建有状态的 Agent 应用
  • 用多 agent 协作处理大型复杂任务

最后一章是附录——CLI 参考、配置模板、常见 FAQ,当字典用。

基于 CC BY-NC-SA 4.0 协议发布