Guardrails AI
repository·main·Indexed 27 days ago
https://github.com/guardrails-ai/guardrailsA Python framework for building reliable AI applications by providing input/output validation and structured data generation from LLMs. It enables the creation of Guards using validators from the Guardrails Hub, Pydantic models, or RAIL files to detect and mitigate risks. The framework supports ReAsk actions for LLM corrections, a standalone Flask-based REST API server, and specialized formatters like JsonFormatter for Hugging Face models.
What's inside guardrails-ai
- The Guardrails Hub is a central repository where you can search and browse validators by category (e.g., ML, LLM, Logic). It provides pre-built validator templates and guard templates to accelerate development. Some validators also support remote validation or hosted inference.
Understand RAIL (Reliable AI Markup Language)
mainRAIL is an XML-based dialect used to define the structure, types, quality criteria, and corrective actions for LLM outputs.
A
.RAILspecification consists of two main components:<output>: Defines the expected structure (e.g., JSON), field types, validation formats, andon-fail-*corrective actions.<messages>: Contains the prompt template and high-level instructions sent to the LLM.
Key features include being language-agnostic, supporting complex nested structures, and providing built-in validation and correction mechanisms.
Integrate with various LLM providers
mainGuardrails provides native support and integrations for multiple LLM providers:
- OpenAI: Native support, including JSON Mode and Function Calling.
- Anthropic: Native support for Claude models.
- Google: Integration with Gemini.
- Azure OpenAI: Support for Azure-hosted deployments.
- LiteLLM: Integration allowing support for 100+ models.
- Ollama: Support for local model serving.
- Databricks: Support for Databricks model serving.
For unsupported models, you can build Custom LLM Wrappers.
Create a Guard object from a RAIL specification
mainTo use a
.RAILfile to validate and correct LLM outputs, create aGuardobject usinggd.Guard.for_rail(). You can then wrap your LLM API call (e.g.,openai.Completion.create) with this guard object. The guard will return a validated and corrected JSON object instead of raw text.import guardrails as gd # Create a Guard object from a RAIL spec file guard = gd.Guard.for_rail('path/to/rail/spec.xml') # Wrap the LLM API call _, validated_output, *rest = guard( openai.Completion.create, **prompt_args, *args, **kwargs )Generate Structured Data for LLMs
mainGuardrails helps ensure LLMs return valid structured data through several mechanisms:
- JSON Function Calling Tool: Generates OpenAI-compatible function/tool definitions.
- JSON Schema Response Format: Generates schemas compatible with OpenAI's strict JSON mode.
- Constrained Decoding: Support for tools like
JSONFormerto enforce structure during generation. - Schema Pruning: Automatically removes extra properties not specified in the schema to maintain strictness.
Use Prompt Elements and Variables in RAIL
mainWithin the
<messages>element of a RAIL spec, you can use several components to build dynamic prompts:Component Syntax Description Variables ${variable_name}User-provided values substituted at runtime. Output Schema ${output_schema}The compiled schema based on the <output>element.Prompt Primitives ${gr.prompt_primitive_name}Pre-constructed prompts for common tasks (e.g., ${gr.xml_prefix_prompt},${gr.json_suffix_prompt}).Example usage in a
<message>:<message role="user"> Given the following document: ${document} ${gr.xml_prefix_prompt} ${output_schema} ${gr.json_suffix_prompt} </message>Define LLM output structure using the `<output>` element
mainThe
<output>element in aRAILspecification defines the expected structure, data types, quality criteria, and corrective actions for LLM outputs. You can specify complex structures like JSON objects, lists, or simple strings.Output Types
- Flat JSON: A collection of scalar elements (e.g.,
string,integer) inside<output>. - JSON Objects: Use the
<object>element. Children of an<object>represent keys in the resulting JSON. If no children are provided, the LLM generates keys based on thenameanddescriptionattributes. - JSON Lists: Use the
<list>element. A list can contain exactly one child element type (e.g., a list of strings). If no child is provided, the LLM generates values based on thenameanddescriptionattributes. - Simple Strings: Use
<output type="string" ... />to specify a direct string output instead of a JSON object.
<!-- Example of a complex JSON RAIL Spec --> <rail version="0.1"> <output> <string name="text" description="The generated text" format="two-words" on-fail-two-words="reask"/> <float name="score" description="The score of the generated text" format="min-val: 0" on-fail-min-val="fix"/> <object name="metadata" description="The metadata associated with the generated text"> <string name="key_1" description="description of key_1" /> </object> </output> </rail>- Flat JSON: A collection of scalar elements (e.g.,
Migrate validator imports to the guardrails_ai namespace
mainValidators are now imported from the PEP 420
guardrails_ainamespace instead ofguardrails.hub.Migration Pattern:
- Old import:
from guardrails.hub import <Export> - New import:
from guardrails_ai.<name> import <Export>
Example for the
DetectPIIvalidator:- Old:
from guardrails.hub import DetectPII - New:
from guardrails_ai.detect_pii import DetectPII
- Old import:
Implement Reasking logic for LLM corrections
mainGuardrails can automatically attempt to correct LLM outputs through 'reasking'.
Reask Types:
- Full Schema Reasks: Re-prompt the LLM for the entire output structure.
- Field-Level Reasks: Request re-generation of specific fields only.
- Skeleton Reasks: Triggered when the JSON structure itself is malformed (e.g., missing braces).
- NonParseableReAsk: Specifically handles cases where the output cannot be parsed as JSON.
You can configure the
Num Reaskslimit to prevent infinite loops during correction attempts.Deploy Guardrails as a standalone server
mainYou can deploy Guardrails as a standalone Flask server to execute guards via API. Key features include:
- OpenAI Compatibility: The server provides endpoints compatible with the OpenAI SDK.
- Deployment Options: Supports Docker (with Gunicorn) and AWS ECS (via Terraform).
- REST API: Validate inputs via HTTP POST requests.
- Scaling: Supports multi-worker deployment using Uvicorn or Gunicorn.
- Configuration: Use the
use_serversetting to route guard execution to the server.
Define Output Structure and Validation in RAIL
mainThe
<output>element specifies the schema for the LLM's response. You can define types likestring,float,integer,list, andobject.For each field, you can specify:
format: The validation criteria (e.g.,format="two-words"orformat="min-val: 0").on-fail-*: The corrective action to take if the format is not met (e.g.,reask,fix, ornoop).
Example of a JSON output specification:
<rail version="0.1"> <output> <string name="text" description="The generated text" format="two-words" on-fail-two-words="reask"/> <float name="score" description="The score" format="min-val: 0" on-fail-min-val="fix"/> <object name="metadata"> <string name="key_1" description="description" /> </object> </output> </rail>Create Input and Output Guards for LLM Validation
mainYou can create a
Guardby combining one or more validators from the Guardrails Hub.- Install a specific validator package (e.g.,
pip install guardrails-ai-regex-match). - Import the validator and use it with
Guard().use(). - Use
OnFailActionto define behavior when validation fails (e.g.,OnFailAction.EXCEPTION).
Example using a single validator:
from guardrails import Guard, OnFailAction from guardrails_ai.regex_match import RegexMatch guard = Guard().use( RegexMatch, regex="\(?\d{3}\)?-? *\d{3}-? *-?\d{4}", on_fail=OnFailAction.EXCEPTION ) guard.validate("123-456-7890") # Guardrail passesfrom guardrails import Guard, OnFailAction from guardrails_ai.regex_match 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)- Install a specific validator package (e.g.,