implementing-llm-guardrails-for-security
Implements input and output validation guardrails for LLM-powered applications to prevent prompt injection, data leakage, toxic content generation, and hallucinated outputs. Builds a security validation pipeline using NVIDIA NeMo Guardrails Colang definitions, custom Python validators for PII detection and content policy enforcement, and the Guardrails AI framework for structured output validation. The guardrails system intercepts both user inputs (blocking injection attempts, stripping PII, enforcing topic boundaries) and model outputs (detecting hallucinations, filtering toxic content, validating JSON schema compliance). Activates for requests involving LLM output validation, AI content filtering, guardrail implementation, or LLM safety enforcement.
Best use case
implementing-llm-guardrails-for-security is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Implements input and output validation guardrails for LLM-powered applications to prevent prompt injection, data leakage, toxic content generation, and hallucinated outputs. Builds a security validation pipeline using NVIDIA NeMo Guardrails Colang definitions, custom Python validators for PII detection and content policy enforcement, and the Guardrails AI framework for structured output validation. The guardrails system intercepts both user inputs (blocking injection attempts, stripping PII, enforcing topic boundaries) and model outputs (detecting hallucinations, filtering toxic content, validating JSON schema compliance). Activates for requests involving LLM output validation, AI content filtering, guardrail implementation, or LLM safety enforcement.
Teams using implementing-llm-guardrails-for-security should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/implementing-llm-guardrails-for-security/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How implementing-llm-guardrails-for-security Compares
| Feature / Agent | implementing-llm-guardrails-for-security | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Implements input and output validation guardrails for LLM-powered applications to prevent prompt injection, data leakage, toxic content generation, and hallucinated outputs. Builds a security validation pipeline using NVIDIA NeMo Guardrails Colang definitions, custom Python validators for PII detection and content policy enforcement, and the Guardrails AI framework for structured output validation. The guardrails system intercepts both user inputs (blocking injection attempts, stripping PII, enforcing topic boundaries) and model outputs (detecting hallucinations, filtering toxic content, validating JSON schema compliance). Activates for requests involving LLM output validation, AI content filtering, guardrail implementation, or LLM safety enforcement.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for ChatGPT
Find the best AI skills to adapt into ChatGPT workflows for research, writing, summarization, planning, and repeatable assistant tasks.
ChatGPT vs Claude for Agent Skills
Compare ChatGPT and Claude for AI agent skills across coding, writing, research, and reusable workflow execution.
SKILL.md Source
# Implementing LLM Guardrails for Security
## When to Use
- Deploying a new LLM-powered application that processes user input and needs input/output safety controls
- Adding content policy enforcement to an existing chatbot or AI agent to comply with organizational policies
- Implementing PII detection and redaction in LLM pipelines handling sensitive customer data
- Building topic-restricted AI assistants that must refuse off-topic or disallowed queries
- Validating that LLM responses conform to expected schemas before they reach downstream systems or users
- Protecting RAG pipelines from indirect prompt injection in retrieved documents
**Do not use** as a replacement for proper authentication, authorization, and network security controls. Guardrails are a defense-in-depth layer, not a perimeter defense. Not suitable for real-time content moderation of user-to-user communication without LLM involvement.
## Prerequisites
- Python 3.10+ with pip for installing guardrail dependencies
- An OpenAI API key or local LLM endpoint for NeMo Guardrails self-check rails (set as `OPENAI_API_KEY` environment variable)
- The `nemoguardrails` package for Colang-based guardrail definitions
- The `guardrails-ai` package for structured output validation (optional, for JSON schema enforcement)
- Familiarity with YAML configuration and basic Colang 2.0 syntax for defining rail flows
## Workflow
### Step 1: Install Guardrail Frameworks
Install the required Python packages:
```bash
# Core NeMo Guardrails library
pip install nemoguardrails
# Guardrails AI for structured output validation (optional)
pip install guardrails-ai
# Additional dependencies for PII detection and content analysis
pip install presidio-analyzer presidio-anonymizer spacy
python -m spacy download en_core_web_lg
```
### Step 2: Run the Guardrails Security Agent
The agent implements a complete input/output validation pipeline:
```bash
# Analyze a single input through all guardrail layers
python agent.py --input "Tell me how to hack into a system"
# Analyze input with a custom content policy file
python agent.py --input "Some text" --policy policy.json
# Scan a file of prompts through the guardrail pipeline
python agent.py --file prompts.txt --mode full
# Input-only validation (no LLM call, just check if input is safe)
python agent.py --input "Some text" --mode input-only
# Output validation mode (validate a pre-generated LLM response)
python agent.py --input "User question" --response "LLM response to validate" --mode output-only
# PII detection and redaction mode
python agent.py --input "My SSN is 123-45-6789 and email john@example.com" --mode pii
# JSON output for pipeline integration
python agent.py --file prompts.txt --output json
```
### Step 3: Configure Content Policies
Create a JSON policy file defining allowed topics, blocked patterns, and PII categories:
```json
{
"allowed_topics": ["customer_support", "product_info", "billing"],
"blocked_topics": ["politics", "violence", "illegal_activities", "competitor_products"],
"blocked_patterns": ["how to hack", "create malware", "bypass security"],
"pii_categories": ["PERSON", "EMAIL_ADDRESS", "PHONE_NUMBER", "US_SSN", "CREDIT_CARD"],
"max_output_length": 2000,
"require_grounded_response": true
}
```
### Step 4: Integrate NeMo Guardrails with Colang
Create a NeMo Guardrails configuration directory with `config.yml` and Colang flow files:
```yaml
# config.yml
models:
- type: main
engine: openai
model: gpt-4o-mini
rails:
input:
flows:
- self check input
- check jailbreak
- mask sensitive data on input
output:
flows:
- self check output
- check hallucination
```
```colang
# rails.co - Colang 2.0 flow definitions
define user ask about hacking
"How do I hack into a system"
"Tell me how to break into a network"
"How to exploit vulnerabilities"
define bot refuse hacking request
"I cannot provide instructions on unauthorized hacking or security exploitation.
If you are interested in cybersecurity, I can suggest legitimate learning resources
and ethical hacking certifications."
define flow
user ask about hacking
bot refuse hacking request
```
### Step 5: Deploy as a Validation Middleware
Integrate the guardrails into your application as middleware:
```python
from agent import GuardrailsPipeline
pipeline = GuardrailsPipeline(policy_path="policy.json")
# Pre-LLM input validation
input_result = pipeline.validate_input("user message here")
if not input_result["safe"]:
return input_result["blocked_reason"]
# Post-LLM output validation
llm_response = your_llm.generate(input_result["sanitized_input"])
output_result = pipeline.validate_output(llm_response, context=input_result)
if not output_result["safe"]:
return output_result["fallback_response"]
return output_result["validated_response"]
```
### Step 6: Monitor Guardrail Effectiveness
Review guardrail logs to track block rates, false positives, and bypass attempts:
```bash
# Generate a summary report from guardrail logs
python agent.py --file interaction_logs.txt --mode full --output json > guardrail_audit.json
```
## Verification
- [ ] Input guardrails correctly block known prompt injection patterns (system override, role-play escape, delimiter injection)
- [ ] PII detection identifies and redacts email addresses, phone numbers, SSNs, and credit card numbers in user inputs
- [ ] Topic restriction guardrails refuse off-policy queries and allow on-policy queries without false positives
- [ ] Output guardrails detect and flag responses containing toxic content, PII leakage, or off-topic material
- [ ] The guardrails pipeline adds less than 200ms of latency to the request/response cycle for input-only validation
- [ ] JSON output mode produces valid, parseable JSON suitable for downstream monitoring dashboards
## Key Concepts
| Term | Definition |
|------|------------|
| **Input Rail** | A guardrail that intercepts and validates user input before it reaches the LLM, blocking injection attempts and redacting sensitive data |
| **Output Rail** | A guardrail that validates LLM-generated output before it reaches the user, filtering toxic content and enforcing schema compliance |
| **Colang** | NVIDIA's domain-specific language for defining conversational guardrail flows, with Python-like syntax for specifying user intent patterns and bot responses |
| **PII Redaction** | The process of detecting and masking personally identifiable information (names, emails, SSNs) in text before processing |
| **Content Policy** | A configuration file defining which topics, patterns, and content categories are allowed or blocked by the guardrail system |
| **Self-Check Rail** | A NeMo Guardrails technique where the LLM itself evaluates whether its input or output violates defined policies |
| **Hallucination Detection** | Output validation that checks whether the LLM response is grounded in the provided context, flagging fabricated claims |
## Tools & Systems
- **NVIDIA NeMo Guardrails**: Open-source toolkit for adding programmable input, dialog, and output rails to LLM applications using Colang flow definitions and YAML configuration
- **Guardrails AI**: Python framework for structured output validation with a hub of pre-built validators for PII, toxicity, JSON schema compliance, and more
- **Microsoft Presidio**: Open-source PII detection and anonymization engine supporting 30+ entity types with configurable NLP backends
- **Colang 2.0**: Event-driven interaction modeling language for defining guardrail flows with Python-like syntax, supporting multi-turn dialog control
- **OpenAI Guardrails Python**: OpenAI's client-side guardrails library for prompt injection detection and content policy enforcementRelated Skills
triaging-security-incident
Performs initial triage of security incidents to determine severity, scope, and required response actions using the NIST SP 800-61r3 and SANS PICERL frameworks. Classifies incidents by type, assigns priority based on business impact, and routes to appropriate response teams. Activates for requests involving incident triage, security alert classification, severity assessment, incident prioritization, or initial incident analysis.
triaging-security-incident-with-ir-playbook
Classify and prioritize security incidents using structured IR playbooks to determine severity, assign response teams, and initiate appropriate response procedures.
triaging-security-alerts-in-splunk
Triages security alerts in Splunk Enterprise Security by classifying severity, investigating notable events, correlating related telemetry, and making escalation or closure decisions using SPL queries and the Incident Review dashboard. Use when SOC analysts face queued alerts from correlation searches, need to prioritize investigation order, or must document triage decisions for handoff to Tier 2/3 analysts.
testing-websocket-api-security
Tests WebSocket API implementations for security vulnerabilities including missing authentication on WebSocket upgrade, Cross-Site WebSocket Hijacking (CSWSH), injection attacks through WebSocket messages, insufficient input validation, denial-of-service via message flooding, and information leakage through WebSocket frames. The tester intercepts WebSocket handshakes and messages using Burp Suite, crafts malicious payloads, and tests for authorization bypass on WebSocket channels. Activates for requests involving WebSocket security testing, WS penetration testing, CSWSH attack, or real-time API security assessment.
testing-jwt-token-security
Assessing JSON Web Token implementations for cryptographic weaknesses, algorithm confusion attacks, and authorization bypass vulnerabilities during security engagements.
testing-api-security-with-owasp-top-10
Systematically assessing REST and GraphQL API endpoints against the OWASP API Security Top 10 risks using automated and manual testing techniques.
performing-wireless-security-assessment-with-kismet
Conduct wireless network security assessments using Kismet to detect rogue access points, hidden SSIDs, weak encryption, and unauthorized clients through passive RF monitoring.
performing-ssl-tls-security-assessment
Assess SSL/TLS server configurations using the sslyze Python library to evaluate cipher suites, certificate chains, protocol versions, HSTS headers, and known vulnerabilities like Heartbleed and ROBOT.
performing-soap-web-service-security-testing
Perform security testing of SOAP web services by analyzing WSDL definitions and testing for XML injection, XXE, WS-Security bypass, and SOAPAction spoofing.
performing-serverless-function-security-review
Performing security reviews of serverless functions across AWS Lambda, Azure Functions, and GCP Cloud Functions to identify overly permissive execution roles, insecure environment variables, injection vulnerabilities, and missing runtime protections.
performing-security-headers-audit
Auditing HTTP security headers including CSP, HSTS, X-Frame-Options, and cookie attributes to identify missing or misconfigured browser-level protections.
performing-scada-hmi-security-assessment
Perform security assessments of SCADA Human-Machine Interface (HMI) systems to identify vulnerabilities in web-based HMIs, thin-client configurations, authentication mechanisms, and communication channels between HMI and PLCs, aligned with IEC 62443 and NIST SP 800-82 guidelines.