Learn/LangChain Mastery/Part 9 · 8. Production, Evaluation & Governance
Lesson 67 of 68
SyllabusLangChain Mastery · Part 9

Input & Output Guardrails

The firewall for your LLM. Validating what goes in and out.

Course outline & contents
LangChain Mastery
Async & High-Throughput PatternsLatency & TTFT OptimizationTracing with LangSmithRAG Evaluation BasicsFaithfulness & RelevancePrompt Injection DefenseInput & Output GuardrailsDeployment & API Serving

An LLM is a probabilistic engine. It usually follows instructions, but sometimes it fails. If it fails in a chat app, it's annoying. If it fails in a medical app (Suggesting poison), it is catastrophic. Guardrails are deterministic code that wraps the probabilistic model.

Block requests before they hit the expensive LLM.

  • PII Detection: "My SSN is 123..." -> Block or Redact.
  • Topic Filtering: "How do I make a bomb?" -> Block.

This saves money and improves safety. Tools: NVIDIA NeMo Guardrails, Lakera Guard.

The model generates an answer. Do we show it to the user?

  1. Format Check: Did it return valid JSON? If not, retry.
  2. Safety Check: Did it generate hate speech? If yes, replace with "I cannot answer that."
  3. Hallucination Check: Run the Faithfulness Eval (see previous lesson). If Score < 0.5, reply "I don't know."
simple_guardrail.py
response = llm.invoke(input)

# Deterministic Guard
if "kill" in response.lower():
  return "Safety Violation Detected."

# Schema Guard (Pydantic)
try:
  data = json.loads(response)
except:
  return "Error: Invalid JSON format."

Guardrails are the "Brakes" of the system. You cannot drive fast if you don't have good brakes. They allow you to deploy powerful models with confidence.

Key Intuition: "The model is the engine. The guardrail is the steering wheel."

Track your progressSign in and your progress follows you across devices.
Sign in to track progress Next lesson
← Previous lessonPrompt Injection DefenseNext lesson →Deployment & API Serving