S-06 · TRACK 03 · PATTERNS

Routing & Parallelization

Khi chuỗi tuyến tính không đủ: chia nhánh theo loại task, chạy song song để tăng tốc hoặc vote. Chapter 2 + 3 sách Gulli.

Buổi 6 — Chúng ta sẽ đi qua gì?
🚩

01 · Vấn đề của chain thuần

Task đa loại → 1 chain không cover hết

🔄

02 · Routing

Classifier chọn nhánh: LLM · Embedding · Rule

03 · Parallelization

Sectioning · Voting · Ensemble

💻

04 · Thực chiến

Code, framework compare, anti-pattern

🎯

05 · Takeaways

5 điểm nhớ + homework

01

Vấn đề
Task đa loại · Chain đơn không đủ

Khi 1 chain phải "gánh" nhiều loại input

1 chain xử lý mọi request

Prompt phình — chứa nhánh if/else cho mọi loại (billing, tech, sales, refund…).

Model confuse — quá nhiều instruction, quyết định sai nhánh xử lý.

Cost cao — mọi request đều gọi full model + full tool.

Latency cao — tuần tự, không tận dụng parallel.

Routing + Parallelization

Router classify loại — gửi vào nhánh chuyên biệt.

• Nhánh nhỏ = prompt ngắn & focused.

• Task độc lập chạy song song — giảm wall-clock time.

Voting N model ⇒ accuracy cao ở task risky.

2 pattern thường đi cặp: Route để chọn nhánh nào, Parallel để chạy nhánh đó đồng thời với các nhánh khác.

02

Pattern 1 · Routing
Classifier chọn nhánh xử lý

3 kiểu router — trade-off latency vs accuracy
Routing = một classifier đọc input, quyết định gửi vào nhánh xử lý nào (specialist prompt, specialist model, hoặc specialist agent).
🧠

LLM Router

1 LLM call chuyên classify. Linh hoạt, hiểu ngôn ngữ tự nhiên.

+50–200ms · $ trung bình · accuracy cao.

🔮

Embedding Router

Embed input, so cosine với template embedding. Nhanh & rẻ.

+5–30ms · $ thấp · phù hợp intent set cố định.

📌

Rule Router

Regex, keyword, giá trị form. Deterministic & audit dễ.

<1ms · $ 0 · giòn với input tự nhiên.

Thực chiến hay dùng lai: rule/embedding chạy trước — hit thì dùng, miss thì fallback LLM router.

Sơ đồ Routing — Customer Support ví dụ
Input

Message KH

"Sao thẻ tôi bị khoá?" · "App crash" · "Muốn nâng gói"…

Router (LLM)

Classify

Output JSON: {intent, confidence}. Fallback nếu confidence < 0.7.

Nhánh A

Billing Agent

Prompt + tool CRM, invoice.

Nhánh B

Technical Agent

Prompt + KB search, log query.

Nhánh C

Sales Agent

Prompt + pricing, upsell.

Fallback

Human handoff

Confidence thấp ⇒ nhân viên.

03

Pattern 2 · Parallelization
Chạy đồng thời để nhanh & chắc

3 biến thể Parallelization

Sectioning

Chia task thành phần độc lập, mỗi phần một LLM call chạy song song. Merge kết quả.

Ví dụ: review PR — 1 kiểm security, 1 kiểm perf, 1 kiểm style.

😊

Voting

Chạy N lần cùng prompt (temp > 0), lấy majority. Đổi cost lấy accuracy.

Ví dụ: math, code gen critical, safety check.

🏆

Ensemble

Chạy N model khác nhau (Claude + GPT + Gemini), tổng hợp. Giảm bias single-model.

Ví dụ: eval nghiêm ngặt, sáng tạo cần đa dạng.

Chi phí = N × base. Chỉ dùng khi value từ độ chính xác vượt chi phí tăng.

04

Thực chiến
Code · Framework · Anti-patterns

Code — Route + Parallel section (asyncio)
route_and_parallel.py
# --- Router ---
async def route(msg: str) -> str:
    r = await llm.classify(msg, labels=["billing", "tech", "sales"])
    return r.label if r.confidence >= 0.7 else "human"

# --- Parallel sectioning ---
async def review_pr(diff: str) -> dict:
    security, perf, style = await asyncio.gather(
        llm.critique(diff, focus="security"),
        llm.critique(diff, focus="performance"),
        llm.critique(diff, focus="style"),
    )
    return {"security": security, "perf": perf, "style": style}

# --- Voting ---
async def vote(prompt: str, n: int = 5) -> str:
    results = await asyncio.gather(*[
        llm.generate(prompt, temperature=0.7) for _ in range(n)
    ])
    return Counter(results).most_common(1)[0][0]  # majority
4 framework — cách implement
Framework Routing Parallelization Ghi chú
LangGraph Conditional edge Fan-out/fan-in node Visualize graph rõ ràng
CrewAI Manager LLM delegates async_execution=True Role-based, ít boilerplate
Google ADK LlmRouter ParallelAgent Native trên Vertex
Claude Code Subagent w/ description matching Multiple tool calls / turn Route bằng match agent description
Khi nào — anti-patterns

✅ Dùng Routing khi…

  • • Input đa loại rõ ràng, mỗi loại cần prompt/tool khác.
  • • Muốn tối ưu cost: route task nhỏ về Haiku, task lớn về Opus.
  • • Cần guardrail chuyên biệt theo loại request.

✅ Dùng Parallel khi…

  • • Task độc lập — không phụ thuộc output nhau.
  • • Cần giảm latency hoặc tăng accuracy (voting).

❌ Anti-patterns

  • Router miss classify ⇒ user bực. Cần confidence threshold + fallback human.
  • Parallel task có dependency ⇒ race condition. Chain lại đi.
  • Voting quá nhiều lần (N > 7) ⇒ cost tăng phi tuyến, marginal accuracy nhỏ.
  • Ensemble không có aggregator ⇒ trả 3 câu trả lời khác nhau cho user.
  • Route bằng LLM cho task đơn giản — rule/regex là đủ.
Case VN 🇳🇻 — 4 kiểu Routing kèm khi nào dùng
Kiểu router Cơ chế Ưu / nhược Dùng khi
LLM-based Prompt classify → output nhãn Linh hoạt / chậm, tốn token Intent tự nhiên, đa dạng
Embedding Vector similarity với template Nhanh / kém khi intent mới Semantic routing intent cố định
Rule-based if/else, regex, keyword Deterministic / giòn Input có schema, keyword rõ
ML classifier Fine-tuned discriminative model Nhanh + chính xác / cần data gán nhãn High traffic, có dataset lịch sử

Router đặt được ở 3 vị trí: đầu chuỗi (phân loại tác vụ chính), giữa (chọn nhánh xử lý), trong subroutine (chọn tool phù hợp). LangGraph phù hợp cho routing phức tạp phụ thuộc trạng thái tích luỹ.

Tổng hợp từ Cẩm nang thực hành xây dựng HTTM (VN Gulli Ch.2) & kinh nghiệm thực chiến.

7 ứng dụng Parallelization thực chiến

📚 1. Nghiên cứu doanh nghiệp

Đồng thời: tìm tin, lấy giá cổ phiếu, kiểm mạng xã hội, truy DB công ty.

📈 2. Phân tích feedback khách

Song song: sentiment, keyword, phân loại, phát hiện khẩn cấp.

✈ 3. Lập kế hoạch du lịch

Đồng thời: vé bay, khách sạn, sự kiện, nhà hàng — 4 API.

✉ 4. Soạn email marketing

Song song: tiêu đề, thân bài, ảnh minh hoạ, CTA text.

✅ 5. Verify input form

Song song: check email format, phone, địa chỉ, ngôn từ thô.

🎤 6. Multimodal social post

Đồng thời: text sentiment + object detection ảnh + mô tả cảnh.

🔬 7. A/B testing / phương án song song

Sinh N biến thể (3 tiêu đề, 5 subject line) rồi so sánh chọn best — ứng dụng cho content ops, ad copy, landing page.

Nguồn: Cẩm nang thực hành xây dựng HTTM (VN Gulli Ch.3) · case đã Việt hoá.

CLI thực chiến — Routing & Parallelization

🤖 Claude Code

# Route qua subagent
mkdir .claude/agents
# billing-agent.md
# tech-agent.md  
# sales-agent.md
# Claude match description

claude
# /agents → list & test

# Parallel — nhiều tool call
# trong 1 turn (native)
# Bash + Read + Grep song song

# Model routing theo task
claude -m haiku-4-5   #nhỏ
claude -m sonnet-4-6  #TB

⚡ Cursor

# Composer mode = router
# Ask · Edit · Agent
# chọn theo intent user

# Rules routing
# .cursor/rules/
#   frontend.mdc
#   backend.mdc
#   sql.mdc
# Match theo globs

# Model per rule
cursor .
# Settings → Models
# Auto pick fast vs slow

# Parallel edit nhiều file
# qua Composer batch

💎 Gemini CLI

# Route model theo task
route() {
  case "$1" in
    simple) M=flash;;
    hard)   M=pro;;
  esac
  gemini -m gemini-2.5-$M -p "$2"
}

# Parallel shell (Linux/macOS)
gemini -p "tóm tắt" < a.txt &
gemini -p "trích key" < a.txt &
gemini -p "sentiment" < a.txt &
wait

# Windows PowerShell:
# Start-Job {gemini ...}

Parallel Windows: PowerShell dùng Start-Job {...} + Wait-Job | Receive-Job. Linux/macOS dùng & + wait.
Route tip: Cursor Auto mode tự chọn model theo độ phức tạp — Claude Code & Gemini CLI cần script route() tự viết. Đo cost/turn để hiệu chỉnh.

05

Takeaways
& homework

5 điều nhớ
1

Routing = chọn nhánh; Parallelization = chạy đồng thời. Thường đi cặp.

2

3 kiểu router: LLM · Embedding · Rule. Ưu tiên lai: rule/embedding trước, LLM fallback.

3

3 biến thể Parallel: Sectioning · Voting · Ensemble. Cost = N × base — tính trước.

4

Router luôn cần confidence threshold + fallback (human hoặc default agent).

5

Chỉ parallel khi task thực sự độc lập. Có dependency ⇒ chain lại.

Bài tập & chuẩn bị buổi 7
📝

Tự kiểm tra

  • • App bạn có bao nhiêu loại intent? Vẽ router 3 nhánh.
  • • Có task nào đang tuần tự mà thực ra independent — có thể parallel?
  • • Chi phí nếu voting N=5 với Sonnet? Đáng đổi không?
📚

Đọc trước

  • • A. Gulli — Ch.2 Routing + Ch.3 Parallelization.
  • • Anthropic — mục Routing / Parallelization.
  • • LangGraph docs — Conditional edges.
🔗

Tài liệu VN

  • Xây dựng AI Agent hiệu quả cho DN.
  • Cách xây dựng & vận hành AI agents.
  • Cẩm nang thực hành xây dựng HTTM.
Hết buổi 6

Buổi 7 — Tool Use
Chuyển agent từ "nói" sang "làm" — function calling, ReAct, code execution.