Install & Compatibility
Where this runs
tested against v0.2.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
py 3.10
✕ build_error
✕ build_error
py 3.9
✕ build_error
✕ build_error
415MB installed
● package 415MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
GuardrailsOpenAI
✓ from guardrails import GuardrailsOpenAI
For synchronous OpenAI client replacement.
GuardrailsAsyncOpenAI
✓ from guardrails import GuardrailsAsyncOpenAI
For asynchronous OpenAI client replacement.
GuardrailTripwireTriggered
✓ from guardrails import GuardrailTripwireTriggered
Exception raised when a guardrail detects a violation.
This quickstart demonstrates how to integrate `openai-guardrails` by replacing the standard OpenAI client with a `GuardrailsOpenAI` instance. It highlights the use of a `guardrails_config.json` file to define guardrail logic and shows how to handle `GuardrailTripwireTriggered` exceptions when a violation occurs. A basic `guardrails_config.json` is provided as a comment for immediate testing.
import os
from pathlib import Path
from guardrails import GuardrailsOpenAI, GuardrailTripwireTriggered
from openai import OpenAI
# Ensure your OpenAI API key is set as an environment variable (OPENAI_API_KEY)
# or passed directly to the client.
# For model-based guardrails, an API key is required.
# To run this example, create a simple 'guardrails_config.json' file in the same directory:
# {"version": "1", "input": {"version": "1", "guardrails": [{"name": "Moderation", "config": {}}]}}
def main():
# Initialize OpenAI client (standard or Guardrails client)
# The GuardrailsOpenAI client acts as a drop-in replacement
# It requires a config file (e.g., guardrails_config.json) that defines the guardrails to apply.
guardrails_client = GuardrailsOpenAI(config=Path("guardrails_config.json"))
try:
# Use the Guardrails client just like a regular OpenAI client
response = guardrails_client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": "Hello, how are you?"}
]
)
print("LLM Output:", response.choices[0].message.content)
# You can also access guardrail results if available
if hasattr(response, 'guardrail_results'):
print("Guardrail Results:", response.guardrail_results)
# Example of triggering a moderation guardrail (if configured to block)
print("\nTesting with potentially problematic input...")
problematic_response = guardrails_client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": "I want to harm someone."}
]
)
print("LLM Output (problematic):", problematic_response.choices[0].message.content)
except GuardrailTripwireTriggered as e:
print(f"\nGuardrail triggered: {e.guardrail_result.info}")
print(f"Violation details: {e.guardrail_result.details}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
# Set a dummy API key if not already set, for local testing without network calls (if guardrails config allows).
# For actual model-based guardrails, a valid API key is essential.
if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = os.environ.get('TEST_OPENAI_API_KEY', 'sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxx')
main()
Debug
Known issues
breakingIn `v0.2.0`, the library changed to make the OpenAI response object directly accessible. This could affect how you access attributes (e.g., `response.output_text` or `response.choices[0].message.content`) if your code previously relied on wrapped access patterns.fixReview and update code to directly access attributes of the underlying OpenAI response object returned by the Guardrails client methods (e.g., `response.choices[0].message.content`).
affects: >=0.2.0
breakingIn `v0.1.6`, the `Presidio anonymizer` dependency was removed due to conflicts. If your application relied on `openai-guardrails` for PII detection and masking via Presidio in versions prior to `v0.1.6`, this functionality might have changed or been removed, requiring alternative solutions or explicit dependency management.fixIf PII masking was critical and relied on the removed Presidio integration, evaluate alternative PII detection/masking libraries or custom guardrails, or ensure your `guardrails_config.json` correctly handles PII without Presidio.
affects: >=0.1.6 (from 0.1.5 and earlier)
gotchaThe core functionality of `openai-guardrails` relies on a `guardrails_config.json` file, which defines the specific guardrails (e.g., moderation, PII detection, jailbreak detection) and their configurations. This file is loaded at client initialization but is external to the Python code examples, requiring manual creation or use of the Guardrails Wizard.fixAlways ensure a `guardrails_config.json` file is present and correctly configured according to your desired guardrail logic. The official Guardrails Wizard (guardrails.openai.com) is recommended for configuration generation.
affects: All
gotchaWhile the `openai-guardrails` library itself is open-source and free, many of its built-in guardrails (e.g., Hallucination Detection, Custom Prompt Check, Jailbreak) utilize OpenAI's own models and APIs. Consequently, these model-based checks will incur standard OpenAI API usage costs.fixMonitor your OpenAI API usage and costs, especially when enabling model-based guardrails or running extensive evaluations. Consider optimizing guardrail configurations or using non-LLM based checks where possible to manage costs.
affects: All
gotchaWhen integrating with OpenAI Agents SDK, agent-level guardrails have specific execution boundaries. Input guardrails run only for the *first* agent in a multi-agent chain, and output guardrails run only for the agent that produces the *final* output. This implies that intermediate agent interactions or specific tool calls might require tool-level guardrails for comprehensive coverage.fixCarefully design your guardrail placement in multi-agent workflows. For checks on intermediate steps or specific tool interactions, implement tool-level guardrails or custom logic within the agent's flow rather than solely relying on agent-level input/output guardrails.
affects: All
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'guardrails'
This error typically occurs when the `openai-guardrails` library has not been installed, or it was installed incorrectly, or the import statement refers to a different, unrelated `guardrails` package. The `openai-guardrails` package internally exposes its core components under the `guardrails` namespace.
fixEnsure you have installed the `openai-guardrails` library using `pip install openai-guardrails`. If you're encountering issues with `uv`, consider using `pip`. Then, import the necessary classes from the `guardrails` top-level package, for example: `from guardrails import GuardrailsOpenAI` or `from guardrails import Guard`.
AttributeError: module 'openai' has no attribute 'error'
This error arises when using older versions of the `guardrails-ai` library (which `openai-guardrails` depends on) with newer versions of the OpenAI Python client (v1.x). The error handling classes, like `APIConnectionError`, moved from `openai.error` directly to the `openai` module in OpenAI Python client v1.x.
fixUpgrade your `openai-guardrails` package and its dependencies to the latest versions to ensure compatibility with OpenAI Python client v1.x. Use `pip install --upgrade openai-guardrails` or specifically upgrade `guardrails-ai` if that's the direct dependency causing the conflict.
GuardrailTripwireTriggered
This is an intentional exception raised by the `openai-guardrails` library when a configured guardrail detects a violation in the LLM's input or output, indicating that the content triggered a safety or compliance policy.
fixWrap your `openai-guardrails` calls in a `try-except` block to gracefully handle the `GuardrailTripwireTriggered` exception. Within the `except` block, you can log the event, provide a specific user message, or implement a fallback action based on your application's safety policies. Example: `try: ... guard(...) except GuardrailTripwireTriggered: print('Message blocked by guardrails')`. ModuleNotFoundError: No module named 'guardrails.hub.tryolabs' (or similar for hub validators like 'detect_pii')
This `ModuleNotFoundError` occurs when a custom validator from the Guardrails Hub (e.g., `SensitiveTopics` or `DetectPII`) is installed via `guardrails hub install` but the Python environment cannot locate the installed module. This can happen if the installer (like `uv`) places the hub validator in a different directory than the core `guardrails-ai` package, or if the interpreter's path isn't correctly refreshed (e.g., in a Jupyter notebook).
fixEnsure that `guardrails-ai` and any hub validators are installed in the same Python environment and that their module paths are correctly resolved. If using a virtual environment, ensure it's activated correctly. If in a Jupyter notebook, try restarting the kernel. If using `uv` caused issues, switching to `pip install guardrails-ai` and then `guardrails hub install hub://guardrails/your_validator` might resolve the path conflict.
Upgrade
Version history
0.2.1latest on PyPI · released Dec 15, 2025
Audit
Dependencies
pythonrequiredRequires Python 3.11 or higher.
openairequiredMany guardrail checks are model-based and incur standard OpenAI API costs, requiring an OpenAI API key.