Skip to main content

input_validation

guardrails hub install hub://guardrails/two_words --quiet
    Installing hub://guardrails/two_words...
✅Successfully installed guardrails/two_words!


Input Validation

Guardrails supports validating inputs (messages) with string validators.

In XML, specify the validators on the messages tag, as such:

from guardrails import Guard

rail_spec = """
<rail version="0.1">
<messages
validators="hub://guardrails/two_words"
on-fail-two-words="exception"
>
<message role="user">
This is not two words
</message>
</messages>

<output type="string">
</output>
</rail>
"""

guard = Guard.for_rail_string(rail_spec)

When fix is specified as the on-fail handler, the prompt will automatically be amended before calling the LLM.

In any other case (for example, exception), a ValidationError will be returned in the outcome.

from guardrails.errors import ValidationError

# Add your OPENAI_API_KEY as an environment variable if it's not already set
# import os
# os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY"

try:
guard(
model="gpt-4o"
)
except ValidationError as e:
print(e)
    /Users/dtam/dev/guardrails/guardrails/validator_service/__init__.py:85: UserWarning: Could not obtain an event loop. Falling back to synchronous validation.
warnings.warn(
/Users/dtam/dev/guardrails/guardrails/validator_service/__init__.py:85: UserWarning: Could not obtain an event loop. Falling back to synchronous validation.
warnings.warn(

When using pydantic to initialize a Guard, input validators can be specified by composition, as such:

from guardrails.hub import TwoWords
from pydantic import BaseModel


class Pet(BaseModel):
name: str
age: int


guard = Guard.for_pydantic(Pet)
guard.use(TwoWords(on_fail="exception"), on="messages")

try:
guard(
model="gpt-4o",
messages=[{"role":"user","content":"This is not two words"}],
)
except ValidationError as e:
print(e)
    Validation failed for field with errors: Value must be exactly two words


/Users/dtam/dev/guardrails/guardrails/validator_service/__init__.py:85: UserWarning: Could not obtain an event loop. Falling back to synchronous validation.
warnings.warn(