Multi-agent + Cost routing — cách tiết kiệm 10-30x phí AI mà giữ chất lượng
Multi-agent (nhiều AI assistant chuyên môn) + Cost routing (chia task theo Haiku/Sonnet/Opus) là pattern advanced AI Coding 2026. Orchestrator Opus lập plan → Sonnet thực thi code → Haiku verify + lookup. Cùng chất lượng nhưng phí giảm 10-30x. Bài này giải thích 4 routing pattern + tools (Claude Code subagents, LangGraph, Vercel AI SDK) + ví dụ thực tế VietCodex tiết kiệm 94% cost.
Mục lục bài viết(27)

Multi-agent + Cost routing: 1 orchestrator Opus 4.7 lập plan ($$$$) → 3 worker Sonnet 4.6 thực thi code/search/test ($$) → 4 mini Haiku 4.5 lookup/format/classify ($). Cùng chất lượng output, cost giảm 10-30x so với all-Opus. Ảnh: AI-generated bằng ChatGPT gpt-image-2.
Hiểu đơn giản nhất
Bạn mở nhà hàng. Cách SAI: thuê 10 đầu bếp Michelin sao Michelin cho mọi việc — đầu bếp 3 sao đứng rửa bát, đầu bếp 3 sao bê bàn. Tổng lương $50k/tháng cho 100 đơn/ngày = không sống nổi.
Cách ĐÚNG: phân vai. 1 head chef (Opus — đắt) lên menu + giám sát. 3 line cook (Sonnet — vừa) nấu món chính. 4 busser + dishwasher (Haiku — rẻ) rửa bát, bưng nước, dọn bàn. Tổng lương $15k/tháng. Quality món ăn vẫn cao vì head chef control + line cook chuyên môn.
Multi-agent + Cost routing y hệt vậy với AI. Bạn không dùng 1 model đắt nhất (Opus) cho mọi task. Bạn route: task khó → Opus, task vừa → Sonnet, task đơn giản → Haiku. Tiết kiệm 10-30x phí mà chất lượng output giữ nguyên.
Tại sao multi-agent? AI 1 size không vừa mọi việc
Đến cuối 2024, dev dùng AI Coding chủ yếu theo pattern single-agent: mở Claude Code / Cursor → prompt → 1 model làm hết. Vấn đề:
- Cost cao — nếu dùng Opus (mạnh nhất) cho mọi task, $20-50/feature
- Context bloat — 1 model phải nhớ mọi thứ về dự án → context window 200k token đầy nhanh
- Quality kém — task đơn giản (lookup file) bị "over-think" → AI bịa
- Slow — Opus chậm hơn Haiku 3-5x cho task nhỏ
Multi-agent pattern (xuất hiện đầu 2025 với Anthropic subagent + LangGraph 0.2) giải quyết:
- Cost routing — chia task theo độ phức tạp, mỗi task dùng model rẻ nhất đủ tốt
- Parallel execution — nhiều agent chạy đồng thời, tăng tốc 3-10x
- Context isolation — mỗi agent có context riêng, không lẫn → quality cao
- Specialization — agent chuyên môn (search, code, test) tốt hơn generalist
Ví dụ thực tế: Anthropic Claude Code 2026 mặc định dùng Sonnet cho execution + Opus khi user gõ /plan (kích hoạt plan mode) + Haiku cho file lookup nội bộ. User chỉ thấy 1 interface, behind-the-scene là 3 model routing. Tại VN, VietCodex methodology áp dụng 10 specialized agent (xem methodology) — mỗi agent dùng model phù hợp.
3 model Claude + pricing 2026
Anthropic 2026 có 3 model chính cho Claude 4 series:

Bar chart so sánh 4 strategy cho cùng workflow 320 task: All Opus = $19.84 (max quality, max cost) → All Sonnet -47% → Smart Routing (Opus + Sonnet) -81% → 3-Model Routing (Opus + Sonnet + Haiku) -90%. Số tiền per-task có thể thay đổi theo workload, nhưng tỷ lệ tiết kiệm giữ nguyên. Ảnh: AI-generated bằng ChatGPT gpt-image-2.
| Model | Input | Output | Latency | Phù hợp |
|---|---|---|---|---|
| Claude Haiku 4.5 | $0.80/M | $4/M | ~300ms first token | Lookup, format, extract, classify, dịch ngắn |
| Claude Sonnet 4.6 | $3/M | $15/M | ~600ms | Code generation, edit file, search, debug nhỏ |
| Claude Opus 4.7 | $15/M | $75/M | ~1500ms | Plan, architecture, debug complex, security review |
Cost ratio: Opus = 18.75x Haiku input, 18.75x Haiku output. Nếu chạy 1M token input + 1M token output:
- Haiku: $4.80
- Sonnet: $18.00
- Opus: $90.00
Insight: 80% task trong workflow là task đơn giản — dùng Haiku tiết kiệm 18x. Chỉ 5% task cần Opus. Smart routing = trung bình $7/feature thay vì $90.
4 routing pattern phổ biến
Pattern 1: Hierarchical (Phân cấp)
Opus là orchestrator lập plan tổng → Sonnet là worker thực thi từng bước → Haiku là assistant lookup + verify.
User request: "Build feature đặt hàng + VNPay"
OPUS (orchestrator):
├─ Plan: 6 vertical slice
├─ Architecture: Next.js + Drizzle + VNPay sandbox
└─ Dispatch slices to Sonnet workers
SONNET (workers, song song):
├─ Worker 1: Build slice 1 (product detail)
├─ Worker 2: Build slice 2 (add cart)
└─ Worker 3: Build slice 3 (view cart)
HAIKU (mini, song song):
├─ Lookup existing similar pattern in codebase
├─ Format JSON response
├─ Extract VNPay error codes from docs
└─ Verify each slice passes acceptance test
Best for: Dự án lớn, nhiều feature, team có structure rõ ràng.
Pattern 2: Parallel sub-agents (Song song)
Orchestrator dispatch nhiều task độc lập đến nhiều agent đồng thời. Aggregator collect kết quả.
Task: "Audit codebase tìm security issue"
Dispatch 5 Haiku agents (song song):
Agent A: Scan /api routes for SQL injection
Agent B: Scan /api routes for XSS
Agent C: Scan auth flow for session leak
Agent D: Scan file upload for path traversal
Agent E: Scan env vars for hardcoded secrets
Tất cả chạy đồng thời, 5 phút thay vì 25 phút sequential.
Sonnet aggregator: nhận 5 report → tổng hợp → ưu tiên fix.
Best for: Task có thể chia thành sub-task độc lập (audit, batch process, parallel research).
Pattern 3: Cost routing per task (Classifier)
Classifier (Haiku rẻ) đoán độ phức tạp task → route đến model phù hợp.
def route(task: str) -> str:
complexity = haiku_classify(task)
# ↑ Haiku classify: simple / medium / complex
if complexity == "simple":
return haiku.complete(task)
elif complexity == "medium":
return sonnet.complete(task)
else:
return opus.complete(task)Best for: Workflow đa dạng task, không biết trước độ phức tạp.
Pattern 4: Cascading fallback (Thử rẻ trước)
Thử Haiku trước → fail thì Sonnet → fail thì Opus.
def cascading(task: str) -> str:
result = haiku.complete(task)
if confidence(result) >= 0.8:
return result
result = sonnet.complete(task)
if confidence(result) >= 0.8:
return result
return opus.complete(task) # always trustBest for: Task có validation rõ (schema match, test pass), confidence đo được. Cẩn thận: cascading thêm latency 2-3x cho task fail-Haiku.
Workflow concrete: build feature với multi-agent routing
Feature: "User submit review (rating + comment)" — 1 slice end-to-end.
| Bước | Task | Model | Cost | Lý do |
|---|---|---|---|---|
| 1 | Plan slice + acceptance criteria | Opus | $0.15 | Reasoning nhẹ |
| 2 | Search codebase tìm pattern review hiện có | Haiku | $0.01 | Lookup đơn giản |
| 3 | Gen schema Drizzle table reviews | Sonnet | $0.05 | Code generation |
| 4 | Gen API endpoint POST /api/reviews | Sonnet | $0.10 | Code generation |
| 5 | Gen form component React | Sonnet | $0.12 | Code generation |
| 6 | Gen Playwright test theo AC | Sonnet | $0.08 | Code generation |
| 7 | Run test → parse output → format report | Haiku | $0.01 | Format đơn giản |
| 8 | Fix bug (nếu test fail) | Sonnet | $0.10 | Debug nhẹ |
| 9 | Review code cuối + security check | Opus | $0.20 | Reasoning |
| 10 | Generate commit message | Haiku | $0.005 | Format đơn giản |
Tổng: $0.82 cho 1 slice.
So với all-Opus (mọi bước): $0.20 × 10 = $2.00 + chậm 3x. So với all-Haiku (chỉ Haiku): $0.05 + quality kém (50% slice fail).
Smart routing: Sweet spot. $0.82/slice, quality ngang Opus, fast Sonnet.
Case study cost savings — VietCodex booking salon
Project: SaaS booking salon 12 chi nhánh (xem TDD case study).
32 slice × 10 task/slice = 320 task tổng.
| Strategy | Cost | Quality | Speed |
|---|---|---|---|
| All Opus | $640 | A+ | Slow (8 ngày) |
| All Sonnet | $96 | A | Medium (6 ngày) |
| All Haiku | $26 | C (60% fail) | Fast (3 ngày) — phải rework |
| Smart routing | $38 | A | Fast (5 ngày) |
Smart routing breakdown:
- 10% Opus (32 task plan + review): $32
- 50% Sonnet (160 code gen): $24
- 40% Haiku (128 lookup + format + classify): $1.30
Total $38 cho 32 slice = $1.20/slice. So với all-Opus $640 = save 94%.
Đáng chú ý: quality NGANG NHAU với all-Opus vì pattern hierarchical (Opus vẫn plan + review final). Sonnet/Haiku chỉ làm phần routine.
Tools 2026 cho multi-agent + routing
1. Claude Code subagents (Anthropic native) — easy nhất
// Trong Claude Code, dùng Agent tool:
Agent({
description: "Search auth files",
subagent_type: "Explore", // dùng Haiku internal
prompt: "Find all files using better-auth in /lib"
})
Agent({
description: "Implement payment slice",
subagent_type: "general-purpose", // dùng Sonnet
prompt: "..."
})
Agent({
description: "Architectural review",
subagent_type: "architect", // dùng Opus
prompt: "..."
})Anthropic tự handle routing model + context. Bạn chỉ cần chọn subagent type.
2. LangGraph (open-source, customizable)
from langgraph.graph import StateGraph, END
# Define graph với 3 node:
graph = StateGraph(State)
graph.add_node("classify", haiku_classifier)
graph.add_node("execute", sonnet_executor)
graph.add_node("review", opus_reviewer)
# Routing logic
graph.add_conditional_edges("classify", route_by_complexity)
graph.add_edge("execute", "review")
graph.set_entry_point("classify")LangGraph cho phép graph phức tạp, conditional edges, retry. Phù hợp production complex.
3. Vercel AI SDK (TypeScript, multi-provider)
import { generateText } from "ai";
import { anthropic } from "@ai-sdk/anthropic";
const model = task.simple
? anthropic("claude-haiku-4-5-20251001")
: task.complex
? anthropic("claude-opus-4-7")
: anthropic("claude-sonnet-4-6");
const { text } = await generateText({ model, prompt });Vercel AI SDK đơn giản, multi-provider (Anthropic + OpenAI + Google + custom). Phù hợp Next.js app.
4. CrewAI (Python, opinionated)
Higher-level framework với Crew + Agent + Task concept. Tốt cho prototype nhanh nhưng overhead cao.
Prompt caching + Batch processing — combo tiết kiệm thêm
Sau cost routing, còn 2 trick giảm cost thêm:
Prompt caching (90% discount)
Anthropic cho cache prompt phần không đổi (system prompt, code context). Request sau:
- Cache hit: read $0.30/M (vs $3/M original) = save 90%
client.messages.create(
model="claude-sonnet-4-6",
system=[
{"type": "text", "text": SYSTEM_PROMPT,
"cache_control": {"type": "ephemeral"}}, # cache!
],
messages=[{"role": "user", "content": user_query}]
)Setup 1 lần, áp dụng tự động. Workflow lặp lại (mỗi feature có context giống) → save 50-90% thêm.
Batch API (50% discount)
Anthropic Batch API: gửi 100 request 1 lúc → process trong 24h → cost rẻ 50%.
Phù hợp: bulk processing (audit 1000 file, dịch 500 record). KHÔNG phù hợp realtime (user đợi).
Combo cost optimization:
- Base: $640 (all Opus, không cache)
-
- Smart routing: $38
-
- Prompt caching: $15
-
- Batch (cho audit job): $10
Total $10 cho project = save 98.4% so với naive approach.
5 cảm bẫy phổ biến
Bẫy 1: "Always Opus" — Mặc định model đắt nhất
Founder mới thường set Opus mặc định "cho chắc". → cost burn 18x, latency 5x chậm.
Mitigation: Default Sonnet 4.6. Escalate Opus chỉ khi: plan, review, complex reasoning.
Bẫy 2: "Always Haiku" — Tiết kiệm quá đà
Dev startup nghèo set Haiku cho mọi task. → 50% code gen fail, phải rework → tốn nhiều hơn.
Mitigation: Haiku chỉ cho lookup/format/classify. Code gen phải Sonnet+.
Bẫy 3: "No prompt caching" — Bỏ qua discount free
90% workflow có phần repeated (system prompt, code context). Không cache = pay 10x.
Mitigation: Setup cache_control: ephemeral cho system prompt + large context. Anthropic docs có example.
Bẫy 4: "Context bloat" — Đẩy nhiều context không cần
Gửi 50k token context khi task chỉ cần 5k → pay 10x.
Mitigation: Tóm tắt context bằng Haiku trước khi đẩy vào Sonnet. Hoặc dùng RAG (Vector DB) tìm relevant chunk.
Bẫy 5: "No observability" — Không đo cost per task
Không log model + cost mỗi request → không biết bottleneck ở đâu để optimize.
Mitigation: Wrap Anthropic SDK với middleware log model + token usage + cost. Anthropic Console cũng có dashboard built-in.
Combine với SDD và TDD — khép cluster
Multi-agent + cost routing không thay thế Spec-driven hay TDD + Slicing — nó tăng cường chúng.
SDD + Multi-agent:
- Opus đọc spec → lập plan + identify edge cases
- Sonnet gen code theo plan
- Haiku verify acceptance criteria
TDD + Multi-agent:
- Sonnet gen test từ acceptance criteria
- Sonnet gen code pass test (GREEN)
- Haiku run test + report result
- Opus review final code chất lượng
Vibe coding + Multi-agent:
- Haiku chính cho speed (vibe = ưu tiên tốc độ)
- Sonnet escalate khi Haiku fail
- Skip Opus (vibe không cần Opus)
4 mode AI Coding 2026 — chọn theo giai đoạn:
| Giai đoạn | Mode | Cost/feature |
|---|---|---|
| Ý tưởng test 0→1 | Vibe coding + Haiku-heavy | $0.50-2 |
| MVP launch | Build MVP + Vibe + Sonnet default | $2-10 |
| Production scale 1→100 | Spec-driven + multi-agent routing | $10-40 |
| Mission-critical (payment, auth) | TDD + Vertical Slicing + Opus review | $40-100 |
Tóm tắt 1 dòng
Multi-agent + Cost routing = pattern advanced AI Coding 2026: orchestrator Opus 4.7 lập plan + worker Sonnet 4.6 execute + mini Haiku 4.5 lookup/format → save 90-95% cost vs all-Opus. 4 routing pattern: Hierarchical, Parallel, Classifier, Cascading. Tools: Claude Code subagents (easy), LangGraph (powerful), Vercel AI SDK (TypeScript). Combo với prompt caching + batch API = save 98%. Khép cluster AI Coding: vibe + MVP + spec + TDD + multi-agent = stack hoàn chỉnh build production.
Đọc tiếp
- TDD + Vertical Slicing — combo TDD với multi-agent cho production critical
- Spec-driven dev — SDD + multi-agent: Opus đọc spec, Sonnet execute
- Build MVP — MVP nên Haiku-heavy, ít cost
- Vibe coding — vibe mode dùng Haiku là chủ yếu
- Claude Code, Cursor, Copilot — tool nào hỗ trợ subagent
- AI Coding là gì? — quay lại tổng quan
- 42 khái niệm nâng cao — MCP, Vector DB, Streaming, Function calling trong glossary
Cần build SaaS production với cost AI tối thiểu? VietCodex áp dụng multi-agent + cost routing cho mọi project — trung bình $30-100 phí Claude API cho cả dự án 4 tuần (so với $1000-3000 nếu naive). Xem methodology hoặc đặt audit FREE 30 phút.