guardrails 101 / tài liệu học/ study notes

Bảy lớp kiểm tra, xếp theo thứ tự chúng chạy

Seven checks, in the order they run

Guardrails chạy bên cạnh agent, không đứng trước nó.

Guardrails run beside the agent, not in front of it.

Một guardrail thì chưa phải là guardrail. Xếp tầng chúng lại, rẻ trước: regex và giới hạn độ dài miễn phí, còn một classifier tốn một model call. Và lúc tripwire bật thì agent đã sinh chữ được một lúc rồi.

One guardrail is not a guardrail. Layer them, cheapest first: regex and length limits are free, a classifier costs a model call. And by the time the tripwire fires, the agent has been generating for a while.

Điều thực sự xảy ra lúc chạy

What actually happens at runtime

Agent và các guardrail đầu vào (relevance, safety) khởi động cùng một lúc. Tripwire giật cầu dao ở giữa chừng — nhưng phần chữ bên trái vạch, nếu không giữ trong buffer, đã rời máy chủ. Moderation là kiểm tra đầu ra: nó chạy trên từng đoạn trong buffer trước khi đoạn đó hiển thị.

The agent and the input guardrails (relevance, safety) start at the same instant. The tripwire throws the breaker mid-stream — but anything left of the line that wasn’t held in a buffer has already left the server. Moderation is an output check: it runs on each buffered chunk before that chunk is shown.

Agent generating in parallel with two input guardrails while moderation checks buffered output; safety trips the wire and the run is cancelled. agent agent bị huỷ cancelled 146 token này đã ra khỏi máy chủ these 146 tokens already left the server relevance safety moderation tripwire thời gian, cùng một trục cho cả bốn lane time, one axis shared by all four lanes

Chọn cái nào

Which one to use

Bắt đầu từ câu hỏi rẻ nhất: có thể không cần lớp nào không?

Start with the cheapest question: can you get away with none of them?

Baseline: không dùng gì cả

The do-nothing baseline

  • Agent chỉ đọc. Không tool ghi, không tiêu tiền, không gửi gì ra ngoài.
  • Người dùng là nội bộ, đã đăng nhập, danh tính rõ ràng.
  • Họ vốn đã có quyền xem mọi thứ agent xem được.
  • Sai thì sửa trong một phút và không ai ngoài công ty nhìn thấy.
  • The agent only reads. No write tools, no spending, nothing sent outside.
  • Users are internal, authenticated, identifiable.
  • They already have access to everything the agent can see.
  • Mistakes are fixable in a minute and nobody outside ever sees them.

Đủ bốn điều đó thì phương án rẻ nhất là: giới hạn độ dài input, rate limit theo người dùng, log toàn bộ hội thoại, và không cấp tool ghi. Bốn dòng cấu hình, 0 đồng mỗi lượt.

If all four hold, the cheapest option is: an input length limit, a per-user rate limit, full conversation logging, and no write tools. Four lines of config, zero per-turn cost.

Câu hỏi phải trả lời trước khi thêm bất kỳ lớp nào: hành động tệ nhất mà agent này làm được là gì? Nếu câu trả lời là “trả lời sai một câu hỏi”, đừng xây gì cả.

The question to answer before adding any layer: what is the worst thing this agent can do? If the answer is “give a wrong answer”, build nothing.

Agent có tool ghi, tiêu tiền, hoặc gửi ra ngoài không?

Does the agent have write, spend, or send-outside tools?

Không — và người dùng là nội bộ: chỉ log + rate limit Dừng ở đây.

No — and users are internal: logging + rate limit only Stop here.

Không — nhưng mở cho công chúng: 01 rules-based 02 relevance để giữ hoá đơn trong tầm kiểm soát, cộng 04 PII (RAG vẫn có thể rò) và 05 moderation.

No — but public-facing: 01 rules-based 02 relevance to keep the bill under control, plus 04 PII (RAG can still leak) and 05 moderation.

Có — bắt buộc 07 mức rủi ro tool làm trước mọi thứ khác. Rồi lần lượt:

Yes — 07 tool risk tiering is mandatory, before anything else. Then, in turn:

Agent đọc dữ liệu bạn không kiểm soát — email, web, RAG ngoài? 03 safety và kiểm tra cả nội dung tool trả về.

Does it read data you don’t control — email, web, external RAG? 03 safety and check tool output too.

Đầu ra tới bên thứ ba, hoặc trộn dữ liệu của nhiều người dùng? 04 PII ở đầu ra, redact chứ đừng chặn.

Does output reach third parties, or mix data from several users? 04 PII on the way out, redact rather than block.

Sản phẩm mở cho công chúng? 05 moderation

Public-facing product? 05 moderation

Streaming, và tổng thời gian guardrail vượt 200ms? 06 chạy song song

Streaming, and total guardrail time over 200ms? 06 optimistic execution


Bảy lớp

The seven layers

Đánh số theo đúng thứ tự chúng chạy trong một lượt: ba lớp đầu vào, hai lớp đầu ra, hai quyết định kiến trúc.

Numbered in the order they run within a turn: three input checks, two output checks, two architectural decisions.

01

Rules-based

đầu vàoinput

Kiểm tra chuỗi thuần, không gọi model. Chưa tới một mili-giây, đúng 0 đồng.

Pure string checks, no model call. Under a millisecond, exactly free.

input → [dài ≤ 4k] → [regex cấm] → [blocklist] → qua

input → [len ≤ 4k] → [banned regex] → [blocklist] → pass

Dùng cho

Use it for

  • Prompt 200k ký tự làm nổ context
  • Số thẻ dán thẳng vào ô chat
  • Ép mã đơn đúng định dạng trước khi gọi tool
  • Ký tự zero-width giấu chỉ thị
  • 200k-character prompts blowing up context
  • Card numbers pasted into chat
  • Enforcing order-ID format before a tool runs
  • Zero-width characters hiding instructions

Được

You get

  • 0 đồng, dưới 1ms
  • Xác định, viết unit test được
  • Chặn 100% cái đã liệt kê
  • Free, sub-millisecond
  • Deterministic, unit-testable
  • Catches 100% of what you listed

Mất

You lose

  • Chỉ bắt được cái đã nghĩ ra trước
  • Blocklist chết khi đổi cách viết
  • Regex quá tay chặn nhầm người thật, và họ không khiếu nại
  • Only catches what you thought of
  • Blocklists die on respelling
  • Over-eager regex blocks real users, who don’t complain

đánh đổitrade-offĐổi khả năng bắt biến thể chưa từng gặp lấy chi phí bằng 0 và kết quả tái lập được.Trading the ability to catch unseen variants for zero cost and reproducible results.

Dấu hiệu: viết được điều kiện đó bằng một câu if mà không cần hiểu ý câu chữ — nó thuộc lớp này.

The tell: you can express it as an if without understanding the sentence — it belongs here.

02

Relevance

đầu vàoinput

Câu này có thuộc phạm vi sản phẩm không? Một model rẻ chấm điểm mỗi lượt.

Is this even on topic? A cheap model scores every turn.

câu hỏi → [on-topic?] → điểm dưới ngưỡng → chặn

question → [on-topic?] → below threshold → block

Dùng cho

Use it for

  • Bot ngân hàng bị hỏi công thức nấu ăn
  • Bot nội bộ thành ChatGPT miễn phí
  • Agent bán hàng bị kéo sang chính trị
  • A banking bot asked for recipes
  • An internal bot repurposed as free ChatGPT
  • A sales agent dragged into politics

Được

You get

  • Cắt lượt lạc đề ở bot public (theo kinh nghiệm, khoảng 10–30%)
  • Khoảng 1/20 chi phí một lượt chính
  • Bề mặt tấn công hẹp lại
  • Cuts off-topic traffic (roughly 10–30%, in our experience)
  • Around 1/20th of a main turn’s cost
  • A narrower attack surface

Mất

You lose

  • Ranh giới “đúng chủ đề” luôn mờ
  • Câu hợp lệ diễn đạt lạ bị chặn nhầm
  • Thêm tính năng là phải viết lại phạm vi
  • “On topic” is always fuzzy
  • Unusual phrasing gets blocked
  • Every new feature means rewriting scope

đánh đổitrade-offĐổi trải nghiệm của nhóm hỏi vòng vo lấy hoá đơn token dự đoán được.Trading the experience of users who ramble for a predictable token bill.

Dấu hiệu: hoá đơn token tăng đều nhưng số ticket được giải quyết đứng yên.

The tell: the token bill grows steadily while resolved tickets stay flat.

03

Safety — jailbreak và injection

Safety — jailbreak and injection

đầu vàoinput

Jailbreak đến từ ô chat. Injection đến từ email, trang web, kết quả RAG — và người dùng có thể hoàn toàn vô tội.

Jailbreaks come through the chat box. Injection comes from email, web pages, RAG results — and the user may be entirely innocent.

chat + nội dung tool trả về → [classifier riêng] → tripwire

chat + tool output → [separate classifier] → tripwire

Dùng cho

Use it for

  • Agent hoàn tiền hoặc chuyển khoản
  • Agent đọc hộp thư rồi tự hành động
  • RAG từ nguồn bạn không kiểm soát
  • Yêu cầu in ra system prompt
  • Agents that refund or transfer
  • Agents that read an inbox and act
  • RAG over sources you don’t control
  • Requests to print the system prompt

Được

You get

  • Bắt được biến thể chưa có trong blocklist
  • Chạy song song, gần như không thêm độ trễ
  • Kiểm tra được cả nội dung tool trả về
  • Catches variants no blocklist holds
  • Runs in parallel, near-zero added latency
  • Can inspect tool output too

Mất

You lose

  • Không bao giờ đạt 100% — đây là bài toán đối kháng
  • Chặn nhầm câu hỏi bảo mật hợp lệ
  • Một model call mỗi lượt, và mỗi lần gọi tool
  • Never 100% — this is adversarial
  • False blocks on real security questions
  • A model call per turn, and per tool call

đánh đổitrade-offĐổi một model call mỗi lượt và vài phần trăm chặn nhầm lấy khả năng bắt đòn chưa ai từng thấy.Trading a model call per turn and a few percent false blocks for catching attacks nobody has seen yet.

Dấu hiệu: agent làm được việc tốn tiền hoặc không đảo ngược được. Không có ngoại lệ.

The tell: the agent can do something costly or irreversible. No exceptions.

04

PII

đầu raoutput

Quét thứ agent sắp nói ra, không phải thứ người dùng vừa nói vào.

Scan what the agent is about to say, not what the user just said.

câu trả lời → [regex + model nhỏ] → redact → gửi

answer → [regex + small model] → redact → send

Dùng cho

Use it for

  • Model nhắc lại số thẻ từ lượt thứ ba
  • RAG kéo nhầm hồ sơ khách hàng khác
  • API key lọt vào câu trả lời rồi vào log
  • The model repeating a card number from turn three
  • RAG pulling another customer’s record
  • An API key landing in an answer, then in logs

Được

You get

  • Bắt lỗi sinh ra bên trong hệ thống của bạn
  • Gần 100% với PII có cấu trúc, tốn 0 đồng
  • Chốt cuối trước lỗi phân quyền RAG
  • Catches failures born inside your system
  • Near-perfect and free on structured PII
  • The last control before a RAG permission bug

Mất

You lose

  • Streaming: chữ đã ra thì không kéo lại được
  • PII không cấu trúc rất khó bắt
  • Redact quá tay làm câu trả lời vô nghĩa
  • Streaming: shipped tokens can’t be recalled
  • Unstructured PII is genuinely hard
  • Over-redaction makes answers meaningless

đánh đổitrade-offĐổi trải nghiệm streaming mượt lấy sự chắc chắn rằng không dữ liệu nào rời hệ thống mà không qua kiểm tra.Trading smooth streaming for certainty that nothing leaves the system unchecked.

Dấu hiệu: đầu ra đi qua mắt bên thứ ba — khách hàng khác, log tập trung, hệ thống ticket.

The tell: your output passes a third party — another customer, a central log, a ticket system.

05

Moderation

đầu raoutput

PII hỏi “cái này của ai”. Moderation hỏi “cái này có nên hiện lên màn hình”.

PII asks “whose is this?”. Moderation asks “should this be on a screen at all?”

câu trả lời → [API có sẵn] → điểm theo hạng mục → ngưỡng của bạn

answer → [off-the-shelf API] → per-category scores → your threshold

Dùng cho

Use it for

  • Sản phẩm cho người dùng cuối, nhất là có thể có trẻ vị thành niên
  • Agent nhắc lại nội dung người khác viết
  • Role-play kéo dài nhiều lượt
  • Consumer products, especially with minors
  • Agents repeating other users’ content
  • Role-play across long conversations

Được

You get

  • Không phải tự train, không phải nuôi tập nhãn
  • Policy do bên cung cấp cập nhật
  • Thường dưới 100ms
  • Nothing to train, no labels to maintain
  • Policy updated by the vendor
  • Usually under 100ms

Mất

You lose

  • Policy chung chặn nhầm domain hẹp: y tế, pháp lý
  • Yếu với tiếng Việt, tiếng lóng, mỉa mai
  • Không phân biệt trích dẫn với phát ngôn
  • General policy misfires in narrow domains
  • Weak on Vietnamese, slang, sarcasm
  • Can’t tell quotation from assertion

đánh đổitrade-offĐổi quyền kiểm soát chi tiết chính sách lấy việc không phải tự xây và tự nuôi một hệ phân loại.Trading fine-grained policy control for not having to build and feed a classifier.

Dấu hiệu: một ảnh chụp màn hình câu trả lời của bạn có thể lên báo.

The tell: a screenshot of one of your answers could end up in a news article.

06

Chạy song song, giật cầu dao

Optimistic execution

kiến trúc chạyruntime

Đừng chờ kiểm tra xong mới gọi agent. Khởi động cả hai cùng lúc, huỷ khi tripwire bật.

Don’t wait for checks before calling the agent. Start both at once, cancel when the tripwire fires.

try: await Runner.run(agent, msg) ‖ input checks
except InputGuardrailTripwireTriggered: ...
except OutputGuardrailTripwireTriggered: ...

Dùng cho

Use it for

  • Chatbot streaming, nơi TTFT là chỉ số người dùng cảm nhận
  • Agent nhiều bước
  • Guardrail đắt: một classifier tử tế mất 300–800ms
  • Streaming chat, where TTFT is what users feel
  • Multi-step agents
  • Expensive checks: 300–800ms per classifier

Được

You get

  • Xoá gần hết thời gian guardrail khỏi độ trễ cảm nhận
  • Lớp thứ tư, thứ năm gần như miễn phí
  • Chỉ trả token thừa ở một phần nhỏ số lượt (ước chừng ~1%)
  • Removes almost all guardrail time from perceived latency
  • The fourth and fifth layers become nearly free
  • Wasted tokens only on a small share of turns (roughly ~1%)

Mất

You lose

  • Trả tiền cho token sinh ra rồi vứt đi
  • Đã stream ra UI thì phải rút chữ lại
  • Tool có tác dụng phụ đã chạy thì không huỷ được
  • You pay for tokens you discard
  • Text already streamed must be taken back
  • Side-effecting tools can’t be cancelled

đánh đổitrade-offĐổi một ít token lãng phí và độ phức tạp khi huỷ lấy độ trễ cảm nhận gần bằng không.Trading some wasted tokens and cancellation complexity for near-zero perceived latency.

Dấu hiệu: người dùng nhìn con trỏ nhấp nháy hơn một giây trước chữ đầu tiên.

The tell: users watch a blinking cursor for over a second before the first character.

07

Mức rủi ro của tool

Tool risk tiering

kiến trúc chạyruntime

Guardrail văn bản kiểm tra chữ. Lớp này kiểm tra quyền — và cái mức cao đánh thức một con người.

Text guardrails check words. This one checks capability — and the high ones wake a human.

low → chạy thẳng
medium → chạy, ghi log, cảnh báo sau
high → vào hàng đợi, chờ người duyệt

low → runs immediately
medium → runs, logged, alerted after
high → queued, waits for approval

Dùng cho

Use it for

  • Hoàn tiền, chuyển khoản, đổi hạn mức
  • Xoá dữ liệu, chạy migration
  • Gửi thư hàng loạt cho khách thật
  • Deploy, mở quyền truy cập
  • Refunds, transfers, limit changes
  • Deleting data, running migrations
  • Bulk mail to real customers
  • Deploys, granting access

Được

You get

  • Chặn lỗi “hiểu đúng chữ nhưng làm sai việc”
  • Không phụ thuộc model hay prompt
  • Hàng rào cuối khi injection đã lọt qua hết
  • Catches “right words, wrong action”
  • Independent of model and prompt
  • The last barrier when injection got through

Mất

You lose

  • Approval fatigue: sau vài trăm lần người ta bấm theo phản xạ
  • Độ trễ tính bằng phút hoặc giờ
  • Cần hàng đợi, thông báo, màn hình duyệt thật
  • Approval fatigue: reflexive clicking sets in
  • Latency measured in minutes or hours
  • Needs a real queue, alerts, approval UI

đánh đổitrade-offĐổi khả năng tự động hoá hoàn toàn lấy một điểm dừng có người chịu trách nhiệm trước mỗi hành động không đảo ngược được.Trading full automation for one accountable stopping point before every irreversible action.

Dấu hiệu: nếu tool này chạy nhầm 100 lần trong 10 phút mà không sửa xong trong ngày — đó là mức high.

The tell: if it fires 100 times in ten minutes and you can’t fix it the same day — it’s high tier.


Bảng đánh đổi

Trade-off table

Đọc cột “bắt được gì” trước, không phải cột chi phí.

Read the “catches” column first, not the cost column.

LớpLayer Chi phí mỗi lượtCost per turn Độ trễ nếu chạy tuần tựLatency if sequential Bắt được gìCatches Chặn nhầmFalse blocks
01 Rules-based 0 đồngfree <1ms đúng cái đã liệt kêexactly what you listed thấp, nhưng âm thầmlow, but silent
02 Relevance ~1/20 lượt chính~1/20 of a turn 100–300ms lạc đề, đốt tokenoff-topic, token burn trung bìnhmedium
03 Safety một model callone model call 300–800ms jailbreak, injectionjailbreaks, injection trung bình–caomedium–high
04 PII regex 0đ + model nhỏfree regex + small model 50–300ms rò dữ liệu ở đầu raleaks on the way out thấp nếu redactlow if you redact
05 Moderation rất rẻ (API)very cheap (API) <100ms nội dung độc hạiharmful content cao ở domain hẹphigh in narrow domains
06 Chạy song song06 Optimistic exec. token bị vứt (ước chừng ~1% lượt)discarded tokens (roughly ~1%) âm — bỏ được độ trễ các lớp trênnegative — removes the layers above không bắt gì, nó là cách chạynothing; it’s how you run khôngnone
07 Mức rủi ro tool07 Tool risk tiering 0đ máy, tốn giờ ngườifree compute, costly hours phút đến giờminutes to hours hành động sai, không phải chữ saiwrong actions, not wrong words đo bằng sự bực bội của người duyệtmeasured in reviewer frustration

Hai lớp bắt cùng một thứ thì bỏ một. Lớp bắt thứ chưa ai bắt thì đắt mấy cũng đáng.

Two layers catching the same thing means dropping one. A layer catching something nothing else does is worth almost any price.


Anti-patterns

Anti-patterns

Sáu lỗi gặp nhiều nhất, và cách sửa.

The six most common mistakes, and the fix.

Viết luật vào system prompt rồi gọi đó là guardrail
Writing rules into the system prompt and calling it a guardrail
Cùng một model, cùng một bề mặt tấn công. Câu ghi đè được prompt thì cũng ghi đè được luật.
Same model, same attack surface. Text that overrides the prompt overrides the rules too.
Đưa kiểm tra ra khỏi prompt của agent: code thuần, hoặc một lần gọi classifier riêng không thấy system prompt của agent.
Move checks out of the agent’s prompt: plain code, or a separate classifier call that never sees the agent’s prompt.
Một guardrail LLM “làm hết mọi việc”
One LLM guardrail that “does everything”
Đắt cho mọi lượt, và khi hỏng thì hỏng toàn bộ cùng lúc.
Expensive on every turn, and when it fails it fails completely.
Xếp tầng, rẻ trước. Mỗi lớp trả lời đúng một câu hỏi.
Layer them, cheapest first. One question per layer.
Chỉ kiểm tra input từ ô chat
Only checking chat box input
Injection ngày nay đến từ email, trang web và kết quả RAG.
Injection now arrives via email, web pages and RAG results.
Kiểm tra mọi nội dung tool trả về trước khi đưa lại cho model.
Check everything a tool returns before it goes back into the model.
Fail-open khi guardrail timeout
Failing open on guardrail timeout
Bạn mất guardrail đúng lúc bị tấn công — và người tấn công biết cách ép timeout.
You lose the guardrail exactly when under attack — and attackers know how to force timeouts.
Quyết định fail-open hay fail-closed theo mức rủi ro của từng tool, và ghi rõ.
Decide fail-open vs fail-closed per tool tier, and write it down.
Chặn xong hiện lỗi kỹ thuật
Showing a technical error after a block
Người dùng thật bị chặn nhầm sẽ không khiếu nại. Họ bỏ đi.
Real users blocked by mistake don’t complain. They leave.
Thông điệp rõ ràng, không đổ lỗi, kèm đường thoát tới người thật.
A clear, non-accusatory message with a route to a human.
Đo guardrail bằng số lần chặn
Measuring guardrails by number of blocks
Con số đó cũng tăng khi bạn chặn nhầm nhiều hơn.
That number also goes up when you block more real users.
Đo precision và recall trên một tập tấn công có nhãn.
Measure precision and recall against a labelled attack set.

Ba câu cần nhớ

Three things to remember

  1. Một guardrail thì chưa phải guardrail — xếp tầng, rẻ trước, và các lớp miễn phí chạy trước khi bạn trả tiền cho model.
  2. Guardrail chạy bên cạnh agent chứ không đứng trước nó; lúc tripwire bật thì chữ đã bắt đầu chảy, nên hãy thiết kế cho tình huống đó.
  3. Hàng rào cuối cùng không phải văn bản mà là quyền: phân mức mọi tool, và để cái mức cao đánh thức một con người.
  1. One guardrail is not a guardrail — layer them, cheapest first, and let the free checks run before you pay for a model.
  2. Guardrails run beside the agent, not in front of it; by the time the tripwire fires the text is already flowing, so design for that.
  3. The last barrier isn’t text, it’s capability: tier every tool, and let the high ones wake a human.