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.

13 phút đọcCập nhật 2026-05-19
Đang tải audio...
Mục lục bài viết(27)
Multi-agent orchestration — Opus orchestrator + Sonnet workers + Haiku mini agents

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:

So sánh 3 model Claude — Haiku 4.5 vs Sonnet 4.6 vs Opus 4.7 + cost routing chart

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.

ModelInputOutputLatencyPhù hợp
Claude Haiku 4.5$0.80/M$4/M~300ms first tokenLookup, format, extract, classify, dịch ngắn
Claude Sonnet 4.6$3/M$15/M~600msCode generation, edit file, search, debug nhỏ
Claude Opus 4.7$15/M$75/M~1500msPlan, 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 trust

Best 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ướcTaskModelCostLý do
1Plan slice + acceptance criteriaOpus$0.15Reasoning nhẹ
2Search codebase tìm pattern review hiện cóHaiku$0.01Lookup đơn giản
3Gen schema Drizzle table reviewsSonnet$0.05Code generation
4Gen API endpoint POST /api/reviewsSonnet$0.10Code generation
5Gen form component ReactSonnet$0.12Code generation
6Gen Playwright test theo ACSonnet$0.08Code generation
7Run test → parse output → format reportHaiku$0.01Format đơn giản
8Fix bug (nếu test fail)Sonnet$0.10Debug nhẹ
9Review code cuối + security checkOpus$0.20Reasoning
10Generate commit messageHaiku$0.005Format đơ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.

StrategyCostQualitySpeed
All Opus$640A+Slow (8 ngày)
All Sonnet$96AMedium (6 ngày)
All Haiku$26C (60% fail)Fast (3 ngày) — phải rework
Smart routing$38AFast (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ạnModeCost/feature
Ý tưởng test 0→1Vibe coding + Haiku-heavy$0.50-2
MVP launchBuild MVP + Vibe + Sonnet default$2-10
Production scale 1→100Spec-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


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.

Câu hỏi thường gặp

Multi-agent là gì? Khác 'AI agent' đơn giản ở đâu?
AI agent đơn giản = 1 model (vd Claude Sonnet) làm mọi task. Multi-agent = nhiều agent chuyên môn phối hợp: 1 orchestrator (Opus) lập plan + nhiều worker (Sonnet) thực thi + nhiều mini (Haiku) lookup/verify. Mỗi agent có scope hẹp → quality cao hơn vì context tập trung. Pattern này phổ biến 2026 sau khi Anthropic release subagent trong Claude Code (early 2025).
Cost routing có thực sự tiết kiệm không?
Có, 10-30x với hầu hết workflow. Lý do: 80% task trong dự án là lookup/format/classify đơn giản — dùng Haiku ($0.8/M input) thay Opus ($15/M) tiết kiệm 18x. 15% là code generation — dùng Sonnet ($3/M) tiết kiệm 5x. Chỉ 5% là plan + reasoning phức tạp dùng Opus. Tổng tiết kiệm: 90-95% cost so với all-Opus.
Claude Haiku có đủ tốt cho code không?
Đủ tốt cho task NHỎ, RÕ: lookup symbol trong codebase, format JSON, extract field, classify ý định, dịch ngắn. KHÔNG đủ cho: viết function mới phức tạp, debug bug logic, design architecture. Quy tắc: nếu task có thể mô tả trong 1 câu rõ ràng + có input/output cụ thể → Haiku. Phức tạp hơn → Sonnet.
Khi nào dùng Opus thay vì Sonnet?
Opus khi: (1) Plan dài cho dự án lớn (1000+ LOC), (2) Debug bug subtle nhiều file, (3) Design architecture mới, (4) Reasoning về security/performance trade-off, (5) Review code chất lượng cao. Sonnet 4.6 đã rất tốt cho execution thường ngày — không cần Opus trừ khi gặp 5 trường hợp trên. Quy tắc thực dụng: dùng Sonnet làm mặc định, escalate Opus khi Sonnet không tự tin.
Prompt caching là gì? Tiết kiệm bao nhiêu?
Prompt caching = Anthropic cache phần prompt không đổi (system prompt, code context) → request sau đọc cache rẻ hơn 10x. Setup 1 lần, áp dụng tự động trong Claude API + Claude Code. Tiết kiệm thêm 50-90% cost cho workflow lặp lại (mỗi feature có context similar). Combine với cost routing = tiết kiệm tổng 95-99%.
Tool nào hỗ trợ multi-agent + routing 2026?
Top 3: (1) **Claude Code subagents** — `Agent` tool với `subagent_type`, native Anthropic, easy nhất. (2) **LangGraph** — graph framework, customizable cao, learning curve. (3) **Vercel AI SDK** — multi-provider, switch model dễ. CrewAI cũng popular nhưng overhead cao. Beginner → Claude Code. Production complex → LangGraph.
Tôi có thể tự build multi-agent không cần framework?
Có, đơn giản hơn bạn nghĩ. Pseudocode: classifier (Haiku) nhận task → route đến model phù hợp → collect result. 50-100 dòng TypeScript với Anthropic SDK + zod schema. Lợi: control hoàn toàn cost, debug dễ. Hại: phải tự handle retry, error, observability. Khuyến nghị: prototype tự build → migrate sang framework khi cần scale.
Cascading routing là gì?
Cascading = thử model rẻ trước, escalate dần khi fail. Pattern: prompt Haiku → nếu confidence > 80% hoặc output match schema thì return; nếu không → retry với Sonnet → nếu vẫn không thì Opus. Tiết kiệm cost vì 70% task Haiku đã đủ, chỉ 30% cần escalate. Cẩn thận: cascading thêm latency 2-3x cho task fail-Haiku. Cân bằng cost/latency theo use case.