As a function
A custom validator can be as simple as a single function if you do not require additional arguments:As a class
If you need to perform more complex operations or require additional arguments to perform the validation, then the validator can be specified as a class that inherits from our base Validator class:On fail
In the code below, afix_value will be supplied in the FailResult. This value will represent a programmatic fix that can be applied to the output if on_fail='fix' is passed during validator initialization.
For more details about on fail actions refer to: On fail actions
Model and LLM integration
Validators are not limited to just programmatic and algorithmic validation. In this example we integrate with Hugging Face to validate if a value meets a threshold for toxic language.Streaming
Validators support streaming validation out of the box. Thevalidate_stream method handles calling _validate with accumulated chunks of a stream when a guard is executed with guard(streaming=True, ...).
By default stream validation is done on a per sentence basis. Validator._chunking_function may be overloaded to provide a custom chunking strategy. This is useful to optimize latency when integrating outside services such as LLMs and controlling how much data a validating model gets to give it more or less context.
The code below in a validator will cause a validator to validate a stream of text 1 paragraph at a time.
Usage
Custom validators must be defined before creating aGuard or RAIL spec in the code, but otherwise can be used like built in validators.