Full-Stack AI Engineering

The model is one layer.The product is the whole stack. Model chỉ là một lớp.Sản phẩm là cả hệ thống.

Eight layers of an LLM product, grouped by what they change: what the model sees, how it behaves, and how it runs in production. Tám lớp của một sản phẩm LLM, chia theo thứ chúng thay đổi: model nhìn thấy gì, hành xử ra sao, và chạy thế nào trên production.

Which one do you need?Bạn cần cái nào?

Start from nothing. Add a layer only when a test shows a failure that layer fixes. Bắt đầu từ con số không. Chỉ thêm một lớp khi một test chỉ ra lỗi mà lớp đó sửa được.

Baseline: you may need none of thisBaseline: có thể bạn chẳng cần lớp nào

One API call to an off-the-shelf model, one careful prompt, 20–50 hand-written test cases. That's enough when:Một lời gọi API tới model có sẵn, một prompt viết cẩn thận, 20–50 test case viết tay. Thế là đủ khi:

  • The task needs general knowledge or data the user can paste in.Tác vụ chỉ cần kiến thức phổ thông hoặc dữ liệu người dùng dán vào được.
  • Traffic is a few thousand requests a day — an API beats self-hosting.Lưu lượng cỡ vài nghìn request/ngày — API rẻ hơn tự host.
  • A human reviews every output.Mọi đầu ra đều có người duyệt.
  • Plain code (if/else, regex, SQL) can do it — then skip the LLM entirely.Code thường (if/else, regex, SQL) làm được — khi đó bỏ hẳn LLM.

Wrong format, wrong voice, ignores rulesSai định dạng, sai giọng, bỏ sót yêu cầu

Missing private knowledge — small enough to fit in contextThiếu kiến thức riêng — đủ nhỏ để vừa context

put it in contextđưa thẳng vào context

Missing knowledge — large corpus that changes oftenThiếu kiến thức — kho lớn, hay thay đổi

Multiple steps, all known in advanceNhiều bước, đều biết trước

fixed workflowworkflow cố định

Next step depends on the previous resultBước sau phụ thuộc kết quả bước trước

Long sessions; the model forgets or driftsPhiên dài; model quên hoặc lạc đề

In production and you don't know why answers are wrongĐã lên production mà không biết vì sao trả lời sai

Too slow or too expensive — after measuringQuá chậm hoặc quá đắt — sau khi đã đo

Data can't leave your infra, or traffic is huge and steadyDữ liệu không được ra ngoài, hoặc lưu lượng rất lớn và đều

The eight layersTám lớp

Codes group layers by family, not by order. The image's 1→8 numbering isn't a sequence.Mã đánh theo họ, không theo thứ tự. Số 1→8 trong ảnh gốc không phải một trình tự.

ContextNgữ cảnh

changes what the model seesthay đổi thứ model nhìn thấy

CTX-1ContextNgữ cảnh

Prompt Engineering

prompt ──► LLM ──► reply

Write instructions, examples and an output format so the model does the right task, consistently.Viết chỉ dẫn, ví dụ mẫu và định dạng đầu ra để model làm đúng việc, ổn định.

Trades long-term stability and a quality ceiling for iteration speed and near-zero cost.Đổi độ ổn định dài hạn và trần chất lượng lấy tốc độ lặp và chi phí gần bằng không.

Use forDùng cho
Fixed-label classification, JSON extraction, rewriting in a brand voice.Phân loại nhãn cố định, trích xuất JSON, viết lại theo giọng thương hiệu.
GainĐược
Minute-long try–fix loop, no infrastructure.Vòng thử–sửa tính bằng phút, không cần hạ tầng.
LoseMất
Can't add knowledge; breaks silently across model versions.Không thêm được kiến thức; dễ vỡ ngầm khi đổi model version.

Signal:Dấu hiệu: "correct" can be described in words.tiêu chí "đúng" mô tả được bằng lời.

CTX-2ContextNgữ cảnh

Context Engineering

sources ──► [select · compress · order] ──► context ──► LLM

Decide everything that enters the context window at each step: instructions, memory, retrieved docs, tool results. Prompting is one part of it.Quyết định mọi thứ đi vào context window ở từng bước: chỉ dẫn, bộ nhớ, tài liệu truy xuất, kết quả tool. Prompt chỉ là một phần trong đó.

Trades system simplicity for stable quality on long tasks and lower token cost.Đổi độ đơn giản của hệ thống lấy chất lượng ổn định trên tác vụ dài và chi phí token thấp hơn.

Use forDùng cho
Long-running agents, cross-session memory, coding on large repos.Agent chạy dài, nhớ qua nhiều phiên, trợ lý code trên repo lớn.
GainĐược
Fewer tokens per call; less "lost in the middle".Ít token hơn mỗi lần gọi; giảm "lost in the middle".
LoseMất
Compression drops facts silently; bugs are hard to reproduce.Nén làm rơi thông tin mà không báo; lỗi khó tái hiện.

Signal:Dấu hiệu: quality drops as the session gets longer.chất lượng tụt dần khi phiên dài ra.

CTX-3ContextNgữ cảnh

RAG

query ──► search ──► rerank ──► LLM ──► answer + sourcesnguồn

Retrieve relevant passages from your own data, put them in context, and answer from them with citations.Truy xuất đoạn liên quan từ dữ liệu riêng, đưa vào context, rồi trả lời dựa trên chúng kèm trích nguồn.

Trades an extra data pipeline to run for knowledge that is always fresh and verifiable.Đổi thêm một pipeline dữ liệu phải vận hành lấy kiến thức luôn mới và có nguồn kiểm chứng.

Use forDùng cho
Internal docs Q&A, support knowledge bases, contract lookup.Hỏi đáp tài liệu nội bộ, knowledge base hỗ trợ khách hàng, tra cứu hợp đồng.
GainĐược
Update knowledge by editing data; per-user access control.Cập nhật kiến thức bằng cách sửa dữ liệu; phân quyền theo người dùng.
LoseMất
Bad retrieval gives confident wrong answers; weak at whole-corpus counts.Truy xuất sai thì trả lời sai đầy tự tin; yếu khi phải đếm/tổng hợp toàn kho.

Signal:Dấu hiệu: the answer already exists in some document.câu trả lời đã nằm sẵn trong một tài liệu nào đó.

Model & controlModel & điều khiển

changes weights or control flowthay đổi trọng số hoặc luồng điều khiển

MDL-1Model & controlModel & điều khiển

Fine-tuning

data ──► tune (SFT · LoRA) ──► tuned model

Keep training a base model on your examples to change its weights — usually supervised fine-tuning with LoRA.Huấn luyện tiếp model gốc trên ví dụ của bạn để thay đổi trọng số — thường là SFT với LoRA.

Trades flexibility for stable behavior and lower per-request cost at scale.Đổi tính linh hoạt lấy hành vi ổn định và chi phí mỗi request thấp hơn ở quy mô lớn.

Use forDùng cho
Strict formats prompts can't hold; distilling a small model for a narrow, high-volume task.Định dạng khắt khe mà prompt không giữ nổi; chưng cất model nhỏ cho tác vụ hẹp, lưu lượng lớn.
GainĐược
Shorter prompts; a small model can match a big one on a narrow task.Prompt ngắn hơn; model nhỏ có thể ngang model lớn trên tác vụ hẹp.
LoseMất
Poor way to add facts; locked to one base model; needs clean data.Không hợp để nạp kiến thức; khoá vào một model gốc; cần dữ liệu sạch.

Signal:Dấu hiệu: best prompt plus examples still misses 10–20% on a fixed task.prompt tốt nhất kèm ví dụ vẫn trượt 10–20% trên một tác vụ cố định.

MDL-2Model & controlModel & điều khiển

Agents

goal ──► LLM ⇄ tools ┄┄ loop until donelặp tới khi xong ──► action

The model chooses the next step in a loop: call a tool, read the result, repeat. In a workflow, code decides the path; in an agent, the model does.Model tự chọn bước tiếp theo trong vòng lặp: gọi tool, đọc kết quả, lặp lại. Ở workflow, code quyết định luồng; ở agent, model quyết định.

Trades predictability of cost, latency and behavior for handling tasks whose steps aren't known upfront.Đổi tính dự đoán được về chi phí, độ trễ, hành vi lấy khả năng xử lý tác vụ không biết trước các bước.

Use forDùng cho
Fixing bugs in a codebase, multi-source research, support across several systems.Sửa lỗi trong codebase, nghiên cứu nhiều nguồn, hỗ trợ khách hàng qua nhiều hệ thống.
GainĐược
Covers open-ended tasks; recovers from tool errors.Bao được tác vụ mở; tự xoay xở khi tool báo lỗi.
LoseMất
Errors compound (0.95¹⁰ ≈ 0.6); cost is unpredictable; prompt injection risk.Lỗi cộng dồn (0,95¹⁰ ≈ 0,6); chi phí khó đoán; rủi ro prompt injection.

Signal:Dấu hiệu: the next step depends on the previous result.bước sau phụ thuộc kết quả bước trước.

OperationsVận hành

gets it into production and keeps it healthyđưa lên production và giữ nó chạy ổn

OPS-1OperationsVận hành

LLM Deployment

code ──► gateway ──► serve (vLLM · SGLang) ──► API

Turn a model into a callable service: provider API, managed cloud, or self-hosted open weights on GPUs.Biến model thành dịch vụ gọi được: API nhà cung cấp, cloud managed, hoặc tự host model open-weight trên GPU.

Self-hosting trades operating cost and frontier quality for data control and low marginal cost at scale.Tự host là đổi chi phí vận hành và chất lượng model hàng đầu lấy quyền kiểm soát dữ liệu và chi phí cận biên thấp ở quy mô lớn.

Use forDùng cho
Data that can't leave your infra; huge steady traffic; your own fine-tuned model.Dữ liệu không được rời hạ tầng; lưu lượng rất lớn và đều; model fine-tune riêng.
GainĐược
Full control; no third-party rate limits or deprecations.Toàn quyền kiểm soát; không lệ thuộc rate limit hay việc ngừng model.
LoseMất
Idle GPUs still cost money; needs GPU ops skills.GPU nhàn rỗi vẫn tốn tiền; cần người giỏi vận hành GPU.

Signal:Dấu hiệu: the API bill exceeds GPUs plus the people to run them.hoá đơn API vượt chi phí GPU cộng người vận hành.

OPS-2OperationsVận hành

LLM Observability

prompt ──► trace (spans) ──► metrics

Record every request as a trace — prompt, context, tool calls, output, tokens, latency, cost — and roll traces up into metrics.Ghi mỗi request thành một trace — prompt, context, tool call, đầu ra, token, độ trễ, chi phí — rồi gộp thành số liệu.

Trades storage cost and data risk for knowing exactly what the system is doing.Đổi chi phí lưu trữ và rủi ro dữ liệu lấy khả năng biết chính xác hệ thống đang làm gì.

Use forDùng cho
Unreproducible wrong answers, cost spikes, slow multi-step agents.Trả lời sai không tái hiện được, chi phí tăng vọt, agent nhiều bước chạy chậm.
GainĐược
Debug with data; catch drift; the best source of test cases.Gỡ lỗi bằng dữ liệu; bắt được drift; nguồn test case tốt nhất.
LoseMất
Logs hold personal data; quality needs evals to measure.Log chứa dữ liệu cá nhân; chất lượng phải có evals mới đo được.

Signal:Dấu hiệu: "it gave a weird answer" and nobody can find the request."nó trả lời lạ lắm" mà không ai tìm được request đó.

OPS-3OperationsVận hành

LLM Optimization

raw LLM ──► opt ──► fast ┄┄ re-run evalschạy lại evals

Cut latency and cost without dropping below a quality threshold: caching, model routing, shorter context, quantization, speculative decoding.Giảm độ trễ và chi phí mà không tụt dưới ngưỡng chất lượng: cache, định tuyến model, rút gọn context, quantization, speculative decoding.

Trades added complexity and quality risk for lower cost and latency.Đổi thêm độ phức tạp và rủi ro tụt chất lượng lấy chi phí và độ trễ thấp hơn.

Use forDùng cho
Long repeated system prompts, mixed easy/hard traffic, VRAM limits.System prompt dài lặp lại, lưu lượng trộn dễ/khó, thiếu VRAM.
GainĐược
Cached input up to ~90% cheaper; INT8 halves weight memory vs FP16.Token đầu vào đọc từ cache rẻ hơn tới ~90%; INT8 giảm nửa bộ nhớ trọng số so với FP16.
LoseMất
Aggressive quantization hurts the hardest cases; blind optimizing wastes effort.Quantization mạnh làm hỏng đúng ca khó nhất; tối ưu mù là phí công.

Signal:Dấu hiệu: traces already show where time and money go.trace đã chỉ rõ thời gian và tiền đi đâu.

The layer the image missed: EvalsLớp ảnh bỏ sót: Evals

A test suite with automated scoring for LLM outputs. Every layer above has to answer "better or worse?" — without evals, the answer is a feeling.Bộ test case có chấm điểm tự động cho đầu ra LLM. Mọi lớp ở trên đều phải trả lời "tốt lên hay tệ đi?" — không có evals, câu trả lời chỉ là cảm giác.

Start with 30–50 real cases, favoring past failures. Score with code where you can; use an LLM judge for soft criteria and check it against humans.Bắt đầu với 30–50 ca thật, ưu tiên ca từng sai. Chấm bằng code khi được; dùng LLM chấm cho tiêu chí mềm và đối chiếu với người.

Trade-offs side by sideĐặt các đánh đổi cạnh nhau

Scroll sideways on small screens.Màn hình nhỏ thì vuốt ngang.

LayerLớp First resultCó kết quả đầu Fixed costChi phí cố định Effect on $/requestTác động $/request Ops difficultyĐộ khó vận hành SolvesGiải quyết
PromptMinutesPhút~0Rises with lengthTăng theo độ dàiLowThấpBehavior, formatHành vi, định dạng
ContextDaysNgàyLowThấpLowersGiảmMediumTrung bìnhLong-task qualityChất lượng tác vụ dài
RAGDays–weeksNgày–tuầnMediumTrung bìnhSlightly raisesTăng nhẹMediumTrung bìnhMissing knowledgeThiếu kiến thức
Fine-tuningWeeksTuầnHighCaoLowersGiảmHighCaoStable behavior at scaleHành vi ổn định ở quy mô lớn
AgentsDays–weeksNgày–tuầnLow–mediumThấp–trung bìnhRaises sharply, unpredictableTăng mạnh, khó đoánHighCaoOpen multi-step tasksTác vụ nhiều bước, mở
Deployment (self-host)Deployment (tự host)WeeksTuầnHighCaoLowers at scaleGiảm ở quy mô lớnVery highRất caoData controlKiểm soát dữ liệu
ObservabilityHoursGiờLowThấpNear zeroGần 0Low–mediumThấp–trung bìnhNot knowing why it failsKhông biết vì sao sai
OptimizationDaysNgàyLow–highThấp–caoLowersGiảmDependsTuỳ kỹ thuậtSlow, expensiveChậm, đắt

Anti-patterns

The mistakes that cost the most time.Những sai lầm tốn thời gian nhất.

MistakeSai lầmWhy it's wrongVì sao saiFixSửa thế nào
Fine-tuning to teach new knowledgeFine-tune để dạy kiến thức mớiFacts are learned poorly, still fabricated, retrain on every data changeModel nhớ sự kiện kém, vẫn bịa, dữ liệu đổi là phải huấn luyện lạiRAG or put it in contextRAG hoặc đưa vào context
An agent for a fixed processDựng agent cho quy trình cố địnhPay cost, latency and risk for nothingChịu chi phí, độ trễ, rủi ro mà không được gìCode-controlled workflowWorkflow do code điều khiển
Stuffing the whole corpus into contextNhét cả kho tài liệu vào contextExpensive, slow, the middle gets missedĐắt, chậm, phần giữa bị bỏ sótSelective retrieval, token budgetTruy xuất chọn lọc, ngân sách token
Editing a prompt and eyeballing outputsSửa prompt rồi nhìn vài câu bằng mắtFixes one case, silently breaks anotherSửa ca này, hỏng ca khác mà không biếtEvals after every changeChạy evals sau mỗi thay đổi
Self-hosting on day one "to save money"Tự host từ đầu "cho rẻ"Idle GPUs cost more than an APIGPU nhàn rỗi đắt hơn APIAPI first, self-host past break-evenAPI trước, tự host khi qua điểm hoà vốn
Optimizing before measuringTối ưu trước khi đoWrong target, needless complexitySai chỗ, thêm phức tạp vô íchObserve, find the bottleneck, then optimizeQuan sát, tìm nút thắt, rồi mới tối ưu
Vector search onlyChỉ dùng vector searchMisses product codes and exact namesTrượt mã sản phẩm, tên riêng chính xácHybrid search + rerankerTìm kiếm lai + reranker
Trusting tool/web output in an agentTin đầu ra tool/web trong agentPrompt injection from external dataPrompt injection từ dữ liệu bên ngoàiTreat as untrusted; limit tool permissionsCoi là không tin cậy; giới hạn quyền tool
Logging only technical errorsChỉ log lỗi kỹ thuậtWrong answers still return HTTP 200Trả lời sai vẫn là HTTP 200Full traces + quality scoringTrace đầy đủ + chấm chất lượng

What we changed from the imageNhững điểm đã hiệu chỉnh so với ảnh

Not a 1→8 roadmapKhông phải lộ trình 1→8

They're parallel layers. Build order: prompt + evals, context + RAG, observability, agents, ops, fine-tuning last.Đây là các lớp song song. Thứ tự nên làm: prompt + evals, context + RAG, observability, agent, vận hành, fine-tune sau cùng.

Context contains prompt and RAGContext bao trùm prompt và RAG

The image puts it last; it's the umbrella. Learn it early.Ảnh đặt nó cuối; thực ra nó là lớp bao trùm. Nên học sớm.

Observe before you optimizeQuan sát trước, tối ưu sau

The image has these two reversed.Ảnh đặt hai lớp này ngược nhau.

Evals were missingẢnh thiếu Evals

Without them, every other layer is guesswork.Không có evals, mọi lớp khác đều là đoán mò.

Three things to rememberBa câu cần nhớ

  1. Start from the baseline — one API call, one good prompt, one eval suite — and add a layer only when numbers show a failure it fixes.Bắt đầu từ baseline — một lời gọi API, một prompt tốt, một bộ evals — và chỉ thêm lớp khi số liệu chỉ ra lỗi mà lớp đó sửa được.
  2. Missing knowledge: fix the context. Wrong behavior: fix the prompt, then fine-tune. Unknown steps: only then an agent.Thiếu kiến thức: sửa ngữ cảnh. Sai hành vi: sửa prompt, rồi mới fine-tune. Bước không biết trước: lúc đó mới dùng agent.
  3. Measure first, optimize second. Observability and evals turn every other layer from guesswork into engineering.Đo trước, tối ưu sau. Observability và evals biến mọi lớp còn lại từ đoán mò thành kỹ thuật.