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.
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 BaseModelfrom langchain.chat_models import init_chat_modelclass Check(BaseModel): on_topic: boolmodel = 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}").textfor 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.
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.