Lesson 115 — Advanced

Runtime Guardrails

Gate release ko filter karta hai, par request ko nahi. Is lesson mein hum Level 8 ke threats ko runtime checks mein badalna, structured output validate karke re-asking, topical rails, agent ke step aur spend caps, aur har guardrail ki latency aur false-positive rate naapna dekhenge.

⏱ 20 min• Advanced• Evaluation as a Release Gate

Guardrails kyun chahiye

Kya hai?

Guardrails matlab model ke aage-peechhe chhote checks jo har request pe chalte hain — input reject ya transform karte hain, output validate karte hain, agent ko rok-te hain. Seatbelt ki tarah, wishful thinking ki nahi.

Kab kaam aata hai?

Public-facing chatbot pe pehle din se; internal tool mein bhi tab jab usmein spending ya external actions ho sakte hain. Jaise hi jawab pe kisi ka bharosa ho, guardrail chahiye.

Kahan milta hai?

App ke middleware layer mein — model call se pehle (input side) aur uske baad (output side); frameworks mein (Guardrails AI, NeMo Guardrails) ya 20-line apni validation code mein.

Gate aur guardrail ka farq yaad rakho: gate = release waqt, guardrail = har request. Gate kaam karta hai us change ka jo tumne jaan-boojh kar kiya; guardrail us change ka jo tumne kabhi socha hi nahi — user ka injection, model ka hallucination, agent ka loop.

Warning: Guardrail ko magic mat maanna. Ye risk kam karte hain, khatam nahi karte — isliye har block aur har re-ask log hota rahe, warna andhere mein tuned filters legit users ko bhi rok rahe honge.

Schema validation aur re-asking

from pydantic import BaseModel, ValidationError

class TicketFields(BaseModel):
    category: str
    priority: str
    summary: str

def extract_fields(msg: str, max_tries: int = 2) -> TicketFields:
    for attempt in range(max_tries + 1):
        raw = call_model(EXTRACT_PROMPT.format(msg=msg))
        try:
            return TicketFields.model_validate_json(raw)
        except ValidationError as e:
            log_guardrail("schema_fail", attempt=attempt, error=str(e)[:200])
            msg_for_model = raw + "\nINVALID. Errors: " + str(e)
    raise GuardrailExhausted(msg)   # re-ask budget khatam -> fallback
Rule: Jahan output kisi downstream system mein jaata hai (database, ticket, API call) wahan schema validation non-negotiable hai. Jahan sirf screen pe dikhta hai wahan bhi rakho — par wahan tolerance zyada chalega.

Topical aur conversational rails

# NeMo Guardrails jaisa rail file (conceptual):

define user intent
  ask_about_product
  off_topic

define flow
  user ask_about_product
  bot give_product_answer

user off_topic
  bot politely_decline  # "is topic mein help nahi kar sakta"

# kaam: input classify -> rail choose -> usi rail ke bot message bolo
# validator se farq: ye BEHAVIOUR define karta hai, sirf format nahi
Scope control: Customer-support bot ke liye topic control ek feature hai, restriction nahi — user ko bhi pata chalta hai ki bot kis tak pe baat karega. Ye expectation setting bhi hai.

Agent ke tool, step aur spend limits

ALLOWED_TOOLS = {"search_kb", "fetch_doc", "create_ticket"}

def run_agent(task: str, budget: dict):
    steps, spent = 0, 0.0
    for step in agent_loop(task):
        steps += 1
        if steps > budget["max_steps"]:
            abort("step limit")
        if spent + est_cost(step) > budget["max_spend"]:
            abort("spend limit")
        check_args(step.tool, step.args)   # allowlist + schema check
        spent += est_cost(step)
        yield step

def check_args(tool, args):
    if tool not in ALLOWED_TOOLS:
        raise GuardrailExhausted(tool + " not allowed")
    ARGS_SCHEMA[tool].model_validate(args)   # galat args execute se pehle
Default deny: Har tool ke liye socho "ye cheez agent ko chahiye hi kyun?" — na ki "ye tool toh useful lagta hai". Capability inflation se bachne ka ek hi tareeka hai: allowlist chhoti rakho.

Latency, false positives aur logging

har guardrail ka report card (rolling window):

check                added_ms   blocked   false_block   reasked
injection_scan          3         12            1            -
pii_scan                8          4            0            -
schema_validate         1          -            -           37
tool_arg_check          2          1            0            -

# added_ms = har request ki latency tax
# false_block = legit user roka gaya — sabse mehnga number
# rule: har block/re-ask log with request_id + reason
Tuning mantra: Guardrail ko business rule ki tarah treat karo: metric hai (blocked, false_block, added_ms), owner hai, aur review cadence hai. Sirf "on kar diya" wali guardrail production mein chup-chaap users kha jaati hai.

Exercise

Question: Schema fail hone par model ko kya karte hain — dobara poochte hain ya seedha drop?

Question: Agent ko ek request mein kitne steps tak chalne ki permission hai — uss cap ka aam naam? (step cap / retry)

Question: Tool ke arguments check karne ke pehle allowlist mein tool ka naam match hona chahiye — is practice ka naam kya hai? (allowlist / blacklist)

Question: Guardrail ki report card mein legit users ko block karne wala rate kis naam se track hota hai?

Common mistakes

Desi example: Club ka security wala bhai

Entry pe ID check (input guard), andar rules (topical rail), aur har order ka limit (spend cap) — security wala bhai sirf "mat aao" nahi bolta, wo report bhi rakhta hai ki kitne roke aur kitne andar gaye:

text
gate pe  : ID check  -> input scan (injection, pii)
andar   : rules     -> topical rail (scope)
counter : per-order limit -> spend + step cap
register: kaun roka kyun -> block log (tuning data)
Interview angle — yahan se sawaal aate hain
  • Q: Input aur output guardrails mein kya check hota hai? — Input: injection, PII; Output: schema, ungrounded claims, leaked secrets, off-topic.
  • Q: Schema validation fail ho toh? — Model ko error ke saath re-ask, capped retries; budget khatam pe fallback ya human handoff.
  • Q: Agent ke unbounded loop se kaise bachein? — Step cap, per-request spend cap, bounded retries, tool allowlist aur args validation.
  • Q: Guardrail ko kaise tune karte ho? — Block/re-ask logs se false-positive rate aur latency naap ke, policy ko data se adjust karke.
Lesson complete?

Runtime pe checks ready — aur unka report card bhi. Agla lesson — Application Serving & Containerization — mein in dono apps (RAG aur agent) ko streaming API aur container stack mein pack karenge.

Popular courses: Data Science Course in Lucknow · AI Course in Lucknow · Python Course in Lucknow · Power BI Course · Data Analytics Course