Cùng một description:
- Giải thích cách description vừa quyết định khi nào Claude gọi subagent, vừa shape những gì main agent truyền vào subagent
- Viết output format có cấu trúc để subagent biết chính xác khi nào đã "xong"
- Thêm section Obstacles Encountered để tránh rediscovery cost
- Áp dụng principle of least privilege khi grant tool cho subagent
- Nhận diện 4 đặc tính của một subagent hiệu quả và self-audit subagent hiện tại
Mở đầu: Subagent "làm gì đó" vs subagent "hoàn thành rõ ràng"
Use this agent to investigate how the authentication system works.
Hai team tạo cùng 1 subagent từ description này. Kết quả:
Team A:
- Subagent chạy 4 phút
- Trả về 800 từ mô tả lan man về JWT, session, OAuth
- Main agent phải đọc lại hết để extract fact cần
- Lần gọi sau, subagent chạy 6 phút vì nó thử thêm góc mới
Team B:
- Subagent chạy 90 giây
- Trả về report 120 từ với 5 section cố định: entry points, validation logic, token lifecycle, edge cases, obstacles
- Main agent dùng fact ngay
- Lần gọi sau, subagent chạy 80 giây — dừng khi đủ 5 section
Điểm khác biệt không nằm ở description (gần như giống nhau). Nằm ở 4 thứ Team B đã làm mà Team A bỏ qua:
- Description cụ thể về scope + input format
- Output format có cấu trúc — subagent biết khi nào xong
- Obstacle reporting — workaround không bị mất
- Tool access tối giản — role rõ ràng, không accident
Bài này dạy bạn 4 kỹ thuật đó — theo thứ tự tác động từ cao đến thấp.
Hiểu cách config data được main agent dùng
Trước khi tune từng field, bạn cần biết chúng được main agent dùng ra sao. Có 2 luồng quan trọng:
┌──────────────────────────────────────────────────────────────┐
│ MAIN AGENT context window │
│ │
│ ┌──── System prompt ─────────────────────────────────────┐ │
│ │ │ │
│ │ Available subagents: │ │
│ │ • code-quality-reviewer — Use this agent to... │ │
│ │ • research-agent — Use this agent when... │ │
│ │ • migration-validator — Use this agent proactively... │ │
│ │ │ │
│ │ (chỉ inject NAME + DESCRIPTION, không inject body) │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ User: "Review code tôi vừa sửa trong checkout service" │
│ │
│ Main agent decides: dùng code-quality-reviewer │
│ Main agent WRITES input prompt dựa trên DESCRIPTION: │
│ → "Review the modified files in checkout service, │
│ precisely: src/checkout/api.ts, src/checkout/util.ts" │
│ │
└──────────────────────────────────────────────────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────┐
│ SUBAGENT context window (isolated, fresh) │
│ │
│ ┌── System prompt = body của config file ───────────────┐ │
│ │ You are an expert code reviewer... │ │
│ │ Output format: 1. Summary / 2. Critical / ... │ │
│ └───────────────────────────────────────────────────────┘ │
│ │
│ Input prompt (từ main agent): "Review the modified files..."│
│ │
│ [Subagent làm việc, return summary] │
└──────────────────────────────────────────────────────────────┘
2 điểm quan trọng:
name+descriptioncủa mọi subagent được đưa vào system prompt của main agent. Đây là cách main agent "biết" subagent nào tồn tại và khi nào dùng.- Khi gọi subagent, main agent tự viết input prompt — và nó dùng
descriptioncủa subagent làm guideline. Tức là description không chỉ điều khiển khi gọi, mà còn shape cả nội dung được truyền vào.
Hiểu được 2 điều này, bạn sẽ thấy tại sao edit 1 dòng description có thể đổi hoàn toàn behavior.
Kỹ thuật 1: Description shaping — viết description điều khiển được 2 layer
Trước: description vague
description: Use this agent to review code.
Main agent khi gọi sẽ viết input prompt kiểu:
Use git diff to find the recent changes and review them.
Subagent phải tự đoán file nào quan trọng. Kết quả: đọc 20 file, review 3 cái không liên quan.
Sau: description với instruction cụ thể
description: |
Use this agent to review recently modified code for quality and security.
You MUST tell the agent precisely which files you want it to review.
Main agent khi gọi bây giờ viết:
Review the following files for quality and security: src/auth/middleware.ts, src/auth/tokens.ts. Focus on JWT validation logic and session handling.
Thấy chưa? Chỉ 1 câu thêm vào description ("You MUST tell the agent precisely which files..."), và input prompt trở nên targeted.
Ví dụ kỹ thuật shaping khác
| Muốn main agent... | Thêm vào description |
|---|---|
| Liệt kê rõ file cần review | "You MUST tell the agent precisely which files to review." |
| Yêu cầu web search trả về source citations | "Return sources that can be cited." |
| Ép truyền cả context dependency | "Include related schema files and environment variables." |
| Specify severity threshold | "Only report issues at HIGH or CRITICAL severity." |
| Force output format | "Return results as markdown table with columns [...]" |
Description template pattern (hiệu quả cao)
description: |
[ONE-LINE PURPOSE.] Use this agent [trigger condition].
[EXPLICIT INSTRUCTION TO MAIN AGENT — dùng YOU MUST / ALWAYS / MAKE SURE...]
Examples:
<example>
Context: [real situation 1]
user: '[concrete message]'
assistant: '[expected behavior]'
</example>
<example>
Context: [real situation 2]
user: '[concrete message]'
assistant: '[expected behavior]'
</example>
Mẹo: Thêm từ "proactively" vào description nếu muốn tăng tần suất Claude tự gọi. Claude đã được train để nhận pattern này.
Kỹ thuật 2: Output format — trái tim của subagent đáng tin
Đây là nâng cấp quan trọng nhất bạn có thể làm cho bất kỳ subagent nào. Nó giải quyết 2 vấn đề:
- Khi nào subagent dừng? Không có format → subagent run lâu, thử thêm angle. Có format → xong đủ section là dừng.
- Output có dùng được ngay không? Không có format → main agent phải parse lan man. Có format → dùng luôn.
Format template chuẩn cho code reviewer
Provide your review in this structured format:
1. Summary
Brief overview of what you reviewed and overall assessment.
2. Critical Issues
Any security vulnerabilities, data integrity risks, or logic errors
that must be fixed immediately.
3. Major Issues
Quality problems, architecture misalignment, or significant
performance concerns.
4. Minor Issues
Style inconsistencies, documentation gaps, or minor optimizations.
5. Recommendations
Suggestions for improvement, refactoring opportunities,
or best practices to apply.
6. Approval Status
Clear statement of whether the code is ready to merge/deploy
or requires changes.
Điểm đáng chú ý:
- 6 section cố định → subagent biết chính xác cần fill đủ 6 cái là xong
- Tên section informative → subagent phân loại issue đúng severity
- Section cuối là binary status (approved / requires changes) → main agent dùng điều hướng workflow
Format template cho research subagent
Return findings in this format:
1. Direct Answer
One sentence answering the specific question asked.
2. Evidence
- File paths and line numbers supporting the answer
- Relevant code snippets (max 5 lines each)
3. Related Context
Other parts of the codebase that interact with this.
List file paths, no need to quote code.
4. Confidence Level
HIGH / MEDIUM / LOW + one sentence why.
5. Obstacles Encountered
(See next section on obstacle reporting.)
Anti-pattern cho output format
❌ Free-form: "Write a review of the code."
❌ Too strict: cố định 50 bullet, bắt output kiểu table phức tạp → subagent sẽ cố format thay vì làm việc
✅ Sweet spot: 5-8 section, mỗi section 1-2 dòng mô tả, không hard-coded word count
Kỹ thuật 3: Obstacle reporting — đừng để workaround bị lost
Hãy tưởng tượng tình huống: subagent của bạn đang làm research, phát hiện phải chạy npm install --legacy-peer-deps thay vì npm install bình thường (do một package xung đột). Nó làm xong task, trả về summary.
- Nếu bạn không yêu cầu obstacle reporting
- Lần sau subagent khác (hoặc main agent) gặp vấn đề tương tự → phải rediscover flag đó. Tốn thời gian, token, và có khi sai hướng.
- Nếu bạn yêu cầu obstacle reporting
- Summary có 1 section ghi rõ: "needed --legacy-peer-deps due to peer dep conflict in react-router". Main agent ghi nhớ, lần sau tránh.
Template Obstacle Encountered
Thêm vào cuối output format:
7. Obstacles Encountered
Report any obstacles encountered during the task. Include:
- Setup issues or environment quirks
- Workarounds discovered during the task
- Commands that needed special flags or configuration
- Dependencies or imports that caused problems
Format: one bullet per obstacle, max 2 sentences each.
If none, write "None."
Ví dụ obstacle section được subagent điền
7. Obstacles Encountered
- Had to use `pnpm install --shamefully-hoist` because dependency
@org/design-system expects peer deps at root level.
- `npm test` failed with memory error on files > 500KB.
Workaround: run with NODE_OPTIONS=--max-old-space-size=4096.
- Type check fails on src/legacy/ — intentional per tsconfig.legacy.
Do not flag this.
3 obstacle này giờ đã persist về main thread. Subagent tiếp theo hoặc human reviewer không phải đi lại đường cũ.
Khi nào cần obstacle section
| Subagent loại | Cần obstacle reporting? |
|---|---|
| Research / explore | Rất cần — environment quirks thường xuyên |
| Code reviewer | Cần — flag setup issues trong codebase |
| Test runner | Cần có (nhưng subagent test runner là anti-pattern — xem Bài 16.3) |
| Migration validator | Cần — DB-specific quirks |
| Copywriting | Không cần — không có "obstacle" kiểu environment |
Kỹ thuật 4: Principle of least privilege — chỉ grant tool thực sự cần
Mỗi tool grant thêm là thêm 2 thứ:
- Risk: Subagent có thể làm việc ngoài ý định (reviewer sửa code!)
- Role dilution: Bạn mất khả năng nhanh chóng biết "subagent này làm gì" chỉ qua nhìn config
Tool access matrix theo loại subagent
┌─────────────────────┬──────────┬──────┬──────┬────────┬───────┐
│ Loại subagent │ Read-only│ Bash │ Edit │ Web │ MCP │
├─────────────────────┼──────────┼──────┼──────┼────────┼───────┤
│ Research / Explore │ ✅ │ ❌ │ ❌ │ ⚠️ │ ⚠️ │
│ Code Reviewer │ ✅ │ ✅ │ ❌ │ ❌ │ ❌ │
│ Migration Validator │ ✅ │ ⚠️ │ ❌ │ ❌ │ ❌ │
│ Styling / Refactor │ ✅ │ ❌ │ ✅ │ ❌ │ ❌ │
│ Test Writer │ ✅ │ ⚠️ │ ✅ │ ❌ │ ❌ │
│ Doc Updater │ ✅ │ ❌ │ ✅ │ ⚠️ │ ❌ │
│ Security Audit │ ✅ │ ⚠️ │ ❌ │ ✅ │ ✅ │
│ Copywriting │ ✅ │ ❌ │ ✅ │ ⚠️ │ ❌ │
└─────────────────────┴──────────┴──────┴──────┴────────┴───────┘
✅ = Rõ ràng cần
⚠️ = Tùy use case cụ thể — grant thận trọng
❌ = Không nên grant
4 nguyên tắc khi cân nhắc grant tool
1. Mặc định deny, explicitly allow. Bắt đầu từ zero tool, chỉ add tool khi có lý do rõ ràng.
2. Read ≠ Execute. Subagent có thể đọc code không có nghĩa phải chạy được code. Reviewer cần Read; chỉ cần Bash khi cần git diff.
3. Write là ranh giới trust nghiêm ngặt. Grant Edit / Write chỉ khi job mô tả tường minh là "thay đổi code" (styling agent, refactor agent). Mọi role "phân tích" / "review" / "research" → không Write.
4. Web/MCP là loot box. Web search và MCP tool mở cửa tới dữ liệu/action ngoài codebase. Chỉ grant khi subagent thực sự cần (ví dụ: research cần web để lookup CVE database).
So sánh: Subagent yếu vs subagent mạnh
| Tiêu chí | Subagent yếu | Subagent mạnh |
|---|---|---|
| Description | "Use for code review" | Cụ thể task + instruction + 2-3 example |
| Output format | Free-form prose | 5-8 section cố định với tên rõ ràng |
| Obstacle reporting | Không có | Có section riêng với format chuẩn |
| Tool access | All tools (for safety) | Chỉ tool thực sự cần |
| Thời gian chạy | Không dự đoán được, lâu | Predictable, dừng đúng lúc |
| Output dùng được ngay? | Cần parse, đôi khi miss | Main agent dùng luôn |
| Debug khi lỗi | Khó, phải re-run | Dễ — đọc section trống biết miss gì |
Ví dụ theo ngành
📝 Về các case studies dưới đây: Đây là pattern minh hoạ — mô tả cách output format + obstacle reporting biến subagent lan man thành structured. Số liệu kết quả là ước lượng illustrative, không phải benchmark từ customer cụ thể.
Engineering — Research subagent với output format chặt
- Vấn đề
- "Team tôi hỏi mãi: 'làm sao thêm feature flag mới?' Tôi phải trả lời lặp lại 1 câu trả lời tương tự mỗi lần."
- Giải pháp
ff-researchersubagent với output format:
1. Direct Answer (1 câu: file nào cần sửa)
2. Code Template (snippet sẵn để copy)
3. Test Pattern (làm sao verify)
4. Related Flags (flag nào ảnh hưởng nếu bật cùng)
5. Obstacles
Kết quả minh hoạ: Query "add flag for checkout redesign" → nhanh chóng có đủ answer + copy-paste template. Team dừng việc ping lead dev — thời gian lead dev dành cho task thật chứ không phải trả lời query lặp lại.
Data — Migration validator với obstacle section
- Vấn đề
- "Mỗi sprint có 5-8 migration. Nửa số đó có quirk DB-specific (Postgres 14 khác 15, RLS policy...). Review gate thường miss."
- Giải pháp
migration-validatoroutput có section:
1. Schema changes summary
2. Critical risks (lock, data loss, break replication)
3. Recommended apply strategy
4. Obstacles (DB version quirks, extension dependencies, special user privileges needed)
Kết quả minh hoạ: Obstacle section reveal rằng một số migration cần tool ngoài (ví dụ pg_repack cho table lớn) — surface sớm những risk mà review gate thường miss, tránh downtime bất ngờ.
Marketing — Copywriting subagent với voice config
- Vấn đề
- "Default Claude Code style quá concise/technical. Khi tôi dùng nó viết landing page copy, output như README file — audience ngủ."
- Giải pháp
copywritersubagent với system prompt dài (brand voice guide) + output format:
1. Headline (8-14 words, benefit-led)
2. Subheadline (20-30 words, emotional hook)
3. 3 Benefit Bullets (max 15 words each, verb-led)
4. CTA (action + urgency)
5. Obstacles (brand voice conflicts, unclear positioning)
Kết quả minh hoạ: Copy ra từ subagent match voice rõ hơn ngay từ draft đầu — review từ Head of Marketing hiếm khi cần major rewrite, chu kỳ approval rút ngắn.
Legal — Clause auditor với explicit scope
- Vấn đề
- "Subagent tôi tạo để audit vendor contract đôi khi bay sang phân tích business implication — ngoài scope."
- Giải pháp
- Thêm vào description "You MUST only compare clauses against the template. Do NOT suggest business strategy or pricing. Do NOT rewrite clauses." Và giới hạn tool chỉ Read + Glob. Kết quả minh hoạ: Subagent dừng chạy loanh quanh ngoài scope. Output consistent 4-5 section mỗi hợp đồng — review gate cho lawyer tập trung, nhanh hơn đáng kể so với khi subagent free-form.
DevOps — Deploy checker với obstacle template
- Vấn đề
- "Deploy checker chạy xong báo 'All 12 checks passed'. Nhưng nếu 1 check dùng flag không chuẩn, lần sau SRE khác không biết."
- Giải pháp
- Thêm obstacle reporting nghiêm:
7. Obstacles Encountered
- List every non-default command or config used during checks.
- If a check passed only after workaround, flag it.
- If a check was skipped due to environment, explain why.
Kết quả minh hoạ: Obstacle section reveal rằng một số health check cần flag non-default (ví dụ curl --insecure do self-signed cert) — surface bug cũ chưa fix. Team log issue ticket, fix tận gốc thay vì cứ chạy workaround mãi.
Anti-patterns — Lỗi thiết kế thường gặp
System prompt "You are a Python expert"
Hiện tượng:
You are an expert Python developer with 10 years of experience.
You specialize in FastAPI and async patterns.
Review my code.
- Tại sao là sai
- Claude đã có kiến thức Python/FastAPI. Expert claim không thêm capability — chỉ tạo ra subagent diễn vai. Tệ hơn: nó làm mờ chỉ dẫn thực sự cần thiết (output format, criteria cụ thể).
- Cách đúng
- Bỏ hết expert claim. Thay bằng instruction về task, output format, criteria.
Output format quá lỏng
Hiện tượng:
Return your findings in a clear, organized way.
- Tại sao là sai
- Subagent sẽ tự bịa format, khác nhau mỗi lần. Main agent khó parse, không predictable.
- Cách đúng
- Fix số section, tên section, và 1 dòng mô tả mỗi section. 5-8 section là sweet spot.
Obstacle section optional ("report if any")
Hiện tượng:
If you encountered any problems, feel free to mention them.
- Tại sao là sai
- Subagent sẽ suy diễn "không có vấn đề đáng kể" và bỏ qua. Workaround vẫn bị lost.
- Cách đúng
- Bắt buộc fill section. Nếu thật sự không có → ghi "None." Mọi setup command/flag non-default → report.
Grant tất cả tool "for safety"
- Hiện tượng
- Tick mọi checkbox tool khi tạo subagent.
- Tại sao là sai
- Reviewer có Edit → có lần nó tự sửa code thay vì report. Research có Write → ghi output vào file khi bạn chỉ muốn summary về main thread.
- Cách đúng
- Zero tool by default. Add từng cái với justification: "cần Bash cho git diff", "cần Read để đọc modified files".
Description chỉ có 1 dòng lý thuyết
Hiện tượng:
description: Use this agent to review code.
- Tại sao là sai
- Main agent không biết phân biệt case nào nên gọi, case nào không.
- Cách đúng
- 1 dòng mô tả + 1 dòng instruction (YOU MUST...) + 2-3
<example>block.
System prompt dài 5 trang nhưng không có format
- Hiện tượng
- System prompt chứa 500 dòng kiến thức domain, nhưng kết thúc bằng "Analyze and report."
- Tại sao là sai
- Knowledge dense không bù được cho thiếu format. Subagent ngập trong info → output lan man.
- Cách đúng
- Knowledge 30%, criteria 30%, output format 40%. Prompt càng ngắn càng tốt miễn là đủ 3 phần.
Áp dụng ngay
Bài tập 1: Audit subagent của bạn (~15 phút)
Lấy subagent code-quality-reviewer đã tạo ở Bài 16.1 (hoặc bất kỳ subagent hiện có).
Bước 1: Mở file config, check 4 checkpoint:
| Checkpoint | File có không? | Ghi chú |
|---|---|---|
| Description có instruction kiểu "YOU MUST..."? | ||
| Description có ≥ 2 <example> block? | ||
| System prompt có section "Output format" với 5-8 section cố định? | ||
| System prompt có section "Obstacles Encountered"? | ||
| Tool access tối giản (không grant Edit cho reviewer)? |
- Bước 2
- Với mỗi checkpoint chưa tick, viết ra 1 dòng fix. Ví dụ: "Thêm 'YOU MUST specify which files to review' vào description".
- Bước 3
- Apply fix lên file config. Save.
Bài tập 2: A/B test description shaping (~15 phút)
Bước 1: Tạo 2 version description cho cùng 1 subagent research:
Version A (vague):
description: Use this agent to research the codebase.
Version B (shaped):
description: |
Use this agent to research specific questions about the codebase.
You MUST provide the agent with:
1. A single specific question
2. Starting file paths or directories (if known)
Return answer in format: Direct Answer + Evidence with file:line refs.
Bước 2: Với mỗi version, ask main agent cùng câu:
Tôi muốn biết authentication middleware nằm ở đâu.
Bước 3: So sánh:
- Version A input prompt main agent viết ra là gì: ___________
- Version B input prompt main agent viết ra là gì: ___________
- Output nào usable hơn: ___________
Bài tập 3 (thử thách): Design output format cho use case mới (~20 phút)
Chọn 1 trong 3 scenario, thiết kế output format 5-8 section:
Scenario A: Subagent analyze log file để tìm root cause của error. Scenario B: Subagent review design mockup (.png/.fig) để flag accessibility issue. Scenario C: Subagent audit contract (.docx) để flag non-standard clauses.
Yêu cầu output format của bạn phải:
- Có section đầu là "Direct Answer" hoặc "Summary" (1-2 câu quick)
- Có ít nhất 2 section phân loại theo severity
- Có section cuối là "Obstacles Encountered"
- Tổng số section: 5-8
Mẹo nâng cao
Mẹo 1: Versioning output format
Khi sửa output format, note version ở đầu system prompt:
Team biết khi nào format thay đổi, tránh surprise khi downstream tool parse report.
Mẹo 2: Shared output format across subagents
Nếu bạn có nhiều subagent reviewer (code, security, accessibility), dùng cùng một skeleton output format. Main agent và human reviewer chỉ cần học format 1 lần.
Mẹo 3: Include "escape hatch" trong format
Thêm section cuối:
8. Out of Scope (optional)
Anything you noticed but was outside the task scope.
Max 3 bullets.
Giữ subagent tập trung vào task, nhưng không "vứt đi" observation có giá trị.
Mẹo 4: Example-driven system prompt
Nếu bạn muốn subagent output theo voice/style cụ thể, include 1-2 example output (không phải example input) ngay trong system prompt:
Example good output:
---
1. Summary: Checkout endpoint adds rate limiting...
2. Critical Issues: None.
3. Major Issues: Missing idempotency key check...
---
Claude copy style từ example nhanh hơn từ instruction.
Tóm tắt bài học
- Description có 2 vai trò: quyết định khi nào gọi subagent, và shape input prompt mà main agent truyền vào. Dùng "YOU MUST..." + examples để kiểm soát cả 2.
- Output format có cấu trúc là nâng cấp lớn nhất — tạo natural stopping point, làm output predictable, biến subagent từ "lan man" thành "đúng 5 section".
- Obstacle Encountered section bắt buộc fill — tránh team rediscover workaround, setup quirks, và flag non-default đã được một subagent tìm ra.
- Tool access tối giản theo role: read-only cho research, bash cho reviewer, edit/write chỉ cho subagent thực sự thay đổi code.
- Effective subagent = 4 đặc tính kết hợp: description cụ thể + output format + obstacle reporting + tool limit. Thiếu 1 trong 4 là subagent dễ vendor off-track.
Tài liệu tham khảo
- Anthropic Research: "Training Claude to be a better manager of subagents" — blog post về multi-agent training
- Claude Code docs: subagent configuration
- Nội bộ bài 16.1 — phần cấu hình
/agentsvà tool categories