Guardrails AI input validation
Quick answer
Use the
guardrails Python SDK to define input and output schemas that validate and constrain AI interactions. Integrate guardrails with your AI client (e.g., OpenAI) to enforce structured input validation and safe outputs automatically.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install guardrails openai>=1.0
Setup
Install the guardrails package and set your OpenAI API key as an environment variable.
- Install Guardrails and OpenAI SDK:
pip install guardrails openai>=1.0 Step by step
Define a Guardrails schema to validate AI input and output, then create a Guard instance wrapping the OpenAI client. This example validates a user prompt and ensures the AI response matches the schema.
import os
from openai import OpenAI
from guardrails import Guard
# Define a simple Guardrails schema for input validation
schema = '''
---
input:
type: object
properties:
question:
type: string
minLength: 10
description: "User question must be at least 10 characters."
required: [question]
output:
type: object
properties:
answer:
type: string
description: "Answer generated by the AI."
required: [answer]
---
'''
# Initialize OpenAI client
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
# Create Guard instance with schema and OpenAI client
guard = Guard.from_openai(client=client, rails=schema)
# Input data to validate
user_input = {"question": "What is Guardrails AI input validation?"}
# Run the guard to validate input and get AI response
response = guard.invoke(user_input)
print("Validated AI response:", response) output
Validated AI response: {'answer': 'Guardrails is a framework that enforces structured input and output validation for AI models, ensuring safe and reliable interactions.'} Common variations
You can use Guardrails with different AI providers like Anthropic or customize schemas for complex nested inputs. Async usage is supported by Guardrails with async clients. You can also stream outputs while validating.
# Example: Using Guardrails with Anthropic (async example)
import os
import asyncio
import anthropic
from guardrails import Guard
async def main():
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
schema = '''
---
input:
type: object
properties:
prompt:
type: string
minLength: 5
required: [prompt]
output:
type: object
properties:
completion:
type: string
required: [completion]
---
'''
guard = Guard.from_anthropic(client=client, rails=schema)
user_input = {"prompt": "Explain AI guardrails."}
response = await guard.ainvoke(user_input)
print("Validated Anthropic response:", response)
asyncio.run(main()) output
Validated Anthropic response: {'completion': 'AI guardrails are rules that ensure AI outputs are safe, valid, and structured.'} Troubleshooting
- If you see validation errors, check that your input matches the schema constraints (e.g., minimum string length).
- Ensure your API key is set correctly in
os.environ. - Guardrails may raise exceptions if the AI output does not conform; handle these with try-except to debug schema mismatches.
try:
response = guard.invoke({"question": "Hi"}) # Too short input
except Exception as e:
print("Validation error:", e) output
Validation error: Input validation failed: 'question' length must be at least 10 characters
Key Takeaways
- Use
guardrailsschemas to enforce structured input and output validation for AI models. - Integrate Guardrails with your AI client to automatically validate and sanitize inputs and outputs.
- Handle validation exceptions to catch and fix input or output mismatches early.
- Guardrails supports multiple AI providers including OpenAI and Anthropic with sync and async usage.
- Define clear JSON schema constraints to ensure safe and reliable AI interactions.