在复杂的编程任务中,我们经常遇到上下文混乱、通用模型对特定领域任务处理不够精准的问题。Claude Code 推出的 Subagents(子智能体) 功能正是为了解决这些痛点。

本教程将详细介绍什么是子智能体、如何创建它们、以及如何利用它们构建高效的自动化工作流。


什么是子智能体 (Subagents)?

子智能体是 Claude Code 中预配置的专用 AI 人格。你可以把它们想象成你团队中的“专家顾问”。

它们的核心特性包括:

  • 独立的上下文窗口:子智能体在独立的上下文中运行,不会污染主对话,让主对话保持专注。
  • 专业技能:通过自定义系统提示词(System Prompt),你可以让它们在特定领域(如代码审查、SQL查询)表现更出色。
  • 灵活的工具权限:你可以为每个子智能体配置不同的工具访问权限(例如,只允许读取,不允许写入)。
  • 可复用性:一次配置,跨项目使用。

快速上手:创建你的第一个智能体

创建子智能体最简单的方法是使用交互式命令行。

  1. 在 Claude Code 中输入命令:
    1. Ask AI /agents
  2. 在弹出的菜单中选择 “Create New Agent”(创建新智能体)。
  3. 定义智能体
    • 建议先让 Claude 帮你生成一个初版,然后按 e 键进入编辑器手动修改。
    • 描述它的用途(Description)和适用场景。
    • 选择它能使用的工具(Tools)。
  4. 保存并使用:保存后,你可以直接通过自然语言调用它: > “Use the code-reviewer subagent to check my recent changes”

核心配置详解

如果你喜欢通过代码精确控制,或者需要手动管理配置文件,这里是详细的技术规范。

1. 文件存储位置与优先级

子智能体以 Markdown 文件形式存储,包含 YAML 头部信息。

类型 存储路径 适用范围 优先级
项目级智能体 .claude/agents/ 仅当前项目 最高
用户级智能体 ~/.claude/agents/ 所有项目通用 较低

注意:如果名字冲突,项目级智能体会覆盖用户级智能体。

2. 文件结构规范

一个标准的子智能体文件(.md)结构如下:

  1. ---
  2. name: your-sub-agent-name # 唯一标识符,使用小写字母和连字符
  3. description: 描述何时应该调用此智能体
  4. tools: tool1, tool2 # 可选。留空则继承主线程所有工具
  5. model: sonnet # 可选。指定模型或使用 'inherit' 继承主对话模型
  6. permissionMode: default # 可选。权限模式
  7. skills: skill1, skill2 # 可选。自动加载的技能
  8. ---
  9. 这里写系统提示词(System Prompt)。
  10. 详细定义角色的能力、行为准则、输出格式以及解决问题的方法。

3. 模型选择 (model 字段)

  • sonnet, opus, haiku: 指定特定的 Claude 模型。
  • inherit: 强烈推荐。让子智能体跟随主对话的模型设置,保持体验一致性。

实战示例:三大常用子智能体配置

以下是官方推荐的三个高频使用场景,你可以直接复制这些代码保存为 .md 文件使用。

示例 1:代码审查专家 (Code Reviewer)

文件路径: .claude/agents/code-reviewer.md

  1. ---
  2. name: code-reviewer
  3. description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.
  4. tools: Read, Grep, Glob, Bash
  5. model: inherit
  6. ---
  7. You are a senior code reviewer ensuring high standards of code quality and security. When invoked:
  8. 1. Run git diff to see recent changes
  9. 2. Focus on modified files
  10. 3. Begin review immediately
  11. Review checklist:
  12. - Code is simple and readable
  13. - Functions and variables are well-named
  14. - No duplicated code
  15. - Proper error handling
  16. - No exposed secrets or API keys
  17. - Input validation implemented
  18. - Good test coverage
  19. - Performance considerations addressed
  20. Provide feedback organized by priority:
  21. - Critical issues (must fix)
  22. - Warnings (should fix)
  23. - Suggestions (consider improving)
  24. Include specific examples of how to fix issues.

示例 2:调试专家 (Debugger)

文件路径: .claude/agents/debugger.md

  1. ---
  2. name: debugger
  3. description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues.
  4. tools: Read, Edit, Bash, Grep, Glob
  5. ---
  6. You are an expert debugger specializing in root cause analysis. When invoked:
  7. 1. Capture error message and stack trace
  8. 2. Identify reproduction steps
  9. 3. Isolate the failure location
  10. 4. Implement minimal fix
  11. 5. Verify solution works
  12. Debugging process:
  13. - Analyze error messages and logs
  14. - Check recent code changes
  15. - Form and test hypotheses
  16. - Add strategic debug logging
  17. - Inspect variable states
  18. For each issue, provide:
  19. - Root cause explanation
  20. - Evidence supporting the diagnosis
  21. - Specific code fix
  22. - Testing approach
  23. - Prevention recommendations
  24. Focus on fixing the underlying issue, not just symptoms.

示例 3:数据科学家 (Data Scientist)

文件路径: .claude/agents/data-scientist.md

  1. ---
  2. name: data-scientist
  3. description: Data analysis expert for SQL queries, BigQuery operations, and data insights. Use proactively for data analysis tasks and queries.
  4. tools: Bash, Read, Write
  5. model: sonnet
  6. ---
  7. You are a data scientist specializing in SQL and BigQuery analysis. When invoked:
  8. 1. Understand the data analysis requirement
  9. 2. Write efficient SQL queries
  10. 3. Use BigQuery command line tools (bq) when appropriate
  11. 4. Analyze and summarize results
  12. 5. Present findings clearly
  13. Key practices:
  14. - Write optimized SQL queries with proper filters
  15. - Use appropriate aggregations and joins
  16. - Include comments explaining complex logic
  17. - Format results for readability
  18. - Provide data-driven recommendations
  19. For each analysis:
  20. - Explain the query approach
  21. - Document any assumptions
  22. - Highlight key findings
  23. - Suggest next steps based on data
  24. Always ensure queries are efficient and cost-effective.

进阶技巧

1. 基于 CLI 的临时动态配置

如果你只是想临时测试一个配置,或者在脚本中使用,可以使用 --agents 参数传入 JSON 对象:

  1. claude --agents '{
  2. "code-reviewer": {
  3. "description": "Expert code reviewer. Use proactively after code changes.",
  4. "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
  5. "tools": ["Read", "Grep", "Glob", "Bash"],
  6. "model": "sonnet"
  7. }
  8. }'

2. 链式调用 (Chaining)

你可以通过自然语言指示 Claude 按顺序调用不同的智能体,形成工作流:

> “First use the code-analyzer subagent to find performance issues, then use the optimizer subagent to fix them.”

3. 可恢复的智能体 (Resumable Agents)

对于需要长时间运行或分阶段的任务,Claude 提供了“断点续传”功能。

工作原理:

  1. 子智能体运行结束后会返回一个唯一的 agentId (例如 “abc123”)。
  2. 对话记录保存在 agent-{agentId}.jsonl 中。
  3. 你可以通过 resume 参数恢复之前的对话上下文。

使用示例:

  • 第一步:”Use the code-analyzer agent to start reviewing the authentication module” -> (返回 ID: abc123)
  • 第二步:”Resume agent abc123 and now analyze the authorization logic as well”

编程方式调用(SDK):

  1. {
  2. "description": "Continue analysis",
  3. "prompt": "Now examine the error handling patterns",
  4. "subagent_type": "code-analyzer",
  5. "resume": "abc123" // 填入上一次执行的 ID
  6. }

最佳实践指南

  1. 从自动生成开始:不要试图完全手写。先用 /agents 命令让 Claude 生成一个草稿,然后在此基础上微调。
  2. 职责单一:遵循“单一职责原则”。不要创建一个“全能智能体”,这会降低性能。
  3. 主动提示:在 description 字段中加入 “use PROACTIVELY”(主动使用)或 “MUST BE USED”(必须使用)等词汇,可以增加 Claude 自动调用该智能体的概率。
  4. 最小权限原则:只给智能体它必须的工具。例如,代码审查员通常只需要读取权限,不需要写入权限。

总结

Claude Code 的子智能体功能极大地扩展了 AI 编程的边界。通过将复杂的任务拆解给专用的“专家”,我们不仅能获得更高质量的代码,还能保持主工作流的清晰与高效。

现在,去尝试创建你的第一个子智能体吧!

参考文档:Claude Code CLI Reference