https://github.com/guardrails-ai/guardrails
Adding guardrails to large language models.
https://github.com/guardrails-ai/guardrails
ai foundation-model gpt-3 llm openai
Last synced: 4 months ago
JSON representation
Adding guardrails to large language models.
- Host: GitHub
- URL: https://github.com/guardrails-ai/guardrails
- Owner: guardrails-ai
- License: apache-2.0
- Created: 2023-01-29T04:11:35.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2025-12-06T05:14:11.000Z (8 months ago)
- Last Synced: 2025-12-09T13:19:41.947Z (7 months ago)
- Topics: ai, foundation-model, gpt-3, llm, openai
- Language: Python
- Homepage: https://www.guardrailsai.com/docs
- Size: 42.9 MB
- Stars: 6,112
- Watchers: 33
- Forks: 485
- Open Issues: 17
-
Metadata Files:
- Readme: README.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
Awesome Lists containing this project
- awesome-vector-databases - Guardrails AI - Python framework for building reliable AI applications through input/output validation, with a hub of pre-built validators for detecting risks like PII, profanity, and logical fallacies in LLM outputs. ([Read more](/details/guardrails-ai.md)) `validation` `safety` `quality-control` (LLM Tools)
- awesome-nlp-llm-spanish-espa-ol - Guardrails AI
- awesome-ai-agents-2026 - Guardrails AI - LLM 出力の検証・修正にガードレールを追加。 (🛡️ エージェントセキュリティ / その他の標準)
- awesome - guardrails-ai/guardrails - Adding guardrails to large language models. (<a name="Python"></a>Python)
- StarryDivineSky - guardrails-ai/guardrails
- AwesomeResponsibleAI - Guardrails
- Awesome-AI-Security - Guardrails - ai/guardrails?logo=github&label=&style=social)](https://github.com/guardrails-ai/guardrails) - Runtime policy enforcement for LLM apps: compose input/output validators (PII, toxicity, jailbreak/PI, regex, competitor checks), then block/redact/rewrite/retry on fail; optional server mode; also supports structured outputs (Pydantic/function-calling). ([↑](#table-of-contents)Tools <a name="tools"></a> / Jailbreak & Policy Enforcement (Guardrails))
- awesome-ai-ml-testing - Guardrails - Framework to validate and clean language model outputs. (🤖 LLM & Chatbot Testing)
- awesome-ChatGPT-repositories - guardrails - Adding guardrails to large language models. (NLP)
- awesome_ai_agents - Guardrails - Guardrails is a Python framework for building reliable AI applications, offering Input/Output Guards to detect and mitigate risks, along with structured data generation from large language models (LLMs) [github](https://github.com/guardrails-ai/guardrails) | [twitter](https://twitter.com/guardrails_ai) (Learning / Repositories)
- Awesome-LLM-RAG-Application - Guardrails - ai/guardrails) (开源工具 / 安全护栏)
- awesome-production-machine-learning - Guardrails - ai/guardrails.svg?style=social) - Guardrails is a package that lets a user add structure, type and quality guarantees to the outputs of large language models. (Privacy and Safety)
- awesome-ai-agents-2026 - Guardrails AI
- awesome-ai-safety - Guardrails AI - Framework for adding structure, type, and quality guarantees to LLM outputs. (Alignment & Training / Guardrails & Output Safety)
- awesome-production-llm - guardrails - ai/guardrails.svg?style=social) Adding guardrails to large language models. (LLM Guardrails / Security)
- awesome-ai-agents - Guardrails AI
- awesome-opensource-ai - Guardrails AI - Input/output validation framework for building reliable AI applications. Detects and mitigates risks through composable validators for PII, toxicity, prompt injection, and structured output validation. Features Guardrails Hub with 50+ pre-built validators. Apache 2.0 licensed.  (10. AI Safety, Alignment & Interpretability)
- awesome-ai-agents - guardrails-ai/guardrails - Guardrails is a Python framework that enhances AI application reliability by providing input/output guards to detect and mitigate risks and generate structured data from large language models. (Security & Privacy Agents / Post-Exploitation Agents)
- awesome-x-ops - Guardrails
- awesome-ai-agents-2025 - Guardrails AI
- awesome-ai-testing - Guardrails AI - Python framework for validating and structuring LLM outputs using composable validators covering toxicity, PII leakage, and hallucination detection. (LLM and AI System Testing)
- llmops - Guardrails AI - ai/guardrails?style=flat-square) | (Security & Safety / Resources)
- awesome-agent-cortex - Guardrails AI - Validation and safety guardrails framework for LLM outputs. (Agent Security and Robustness / Benchmark Reality Check (real-world tool use))
- awesome-llm-tools - Guardrails AI
- awesome-agent-frameworks - Guardrails - ai/guardrails?style=social) - Python framework for adding input and output guards to AI applications and generating structured data from LLMs. (Observability / evals)
- awesome-rag - Guardrails AI - Framework for implementing security guardrails (Security and Privacy Considerations / Comparison Guides)
- awesome-mllm-guardrails - Code
- awesome-automation-for-knowledge-work - Guardrails AI - ai/guardrails.svg)](https://github.com/guardrails-ai/guardrails) - Validation and structured generation guardrails. (Tool Families / Typed-output and structuring tools)
- awesome-genai-security - Guardrails AI - Input/output validation for LLMs. (Tools of Trade / Guardrails & Firewalls)
- awesome-ai-engineering - Guardrails - "Adding guardrails to large language models". (Tools / Libraries)
- awesome-open-data-centric-ai - guardrails - ai/guardrails?style=social) | <a href="https://github.com/guardrails-ai/guardrails/blob/main/LICENSE"><img src="https://img.shields.io/github/license/guardrails-ai/guardrails" height="15"/></a> | (Security and robustness)
- awesome-rust-ai-libraries - Guardrails - A Python framework for building reliable AI applications, offering Input/Output Guards to detect and mitigate risks, along with structured data generation capabilities from large language models. ([Read more](/details/guardrails.md)) `Safety` `Validation` `Risk Mitigation` (LLM Tools)
- awesome-auditable-ai - Tool - source Python framework that runs input and output guards in an application, composing validators from Guardrails Hub (toxicity, PII, hallucination, and more) to detect and mitigate risks. (Runtime Monitoring and Guardrails)
- awesome-ai-agents - Guardrails AI - ai/guardrails) | Output validation and guardrails for LLM responses | (⚙️ Agent Operations / 🔒 Security & Governance)
README

[](https://opensource.org/licenses/Apache-2.0)

[](https://pepy.tech/project/guardrails-ai)
[](https://github.com/guardrails-ai/guardrails/actions/workflows/ci.yml)
[](https://codecov.io/gh/guardrails-ai/guardrails)
[](https://microsoft.github.io/pyright/)
[](https://x.com/guardrails_ai)
[](https://discord.gg/U9RKkZSBgx)
[](https://guardrailsai.com/guardrails/docs)
[](https://www.guardrailsai.com/blog)
[](https://gurubase.io/g/guardrails)
## News and Updates
- **[Feb 12, 2025]** We just launched Guardrails Index -- the first of its kind benchmark comparing the performance and latency of 24 guardrails across 6 most common categories! Check out the index at index.guardrailsai.com
## What is Guardrails?
Guardrails is a Python framework that helps build reliable AI applications by performing two key functions:
1. Guardrails runs Input/Output Guards in your application that detect, quantify and mitigate the presence of specific types of risks. To look at the full suite of risks, check out [Guardrails Hub](https://guardrailsai.com/hub/).
2. Guardrails help you generate structured data from LLMs.
### Guardrails Hub
Guardrails Hub is a collection of pre-built measures of specific types of risks (called 'validators'). Multiple validators can be combined together into Input and Output Guards that intercept the inputs and outputs of LLMs. Visit [Guardrails Hub](https://guardrailsai.com/hub/) to see the full list of validators and their documentation.
## Installation
```python
pip install guardrails-ai
```
## Getting Started
### Create Input and Output Guards for LLM Validation
1. Download and configure the Guardrails Hub CLI.
```bash
pip install guardrails-ai
guardrails configure
```
2. Install a guardrail from Guardrails Hub.
```bash
guardrails hub install hub://guardrails/regex_match
```
3. Create a Guard from the installed guardrail.
```python
from guardrails import Guard, OnFailAction
from guardrails.hub import RegexMatch
guard = Guard().use(
RegexMatch, regex="\(?\d{3}\)?-? *\d{3}-? *-?\d{4}", on_fail=OnFailAction.EXCEPTION
)
guard.validate("123-456-7890") # Guardrail passes
try:
guard.validate("1234-789-0000") # Guardrail fails
except Exception as e:
print(e)
```
Output:
```console
Validation failed for field with errors: Result must match \(?\d{3}\)?-? *\d{3}-? *-?\d{4}
```
4. Run multiple guardrails within a Guard.
First, install the necessary guardrails from Guardrails Hub.
```bash
guardrails hub install hub://guardrails/competitor_check
guardrails hub install hub://guardrails/toxic_language
```
Then, create a Guard from the installed guardrails.
```python
from guardrails import Guard, OnFailAction
from guardrails.hub import CompetitorCheck, ToxicLanguage
guard = Guard().use(
CompetitorCheck(["Apple", "Microsoft", "Google"], on_fail=OnFailAction.EXCEPTION),
ToxicLanguage(threshold=0.5, validation_method="sentence", on_fail=OnFailAction.EXCEPTION)
)
guard.validate(
"""An apple a day keeps a doctor away.
This is good advice for keeping your health."""
) # Both the guardrails pass
try:
guard.validate(
"""Shut the hell up! Apple just released a new iPhone."""
) # Both the guardrails fail
except Exception as e:
print(e)
```
Output:
```console
Validation failed for field with errors: Found the following competitors: [['Apple']]. Please avoid naming those competitors next time, The following sentences in your response were found to be toxic:
- Shut the hell up!
```
### Use Guardrails to generate structured data from LLMs
Let's go through an example where we ask an LLM to generate fake pet names. To do this, we'll create a Pydantic [BaseModel](https://docs.pydantic.dev/latest/api/base_model/) that represents the structure of the output we want.
```py
from pydantic import BaseModel, Field
class Pet(BaseModel):
pet_type: str = Field(description="Species of pet")
name: str = Field(description="a unique pet name")
```
Now, create a Guard from the `Pet` class. The Guard can be used to call the LLM in a manner so that the output is formatted to the `Pet` class. Under the hood, this is done by either of two methods:
1. Function calling: For LLMs that support function calling, we generate structured data using the function call syntax.
2. Prompt optimization: For LLMs that don't support function calling, we add the schema of the expected output to the prompt so that the LLM can generate structured data.
```py
from guardrails import Guard
import openai
prompt = """
What kind of pet should I get and what should I name it?
${gr.complete_json_suffix_v2}
"""
guard = Guard.for_pydantic(output_class=Pet, prompt=prompt)
raw_output, validated_output, *rest = guard(
llm_api=openai.completions.create,
engine="gpt-3.5-turbo-instruct"
)
print(validated_output)
```
This prints:
```
{
"pet_type": "dog",
"name": "Buddy
}
```
### Guardrails Server
Guardrails can be set up as a standalone service served by Flask with `guardrails start`, allowing you to interact with it via a REST API. This approach simplifies development and deployment of Guardrails-powered applications.
1. Install: `pip install "guardrails-ai"`
2. Configure: `guardrails configure`
3. Create a config: `guardrails create --validators=hub://guardrails/two_words --guard-name=two-word-guard`
4. Start the dev server: `guardrails start --config=./config.py`
5. Interact with the dev server via the snippets below
```
# with the guardrails client
import guardrails as gr
gr.settings.use_server = True
guard = gr.Guard(name='two-word-guard')
guard.validate('this is more than two words')
# or with the openai sdk
import openai
openai.base_url = "http://localhost:8000/guards/two-word-guard/openai/v1/"
os.environ["OPENAI_API_KEY"] = "youropenaikey"
messages = [
{
"role": "user",
"content": "tell me about an apple with 3 words exactly",
},
]
completion = openai.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
)
```
For production deployments, we recommend using Docker with Gunicorn as the WSGI server for improved performance and scalability.
## FAQ
#### I'm running into issues with Guardrails. Where can I get help?
You can reach out to us on [Discord](https://discord.gg/gw4cR9QvYE) or [Twitter](https://twitter.com/guardrails_ai).
#### Can I use Guardrails with any LLM?
Yes, Guardrails can be used with proprietary and open-source LLMs. Check out this guide on [how to use Guardrails with any LLM](https://guardrailsai.com/guardrails/docs/how-to-guides/using_llms).
#### Can I create my own validators?
Yes, you can create your own validators and contribute them to Guardrails Hub. Check out this guide on [how to create your own validators](https://guardrailsai.com/guardrails/docs/hub/how_to_guides/custom_validator).
#### Does Guardrails support other languages?
Guardrails can be used with Python and JavaScript. Check out the docs on how to use Guardrails from JavaScript. We are working on adding support for other languages. If you would like to contribute to Guardrails, please reach out to us on [Discord](https://discord.gg/gw4cR9QvYE) or [Twitter](https://twitter.com/guardrails_ai).
## Contributing
We welcome contributions to Guardrails!
Get started by checking out Github issues and check out the [Contributing Guide](CONTRIBUTING.md). Feel free to open an issue, or reach out if you would like to add to the project!