### Install Dependencies
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/text_summarization_quality.ipynb
Installs the necessary numpy package for the example.
```python
! pip install numpy -q
```
--------------------------------
### Setup and Imports for Guardrails
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/how_to_guides/use_on_fail_actions.ipynb
Imports necessary Guardrails components and installs the DetectPII hub if not already present. This setup is required before using Guardrails validators.
```python
from guardrails import Guard, install
try:
from guardrails.hub import DetectPII
except ImportError:
install("hub://guardrails/detect_pii")
from guardrails.hub import DetectPII
```
--------------------------------
### Install CompetitorCheck Validator
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/competitors_check.ipynb
Install the necessary libraries and the CompetitorCheck validator from the Guardrails Hub. Ensure NLTK is also installed.
```python
! pip install nltk --quiet
! guardrails hub install hub://guardrails/competitor_check --quiet
```
--------------------------------
### Install Chess Library
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/valid_chess_moves.ipynb
Install the 'chess' library quietly using pip.
```bash
! pip install chess --quiet
```
--------------------------------
### Install Development Environment
Source: https://github.com/guardrails-ai/guardrails/blob/main/CONTRIBUTING.md
Commands to install dependencies and configure pre-commit hooks for local development.
```bash
make dev
```
```bash
pre-commit install
```
--------------------------------
### Install Provenance LLM Guardrail
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/provenance.ipynb
Installs the ProvenanceLLM guardrail from the Guardrails hub. Use the --quiet flag to suppress verbose output during installation.
```bash
!guardrails hub install hub://guardrails/provenance_llm --quiet
```
--------------------------------
### Install sqlvalidator Package
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/syntax_error_free_sql.ipynb
Installs the sqlvalidator package, which is required for validating SQL syntax. The -q flag suppresses installation output.
```python
! pip install sqlvalidator -q
```
--------------------------------
### Install Regex Match Hub Module
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/regex_validation.ipynb
Installs the regex_match module from the Guardrails hub.
```python
!guardrails hub install hub://guardrails/regex_match --quiet
```
--------------------------------
### Install DetectPII dependencies
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/check_for_pii.ipynb
Install the required Presidio libraries and the DetectPII validator from the Guardrails Hub.
```bash
# Install the necessary packages
! pip install presidio-analyzer presidio-anonymizer -q
! python -m spacy download en_core_web_lg -q
! guardrails hub install hub://guardrails/detect_pii --quiet
```
--------------------------------
### Install Guardrails Hub package
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/translation_with_quality_check.ipynb
Installs the high_quality_translation guard from the Guardrails hub.
```python
!guardrails hub install hub://brainlogic/high_quality_translation -q
```
--------------------------------
### XML to JSON Mapping Examples
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/select_choice_based_on_action.ipynb
Examples demonstrating how specific XML tags map to corresponding JSON structures.
```xml
```
```json
{'foo': 'example one'}
```
```xml
```
```json
{"bar": ['STRING ONE', 'STRING TWO', etc.]}
```
--------------------------------
### Guardrails Prompt Primitive Example
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/how_to_guides/rail.md
Example of guardrails prompt primitives used within a RAIL specification. `${gr.xml_prefix_prompt}` and `${gr.json_suffix_prompt}` are used to guide the LLM's output format and behavior.
```xml
${gr.xml_prefix_prompt}
```
```xml
${gr.json_suffix_prompt}
```
--------------------------------
### Install Guardrails Hub Validators
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/guardrails_with_chat_models.ipynb
Installs the 'lowercase', 'two_words', and 'one_line' validators from the Guardrails Hub. Use the '--quiet' flag to suppress output during installation. Also installs the 'pypdfium2' library for PDF processing.
```bash
!guardrails hub install hub://guardrails/lowercase --quiet
!guardrails hub install hub://guardrails/two_words --quiet
!guardrails hub install hub://guardrails/one_line --quiet
%pip install pypdfium2
```
--------------------------------
### Install Provenance Embeddings Guardrail
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/provenance.ipynb
Installs the ProvenanceEmbeddings guardrail from the Guardrails hub. Use the --quiet flag to suppress verbose output during installation.
```bash
!guardrails hub install hub://guardrails/provenance_embeddings --quiet
```
--------------------------------
### Install and Import Guardrails Hub Validators
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/how_to_guides/streaming_structured_data.ipynb
Installs necessary validators from the Guardrails hub if they are not already available. This setup is crucial for using custom validation logic.
```python
try:
from guardrails.hub import LowerCase, UpperCase, ValidRange, OneLine
except ImportError:
gd.install("hub://guardrails/valid_range")
gd.install("hub://guardrails/uppercase")
gd.install("hub://guardrails/lowercase")
gd.install("hub://guardrails/one_line")
from guardrails.hub import LowerCase, UpperCase, ValidRange, OneLine
```
--------------------------------
### Example Output String
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/how_to_guides/output.md
A simple string output.
```text
string output
```
--------------------------------
### Install Guardrails Hub Package
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/select_choice_based_on_action.ipynb
Installs the required valid_choices hub package.
```python
!guardrails hub install hub://guardrails/valid_choices --quiet
```
--------------------------------
### Install alt-profanity-check Package
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/translation_to_specific_language.ipynb
Install the necessary package for profanity checking. Use the --quiet flag to suppress verbose output during installation.
```python
! pip install alt-profanity-check --quiet
```
--------------------------------
### Install RegexMatch Validator
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/lite_llm_defaults.ipynb
Installs the RegexMatch validator from the Guardrails hub.
```bash
! guardrails hub install hub://guardrails/regex_match --quiet
```
--------------------------------
### Configure Guardrails CLI
Source: https://github.com/guardrails-ai/guardrails/blob/main/README.md
Install the Guardrails package and initialize the configuration.
```bash
pip install guardrails-ai
guardrails configure
```
--------------------------------
### Install SimilarToPreviousValues Hub
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/value_within_distribution.ipynb
Installs the SimilarToPreviousValues validator from the Guardrails Hub. Use the --quiet flag to suppress output.
```bash
!guardrails hub install hub://guardrails/similar_to_previous_values --quiet
```
--------------------------------
### Install Guardrails Hub Validators
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/guard_use.ipynb
Installs the regex_match and valid_range validators from the Guardrails hub. Use the --quiet flag to suppress verbose output during installation.
```bash
! guardrails hub install hub://guardrails/regex_match --quiet
! guardrails hub install hub://guardrails/valid_range --quiet
```
--------------------------------
### XML to JSON Mapping Examples
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/generate_structured_data_cohere.ipynb
Examples demonstrating how various XML structures map to their corresponding JSON representations.
```xml
```
```json
{'foo': 'example one'}
```
```xml
```
```json
{"bar": ['STRING ONE', 'STRING TWO', etc.]}
```
```xml
```
```json
{'baz': {'foo': 'Some String', 'index': 1}}
```
--------------------------------
### Install Guardrails Hub Validators
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/generate_structured_data.ipynb
Installs necessary validators from the Guardrails Hub. Use the --quiet flag to suppress output during installation.
```bash
!guardrails hub install hub://guardrails/valid_length --quiet
```
```bash
!guardrails hub install hub://guardrails/two_words --quiet
```
```bash
!guardrails hub install hub://guardrails/valid_range --quiet
```
--------------------------------
### XML to JSON Mapping Examples
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/syntax_error_free_sql.ipynb
Examples demonstrating the conversion of XML elements into corresponding JSON structures.
```xml
```
```json
{'foo': 'example one'}
```
```xml
```
```json
{"bar": ['STRING ONE', 'STRING TWO', etc.]}
```
```xml
```
```xml
```
```xml
```
```xml
```
--------------------------------
### Initialize Query Engine with Custom Templates
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/llamaindex-output-parsing.ipynb
Configure a query engine with custom text QA and refine templates, along with an LLM predictor. This setup is used to query the index for specific information.
```python
query_engine = index.as_query_engine(
text_qa_template=qa_prompt,
refine_template=refine_prompt,
llm_predictor=llm_predictor,
)
```
--------------------------------
### Example of Invalid JSON Response
Source: https://github.com/guardrails-ai/guardrails/blob/main/tests/integration_tests/test_assets/pydantic/compiled_prompt_reask_2.txt
This JSON response contains an invalid value for 'zip_code' which is 'None' and has associated error messages indicating it should be numeric and start with '9'.
```json
{
"people": [
{
"zip_code": {
"incorrect_value": "None",
"error_messages": [
"Zip code must be numeric.",
"Zip code must be in California, and start with 9."
]
}
}
]
}
```
--------------------------------
### Initialize Logging and Load Documents
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/llamaindex-output-parsing.ipynb
Configure logging and load documents from the local directory.
```python
import logging
import sys
from llama_index import VectorStoreIndex, SimpleDirectoryReader
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))
```
```python
# load documents
documents = SimpleDirectoryReader("./data/paul_graham/").load_data()
```
--------------------------------
### Raw LLM Output Example
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/extracting_entities.ipynb
A snippet showing the raw JSON output structure from an LLM.
```json
{
"fees": [
```
--------------------------------
### Install RestrictToTopic Validator
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/response_is_on_topic.ipynb
Installs the RestrictToTopic validator from the Guardrails Hub. The --quiet flag suppresses verbose output during installation.
```bash
!guardrails hub install hub://tryolabs/restricttotopic --quiet
```
--------------------------------
### Instructions Class
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/api_reference/llm_interaction.md
A concrete implementation of BasePrompt for secondary LLM instructions.
```APIDOC
## Instructions Class
### Description
Instructions class, a subclass of BasePrompt. The instructions are passed to the LLM as secondary input. Different models may use these differently, for example, chat models may receive instructions in the system-prompt.
### Methods
#### `format(**kwargs) -> "Instructions"`
Format the prompt using the given keyword arguments. This method applies the provided arguments to the instructions template.
```
--------------------------------
### Validated Output Example
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/no_secrets_in_generated_text.ipynb
Displays the structured, validated version of the LLM output.
```json
{
'api_help': 'curl https://api.openai.com/v1/completions -H \'Content-Type: application/json\' -H \'Authorization: Bearer YOUR_API_KEY\' -d \'{"model": "text-davinci-003", "prompt": "Once upon a time", "max_tokens": 50}\''
}
```
--------------------------------
### Raw LLM Output Example
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/no_secrets_in_generated_text.ipynb
Displays the raw JSON response received from an LLM call.
```json
{
"api_help": "curl https://api.openai.com/v1/completions -H 'Content-Type: application/json' -H 'Authorization: Bearer YOUR_API_KEY' -d '{"model": "text-davinci-003", "prompt": "Once upon a time", "max_tokens": 50}'"
}
```
--------------------------------
### Initialize BasePrompt
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/api_reference/llm_interaction.md
Initialize and substitute constants in the prompt.
```python
def __init__(source: str,
output_schema: Optional[str] = None,
*,
xml_output_schema: Optional[str] = None)
```
--------------------------------
### Format Instructions
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/api_reference/llm_interaction.md
Format the instructions using the given keyword arguments.
```python
def format(**kwargs) -> "Instructions"
```
--------------------------------
### Install Toxic Language Validator
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/how_to_guides/remote_validation_inference.ipynb
Installs the Toxic Language validator from the Guardrails Hub. Use the --quiet flag for silent installation. The --no-install-local-models flag can be used to opt into remote inferencing if local models were not installed during `guardrails configure`.
```bash
guardrails hub install hub://guardrails/toxic_language --quiet;
# This will not download local models if you opted into remote inferencing during guardrails configure
# If you did not opt in, you can explicitly opt in for just this validator by passing the --no-install-local-models flag
```
--------------------------------
### Initialize source data list in Python
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/provenance.ipynb
Defines a list of strings containing instructional text for cat litter box maintenance.
```python
sources = [
"""1 Move the litter box to the right location. Cats may stop using the litter box after a scary experience in the
area, such as a loud noise or harassment by another pet. [2] They may also dislike the spot you chose after moving
the litter box, or moving to a new home. Keep the litter box in a quiet, low-traffic spot where the cat can see
people coming. Choose a room with at least two exits so the cat doesn't feel cornered. [3] Keep litter boxes away
from food and water bowls. Cats do not like to combine these two areas. Signs that your cat may have had an
unpleasant experience in the litter box including running quickly in and out of the litter box, or using an area
near the litter box. [4] Try moving the box to a new room if you notice this. Keep at least one litter box on every
floor of a multistory home. [5] Keep litter boxes away from food and water bowls. Cats do not like to combine these
two areas. Signs that your cat may have had an unpleasant experience in the litter box including running quickly in
and out of the litter box, or using an area near the litter box. [4] Try moving the box to a new room if you notice
this. Keep at least one litter box on every floor of a multistory home. [5] 2 Play with toys near the litter box.
Play with your cat in the same general area as the litter box. Leave toys (but not food) in the room so the cat
spends time there and develops positive associations. [6] You can bring the cat to the litter box to investigate on
its own, but do not drop it inside or reward it with treats for using it. These tactics can backfire by making the
cat uncomfortable or afraid. [7] Unlike dogs, cats should choose the litter box on their own, especially if they
used one in the past. You can bring the cat to the litter box to investigate on its own, but do not drop it inside
or reward it with treats for using it. These tactics can backfire by making the cat uncomfortable or afraid. [7]
Unlike dogs, cats should choose the litter box on their own, especially if they used one in the past. 3 Keep the
litter box clean. [8] If your cat perches on the edge of the box or eliminates right next to it, the box might be
too dirty for it. Remove clumps and top up with fresh litter at least once a day, preferably twice. Rinse the
litter box once a week with baking soda or unscented soap. [9] If you use non-clumping litter, change the whole box
every couple days to prevent odor build up, which can drive away the cat. [10] Do not clean the litter box with
scented products. Do not use a disinfectant unless it is specifically made for litter boxes, as many of them
contain chemicals toxic to cats. [11] If you use non-clumping litter, change the whole box every couple days to
prevent odor build up, which can drive away the cat. [10] Do not clean the litter box with scented products. Do not
use a disinfectant unless it is specifically made for litter boxes, as many of them contain chemicals toxic to
cats. [11] 4 Switch to new litter gradually. If you bought a different kind of litter, introduce it slowly. Mix a
little of it in with the old type, and gradually increase the proportion each time you change the litter box. [12]
Cats usually find it easier to adjust to unscented litter with a similar texture to their old litter. [13] If the
old type of litter is no longer available, buy two or three new types. Put them in separate litter boxes side by
side and let the cat choose its favorite. Try adjusting the depth of the litter, especially if it has a different
texture than the cat is used to. Many cats prefer a shallow layer of litter, less than two inches (5 cm.) deep.
Long-haired cats often like an extra-shallow layer so they can dig to the floor of the box. [14] If the old type of
litter is no longer available, buy two or three new types. Put them in separate litter boxes side by side and let
the cat choose its favorite. Try adjusting the depth of the litter, especially if it has a different texture than
the cat is used to. Many cats prefer a shallow layer of litter, less than two inches (5 cm.) deep. Long-haired cats
often like an extra-shallow layer so they can dig to the floor of the box. [14] 5 Troubleshoot new litter boxes. If
your cat hasn't responded well to a recent litter box replacement, try these adjustments to make it more appealing:
[15] Some cats prefer covered boxes, and other prefer open trays. Try adding or removing the hood. Remove plastic
liners from the litter box. These can snag a cat's claws. [16] Most cats adjust well to self-cleaning litter boxes
but not all. There is a risk of an anxious cat being frightened by the motor, and refusing to use the box as a
result. If in doubt it’s best to stick with a regular litter box. If the box is smaller than the old one, you
probably need to replace it with something larger. A large box with low sides works best; some people use a plastic"""
]
```
--------------------------------
### Initialize Guard with a Validator for Streaming
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/how_to_guides/streaming.ipynb
Set up a Guard instance and use a validator like CompetitorCheck. This example demonstrates how to initialize Guardrails for streaming by setting the 'stream' parameter to 'True' in the guard call.
```python
from guardrails.hub import CompetitorCheck
prompt = "Tell me about the Apple Iphone"
guard = gd.Guard().use(CompetitorCheck(["Apple"]))
```
--------------------------------
### Install SecretsPresent Validator
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/secrets_detection.ipynb
Installs the required validator package from the Guardrails Hub.
```bash
!guardrails hub install hub://guardrails/secrets_present --quiet
```
--------------------------------
### Initialize OpenAI Model and LangChain Components
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/langchain_integration.ipynb
Import necessary classes from langchain_openai and langchain_core, and initialize the ChatOpenAI model. This sets up the language model for use in the chain.
```python
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
model = ChatOpenAI(model="gpt-4")
```
--------------------------------
### AsyncGuard Initialization Methods
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/api_reference/guards.md
Methods for initializing an AsyncGuard instance.
```APIDOC
### Class Method: `for_pydantic`
```python
@classmethod
def for_pydantic(cls, output_class: ModelOrListOfModels, *, messages: Optional[List[Dict]] = None, reask_messages: Optional[List[Dict]] = None, name: Optional[str] = None, description: Optional[str] = None, output_formatter: Optional[Union[str, BaseFormatter]] = None)
```
### Class Method: `for_string`
```python
@classmethod
def for_string(cls, validators: Sequence[Validator], *, string_description: Optional[str] = None, messages: Optional[List[Dict]] = None, reask_messages: Optional[List[Dict]] = None, name: Optional[str] = None, description: Optional[str] = None)
```
### Class Method: `from_dict`
```python
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional["AsyncGuard"]
```
```
--------------------------------
### Pin to Safe Version
Source: https://github.com/guardrails-ai/guardrails/blob/main/SECURITY_ADVISORY.md
To ensure you are not using the compromised version, pin your installation to a safe version. This is the recommended first step for all users.
```text
guardrails-ai==0.10.0
```
--------------------------------
### RAIL Spec Example
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/how_to_guides/output.md
An example of a RAIL specification defining an output string with validators.
```xml
```
--------------------------------
### Initialize Guard and Parse Output
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/guardrails_server.ipynb
Configures logging and uses a Guard instance to validate LLM output.
```python
import logging
from rich import print
from guardrails import configure_logging
from guardrails import Guard, settings
settings.use_server = True
configure_logging(None, log_level=logging.DEBUG)
name_case = Guard(name="name-case")
response = name_case.parse(llm_output="Guardrails AI")
print(response)
```
--------------------------------
### Example JSON Response
Source: https://github.com/guardrails-ai/guardrails/blob/main/tests/integration_tests/test_assets/pydantic/msg_compiled_prompt_reask.txt
This is an example of a JSON response that has incorrect values and is missing a required property.
```json
{
"name": "Inception",
"director": "Christopher Nolan"
}
```
--------------------------------
### Example Output JSON Structure
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/how_to_guides/output.md
An example of the JSON output that conforms to the specified RAIL spec.
```json
{
"text": "string output",
"score": 0.0,
"metadata": {
"key_1": "string",
...
}
}
```
--------------------------------
### Download Data for LlamaIndex
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/llamaindex-output-parsing.ipynb
Prepare the local directory and download the sample essay text file.
```bash
!mkdir -p 'data/paul_graham/'
!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'
```
--------------------------------
### Prompt Class
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/api_reference/llm_interaction.md
A concrete implementation of BasePrompt for primary LLM instructions.
```APIDOC
## Prompt Class
### Description
Prompt class, a subclass of BasePrompt. The prompt is passed to the LLM as primary instructions.
### Methods
#### `format(**kwargs) -> "Prompt"`
Format the prompt using the given keyword arguments. This method applies the provided arguments to the prompt template.
```
--------------------------------
### Install ValidPython Validator
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/bug_free_python_code.ipynb
Install the necessary validator from the Guardrails hub to check for valid Python syntax.
```python
!guardrails hub install hub://reflex/valid_python --quiet
```
--------------------------------
### RAIL Spec Example
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/how_to_guides/rail.md
An example of a RAIL specification defining an output string with validators and quality criteria.
```xml
```
--------------------------------
### Configure Output Summary
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/summarizer.ipynb
Defines the output summary configuration using the all-MiniLM-L6-v2 model.
```xml
```
--------------------------------
### Initialize AsyncGuard with CompetitorCheck
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/how_to_guides/async_streaming.ipynb
Create an AsyncGuard object and use the CompetitorCheck validator, specifying a list of competitors to check against.
```python
from guardrails.hub import CompetitorCheck
prompt = "Tell me about the Apple Iphone"
guard = gd.AsyncGuard().use(CompetitorCheck(["Apple"]))
```
--------------------------------
### Run Development Workflow Tasks
Source: https://github.com/guardrails-ai/guardrails/blob/main/CONTRIBUTING.md
Standard commands for testing, formatting, and static analysis before committing changes.
```bash
make test
```
```bash
make autoformat
```
```bash
make type
```
```bash
make docs-gen
```
--------------------------------
### Basic Guardrails Usage
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/text_summarization_quality.ipynb
Demonstrates the basic usage of the `guard` function with a prompt and prompt parameters. Requires setting the OPENAI_API_KEY environment variable.
```python
os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY"
raw_llm_response, validated_response, *rest = guard(
messages=[{"role": "user", "content": prompt}],
prompt_params={"document": document},
model="gpt-5-nano",
max_tokens=2048,
temperature=1,
)
print(f"Validated Output: {validated_response}")
```
--------------------------------
### Example JSON Output with Nested Objects
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/how_to_guides/output.md
An example of a JSON output containing a nested object with validated string and integer values.
```json
{
"some_object": {
"some_str_key": "SOME STRING",
"some_other_key": 0
}
}
```
--------------------------------
### Install Guardrails Hub Validators
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/langchain_integration.ipynb
Install specific validators from the Guardrails Hub, such as 'competitor_check' and 'toxic_language'. These validators can be used to enforce content constraints.
```bash
guardrails hub install hub://guardrails/competitor_check --quiet
```
```bash
guardrails hub install hub://guardrails/toxic_language --quiet
```
--------------------------------
### Format BasePrompt
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/api_reference/llm_interaction.md
Format the prompt using keyword arguments.
```python
def format(**kwargs) -> "BasePrompt"
```
--------------------------------
### Initialize and Execute Guard
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/generate_structured_data_cohere.ipynb
Create a guard instance from a Pydantic model and execute it against an LLM prompt.
```python
from rich import print
import guardrails as gd
guard = gd.Guard.for_pydantic(output_class=Orders)
raw_llm_response, validated_response, *rest = guard(
messages=[{"role": "user", "content": prompt}],
model="command-r-08-2024",
max_tokens=1024,
temperature=0.3,
)
```
--------------------------------
### Install Guardrails Validators
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/summarizer.ipynb
Installs necessary Guardrails validators for summarization tasks, including reading time, semantic similarity, and valid length. Requires numpy.
```python
%pip install numpy -q
! guardrails hub install hub://guardrails/reading_time --quiet --install-local-models
! guardrails hub install hub://guardrails/similar_to_document --quiet --install-local-models
! guardrails hub install hub://guardrails/valid_length --quiet --install-local-models
```
--------------------------------
### Initialize AsyncGuard
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/api_reference/guards.md
Constructor for the AsyncGuard instance.
```python
def __init__(*args, **kwargs)
```
--------------------------------
### XML to JSON Conversion Examples
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/translation_to_specific_language.ipynb
These examples show how Guardrails AI parses XML structures and converts them into JSON objects, applying specified formats to string values.
```xml
```
```xml
```
```xml
```
--------------------------------
### Raw LLM Output Example
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/how_to_guides/streaming_structured_data.ipynb
This is an example of raw output from a Large Language Model, demonstrating a JSON structure with nested data including a list of symptoms, each with a symptom description and affected area.
```json
{
"gender": "female",
"age": 152,
"symptoms": [
{
"symptom": "chronic macular rash",
"affected_area": "face"
}
]
}
```
--------------------------------
### RAIL Specification Example
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/how_to_guides/rail.md
An example of a RAIL specification using the messages element to define system and user prompts. It includes variables, output schema, and prompt primitives for structured LLM interactions.
```xml
You are a helpful assistant only capable of communicating with valid JSON, and no other text.
Given the following document, answer the following questions. If the answer doesn't exist in the document, enter 'None'.
${document}
${gr.xml_prefix_prompt}
${output_schema}
${gr.json_suffix_prompt}
```
--------------------------------
### Import Guardrails and OpenAI
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/regex_validation.ipynb
Initializes the necessary imports for Guardrails and sets up the environment for API usage.
```python
from guardrails import Guard
from guardrails.hub import RegexMatch
from rich import print
# Set your OPENAI_API_KEY as an environment variable
# import os
# os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY"
```
--------------------------------
### XML Schema Validation Examples
Source: https://github.com/guardrails-ai/guardrails/blob/main/docs/examples/summarizer.ipynb
These examples illustrate how specific XML schema definitions are evaluated against JSON data structures. Use these to understand format constraints like 'two-words', 'upper-case', and '1-indexed'.
```xml
The following XML is invalid:
- `` => `{'foo': 'example one'}`
- `` => `{"bar": ['STRING ONE', 'STRING TWO', etc.]}`
- `` => `{'baz': {'foo': 'Some String', 'index': 1}}`
```
```json
The following JSON is invalid:
- `` => `{'foo': 'example one'}`
- `` => `{"bar": ['STRING ONE', 'STRING TWO', etc.]}`
- `` => `{'baz': {'foo': 'Some String', 'index': 1}}`
```
```xml
The following XML is valid:
- `` => `{'foo': 'example one'}`
- `` => `{"bar": ['STRING ONE', 'STRING TWO', etc.]}`
```