jvinhit//lab

Search posts

Type to search across journal entries.

navigate open esc close

Choosing an LLM for Agents: A Durable Framework Beyond Leaderboards

A senior engineer framework for model selection — capability tiers, context, modality, cost, privacy, tool use — plus routing, cascades, and why benchmarks lie.

Bảng xếp hạng model lỗi thời trước khi bạn đọc xong. Vendor ship checkpoint mới hàng tuần, giá thay đổi, và workload agent của bạn không giống MMLU. Kỹ năng bền vững không phải nhớ model #1 hôm nay — mà là xây framework chọn model chạy lại mỗi quý.

Bài này đưa framework đó: capability tier, ràng buộc cứng, shortlist theo eval, và pattern production như routing và cascade. Để xem catalog model cụ thể, xem LLM Models Comparison GuideOpen Source LLM Ecosystem — bài này ở tầng quyết định.

Mở demo đầy đủ:


Bắt đầu từ ràng buộc, không phải hype

Trước khi so benchmark, ghi rõ agent bắt buộc đáp ứng gì. Đây là cửa pass/fail — model 95 điểm leaderboard nhưng không chạy trong VPC của bạn thì bị loại.

Constraint categoryQuestions to answer
Data & privacyCan prompts leave your network? PII, HIPAA, SOC2?
Latency & UXSub-second first token? Streaming required?
ModalityText only, or vision/audio for documents and screenshots?
Context lengthMax input per turn — 8k, 128k, 1M tokens?
Output shapeJSON schema, tool calls, free-form prose?
Cost envelopeBudget per task, per user/day, or per 1M tokens?
Ops maturityManaged API vs self-host GPUs vs hybrid?

Callout: Ràng buộc loại 80% ứng viên trước khi bạn mở trang benchmark. Coi “có thể cần vision sau” là preference mềm, không phải gate cứng — trừ khi product đã ship input ảnh.


Capability tier — nghĩ theo class, không theo SKU

Thị trường gom thành vài tier đại diện ít lỗi thời dù tên model thay đổi. Map workload lên tier trước; chọn checkpoint cụ thể sau.

┌─────────────────────────────────────────────────────────────────┐
│  TIER              │  TYPICAL USE IN AGENTS                     │
├────────────────────┼────────────────────────────────────────────┤
│  Frontier / large  │  Hard reasoning, ambiguous specs, codegen  │
│  Mid / balanced    │  Default production agent loop, tool use   │
│  Small / fast      │  Routing, classification, simple extract   │
│  Reasoning model   │  Math, planning, verify-before-act steps   │
│  Open-weight       │  VPC-only, fine-tune, air-gapped deploy     │
└────────────────────┴────────────────────────────────────────────┘

Frontier / large tối đa capability tổng quát với cost và latency cao nhất. Dùng khi lỗi đắt — legal review, codegen phức tạp, refactor nhiều file.

Mid / balanced là tier workhorse cho hầu hết agent product. Tool-calling, structured output, instruction-following thường “đủ tốt” với cost thấp hơn frontier 3–10×.

Small / fast mạnh ở routingprefilter — intent detection, safety classifier, tóm tắt log trước khi escalate. Đừng giả định small model thay mid tier trên vòng tool nhiều bước mà không đo.

Reasoning model (extended thinking, CoT sẵn) đổi latency và cost lấy logic khó. Chúng không phải default cho chat UX nhưng xuất sắc làm mục tiêu escalate khi model rẻ fail verification.

Open-weight / self-host mua data sovereignty và tự do fine-tune, đổi lại GPU ops, tradeoff quantization, tool-calling không đồng đều. Xem Open Source LLM Ecosystem cho pattern deploy.


Context length — nhu cầu vs chi trả

Context dài không miễn phí dù quảng cáo vậy. Nhiều provider tính input token tuyến tính; cost attention tăng siêu tuyến tính trên một số kiến trúc. Nhét 500k token vào cửa sổ 1M có thể đắt hơn tóm tắt theo chunk bằng model rẻ.

SignalPrefer long-context tierPrefer chunk + RAG / summarize
Whole-repo reasoning in one shot
Mostly retrieval over fixed corpus
Latency-sensitive chat
Legal doc “read everything” audit
Recurring same large context✓ (cache / index)

Callout: Context window là trần, không đảm bảo chất lượng. Model mất độ chính xác “needle” giữa prompt khổng lồ — validate bằng eval long-input của bạn. Phần 1 cover token economics sâu: Tokens & Context Windows.


Modality — vision, audio, và agent UX

Agent multimodal không còn là “text model + OCR wrapper” năm 2026. Vision native hiểu layout, chart, screenshot UI — quan trọng cho browser agent và document workflow.

Khi đánh giá modality fit:

  • Bắt buộc: Nếu user upload ảnh hoặc PDF render trang, lọc tier có vision sớm.
  • Audio: Voice agent real-time thêm budget latency ASR/TTS tách khỏi LLM latency.
  • Doc có cấu trúc: Bảng và form thường cần vision hoặc parser chuyên — đừng giả định convert markdown giữ nguyên semantics.

Reasoning vs non-reasoning model

Chat model chuẩn trả lời một forward pass mỗi token. Reasoning model dành thêm compute — CoT nội bộ, self-consistency, hoặc search — trước khi phát câu trả lời user thấy.

DimensionNon-reasoning (Mid/Frontier chat)Reasoning tier
LatencyLower, predictable streamingHigh, bursty
Cost per taskToken-linearOften 5–20× for hard problems
Best forTool loops, extraction, dialogueProof, planning, ambiguous math
Agent patternDefault loopEscalation after failed verify

Dùng reasoning model có chọn lọc: router gửi bước dễ sang mid tier, bước khó sang reasoning tier, không mặc định ngược lại. Knob sampling Phần 2 vẫn áp dụng — temperature thấp cho bước verification.


Latency, throughput, và SLA math

Latency agent là tổng nhiều LLM call cộng tool I/O. Chọn model ảnh hưởng mọi tầng:

User message
    → router model (small, ~100ms)
    → planner model (mid, ~800ms)
    → tool execution (variable)
    → synthesizer model (mid, ~600ms)
    → optional verifier (small or reasoning)
= perceived latency budget

TTFT quan trọng cho streaming UX. Tokens/giây quan trọng cho codegen dài. Batch API đổi latency lấy giảm 50% cost — ổn cho eval offline, sai cho agent tương tác.

Chọn tier theo bước, không theo product: Cùng agent có thể gọi small classify, mid act, reasoning repair.


Cost mỗi token — và mỗi task thành công

Giá niêm yết là cận dưới. Cost thực gồm retry, prompt dài thừa, parse tool fail, và escalate.

Cost driverMitigation
Input-heavy promptsPrompt compression, caching, retrieve don’t stuff
Multi-step loopsStep caps, cheaper model for drafts
Reasoning taxGate with verifier; don’t run o-class on every turn
Output bloatStopping criteria (Part 4), max_tokens discipline

Chuẩn hóa so sánh theo cost mỗi task thành công trên eval set, không chỉ cost/1M token riêng lẻ. Pattern sâu: LLM Cost Optimization Patterns.


Open-weight vs proprietary

FactorProprietary APIOpen-weight self-host
Time to first agentHoursDays–weeks (GPU, quant, serving)
Data residencyVendor DPA / regionFull control
Fine-tuningOften limited / expensiveFull weights, LoRA, distillation
Tool callingUsually matureModel-dependent, test hard
Model churnVendor deprecates versionsYou control upgrade cadence

Hybrid phổ biến: proprietary prototype, open-weight production regulated, hoặc open small routing + proprietary bước khó.


Fine-tunability — khi weight thắng prompt

Fine-tune giúp khi có nhiều ví dụ hành vi hẹp mà prompt không ổn định — tone, schema lạ, jargon domain, bias chọn tool. Hại khi task đổi hàng tuần hoặc thiếu eval data. Phần 6 cover tradeoff: Fine-tuning vs Prompting vs RAG.

Open-weight thống trị fine-tune; API proprietary ngày càng có tuning kiểu adapter trên mid tier. Luôn fine-tune trên cùng eval harness dùng để chọn model.


Tool-calling và structured output

Agent sống chết ở function call đáng tinJSON đúng schema. Benchmark capability hiếm khi đo; eval của bạn phải đo.

Checklist shortlist model cho tool use:

  • Parallel tool calls supported?
  • Strict JSON / response_format / grammar constraints?
  • Behavior when tool returns error — retry or hallucinate?
  • Multi-turn tool loops stable at temperature 0.1–0.3?
  • Native vs prompt-wrapped tool protocols (compare latency)

Phần 9 đi sâu implementation: Function Calling & Tool Use.

Ví dụ fragment schema tool agent:

{
  "name": "search_docs",
  "description": "Semantic search over internal wiki",
  "parameters": {
    "type": "object",
    "properties": {
      "query": { "type": "string" },
      "limit": { "type": "integer", "minimum": 1, "maximum": 20 }
    },
    "required": ["query"]
  }
}

Chạy 50–200 scenario tool-call mỗi model; báo tỷ lệ parse thành côngtask success downstream riêng.


Benchmark — signal hữu ích, default nguy hiểm

Benchmark công khai (MMLU, HumanEval, MATH, v.v.) xếp hạng kiến thức tổng quát và thi cử, không phải workflow triage ticket của agent bạn. Ba vấn đề hệ thống:

  1. Contamination — training data trùng test set; điểm phình.
  2. Gaming — vendor tối ưu cho task leaderboard.
  3. Distribution shift — user, tool, và failure mode của bạn khác.

Callout: Model +2 điểm MMLU không chứng minh nó parse tool create_invoice đúng. Coi benchmark công khai là định hướng, không phải chọn model.

Xây eval riêng — Phần 7 là playbook: Evaluating LLMs & Agents. Harness chọn model tối thiểu:

1. 30–50 golden tasks from production logs (redacted)
2. Metrics: success, tool accuracy, latency p95, cost per task
3. Run all tier candidates with identical prompts + tools
4. Blind review of failures — model vs prompt vs tool bug
5. Pick winner on Pareto frontier (quality × cost × latency)

Chạy lại khi vendor ship checkpoint mới hoặc mix task đổi.


Model routing và fallback

Routing gửi mỗi request tới tier rẻ nhất xử lý được. Signal cho router:

  • Intent classification (small model or embeddings)
  • Estimated complexity (token count, tool count, user tier)
  • Confidence from previous step
  • Explicit user mode (“fast” vs “thorough”)

Fallback xử lý outage provider và cliff chất lượng:

Primary: Mid tier (Vendor A)
  ↓ timeout / 5xx
Fallback: Mid tier (Vendor B)
  ↓ repeated tool-parse failure
Escalate: Frontier tier
  ↓ still failing
Degrade: Human handoff + log for eval

Đừng đổi tier im lặng không log — eval drift sẽ làm bạn bối rối. Version policy router như code khác.


Cascade — rẻ trước, đắt khi cần

Cascade chạy model nhanh rẻ trước, chỉ chạy lại model mạnh hơn khi verification fail. Pattern kinh điển:

Small → draft answer or tool plan
Verifier (rules + small LLM) → pass?
  yes → return
  no  → Mid re-run with verifier feedback
        still fail? → Reasoning tier

Cascade cắt cost trung bình 40–70% trên workload độ khó hỗn hợp khi verification rẻ và chính xác. Verifier là then chốt — đầu tư vào nó.

Kết hợp cascade với cache (pattern memory Phần 5) và prompt template (Phần 3) để tiết kiệm chồng lên nhau.


Workflow chọn model lặp lại được

Dùng checklist này mỗi quý hoặc trước khi ship tính năng agent lớn:

StepAction
1Document hard constraints (privacy, latency, modality, context)
2Map workload to tier (frontier / mid / small / reasoning / open)
3Build shortlist from comparison guide
4Run private eval harness (Part 7) — 30+ golden tasks
5Measure cost per successful task, not list price
6Prototype routing + cascade in staging
7Log tier decisions in production for continuous re-eval
CONSTRAINTS → TIER → SHORTLIST → EVAL → ROUTING DESIGN → SHIP → RE-EVAL

Anti-pattern thường gặp

  • Frontier mọi nơi — đốt budget; mid tier xử lý 70% bước agent.
  • Săn leaderboard — tối ưu skill không liên quan.
  • Bỏ qua eval tool-call — chat tốt ≠ agent tốt.
  • Lock-in một vendor — không fallback khi API deprecate version.
  • Chọn tĩnh — model chọn ở hackathon không review lại.

Điểm chính

  • Chọn theo tier và ràng buộc trước, checkpoint cụ thể sau.
  • Context dài, vision, reasoning là nâng cấp trả phí — chỉ dùng khi eval chứng minh cần.
  • Benchmark công khai định hướng; eval của bạn quyết định (Phần 7).
  • Agent production dùng routing, fallback, cascade — không một model cho mọi bước.
  • Chạy lại chọn model khi checkpoint, giá, hoặc mix task đổi.

Tiếp theo: khi đã có shortlist model, vòng agent phụ thuộc gọi tool đáng tinFunction Calling & Tool Use.


Loạt bài Building AI Agents

  1. Tokens & Context Windows
  2. Sampling: temperature, top_p, top_k
  3. Prompt Engineering for Agents
  4. Stopping Criteria & Output Control
  5. Context Engineering & Memory
  6. Fine-tuning vs Prompting vs RAG
  7. Evaluating LLMs & Agents
  8. Choosing a Model (current)
  9. Function Calling & Tool Use
  10. Agent Patterns: ReAct, Reflection, Planning