taw·lmsĐăng nhập
Claude Code thực chiến — best practices từ Anthropic

Bài 8 · Best practices từ Anthropic Engineering

Sub-agents — tách context riêng cho task chuyên biệt

Bài học này chưa có video. Cứ đọc nội dung phía dưới nhé.

Sub-agent là gì?

Sub-agent = AI assistant chuyên biệt trong Claude Code, chạy với:

  • Context window RIÊNG
  • System prompt RIÊNG
  • Tool access RIÊNG (giới hạn theo nhu cầu)

Khi gặp task match description, Claude delegate cho sub-agent → sub-agent chạy độc lập → trả về summary.

Vì sao cần?

  1. Preserve main context — research nặng không làm bẩn conversation chính
  2. Enforce constraint — sub-agent chỉ có Read/Grep, không có Edit → safe
  3. Reuse config — share giữa nhiều project qua ~/.claude/agents/
  4. Specialize behavior — system prompt focused cho domain cụ thể
  5. Cost control — dùng Haiku cho task đơn giản, Opus cho phức tạp

Cách tạo

File .claude/agents/<name>.md:

---
name: security-reviewer
description: Review code for security vulnerabilities (injection, auth, secrets)
tools: Read, Grep, Glob, Bash
model: opus
---
You are a senior security engineer. Review code for:
- Injection vulnerabilities (SQL, XSS, command injection)
- Authentication and authorization flaws
- Secrets or credentials in code
- Insecure data handling

Provide specific line references and suggested fixes.

Sub-agent kích hoạt khi nào?

  • Tự động: Claude đọc description, match đúng → delegate
  • Thủ công: nói rõ "use subagent security-reviewer to check auth.ts"

Ví dụ thực tế

> Use a subagent to research how rate limiting is done across our codebase.
  Then come back with a 1-paragraph summary.

→ Sub-agent đọc 20 file, dùng 50K token trong context riêng → main agent chỉ nhận 200-word summary.

→ Tiết kiệm context, focus chính giữ sạch.

Khi nào KHÔNG nên dùng?

  • Task ngắn (1-2 file) — overhead delegation không bù lại
  • Task cần thấy reasoning chi tiết — summary mất nuance
  • Task yêu cầu nhiều round-trip user — sub-agent không hỏi lại được

Patterns thường gặp

PatternSub-agent type
Research before codingcodebase-explorer (Read, Grep, Glob)
Code reviewsecurity-reviewer (Read, Grep)
Test gentest-writer (Read, Write, Bash)
Doc gendoc-generator (Read, Write)
Refactor at scalemigration-bot (Read, Edit, Bash)

Lưu ý

Sub-agent trong cùng session. Nếu muốn nhiều session song song → xem background agents + agent teams (concept khác).

Khác MCP server, hook, skill ở đâu?

TriggerPersist data?Tool subset?
Sub-agentMatch descriptionNoYes
SkillMatch descriptionNoNo
HookPre/post actionOptionalNo
MCP serverTool callYes (own process)Yes

Nguồn chính thống: code.claude.com/docs/en/sub-agents

Bạn đang xem ở chế độ preview công khai. Để nộp bài tập, hỏi AI tutor, và làm quiz — đăng nhập.
Infrastructure noise — vì sao benchmark agent không nên tin 100%