Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Implementing Content Safety Guardrails

Welcome to the second lesson in our module on LLM Security and Governance. Last time, we focused on a very specific, but critical, type of guardrail: a pipeline to detect and redact Personally Identifiable Information (PII). You learned how to protect sensitive user data before it ever reaches an LLM, a foundational practice for building secure applications.

In this lesson, we will broaden our scope to explore the general concept of input and output guardrails. These are the mechanisms that allow you to enforce your application's rules of engagement, ensuring the LLM's behavior remains safe, on-topic, and aligned with your operational policies. We'll move beyond just PII to cover content safety, topic restrictions, and preventing malicious use cases like prompt injection.

To achieve this, we will explore two powerful open-source frameworks: Guardrails AI, a lightweight and highly practical library for adding validators to your code, and NVIDIA NeMo Guardrails, a comprehensive framework for building steerable, enterprise-grade conversational agents. Your background in building and managing robust systems will be a great asset here, as implementing guardrails is fundamentally about adding layers of control and reliability to your AI services.

1. The Role of Guardrails in LLM Systems

In the previous lesson, you saw how a pipeline could intercept and modify data flowing to and from an LLM. This is the core idea behind guardrails. They are structured, rule-based systems that act as checkpoints to monitor, filter, and control the interactions between a user and an LLM.

Guardrails can be applied at different stages of the request lifecycle:

This flowchart shows the key integration points for guardrails in an LLM application. They can validate user input, detect malicious prompts (injection), control tool usage, and sanitize the final output before it's sent back to the user.

This layered approach is essential for several reasons:

  • Content Safety: To prevent the LLM from generating toxic, biased, or otherwise harmful responses.
  • Topic Adherence: To keep a specialized chatbot focused on its domain. For example, a customer support bot for an energy utility should not offer medical advice.
  • Security: To mitigate risks like "prompt injection" or "jailbreaking," where users attempt to bypass the model's safety instructions and manipulate its behavior.
  • Compliance: To ensure responses align with company policies, brand voice, and industry regulations.

Let's now dive into how you can implement these checks using a practical, code-first framework.

2. Practical Implementation with Guardrails AI

Guardrails AI is an open-source Python library that allows you to add specific, often reusable, validation steps to your LLM interactions. It is particularly useful for surgical interventions—checking for a specific issue and defining a clear action to take if the check fails.

The video below offers an excellent, in-depth tutorial on using Guardrails AI. It covers the core concepts and demonstrates how to use several pre-built validators for common safety and security concerns.

Guardrails for LLM Applications | Complete Tutorial for AI Developers WIth Guardrails AI

This tutorial from Sunny Savita provides a complete walkthrough of the Guardrails AI library, from basic concepts to advanced custom functions.

Please watch the following segments to see how different guardrails are implemented: What are Guardrails?: This section introduces the core concepts and provides clear examples of why guardrails are needed for correctness, consistency, and safety. Profanity Validator: Watch how the profanity_free validator is used to check for abusive language. Pay attention to the on_fail="exception" parameter, which dictates the action upon failure. Custom Failure Logic: This shows how to pass a custom Python function to the on_fail parameter, giving you complete control over how to handle a validation failure (e.g., sanitizing the output instead of just throwing an error). Toxicity Validator: Learn about the toxic_language validator and how to configure its sensitivity using the threshold parameter. Jailbreak Detection: This is a critical security guardrail. See how the detect_jailbreak validator identifies prompts designed to manipulate the LLM. Custom Jailbreak Logic: As an alternative to a pre-built validator, observe how a simple Python function with a list of suspicious keywords can be used to detect prompt injection attempts. This pattern is highly extensible.

As you can see, Guardrails AI provides a powerful and flexible way to add checks to both user inputs (like jailbreak detection) and model outputs (like toxicity checks). The on_fail parameter is key, as it lets you decide whether to block the request (exception), attempt to self-correct (fix), or trigger your own custom logic.

For a complete, end-to-end code example, the following article shows how to integrate Guardrails AI into a LangGraph workflow—a modern approach to building agentic applications.

Getting started with Guardrails using Guardrails Ai and LangGraph

This article by Prajwal B M provides a great practical example of wiring both input and output guardrails into a single application graph.

Please read the article from the beginning up to the "Output" section. Focus on the following parts of the code: What are guardrails?: This section provides a concise summary of guardrail use cases. Installation: Note the commands to install the library and specific validators from the hub. Input Guardrails Function: Study the input_guardrails function. See how it combines CompetitorCheck, ToxicLanguage, and DetectJailbreak to validate the user's prompt before it's sent to the model. Output Guardrails Function: Similarly, look at the output_guardrails function, which validates the model's generated response. Workflow Definition: Observe how the LangGraph workflow wires these functions together, creating distinct steps for input validation, model invocation, and output validation.

3. A Declarative Framework: NVIDIA NeMo Guardrails

While Guardrails AI excels at adding specific validators programmatically, NVIDIA NeMo Guardrails offers a more holistic and declarative approach. It's an open-source framework designed to build entire conversational applications that are safe and steerable by default. Instead of writing Python code for each check, you define the desired behavior in configuration files.

This diagram shows the high-level architecture of NeMo Guardrails. It acts as an intermediary, applying various policies (like off-topic detection and content moderation) to user prompts before they reach the LLM, and to the LLM's response before it reaches the user.

The core of NeMo Guardrails is Colang, a specialized modeling language for defining conversational flows and policies.

Enhancing LLM Capabilities with NeMo Guardrails on Amazon ...

This AWS blog post provides an excellent introduction to the NeMo Guardrails framework and the concepts behind it.

Please read the following sections to understand its architecture and how to define guardrails declaratively: What is Nemo Guardrails?: This introduces the framework and the concept of different "rails" (Input, Output, Dialog). An Introduction to Colang: This section explains the simple, natural-language-like syntax of Colang for defining user messages, bot responses, and conversational flows. Flows in NeMo Guardrails: This is key to enforcing topic restrictions. Study the define flow unrelated question example, which shows how to define a policy to refuse questions that are off-topic for a pet supply chatbot. Intent Capturing and Flow Selection: Learn how NeMo uses a combination of pattern matching and an underlying LLM call to classify the user's intent, which then determines which flow to execute. Maintaining Conversation Integrity: This short section provides a concrete example of how the unrelated question flow works in practice, steering a conversation back on topic.

To see NeMo Guardrails in action, the following video provides a practical demonstration and a clear explanation of its mechanics.

NVIDIA NeMo Guardrails: Full Walkthrough for Chatbots / AI

This video by James Briggs is a full walkthrough of NeMo Guardrails, starting from the core concepts and ending with a working implementation.

Please watch these segments to see how the concepts from the article are applied: Configuration Files: See how the config.yml and a Colang file (.co) are used to define the chatbot's behavior, including a guardrail for blocking political discussions. Live Demonstration: Watch a command-line chat session where the guardrail successfully identifies and blocks a political question, providing a canned response instead. Mechanism Explained: This part explains how NeMo Guardrails works under the hood. It uses an embedding model to semantically compare a user's input against the examples you provide in your Colang file to determine the user's intent. This is how it can recognize a political question even if it doesn't exactly match your examples.

By using a declarative language like Colang, you can define complex behavioral policies that are often easier to manage and audit than equivalent Python code, which is a significant advantage in an enterprise environment.

Conclusion

In this lesson, you've expanded your understanding of guardrails from the specific case of PII redaction to the broader challenge of enforcing content safety and topic restrictions. You now have two powerful tools at your disposal for implementing these essential controls.

Key Takeaways:

  • Guardrails are rule-based systems that act as checkpoints for inputs and outputs to ensure safety, security, and policy alignment.
  • Guardrails AI is a Python-native library ideal for adding specific, programmatic validators (e.g., for toxicity, profanity, or jailbreaking) into your existing application logic.
  • NVIDIA NeMo Guardrails is a comprehensive framework for building safe conversational agents from the ground up, using a declarative language called Colang to define conversational flows and behavioral policies.
  • Input guardrails protect your system from malicious or off-topic user prompts, while output guardrails ensure the LLM's responses are safe and appropriate before being shown to the user.

Implementing guardrails is a non-negotiable part of LLM-Ops. The actions taken by these guardrails—blocking a prompt, sanitizing an output, or re-routing a conversation—are significant security and operational events. This leads us directly to our next topic: configuring fine-grained audit logging. We will explore how to capture prompt/response data and model access patterns for compliance, troubleshooting, and continuous improvement.

Can't find a good explanation? Sign up and we'll make it for you

Sign up