Subagents ใน SDK
กำหนดและเรียกใช้ subagents เพื่อแยก context, รัน tasks แบบ parallel, และใช้คำแนะนำเฉพาะทางใน Claude Agent SDK applications
Subagents คือ agent instances แยกกันที่ main agent ของคุณสามารถ spawn เพื่อจัดการ subtasks ที่เน้นเรื่องเดียว ใช้ subagents เพื่อแยก context สำหรับ subtasks ที่เน้น, รันการวิเคราะห์หลายอย่างแบบ parallel, และใช้คำแนะนำเฉพาะทางโดยไม่เพิ่มลงใน prompt ของ main agent
คู่มือนี้อธิบายวิธีกำหนดและใช้ subagents ใน SDK โดยใช้ parameter agents
ภาพรวม
คุณสามารถสร้าง subagents ได้สามวิธี:
- แบบ Programmatic: ใช้ parameter
agentsใน options ของquery()(TypeScript, Python) - แบบ Filesystem-based: กำหนด agents เป็นไฟล์ markdown ในไดเรกทอรี
.claude/agents/(ดู การกำหนด subagents เป็นไฟล์) - Built-in general-purpose: Claude สามารถเรียกใช้ built-in
general-purposesubagent ได้ทุกเวลาผ่าน Agent tool โดยไม่ต้องกำหนดอะไร
คู่มือนี้เน้นที่แนวทาง programmatic ซึ่งแนะนำสำหรับ SDK applications
เมื่อคุณกำหนด subagents Claude จะตัดสินใจว่าจะเรียกใช้มันหรือไม่ตาม field description ของแต่ละ subagent เขียนคำอธิบายที่ชัดเจนที่อธิบายว่าควรใช้ subagent เมื่อใด และ Claude จะ delegate งานที่เหมาะสมโดยอัตโนมัติ
ประโยชน์ของการใช้ Subagents
Context isolation
Subagent แต่ละตัวรันใน conversation ใหม่ที่สด การเรียก tool ระดับกลางและผลลัพธ์จะอยู่ภายใน subagent; เฉพาะ final message ของมันเท่านั้นที่จะกลับไปยัง parent
ตัวอย่าง: research-assistant subagent สามารถสำรวจไฟล์หลายสิบรายการโดยไม่มีเนื้อหาใดสะสมใน main conversation Parent จะได้รับสรุปที่กระชับ ไม่ใช่ทุกไฟล์ที่ subagent อ่าน
Parallelization
Subagents หลายตัวสามารถรันพร้อมกัน ดังนั้น subtasks อิสระจะเสร็จสิ้นในเวลาที่ช้าที่สุดแทนที่จะเป็นผลรวมของทั้งหมด
ตัวอย่าง: ระหว่าง code review คุณสามารถรัน style-checker, security-scanner, และ test-coverage subagents พร้อมกันแทนที่จะทำทีละตัว
คำแนะนำและความรู้เฉพาะทาง
Subagent แต่ละตัวสามารถมี system prompts ที่ปรับแต่งพร้อมความเชี่ยวชาญเฉพาะ, แนวปฏิบัติที่ดีที่สุด, และข้อจำกัด
ตัวอย่าง: database-migration subagent สามารถมีความรู้โดยละเอียดเกี่ยวกับแนวปฏิบัติ SQL, กลยุทธ์ rollback, และการตรวจสอบความสมบูรณ์ของข้อมูล
ข้อจำกัดของ Tool
Subagents สามารถจำกัดไว้เฉพาะ tools บางรายการ ลดความเสี่ยงของการกระทำที่ไม่ได้ตั้งใจ
ตัวอย่าง: doc-reviewer subagent อาจมีสิทธิ์เข้าถึงเฉพาะ Read และ Grep tools ซึ่งทำให้มั่นใจว่ามันวิเคราะห์ได้ แต่ไม่สามารถแก้ไขไฟล์เอกสารของคุณโดยไม่ตั้งใจ
การสร้าง Subagents
การกำหนดแบบ Programmatic (แนะนำ)
กำหนด subagents โดยตรงในโค้ดของคุณโดยใช้ parameter agents ตัวอย่างนี้สร้าง subagents สองตัว: code reviewer ที่มีสิทธิ์เข้าถึงแบบอ่านอย่างเดียว และ test runner ที่สามารถ execute commands ได้ Claude เรียกใช้ subagents ผ่าน Agent tool ดังนั้นรวม Agent ใน allowedTools เพื่อ auto-approve การเรียกใช้ subagents โดยไม่ต้องขอ permission:
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition
async def main():
async for message in query(
prompt="Review the authentication module for security issues",
options=ClaudeAgentOptions(
# Auto-approve these tools, including Agent for subagent invocation
allowed_tools=["Read", "Grep", "Glob", "Agent"],
agents={
"code-reviewer": AgentDefinition(
# description tells Claude when to use this subagent
description="Expert code review specialist. Use for quality, security, and maintainability reviews.",
# prompt defines the subagent's behavior and expertise
prompt="""You are a code review specialist with expertise in security, performance, and best practices.
When reviewing code:
- Identify security vulnerabilities
- Check for performance issues
- Verify adherence to coding standards
- Suggest specific improvements
Be thorough but concise in your feedback.""",
# tools restricts what the subagent can do (read-only here)
tools=["Read", "Grep", "Glob"],
# model overrides the default model for this subagent
model="sonnet",
),
"test-runner": AgentDefinition(
description="Runs and analyzes test suites. Use for test execution and coverage analysis.",
prompt="""You are a test execution specialist. Run tests and provide clear analysis of results.
Focus on:
- Running test commands
- Analyzing test output
- Identifying failing tests
- Suggesting fixes for failures""",
# Bash access lets this subagent run test commands
tools=["Bash", "Read", "Grep"],
),
},
),
):
if hasattr(message, "result"):
print(message.result)
asyncio.run(main())
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Review the authentication module for security issues",
options: {
// Auto-approve these tools, including Agent for subagent invocation
allowedTools: ["Read", "Grep", "Glob", "Agent"],
agents: {
"code-reviewer": {
// description tells Claude when to use this subagent
description:
"Expert code review specialist. Use for quality, security, and maintainability reviews.",
// prompt defines the subagent's behavior and expertise
prompt: `You are a code review specialist with expertise in security, performance, and best practices.
When reviewing code:
- Identify security vulnerabilities
- Check for performance issues
- Verify adherence to coding standards
- Suggest specific improvements
Be thorough but concise in your feedback.`,
// tools restricts what the subagent can do (read-only here)
tools: ["Read", "Grep", "Glob"],
// model overrides the default model for this subagent
model: "sonnet"
},
"test-runner": {
description:
"Runs and analyzes test suites. Use for test execution and coverage analysis.",
prompt: `You are a test execution specialist. Run tests and provide clear analysis of results.
Focus on:
- Running test commands
- Analyzing test output
- Identifying failing tests
- Suggesting fixes for failures`,
// Bash access lets this subagent run test commands
tools: ["Bash", "Read", "Grep"]
}
}
}
})) {
if ("result" in message) console.log(message.result);
}
การ Configure AgentDefinition
| Field | Type | Required | คำอธิบาย |
|---|---|---|---|
description | string | ใช่ | คำอธิบายภาษาธรรมชาติว่าเมื่อใดควรใช้ agent นี้ |
prompt | string | ใช่ | System prompt ของ agent ที่กำหนดบทบาทและพฤติกรรม |
tools | string[] | ไม่ | Array ของชื่อ tool ที่อนุญาต ถ้าละไว้จะสืบทอด tools ทั้งหมด |
disallowedTools | string[] | ไม่ | Array ของชื่อ tool ที่จะลบออกจาก tool set ของ agent |
model | string | ไม่ | Model override สำหรับ agent นี้ รับ alias เช่น 'fable', 'opus', 'sonnet', 'haiku' |
skills | string[] | ไม่ | List ชื่อ skill ที่จะ preload เข้า context ของ agent เมื่อเริ่มต้น |
maxTurns | number | ไม่ | จำนวน turns สูงสุดก่อนที่ agent จะหยุด |
background | boolean | ไม่ | รัน agent นี้เป็น background task แบบ non-blocking เมื่อถูกเรียกใช้ |
effort | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | number | ไม่ | ระดับ reasoning effort สำหรับ agent นี้ |
permissionMode | PermissionMode | ไม่ | Permission mode สำหรับการ execute tool ภายใน agent นี้ |
ตั้งแต่ Claude Code v2.1.172 subagents สามารถ spawn subagents ของตัวเองได้ background subagent ห้าระดับต่ำกว่า main agent ไม่สามารถ spawn subagents เพิ่มเติมได้; foreground subagents สามารถ spawn ได้ทุกความลึก
สิ่งที่ Subagents สืบทอด
Context window ของ subagent เริ่มต้นใหม่ (ไม่มี parent conversation) แต่ไม่ว่างเปล่า ช่องทางเดียวจาก parent ไปยัง subagent คือ prompt string ของ Agent tool ดังนั้นรวม file paths, error messages, หรือการตัดสินใจที่ subagent ต้องการโดยตรงใน prompt นั้น
| Subagent ได้รับ | Subagent ไม่ได้รับ |
|---|---|
System prompt ของตัวเอง (AgentDefinition.prompt) และ prompt ของ Agent tool | ประวัติ conversation หรือผลลัพธ์ tool ของ parent |
Project CLAUDE.md (โหลดผ่าน settingSources) | เนื้อหา skill ที่ preload นอกจากจะระบุใน AgentDefinition.skills |
Tool definitions (สืบทอดจาก parent หรือ subset ใน tools) | System prompt ของ parent |
การเรียกใช้ Subagents
การเรียกใช้อัตโนมัติ
Claude ตัดสินใจโดยอัตโนมัติว่าจะเรียกใช้ subagents เมื่อใดตาม task และ description ของแต่ละ subagent
การเรียกใช้อย่างชัดเจน
เพื่อรับประกันว่า Claude จะใช้ subagent เฉพาะ ให้ระบุชื่อมันใน prompt ของคุณ:
"Use the code-reviewer agent to check the authentication module"
Dynamic Agent Configuration
คุณสามารถสร้าง agent definitions แบบ dynamic ตาม runtime conditions ตัวอย่างนี้สร้าง security reviewer ที่มีระดับความเข้มงวดต่างกัน:
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition
# Factory function that returns an AgentDefinition
def create_security_agent(security_level: str) -> AgentDefinition:
is_strict = security_level == "strict"
return AgentDefinition(
description="Security code reviewer",
prompt=f"You are a {'strict' if is_strict else 'balanced'} security reviewer...",
tools=["Read", "Grep", "Glob"],
model="opus" if is_strict else "sonnet",
)
async def main():
async for message in query(
prompt="Review this PR for security issues",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Grep", "Glob", "Agent"],
agents={
"security-reviewer": create_security_agent("strict")
},
),
):
if hasattr(message, "result"):
print(message.result)
asyncio.run(main())
import { query, type AgentDefinition } from "@anthropic-ai/claude-agent-sdk";
function createSecurityAgent(securityLevel: "basic" | "strict"): AgentDefinition {
const isStrict = securityLevel === "strict";
return {
description: "Security code reviewer",
prompt: `You are a ${isStrict ? "strict" : "balanced"} security reviewer...`,
tools: ["Read", "Grep", "Glob"],
model: isStrict ? "opus" : "sonnet"
};
}
for await (const message of query({
prompt: "Review this PR for security issues",
options: {
allowedTools: ["Read", "Grep", "Glob", "Agent"],
agents: {
"security-reviewer": createSecurityAgent("strict")
}
}
})) {
if ("result" in message) console.log(message.result);
}
การตรวจจับการเรียกใช้ Subagent
Subagents ถูกเรียกใช้ผ่าน Agent tool หากต้องการตรวจจับเมื่อ subagent ถูกเรียกใช้ ให้ตรวจสอบ tool_use blocks ที่ name เป็น "Agent" Messages จากภายใน context ของ subagent จะมี field parent_tool_use_id
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition, ToolUseBlock
async def main():
async for message in query(
prompt="Use the code-reviewer agent to review this codebase",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Glob", "Grep", "Agent"],
agents={
"code-reviewer": AgentDefinition(
description="Expert code reviewer.",
prompt="Analyze code quality and suggest improvements.",
tools=["Read", "Glob", "Grep"],
)
},
),
):
# Check for subagent invocation
if hasattr(message, "content") and message.content:
for block in message.content:
if isinstance(block, ToolUseBlock) and block.name in ("Task", "Agent"):
print(f"Subagent invoked: {block.input.get('subagent_type')}")
# Check if this message is from within a subagent's context
if hasattr(message, "parent_tool_use_id") and message.parent_tool_use_id:
print(" (running inside subagent)")
if hasattr(message, "result"):
print(message.result)
asyncio.run(main())
ข้อจำกัดของ Tool
Subagents สามารถจำกัดสิทธิ์เข้าถึง tool ผ่าน field tools:
| Use case | Tools | คำอธิบาย |
|---|---|---|
| Read-only analysis | Read, Grep, Glob | ตรวจสอบโค้ดแต่ไม่สามารถแก้ไขหรือ execute |
| Test execution | Bash, Read, Grep | รัน commands และวิเคราะห์ output |
| Code modification | Read, Edit, Write, Grep, Glob | Read/write เต็มรูปแบบโดยไม่มีการ execute |
| Full access | Tools ทั้งหมด | สืบทอด tools ทั้งหมดจาก parent (ละเว้น field tools) |
การแก้ไขปัญหา
Claude ไม่ Delegate ให้ Subagents
หาก Claude ทำ tasks โดยตรงแทนที่จะ delegate ให้ subagent:
- ตรวจสอบว่า Agent invocations ได้รับการอนุมัติ: รวม
AgentในallowedToolsเพื่อ auto-approve การเรียก subagent โดยไม่มีมัน Agent invocations จะ fall through ไปยัง callbackcanUseToolหรือถูกปฏิเสธใน modedontAsk - ใช้ explicit prompting: ระบุ subagent ตามชื่อใน prompt ของคุณ
- เขียนคำอธิบายที่ชัดเจน: อธิบายว่าควรใช้ subagent เมื่อใด
เอกสารที่เกี่ยวข้อง
- Claude Code subagents: เอกสาร subagent ครบถ้วนรวมถึงการกำหนดแบบ filesystem-based
- Dynamic workflows: orchestrate subagents หลายตัวจาก script
- ภาพรวม SDK: เริ่มต้นกับ Claude Agent SDK