How-To Guide

How to Implement Guardrails for LLM Outputs

Validate, constrain and repair large language model output before it reaches users, with schema checks, allow-list tools and safe fallbacks.

On this page

  1. Introduction
  2. Treat Model Output as Untrusted Input
  3. Validate with a Strict Schema
  4. Allow-Listing Tools and Actions
  5. Retry, Repair and Fallback Ladders
  6. Output Content Guardrails
  7. Measuring Guardrail Effectiveness
  8. Common Pitfalls and Conclusion

Introduction

A language model is a probabilistic text generator, not a function with a contract. It will occasionally return JSON with a trailing comma, invent a field that does not exist, call a tool with the wrong argument types, or produce text that is syntactically valid but semantically out of policy. If that output flows straight into a database write, a downstream API call or a user’s screen, the model’s mistakes become your system’s bugs. Guardrails are the deterministic layer between the model and everything downstream: they cap what the output is allowed to be and what it is allowed to do.

Treat Model Output as Untrusted Input

The single most useful mental model is to treat everything the model returns the way you treat a request body from the public internet. It is untrusted until it passes validation. That means parsing it with a strict schema, rejecting unknown fields, checking types and ranges, and refusing to execute anything that did not validate. This framing removes the temptation to trust the model because it is usually right.

Under this model the guardrail is not a filter you sprinkle on the output; it is a boundary. Nothing crosses it without a pass. Downstream code that consumes model output should only ever see the typed, validated structure, never the raw string.

Validate with a Strict Schema

Define the expected shape as a schema and parse the model output against it. Zod, Pydantic and JSON Schema all work. Configure strict mode so extra keys are rejected rather than silently passed through, because a model that hallucinates a field named is_admin should not be able to smuggle it into your persistence layer. Validation errors are the signal that a retry or a fallback is needed, so they must be structured, not swallowed.

Constrain the model at the same time you validate it. Structured output features such as JSON mode or a response schema make the model far more likely to produce conforming output, which reduces how often the guardrail has to reject. Belt and braces: constrain generation, then validate the result.

import { z } from 'zod';

const AnswerSchema = z.object({
  answer: z.string().min(1).max(4000),
  confidence: z.number().min(0).max(1),
  citations: z.array(z.string().url()).max(5),
}).strict(); // reject unknown keys

export function parseModelOutput(raw: string) {
  let json: unknown;
  try {
    json = JSON.parse(raw);
  } catch {
    return { ok: false as const, reason: 'invalid_json' };
  }
  const result = AnswerSchema.safeParse(json);
  if (!result.success) return { ok: false as const, reason: 'schema' };
  return { ok: true as const, value: result.data };
}

Allow-Listing Tools and Actions

When the model can call tools, the guardrail is an allow-list of tool names, each with its own argument schema. Reject any tool name that is not on the list, and validate arguments before executing. A model that has been prompt-injected by content in a retrieved document may try to invoke a tool you never intended to expose, and the allow-list is what stops it.

Separate read tools from write tools and require an explicit policy for writes. A read tool that queries a database is low risk; a write tool that deletes rows is not. Route write tools through the same authorisation checks a human user would face, and never let the model’s confidence substitute for a permission check. Side effects should be idempotent where possible and logged with the model’s reasoning so a wrong action is auditable.

const TOOLS: Record<string, z.ZodTypeAny> = {
  searchDocs: z.object({ query: z.string().min(1).max(200) }),
  sendEmail: z.object({ to: z.string().email(), body: z.string().max(5000) }),
};

export function authorizeTool(name: string, args: unknown) {
  const schema = TOOLS[name];
  if (!schema) throw new Error('tool_not_allowed: ' + name);
  const parsed = schema.safeParse(args);
  if (!parsed.success) throw new Error('invalid_tool_args');
  return { name, args: parsed.data };
}

Retry, Repair and Fallback Ladders

When validation fails, do not retry blindly with the same prompt. Feed the structured validation error back to the model and ask it to correct only the offending fields. A bounded repair loop, typically one or two attempts, fixes most formatting errors. If repair still fails, fall back to a safe default: a canned response, a degraded answer, or a clear error the UI can render.

Bound the loop. An unbounded repair loop multiplies cost and latency and can mask a prompt that is simply wrong. After the last attempt, surface the failure instead of returning malformed data. The fallback must itself be valid, which is easy to guarantee when it is a constant, and it must be visible in metrics so you can see how often the guardrail rejected output.

Output Content Guardrails

Schema and tool constraints cover structure; content guardrails cover meaning. Detect personally identifiable information, secrets and credentials in output and redact them. Enforce formatting rules such as maximum length and markdown safety. If the model produces HTML that will be rendered, sanitise it rather than trusting it, because a model can emit script tags just as a user can.

Keep content checks deterministic and explainable. A classifier that flags policy violations can be a useful second layer, but it should not be the only layer, because classifiers have their own error rates. Combine rules you can reason about with statistical checks, and log every redaction so you can audit what was removed and why.

Measuring Guardrail Effectiveness

Instrument the guardrail itself. Track how often output fails parsing, how often it fails schema validation, how often the repair loop succeeds, and how often it falls back. These counters tell you whether the model or the prompt is drifting. A sudden rise in schema failures is an early warning that a model upgrade or a prompt edit changed behaviour.

Also measure the cost of the guardrail. Validation is cheap, but a repair round trip doubles token spend and latency. Report the guardrail overhead as a fraction of total request cost so you can decide whether to invest in better structured-output configuration that reduces rejections in the first place.

Common Pitfalls and Conclusion

Do not trust the model’s own claim that it followed the rules; a model that says “here is valid JSON” can still return invalid JSON. Do not use lenient parsing that coerces wrong types into passing. Do not let a single tool call run without an allow-list just because it worked in testing. Do not retry without feeding the error back, which wastes tokens on the same mistake. And do not forget that retrieved content is untrusted too, so prompt-injection through documents must be treated as a real input path.

Guardrails turn a probabilistic generator into a component your system can rely on: constrain generation, validate strictly, allow-list actions, repair at most a bounded number of times, fall back to something safe, and measure every rejection. The model does not have to be perfect; the boundary around it has to be.

Sources: OpenAI: Structured Outputs, OWASP Top 10 for LLM Applications, Zod: TypeScript-first schema validation.

FAQ

Should I validate output or just ask the model to be careful?
Both, but validation is the part that is enforceable. Prompting reduces the frequency of errors, while schema validation is what guarantees a malformed output never reaches downstream code. Constrain generation and then validate the result.
How many repair attempts are reasonable?
One or two. Past that, each attempt spends tokens and latency without new information, and a persistent failure usually means the prompt or the output schema is wrong rather than the generation being unlucky.

Related Examples