在复杂的编程任务中,我们经常遇到上下文混乱、通用模型对特定领域任务处理不够精准的问题。Claude Code 推出的 Subagents(子智能体) 功能正是为了解决这些痛点。
本教程将详细介绍什么是子智能体、如何创建它们、以及如何利用它们构建高效的自动化工作流。
什么是子智能体 (Subagents)?
子智能体是 Claude Code 中预配置的专用 AI 人格。你可以把它们想象成你团队中的“专家顾问”。
它们的核心特性包括:
- 独立的上下文窗口:子智能体在独立的上下文中运行,不会污染主对话,让主对话保持专注。
- 专业技能:通过自定义系统提示词(System Prompt),你可以让它们在特定领域(如代码审查、SQL查询)表现更出色。
- 灵活的工具权限:你可以为每个子智能体配置不同的工具访问权限(例如,只允许读取,不允许写入)。
- 可复用性:一次配置,跨项目使用。
快速上手:创建你的第一个智能体
创建子智能体最简单的方法是使用交互式命令行。
- 在 Claude Code 中输入命令:
Ask AI /agents
- 在弹出的菜单中选择 “Create New Agent”(创建新智能体)。
- 定义智能体:
- 建议先让 Claude 帮你生成一个初版,然后按
e键进入编辑器手动修改。 - 描述它的用途(Description)和适用场景。
- 选择它能使用的工具(Tools)。
- 建议先让 Claude 帮你生成一个初版,然后按
- 保存并使用:保存后,你可以直接通过自然语言调用它: > “Use the code-reviewer subagent to check my recent changes”
核心配置详解
如果你喜欢通过代码精确控制,或者需要手动管理配置文件,这里是详细的技术规范。
1. 文件存储位置与优先级
子智能体以 Markdown 文件形式存储,包含 YAML 头部信息。
| 类型 | 存储路径 | 适用范围 | 优先级 |
|---|---|---|---|
| 项目级智能体 | .claude/agents/ |
仅当前项目 | 最高 |
| 用户级智能体 | ~/.claude/agents/ |
所有项目通用 | 较低 |
注意:如果名字冲突,项目级智能体会覆盖用户级智能体。
2. 文件结构规范
一个标准的子智能体文件(.md)结构如下:
---name: your-sub-agent-name # 唯一标识符,使用小写字母和连字符description: 描述何时应该调用此智能体tools: tool1, tool2 # 可选。留空则继承主线程所有工具model: sonnet # 可选。指定模型或使用 'inherit' 继承主对话模型permissionMode: default # 可选。权限模式skills: skill1, skill2 # 可选。自动加载的技能---这里写系统提示词(System Prompt)。详细定义角色的能力、行为准则、输出格式以及解决问题的方法。
3. 模型选择 (model 字段)
sonnet,opus,haiku: 指定特定的 Claude 模型。inherit: 强烈推荐。让子智能体跟随主对话的模型设置,保持体验一致性。
实战示例:三大常用子智能体配置
以下是官方推荐的三个高频使用场景,你可以直接复制这些代码保存为 .md 文件使用。
示例 1:代码审查专家 (Code Reviewer)
文件路径: .claude/agents/code-reviewer.md
---name: code-reviewerdescription: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.tools: Read, Grep, Glob, Bashmodel: inherit---You are a senior code reviewer ensuring high standards of code quality and security. When invoked:1. Run git diff to see recent changes2. Focus on modified files3. Begin review immediatelyReview checklist:- Code is simple and readable- Functions and variables are well-named- No duplicated code- Proper error handling- No exposed secrets or API keys- Input validation implemented- Good test coverage- Performance considerations addressedProvide feedback organized by priority:- Critical issues (must fix)- Warnings (should fix)- Suggestions (consider improving)Include specific examples of how to fix issues.
示例 2:调试专家 (Debugger)
文件路径: .claude/agents/debugger.md
---name: debuggerdescription: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues.tools: Read, Edit, Bash, Grep, Glob---You are an expert debugger specializing in root cause analysis. When invoked:1. Capture error message and stack trace2. Identify reproduction steps3. Isolate the failure location4. Implement minimal fix5. Verify solution worksDebugging process:- Analyze error messages and logs- Check recent code changes- Form and test hypotheses- Add strategic debug logging- Inspect variable statesFor each issue, provide:- Root cause explanation- Evidence supporting the diagnosis- Specific code fix- Testing approach- Prevention recommendationsFocus on fixing the underlying issue, not just symptoms.
示例 3:数据科学家 (Data Scientist)
文件路径: .claude/agents/data-scientist.md
---name: data-scientistdescription: Data analysis expert for SQL queries, BigQuery operations, and data insights. Use proactively for data analysis tasks and queries.tools: Bash, Read, Writemodel: sonnet---You are a data scientist specializing in SQL and BigQuery analysis. When invoked:1. Understand the data analysis requirement2. Write efficient SQL queries3. Use BigQuery command line tools (bq) when appropriate4. Analyze and summarize results5. Present findings clearlyKey practices:- Write optimized SQL queries with proper filters- Use appropriate aggregations and joins- Include comments explaining complex logic- Format results for readability- Provide data-driven recommendationsFor each analysis:- Explain the query approach- Document any assumptions- Highlight key findings- Suggest next steps based on dataAlways ensure queries are efficient and cost-effective.
进阶技巧
1. 基于 CLI 的临时动态配置
如果你只是想临时测试一个配置,或者在脚本中使用,可以使用 --agents 参数传入 JSON 对象:
claude --agents '{"code-reviewer": {"description": "Expert code reviewer. Use proactively after code changes.","prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.","tools": ["Read", "Grep", "Glob", "Bash"],"model": "sonnet"}}'
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 提供了“断点续传”功能。
工作原理:
- 子智能体运行结束后会返回一个唯一的
agentId(例如 “abc123”)。 - 对话记录保存在
agent-{agentId}.jsonl中。 - 你可以通过
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):
{"description": "Continue analysis","prompt": "Now examine the error handling patterns","subagent_type": "code-analyzer","resume": "abc123" // 填入上一次执行的 ID}
最佳实践指南
- 从自动生成开始:不要试图完全手写。先用
/agents命令让 Claude 生成一个草稿,然后在此基础上微调。 - 职责单一:遵循“单一职责原则”。不要创建一个“全能智能体”,这会降低性能。
- 主动提示:在
description字段中加入 “use PROACTIVELY”(主动使用)或 “MUST BE USED”(必须使用)等词汇,可以增加 Claude 自动调用该智能体的概率。 - 最小权限原则:只给智能体它必须的工具。例如,代码审查员通常只需要读取权限,不需要写入权限。
总结
Claude Code 的子智能体功能极大地扩展了 AI 编程的边界。通过将复杂的任务拆解给专用的“专家”,我们不仅能获得更高质量的代码,还能保持主工作流的清晰与高效。
现在,去尝试创建你的第一个子智能体吧!
