subagent-creation

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Claude Code Subagent Creation

Claude Code子代理创建

When to use this skill

何时使用此技能

  • Defining specialized AI experts for specific tasks
  • Creating reusable agent configurations for team workflows
  • Implementing task delegation patterns
  • Setting up automated code review, debugging, or analysis workflows
  • Creating agents with custom prompts and tool permissions
  • 为特定任务定义专业AI专家
  • 为团队工作流创建可复用的代理配置
  • 实现任务委派模式
  • 搭建自动化代码审查、调试或分析工作流
  • 创建带有自定义提示词和工具权限的代理

Instructions

操作指南

Step 1: Understanding Subagents

步骤1:了解子代理

Claude Code subagents are pre-configured AI experts that the main Claude delegates work to.
Core benefits:
  • Context isolation: Each agent has separate 200K token context
  • Specialized expertise: Focused prompts for specific domains
  • Reusability: Share agents via Git across projects
  • Flexible permissions: Control which tools each agent can use
  • No nesting: Prevents infinite loops - subagents cannot spawn more subagents
Agent types:
  • Built-in agents: Explore (read-only, Haiku), Plan (research), General-purpose (Sonnet)
  • Custom agents: User-defined with custom prompts and permissions
Claude Code子代理是预先配置的AI专家,由主Claude将工作委派给它们。
核心优势:
  • 上下文隔离:每个代理拥有独立的200K令牌上下文
  • 专业领域专长:针对特定领域的聚焦提示词
  • 可复用性:通过Git在项目间共享代理
  • 灵活权限:控制每个代理可使用的工具
  • 无嵌套:防止无限循环 - 子代理无法生成更多子代理
代理类型:
  • 内置代理:Explore(只读,Haiku模型)、Plan(研究)、通用型(Sonnet模型)
  • 自定义代理:用户定义,带有自定义提示词和权限

Step 2: Agent Configuration File

步骤2:代理配置文件

Subagents are defined as Markdown files with YAML frontmatter.
File location (priority order):
  1. Project-level:
    .claude/agents/{agent-name}.md
  2. User-level:
    ~/.claude/agents/{agent-name}.md
File format:
markdown
---
name: code-reviewer
description: Review code changes for quality, security, and best practices. Use immediately after code changes.
tools: [Read, Grep, Glob, Bash, LSP]
model: inherit
---
子代理通过带有YAML前置元数据的Markdown文件定义。
文件位置(优先级顺序):
  1. 项目级:
    .claude/agents/{agent-name}.md
  2. 用户级:
    ~/.claude/agents/{agent-name}.md
文件格式:
markdown
---
name: code-reviewer
description: Review code changes for quality, security, and best practices. Use immediately after code changes.
tools: [Read, Grep, Glob, Bash, LSP]
model: inherit
---

Code Reviewer

Code Reviewer

You are a senior code reviewer with expertise in:
  • Code quality and maintainability
  • Security vulnerabilities
  • Performance optimization
  • Best practices and design patterns
You are a senior code reviewer with expertise in:
  • Code quality and maintainability
  • Security vulnerabilities
  • Performance optimization
  • Best practices and design patterns

Review Checklist

Review Checklist

  • Does the code follow project conventions?
  • Are there any security vulnerabilities?
  • Is the code readable and maintainable?
  • Are there performance concerns?
  • Are tests adequate?
  • Is documentation complete?
  • Does the code follow project conventions?
  • Are there any security vulnerabilities?
  • Is the code readable and maintainable?
  • Are there performance concerns?
  • Are tests adequate?
  • Is documentation complete?

Review Guidelines

Review Guidelines

  1. Prioritize critical issues: Security bugs, data races, memory leaks
  2. Be constructive: Provide clear explanations and suggestions
  3. Consider trade-offs: Don't optimize prematurely
  4. Reference standards: Link to relevant docs/style guides
  1. Prioritize critical issues: Security bugs, data races, memory leaks
  2. Be constructive: Provide clear explanations and suggestions
  3. Consider trade-offs: Don't optimize prematurely
  4. Reference standards: Link to relevant docs/style guides

Output Format

Output Format

undefined
undefined

Critical Issues (Must Fix)

Critical Issues (Must Fix)

  • Issue: Description File: path/to/file.ts:123 Suggestion: How to fix
  • Issue: Description File: path/to/file.ts:123 Suggestion: How to fix

Suggestions (Should Fix)

Suggestions (Should Fix)

...
...

Nice to Have

Nice to Have

...
undefined
...
undefined

Step 3: YAML Frontmatter Configuration

步骤3:YAML前置元数据配置

Required fields:
FieldTypeDescription
name
stringAgent identifier (kebab-case)
description
stringWhen to use this agent (1-2 sentences)
tools
listTools the agent can access (omit to inherit)
Optional fields:
FieldTypeDescriptionDefault
model
stringModel to use
inherit
version
stringAgent versionNone
Model options:
  • inherit
    : Use same model as main Claude
  • sonnet
    : Claude 3.5 Sonnet
  • haiku
    : Claude 3 Haiku (faster, cheaper)
  • opus
    : Claude 3 Opus
Tool options:
Read
,
Write
,
Edit
,
Grep
,
Glob
,
Bash
,
LSP
tools
必填字段:
字段类型描述
name
字符串代理标识符(短横线命名法)
description
字符串何时使用此代理(1-2句话)
tools
列表代理可访问的工具(省略则继承主代理权限)
可选字段:
字段类型描述默认值
model
字符串使用的模型
inherit
version
字符串代理版本
模型选项:
  • inherit
    : 使用与主Claude相同的模型
  • sonnet
    : Claude 3.5 Sonnet
  • haiku
    : Claude 3 Haiku(更快、更便宜)
  • opus
    : Claude 3 Opus
工具选项:
Read
,
Write
,
Edit
,
Grep
,
Glob
,
Bash
,
LSP
tools

Step 4: System Prompt Writing

步骤4:系统提示词编写

Best practices:
  1. Define role clearly: "You are a [role] with expertise in [domains]"
  2. Include checklist: Concrete steps for evaluation/execution
  3. Provide examples: Show input-output pairs
  4. Specify format: Define exactly how results should be presented
  5. Set boundaries: What the agent should NOT do
Example prompt structure:
markdown
You are a [ROLE] specializing in [DOMAIN].
最佳实践:
  1. 明确定义角色: "你是一名[角色],在[领域]拥有专业知识"
  2. 包含检查清单: 用于评估/执行的具体步骤
  3. 提供示例: 展示输入输出配对
  4. 指定格式: 明确定义结果的呈现方式
  5. 设置边界: 代理不应该做什么
示例提示词结构:
markdown
You are a [ROLE] specializing in [DOMAIN].

Responsibilities

Responsibilities

  • Task 1
  • Task 2
  • Task 1
  • Task 2

Process

Process

  1. Step 1: ...
  2. Step 2: ...
  1. Step 1: ...
  2. Step 2: ...

Checklist

Checklist

  • Item 1
  • Item 2
  • Item 1
  • Item 2

Output Format

Output Format

[Template]
[Template]

Constraints

Constraints

  • Constraint 1
  • Constraint 2
undefined
  • Constraint 1
  • Constraint 2
undefined

Step 5: Creating Common Agent Types

步骤5:创建常见代理类型

Agent 1: Code Reviewer

代理1:代码审查者

.claude/agents/code-reviewer.md
:
markdown
---
name: code-reviewer
description: Review code changes for quality, security, and best practices.
tools: [Read, Grep, Glob, LSP]
model: inherit
---
.claude/agents/code-reviewer.md
:
markdown
---
name: code-reviewer
description: Review code changes for quality, security, and best practices.
tools: [Read, Grep, Glob, LSP]
model: inherit
---

Code Reviewer

Code Reviewer

Review code changes focusing on:
  1. Security: Authentication, authorization, injection risks
  2. Quality: Clean code principles, maintainability
  3. Performance: Time/space complexity, bottlenecks
  4. Tests: Coverage, edge cases
Review code changes focusing on:
  1. Security: Authentication, authorization, injection risks
  2. Quality: Clean code principles, maintainability
  3. Performance: Time/space complexity, bottlenecks
  4. Tests: Coverage, edge cases

Priority Levels

Priority Levels

  • Critical: Security vulnerabilities, data corruption
  • High: Performance issues, logic errors
  • Medium: Code smell, missing tests
  • Low: Style, minor improvements
undefined
  • Critical: Security vulnerabilities, data corruption
  • High: Performance issues, logic errors
  • Medium: Code smell, missing tests
  • Low: Style, minor improvements
undefined

Agent 2: Debugger

代理2:调试者

.claude/agents/debugger.md
:
markdown
---
name: debugger
description: Analyze errors and implement fixes. Use when encountering bugs or failures.
tools: [Read, Write, Edit, Bash, Grep, Glob, LSP]
model: inherit
---
.claude/agents/debugger.md
:
markdown
---
name: debugger
description: Analyze errors and implement fixes. Use when encountering bugs or failures.
tools: [Read, Write, Edit, Bash, Grep, Glob, LSP]
model: inherit
---

Debugger

Debugger

Systematically debug issues:
  1. Understand the problem: Read error messages, logs
  2. Reproduce: Try to recreate the issue
  3. Analyze: Identify root cause
  4. Fix: Implement minimal fix
  5. Verify: Confirm the fix works
  6. Test: Check for regressions
Systematically debug issues:
  1. Understand the problem: Read error messages, logs
  2. Reproduce: Try to recreate the issue
  3. Analyze: Identify root cause
  4. Fix: Implement minimal fix
  5. Verify: Confirm the fix works
  6. Test: Check for regressions

Debugging Strategy

Debugging Strategy

  • Use
    grep
    to search for error-related code
  • Check recent changes with
    git log
  • Add logging if needed to trace execution
  • Fix one issue at a time
  • Verify fix doesn't break existing functionality
undefined
  • Use
    grep
    to search for error-related code
  • Check recent changes with
    git log
  • Add logging if needed to trace execution
  • Fix one issue at a time
  • Verify fix doesn't break existing functionality
undefined

Agent 3: Test Writer

代理3:测试用例编写者

.claude/agents/test-writer.md
:
markdown
---
name: test-writer
description: Write comprehensive unit and integration tests for new code.
tools: [Read, Write, Edit, Grep, Glob]
model: inherit
---
.claude/agents/test-writer.md
:
markdown
---
name: test-writer
description: Write comprehensive unit and integration tests for new code.
tools: [Read, Write, Edit, Grep, Glob]
model: inherit
---

Test Writer

Test Writer

Write tests following these principles:
  1. AAA pattern: Arrange, Act, Assert
  2. Descriptive names: Test names explain what they verify
  3. One assertion per test: Clear failure reasons
  4. Test happy path: Main functionality
  5. Test edge cases: Boundary conditions, nulls, errors
  6. Mock external dependencies: Isolate code under test
Write tests following these principles:
  1. AAA pattern: Arrange, Act, Assert
  2. Descriptive names: Test names explain what they verify
  3. One assertion per test: Clear failure reasons
  4. Test happy path: Main functionality
  5. Test edge cases: Boundary conditions, nulls, errors
  6. Mock external dependencies: Isolate code under test

Test Coverage Goals

Test Coverage Goals

  • Unit tests: 80%+ coverage
  • Integration tests: Critical user flows
  • E2E tests: Key user journeys
  • Unit tests: 80%+ coverage
  • Integration tests: Critical user flows
  • E2E tests: Key user journeys

Framework-Specific Guidelines

Framework-Specific Guidelines

Jest: Use
describe
,
test
,
expect
,
beforeEach
,
afterEach
Pytest: Use
def test_
,
assert
,
@pytest.fixture
Go testing: Use
TestXxx
,
t.Run
,
assert.Equal
undefined
Jest: Use
describe
,
test
,
expect
,
beforeEach
,
afterEach
Pytest: Use
def test_
,
assert
,
@pytest.fixture
Go testing: Use
TestXxx
,
t.Run
,
assert.Equal
undefined

Agent 4: Performance Analyzer

代理4:性能分析者

.claude/agents/performance-analyzer.md
:
markdown
---
name: performance-analyzer
description: Analyze code performance and identify optimization opportunities.
tools: [Read, Grep, Glob, LSP]
model: sonnet
---
.claude/agents/performance-analyzer.md
:
markdown
---
name: performance-analyzer
description: Analyze code performance and identify optimization opportunities.
tools: [Read, Grep, Glob, LSP]
model: sonnet
---

Performance Analyzer

Performance Analyzer

Focus on:
  1. Time complexity: Algorithm efficiency
  2. Space complexity: Memory usage
  3. Database queries: N+1 queries, missing indexes
  4. I/O operations: File system, network calls
  5. Caching: Missed caching opportunities
Focus on:
  1. Time complexity: Algorithm efficiency
  2. Space complexity: Memory usage
  3. Database queries: N+1 queries, missing indexes
  4. I/O operations: File system, network calls
  5. Caching: Missed caching opportunities

Analysis Steps

Analysis Steps

  1. Profile code to find hotspots
  2. Review algorithm choices
  3. Check database query patterns
  4. Look for redundant computations
  5. Identify parallelization opportunities
  1. Profile code to find hotspots
  2. Review algorithm choices
  3. Check database query patterns
  4. Look for redundant computations
  5. Identify parallelization opportunities

Report Format

Report Format

undefined
undefined

Performance Issues Found

Performance Issues Found

Critical (High Impact)

Critical (High Impact)

  • Impact: [description] Suggestion: [optimization]
  • Impact: [description] Suggestion: [optimization]

Moderate (Medium Impact)

Moderate (Medium Impact)

...
...

Low (Minor)

Low (Minor)

...
undefined
...
undefined

Agent 5: Documentation Writer

代理5:文档编写者

.claude/agents/doc-writer.md
:
markdown
---
name: doc-writer
description: Write clear, comprehensive documentation for code, APIs, and features.
tools: [Read, Write, Edit, Grep, Glob]
model: inherit
---
.claude/agents/doc-writer.md
:
markdown
---
name: doc-writer
description: Write clear, comprehensive documentation for code, APIs, and features.
tools: [Read, Write, Edit, Grep, Glob]
model: inherit
---

Documentation Writer

Documentation Writer

Write documentation that is:
  • Clear: Simple language, avoid jargon
  • Complete: Cover all use cases
  • Accurate: Keep docs in sync with code
  • Actionable: Include examples
  • Searchable: Use consistent terminology
Write documentation that is:
  • Clear: Simple language, avoid jargon
  • Complete: Cover all use cases
  • Accurate: Keep docs in sync with code
  • Actionable: Include examples
  • Searchable: Use consistent terminology

Documentation Types

Documentation Types

  • README: Project overview, setup, usage
  • API docs: Endpoints, parameters, examples
  • Code comments: Why, not what
  • Changelog: Version history, breaking changes
  • README: Project overview, setup, usage
  • API docs: Endpoints, parameters, examples
  • Code comments: Why, not what
  • Changelog: Version history, breaking changes

Writing Guidelines

Writing Guidelines

  1. Start with user goals
  2. Provide examples for each feature
  3. Link related documentation
  4. Update docs when code changes
  5. Use active voice and present tense
undefined
  1. Start with user goals
  2. Provide examples for each feature
  3. Link related documentation
  4. Update docs when code changes
  5. Use active voice and present tense
undefined

Step 6: CLI Configuration

步骤6:CLI配置

Create agents via CLI for automation:
Single agent:
bash
claude --agents '{
  "code-reviewer": {
    "description": "Review code changes for quality and security",
    "tools": ["Read", "Grep", "Glob", "LSP"],
    "model": "inherit"
  }
}'
Multiple agents:
bash
claude --agents '{
  "code-reviewer": {"description": "...", "tools": ["Read"]},
  "debugger": {"description": "...", "tools": ["Read", "Write", "Edit"]},
  "test-writer": {"description": "...", "tools": ["Read", "Write"]}
}'
Add hooks for automation:
bash
undefined
通过CLI创建代理以实现自动化:
单个代理:
bash
claude --agents '{
  "code-reviewer": {
    "description": "Review code changes for quality and security",
    "tools": ["Read", "Grep", "Glob", "LSP"],
    "model": "inherit"
  }
}'
多个代理:
bash
claude --agents '{
  "code-reviewer": {"description": "...", "tools": ["Read"]},
  "debugger": {"description": "...", "tools": ["Read", "Write", "Edit"]},
  "test-writer": {"description": "...", "tools": ["Read", "Write"]}
}'
添加自动化钩子:
bash
undefined

PostToolUse hook - automatically invoke debugger on errors

PostToolUse hook - automatically invoke debugger on errors

claude --hooks '{ "PostToolUse": { "onError": "debugger" } }'
undefined
claude --hooks '{ "PostToolUse": { "onError": "debugger" } }'
undefined

Step 7: Using Subagents

步骤7:使用子代理

Explicit Invocation

显式调用

Directly call an agent:
"Use code-reviewer to review the recent authentication changes."
"Invoke debugger agent to fix the failing test."
直接调用代理:
"Use code-reviewer to review the recent authentication changes."
"Invoke debugger agent to fix the failing test."

Automatic Delegation

自动委派

Claude automatically delegates based on agent descriptions:
"Refactor the authentication logic for better security."
→ Claude delegates to: code-reviewer (security expert)
"Fix the database connection timeout error."
→ Claude delegates to: debugger (error fixing)
Claude会根据代理描述自动委派任务:
"Refactor the authentication logic for better security."
→ Claude delegates to: code-reviewer (security expert)
"Fix the database connection timeout error."
→ Claude delegates to: debugger (error fixing)

Agent Chaining

代理链式调用

Chain multiple agents for complex tasks:
"Use performance-analyzer to identify bottlenecks, then debugger to fix them."
"Let code-reviewer check the changes, then doc-writer update the documentation."
为复杂任务链式调用多个代理:
"Use performance-analyzer to identify bottlenecks, then debugger to fix them."
"Let code-reviewer check the changes, then doc-writer update the documentation."

Resume Previous Context

恢复之前的上下文

Resume a previous agent session:
"Resume the code-reviewer session with agentId abc123 to continue where we left off."
恢复之前的代理会话:
"Resume the code-reviewer session with agentId abc123 to continue where we left off."

Step 8: Version Control

步骤8:版本控制

Share agents via Git:
Commit agents:
bash
cd /path/to/project
git add .claude/agents/
git commit -m "feat: add code-reviewer and debugger agents"
git push
Clone project with agents:
bash
git clone https://github.com/myorg/project.git
通过Git共享代理:
提交代理:
bash
cd /path/to/project
git add .claude/agents/
git commit -m "feat: add code-reviewer and debugger agents"
git push
克隆包含代理的项目:
bash
git clone https://github.com/myorg/project.git

Agents are automatically available in .claude/agents/

Agents are automatically available in .claude/agents/

undefined
undefined

Examples

示例

Example 1: Complete Agent Creation Workflow

示例1:完整的代理创建工作流

bash
undefined
bash
undefined

1. Create project-level agents directory

1. Create project-level agents directory

mkdir -p .claude/agents
mkdir -p .claude/agents

2. Create code-reviewer agent

2. Create code-reviewer agent

cat > .claude/agents/code-reviewer.md << 'EOF'

name: code-reviewer description: Review code changes for quality, security, and best practices. tools: [Read, Grep, Glob, LSP] model: inherit

cat > .claude/agents/code-reviewer.md << 'EOF'

name: code-reviewer description: Review code changes for quality, security, and best practices. tools: [Read, Grep, Glob, LSP] model: inherit

Code Reviewer

Code Reviewer

Review code focusing on security, quality, performance, and tests.
Review code focusing on security, quality, performance, and tests.

Priority

Priority

  • Critical: Security vulnerabilities, data corruption
  • High: Performance issues, logic errors
  • Medium: Code smell, missing tests
  • Low: Style improvements EOF
  • Critical: Security vulnerabilities, data corruption
  • High: Performance issues, logic errors
  • Medium: Code smell, missing tests
  • Low: Style improvements EOF

3. Commit to Git

3. Commit to Git

git add .claude/agents/code-reviewer.md git commit -m "feat: add code-reviewer subagent" git push
undefined
git add .claude/agents/code-reviewer.md git commit -m "feat: add code-reviewer subagent" git push
undefined

Example 2: Automated Code Review Workflow

示例2:自动化代码审查工作流

Scenario: After completing a feature, automatically review code.
Setup:
bash
undefined
Scenario: After completing a feature, automatically review code.
Setup:
bash
undefined

Create post-commit hook

Create post-commit hook

cat > .git/hooks/post-commit << 'EOF' #!/bin/bash claude --agents '{ "code-reviewer": { "description": "Review HEAD commit for quality and security", "tools": ["Read", "Grep", "Glob", "LSP"], "model": "inherit" } }' << INPUT Review the changes in the most recent commit. INPUT EOF chmod +x .git/hooks/post-commit

**Usage**:
```bash
git commit -m "feat: add user authentication"
cat > .git/hooks/post-commit << 'EOF' #!/bin/bash claude --agents '{ "code-reviewer": { "description": "Review HEAD commit for quality and security", "tools": ["Read", "Grep", "Glob", "LSP"], "model": "inherit" } }' << INPUT Review the changes in the most recent commit. INPUT EOF chmod +x .git/hooks/post-commit

**Usage**:
```bash
git commit -m "feat: add user authentication"

Post-commit hook automatically invokes code-reviewer

Post-commit hook automatically invokes code-reviewer

undefined
undefined

Example 3: Multi-Agent Pipeline

示例3:多代理流水线

Scenario: Code → Review → Test → Document
markdown
In Claude Code:

"Here's the new payment processing code I just wrote. 

Use the following agents in sequence:
1. code-reviewer - Check for security issues and quality
2. test-writer - Write unit tests for the payment flow
3. doc-writer - Update API documentation

Return a summary of all findings."
Scenario: Code → Review → Test → Document
markdown
In Claude Code:

"Here's the new payment processing code I just wrote. 

Use the following agents in sequence:
1. code-reviewer - Check for security issues and quality
2. test-writer - Write unit tests for the payment flow
3. doc-writer - Update API documentation

Return a summary of all findings."

Example 4: Specialized Domain Agent

示例4:专业领域代理

.claude/agents/database-expert.md
:
markdown
---
name: database-expert
description: Design and optimize database schemas, queries, and migrations.
tools: [Read, Write, Edit, Grep, Glob, Bash]
model: sonnet
---
.claude/agents/database-expert.md
:
markdown
---
name: database-expert
description: Design and optimize database schemas, queries, and migrations.
tools: [Read, Write, Edit, Grep, Glob, Bash]
model: sonnet
---

Database Expert

Database Expert

Expertise in:
  • SQL design (PostgreSQL, MySQL, SQLite)
  • NoSQL design (MongoDB, Redis, DynamoDB)
  • Query optimization and indexing
  • Migration strategies
  • Data modeling and normalization
Expertise in:
  • SQL design (PostgreSQL, MySQL, SQLite)
  • NoSQL design (MongoDB, Redis, DynamoDB)
  • Query optimization and indexing
  • Migration strategies
  • Data modeling and normalization

Review Checklist

Review Checklist

  • Schema normalized? (3NF for relational DBs)
  • Appropriate indexes?
  • Query performance acceptable?
  • Foreign keys/constraints defined?
  • Migration reversible?
  • Backup strategy documented?
  • Schema normalized? (3NF for relational DBs)
  • Appropriate indexes?
  • Query performance acceptable?
  • Foreign keys/constraints defined?
  • Migration reversible?
  • Backup strategy documented?

Optimization Tips

Optimization Tips

  1. Use EXPLAIN ANALYZE to analyze query plans
  2. Create composite indexes for multi-column WHERE clauses
  3. Avoid SELECT * in production
  4. Use connection pooling
  5. Implement read replicas for read-heavy workloads
undefined
  1. Use EXPLAIN ANALYZE to analyze query plans
  2. Create composite indexes for multi-column WHERE clauses
  3. Avoid SELECT * in production
  4. Use connection pooling
  5. Implement read replicas for read-heavy workloads
undefined

Design Principles

设计原则

  1. Single responsibility: Each agent has one focused role
  2. Minimal permissions: Only grant tools actually needed
  3. Detailed prompts: Include checklists, steps, examples
  4. Model selection: Choose model based on task complexity
  5. Version control: Track agent configurations in Git
  6. Reusability: Design agents to work across projects
  7. Clear descriptions: Help Claude understand when to delegate
  1. 单一职责:每个代理拥有一个聚焦的角色
  2. 最小权限:仅授予实际需要的工具权限
  3. 详细提示词:包含检查清单、步骤和示例
  4. 模型选择:根据任务复杂度选择模型
  5. 版本控制:在Git中跟踪代理配置
  6. 可复用性:设计可跨项目使用的代理
  7. 清晰描述:帮助Claude了解何时进行委派

Common Patterns

常见模式

PatternUse CaseExample
Code → Review → FixIterative improvementCode changes, review, implement fixes
Analyze → OptimizePerformanceProfile, identify issues, optimize
Design → Implement → TestFeature developmentDesign, write code, test
Document → DeployReleaseUpdate docs, deploy
模式使用场景示例
代码 → 审查 → 修复迭代改进代码变更、审查、实施修复
分析 → 优化性能优化性能分析、识别问题、优化
设计 → 实现 → 测试功能开发设计、编写代码、测试
文档 → 部署发布更新文档、部署

Best Practices

最佳实践

  1. Start with tools: Define what the agent needs, not what you think it needs
  2. Inherit model: Use
    model: inherit
    unless you need specific behavior
  3. Test prompts: Verify agents work as expected before relying on them
  4. Iterate: Improve agent prompts based on real usage
  5. Document agent usage: Add README notes on when/how to use each agent
  6. Use built-in agents: Explore, Plan, General-purpose cover many common cases
  1. 从工具开始:定义代理实际需要的工具,而非你认为它需要的
  2. 继承模型:除非需要特定行为,否则使用
    model: inherit
  3. 测试提示词:在依赖代理之前,验证其是否按预期工作
  4. 迭代改进:根据实际使用情况优化代理提示词
  5. 记录代理用法:添加README说明每个代理的使用时机和方式
  6. 使用内置代理:Explore、Plan、通用型代理可覆盖许多常见场景

Common Pitfalls

常见陷阱

  • Too broad scope: Agents should focus on one domain, not do everything
  • Missing constraints: Specify what agents should NOT do
  • Over-permissive tools: Grant minimal tools needed for the task
  • Unclear descriptions: Make descriptions specific so Claude knows when to delegate
  • No examples: Show input/output patterns in prompts
  • 范围过宽:代理应聚焦于一个领域,而非包揽所有工作
  • 缺少约束:明确指定代理不应该做什么
  • 权限过度开放:仅授予完成任务所需的最小工具权限
  • 描述模糊:让描述足够具体,以便Claude了解何时进行委派
  • 缺少示例:在提示词中展示输入输出模式

References

参考资料