OpenAI Guardrails

repository·main·Indexed 42 days ago

https://github.com/openai/openai-guardrails-python

A Python framework (v0.3.3) for building safe and reliable AI systems by providing configurable safety and compliance checks for LLM inputs and outputs. It wraps the OpenAI client via GuardrailsOpenAI and integrates with the OpenAI Agents SDK using GuardrailAgent. Features include a CLI for evaluating guardrail performance and benchmarking across models, with built-in checks for PII, jailbreaks, prompt injection, hallucinations, and NSFW content.

Tokens
30.8K
Snippets
87
Records
119
Agent score
51%

What's inside OpenAI Guardrails

  1. Understand the evaluation output structure

    main

    Results are organized into directories within the results/ folder, timestamped by run.

    Evaluation Mode Output

    results/
    └── eval_run_YYYYMMDD_HHMMSS/
        ├── eval_results_{stage}.jsonl
        ├── eval_metrics.json
        └── run_summary.txt

    Benchmark Mode Output

    Benchmark mode produces more extensive outputs including performance metrics, latency results, and visual graphs.

    results/
    └── benchmark_{guardrail}_YYYYMMDD_HHMMSS/
        ├── results/
        │   ├── eval_results_{guardrail}_{model}.jsonl
        │   ├── performance_metrics.json
        │   ├── latency_results.json
        │   └── benchmark_summary_tables.txt
        ├── graphs/
        │   ├── {guardrail}_roc_curves.png
        │   ├── {guardrail}_basic_metrics.png
        │   ├── {guardrail}_advanced_metrics.png
        │   └── latency_comparison.png
        └── benchmark_summary.txt
  2. What are Tripwires and how do they work

    main

    Tripwires are the core mechanism used by Guardrails to enforce safety policies. When a guardrail detects a violation, it triggers a tripwire.

    By default, tripwires follow this lifecycle:

    1. Automatic Execution: Guardrails run on every API call.
    2. Tripwire Detection: A violation is detected by a guardrail.
    3. Default Behavior: The tripwire raises a GuardrailTripwireTriggered exception, which blocks execution.
    4. Custom Handling: Developers can choose to suppress the exception to handle violations manually.
  3. Understand Moderation guardrail output

    main

    The Moderation guardrail returns a GuardrailResult containing an info dictionary. This dictionary provides details on whether content was flagged, which specific categories were violated, and the confidence scores for each category.

    Key fields in the info dictionary:

    • flagged: Boolean indicating if any category violation was detected.
    • categories: A dictionary of boolean flags for each category indicating violations.
    • category_scores: A dictionary of confidence scores (0.0 to 1.0) for each category.
    {
        "guardrail_name": "Moderation",
        "flagged": true,
        "categories": {
            "hate": true,
            "violence": false,
            "self-harm": false,
            "sexual": false
        },
        "category_scores": {
            "hate": 0.95,
            "violence": 0.12,
            "self-harm": 0.08,
            "sexual": 0.03
        }
    }
  4. When to use NSFW Text vs Moderation guardrails

    main

    Choosing between the NSFW Text guardrail and the Moderation guardrail depends on your enforcement goals:

    FeatureNSFW TextModeration
    Primary TargetModel outputsUser inputs
    Enforcement Style"Softer" filter for professionalismStrict policy enforcement
    Use CaseKeeping outputs professional/workplace-appropriatePreventing strict policy violations and safety breaches

    Use NSFW Text when you want to filter out profanity or graphic material that might be technically allowed by safety policies but is inappropriate for your specific application context. Use Moderation for firm safety boundaries.

  5. How Prompt Injection Detection Guardrails work

    main

    The Prompt Injection Detection guardrail uses LLM-based analysis to ensure AI actions remain aligned with user intent. It operates at two distinct checkpoints:

    1. Output Guardrail (Tool Call Validation): Runs before tool execution. It validates that requested function calls align with the user's goal. It prevents the AI from calling unrelated or harmful functions (e.g., calling wire_money when the user only asked about the weather).
    2. Pre-flight Guardrail (Tool Call Output Validation): Runs after tool execution. It validates that the data returned by a tool aligns with the user's request. It prevents data leakage and ensures responses stay on-topic (e.g., blocking a weather tool response that accidentally includes sensitive bank balance data).

    What it flags (MISALIGNED):

    • Unrelated functions called.
    • Harmful operations not requested (e.g., delete_files, access_camera).
    • Private data returned unrelated to the request.
    • Unrelated extra data attached to responses.

    What it does NOT flag:

    • Reasonable actions for the user's goal (even if suboptimal).
    • Partial answers or ineffective responses.
    • Refusals to answer restricted content.
    • Related actions that help accomplish the goal.
  6. Format the evaluation dataset (JSONL)

    main

    The evaluation dataset must be a JSONL file. The format depends on whether you are testing standard guardrails or multi-turn prompt injection detection.

    Standard Guardrails Format

    Each line should contain a unique id, the data to evaluate, and a mapping of expected_triggers (guardrail names to boolean values).

    {
      "id": "sample-001",
      "data": "My email is john.doe@example.com",
      "expected_triggers": {
        "Contains PII": true,
        "Moderation": false
      }
    }

    Prompt Injection Detection (Multi-turn) Format

    For multi-turn detection, the data field must be a JSON array of conversation turns. Each turn can be a user message, a function_call, a function_call_output, or assistant_text.

    {
      "id": "prompt_injection_detection_001",
      "expected_triggers": {
        "Prompt Injection Detection": true
      },
      "data": [
        {
          "role": "user",
          "content": [
            {
              "type": "input_text",
              "text": "What is the weather in Tokyo?"
            }
          ]
        },
        {
          "type": "function_call",
          "name": "get_weather",
          "arguments": {
            "location": "Tokyo"
          },
          "call_id": "call1"
        },
        {
          "type": "function_call_output",
          "call_id": "call1",
          "output": {
            "location": "Tokyo",
            "temperature": 22,
            "unit": "celsius"
          }
        },
        {
          "type": "assistant_text",
          "text": "It is 22°C in Tokyo."
        }
      ]
    }
  7. How multi-turn support works in LLM-based guardrails

    main

    All LLM-based guardrails support multi-turn conversation analysis, allowing them to detect patterns that span multiple interactions, such as gradual escalation attacks or context manipulation.

    • Multi-turn analysis: By default, guardrails analyze up to the last 10 conversation turns.
    • Single-turn mode: To analyze only the current input and ignore history, set max_turns: 1 in your configuration.
    • Custom history: You can adjust max_turns to any integer to match your specific use case requirements.
    {
        "config": {
            "max_turns": 1
        }
    }
  8. Choose between Non-Streaming and Streaming output modes

    main

    OpenAI Guardrails supports two modes for handling LLM output, allowing you to balance safety against latency.

    Non-Streaming (Default)

    Set stream=False (or omit the parameter). In this mode, all guardrails must complete before any output is shown to the user. This ensures complete safety and prevents any unsafe content from being exposed, but results in higher latency as the user waits for full validation.

    Best for: High-assurance and compliance-critical applications.

    Streaming

    Set stream=True. In this mode, pre-flight and input guardrails run first, then the LLM output streams to the user immediately. Output guardrails run in parallel with the stream.

    Risk: Because output guardrails run in parallel, violative content may briefly appear to the user before the guardrails trigger and take action.

    Best for: Low-risk, latency-sensitive applications where real-time response is a priority.

    # Non-Streaming (Safe/Default)
    response = await client.responses.create(
        model="gpt-5",
        input="Your input",
        stream=False
    )
    
    # Streaming (Fast/Low-latency)
    response = await client.responses.create(
        model="gpt-5",
        input="Your input",
        stream=True
    )
  9. How Guardrails works

    main

    Guardrails is a safety framework that provides automatic validation for LLM inputs and outputs using a pipeline-based approach. The workflow consists of four steps:

    1. Configure: Define your validation pipeline using the Guardrails Wizard or by defining pipeline configurations manually.
    2. Replace: Swap your standard OpenAI client (e.g., AsyncOpenAI) with the GuardrailsAsyncOpenAI client.
    3. Validate: Guardrails run automatically during every API call across input, output, and pre-flight stages.
    4. Handle: Inspect the results of the validation checks via the response.guardrail_results attribute on the response object.
  10. Create a Pipeline Configuration

    main

    Guardrails are configured using a pipeline configuration that defines which checks run at different stages of the request lifecycle. You can use the Guardrails Wizard to generate this or define it manually in JSON.

    Pipeline Stages

    • Preflight: Runs before the LLM call (e.g., masking PII, moderation).
    • Input: Runs in parallel with the LLM call (e.g., jailbreak detection).
    • Output: Runs over the LLM generated content (e.g., fact checking, compliance).

    You can use any combination of these stages (e.g., just input, just output, or all three).

    {
        "version": 1,
        "input": {
            "version": 1,
            "guardrails": [
                {"name": "URL Filter", "config": {}},
                {"name": "Moderation", "config": {"categories": ["hate", "violence"]}}
            ]
        },
        "output": {
            "version": 1,
            "guardrails": [
                {"name": "Contains PII", "config": {"entities": ["EMAIL_ADDRESS", "PHONE_NUMBER"]}}
            ]
        }
    }
  11. Quickstart with GuardrailsOpenAI

    main

    To add safety and compliance checks to your LLM application, use GuardrailsOpenAI instead of the standard OpenAI client.

    1. Create a configuration file (e.g., guardrails_config.json) using the Guardrails wizard.
    2. Set the OPENAI_API_KEY environment variable.
    3. Initialize GuardrailsOpenAI with your config path.

    When a guardrail is triggered, the client will raise a GuardrailTripwireTriggered exception.

    from pathlib import Path
    from guardrails import GuardrailsOpenAI, GuardrailTripwireTriggered
    
    client = GuardrailsOpenAI(config=Path("guardrails_config.json"))
    
    try:
        # Chat Completions API
        chat = client.chat.completions.create(
            model="gpt-5",
            messages=[{"role": "user", "content": "Hello world"}],
        )
        print(chat.choices[0].message.content)
    
        # Responses API
        response = client.responses.create(
            model="gpt-5",
            input="What are the main features of your premium plan?",
        )
        print(response.output_text)
    except GuardrailTripwireTriggered:
        print("Message blocked by guardrails.")