Generating strings that don't have any secrets
Note
To download this example as a Jupyter notebook, click here.
In this example, we will use Guardrails to generate strings that don't have any secrets.
This is also a good example to show how to use the custom Validators in the RAIL
specification.
Objective
We want to ask help with an API, but make sure that the generated text has no secrets.
Step 1: Create the RAIL Spec
Ordinarily, we would create an RAIL spec in a separate file. For the purposes of this example, we will create the spec in this notebook as a string following the RAIL syntax. For more information on RAIL, see the RAIL documentation. We will also show the same RAIL spec in a code-first format using a Pydantic model.
In this RAIL spec, we:
- Create a custom Validator that checks if a string has any secrets. This is a simple example, but you can use this to create more complex Validators. For more information on creating custom Validators, see the Validators documentation.
- Create a
output
schema that returns an object with aapi_help
key.
First the custom Validator:
from guardrails.validators import Validator, register_validator, PassResult, FailResult, ValidationResult
import re
from typing import Dict, Any
OPENAI_KEY_PATTERN = re.compile(r"sk-[a-zA-Z0-9]{24}")
@register_validator(name="no-code-secrets", data_type="string")
class NoCodeSecrets(Validator):
def validate(self, value: Any, metadata: Dict) -> ValidationResult:
global OPENAI_KEY_PATTERN
if re.search(OPENAI_KEY_PATTERN, value) is not None:
# Corrected value should replace the OpenAI API key with "sk-xxx"
correct_value = re.sub(OPENAI_KEY_PATTERN, "sk-xxx", value)
raise FailResult(
error_message=f"Value {value} is an OpenAI API key.",
fix_value=correct_value,
)
return PassResult()
Now we can use the validator in a Rail spec:
rail_str = """
<rail version="0.1">
<output>
<string description="Show an example curl command for using openai Completion API" format="no-code-secrets" name="api_help" on-fail-no-code-secrets="fix"></string>
</output>
<prompt>
How do I use OpenAI's Completion API?
${gr.complete_json_suffix}
</prompt>
</rail>
"""
Or in a Pydantic model:
Step 2: Create a Guard
object with the RAIL Spec
We create a gd.Guard
object that will check, validate and correct the output of the LLM. This object:
- Enforces the quality criteria specified in the RAIL spec.
- Takes corrective action when the quality criteria are not met.
- Compiles the schema and type info from the RAIL spec and adds it to the prompt.
From the XML RAIL spec:
Or from the Pydantic model:
We see the prompt that will be sent to the LLM.
Step 3: Wrap the LLM API call with Guard
The guard
wrapper returns the raw_llm_respose (which is a simple string), and the validated and corrected output (which is a dictionary).
We can see that the output is a dictionary with the correct schema and types.