AI Hints
LangChain · Lesson 92 of 120

Guardrails

Checking inputs and outputs.

⏱ 2 min read▶ Video at 1:44:29🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

A bookshop assistant shouldn't write homework essays, or give medical advice. Guardrails are checks around the model. One before, to stop off topic or harmful requests, and one after, to catch bad answers.

Guardrails
From the video: Guardrails
  • Stay on topic
  • Checks around the model
  • Before and after

An input guardrail

A small, cheap model call classifies each message, with structured output. Is it about books, or the shop? If not, we reply with a polite refusal, and never call the main assistant. Run it. The book question is allowed, and the homework request is blocked.

guardrail.pypython
from pydantic import BaseModel
from langchain.chat_models import init_chat_model

class Check(BaseModel):
    on_topic: bool

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
checker = model.with_structured_output(Check)

def assistant(message):
    verdict = checker.invoke(f"Is this message about books or a bookshop? {message}")
    if not verdict.on_topic:
        return "Sorry, I can only help with books and our shop."
    return model.invoke(f"You are a bookshop assistant. One sentence. {message}").text

for msg in ["Can you recommend a mystery novel?", "Write my history homework essay."]:
    print(msg, "->", assistant(msg).strip())
Output
Can you recommend a mystery novel? -> If you enjoy a thrilling puzzle with a brilliant
detective, you simply must read *The Murder of Roger Ackroyd* by Agatha Christie.
Write my history homework essay. -> Sorry, I can only help with books and our shop.

Kinds of guardrails

Input guardrails check requests before the model sees them. Topic, abuse, or injection attempts. Output guardrails check answers before the customer sees them. No promises the shop can't keep, no personal data, no rude language. In agents, middleware is a natural place for both.

keyvalue
Inputtopic, abuse, injection
Outputpromises, PII, tone
Cheapsmall model or rules
In agentsmiddleware

Summary

Guardrails check inputs before the model, and outputs after it. A small classifier is often enough. Next, hiding personal data.

Key takeaways
  • Check input first
  • Check output after
  • Refuse politely
Next up: PII Redaction — hiding personal data