How to Intermediate · 3 min read

Guardrails AI output validation

Quick answer
Use Guardrails to define schemas and constraints that validate AI outputs automatically. Integrate guardrails Python SDK with your AI calls to enforce output formats and content rules before processing results.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install openai>=1.0
  • pip install guardrails-ai

Setup

Install the required packages and set your environment variables for API keys.

bash
pip install openai guardrails-ai

Step by step

Define a guardrail schema to validate AI output and integrate it with OpenAI's Python SDK for chat completions.

python
import os
from openai import OpenAI
from guardrails import Guard

# Define a simple guardrail schema as YAML string
schema = '''
- name: response
  type: str
  required: true
  constraints:
    - type: length
      min: 10
      max: 200
'''

def main():
    # Initialize OpenAI client
    client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

    # Initialize Guardrails with schema
    guard = Guard.from_yaml(schema)

    # Prepare user message
    messages = [{"role": "user", "content": "Explain AI guardrails."}]

    # Call OpenAI chat completion
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=messages
    )

    # Extract raw content
    raw_output = response.choices[0].message.content

    # Validate output with guardrails
    validated_output = guard.parse(raw_output)

    print("Validated output:", validated_output["response"])

if __name__ == "__main__":
    main()
output
Validated output: AI guardrails are rules and schemas that ensure AI outputs meet safety, format, and content requirements.

Common variations

  • Use async calls with asyncio and OpenAI async client.
  • Apply guardrails to different models like gpt-4o-mini or claude-3-5-sonnet-20241022.
  • Define complex schemas with nested fields and enumerations for structured output validation.
python
import asyncio
import os
from openai import OpenAI
from guardrails import Guard

schema = '''
- name: response
  type: str
  required: true
  constraints:
    - type: length
      min: 10
      max: 200
'''

async def main():
    client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
    guard = Guard.from_yaml(schema)

    messages = [{"role": "user", "content": "Explain AI guardrails asynchronously."}]

    response = await client.chat.completions.acreate(
        model="gpt-4o-mini",
        messages=messages
    )

    raw_output = response.choices[0].message.content
    validated_output = guard.parse(raw_output)
    print("Validated async output:", validated_output["response"])

if __name__ == "__main__":
    asyncio.run(main())
output
Validated async output: AI guardrails help ensure outputs are safe, accurate, and follow defined formats.

Troubleshooting

  • If validation fails with guard.parse(), check your schema constraints and the AI output format.
  • Ensure your API key is set correctly in os.environ["OPENAI_API_KEY"].
  • Use logging or print raw AI outputs to debug unexpected formats.

Key Takeaways

  • Use guardrails schemas to enforce AI output format and content validation automatically.
  • Integrate guardrails with your AI SDK calls to catch and handle invalid outputs before further processing.
  • Define clear constraints in your guardrail YAML to ensure outputs meet your application's safety and correctness needs.
Verified 2026-04 · gpt-4o-mini, claude-3-5-sonnet-20241022
Verify ↗