Yashotantra Academy logo
level 1
Curious · 0 XP
streak
0d
perfect
0
badges
0

100 XP to Apprentice

Security · medium

5. Guardrails as typed validators

Validate structure and content, then repair or refuse — never ship unchecked output.

1 min read3 questionsup to 50 XPtopic 5/14

Read in another language

AI translates the explanation and quiz text while preserving code and answer scoring.

Treat model output like form input from the internet. A guardrail chain has three stages: schema validation, content policy, then business rules.

ts
const Answer = z.object({
  reply: z.string().max(1200),
  citations: z.array(z.string().url()).min(1),
  refund_amount: z.number().min(0).max(500),
});

async function guarded(input: string, attempt = 0): Promise<z.infer<typeof Answer>> {
  const raw = await model(input);
  const parsed = Answer.safeParse(raw);
  if (!parsed.success) {
    if (attempt >= 2) throw new GuardrailError("schema", parsed.error);
    return guarded(input + "\nPrevious output was invalid: " + parsed.error.message, attempt + 1);
  }
  if (!parsed.data.citations.every(inCorpus)) throw new GuardrailError("citation_not_in_corpus");
  return parsed.data;
}

Note the business rule doing real work: a citation that is not in your corpus is a hallucination, and a `refund_amount` cap turns a prompt-level wish into an enforced invariant. Emit a metric per guardrail name so you can see which one fires most.

Exercise: add a guardrail counter to your dashboard and find the single most-triggered rule; it usually points at a prompt or schema defect rather than a model defect.

How to study this topic

  1. 1. Read the explanation once end to end, skipping the code.
  2. 2. Re-read the code snippets and say out loud what each line does.
  3. 3. Answer the quiz without scrolling back — that is the real check.
  4. 4. Read every explanation, even for the answers you got right.

Scoring

  • · Up to 30 XP from quiz accuracy.
  • · +15 XP for a perfect first attempt.
  • · +5 XP while a 3-day streak is running.
  • · 75% or higher marks the topic complete.

Check your understanding

  1. 1. Why enforce limits like a maximum refund in code?

  2. 2. Best response to a schema validation failure?

  3. 3. Why check citations against your own corpus?

Badges

First light
Pass your first topic
Sharp shooter
3 perfect first-try quizzes
On a roll
Study 3 days in a row
Week warrior
Study 7 days in a row
Grinder
Earn 500 XP
Deep diver
Earn 1500 XP