Guardrail¶
- class opik.guardrails.guardrail.Guardrail(guards: List[Guard], guardrail_timeout: int | None = None)¶
Bases:
objectClient for the Opik Guardrails API.
This class provides a way to validate text against a set of guardrails.
- classmethod from_stored_policies(names: Sequence[str] | None = None, guardrail_timeout: int | None = None) Guardrail¶
Build a Guardrail from guardrail policies stored in your Opik workspace.
A policy is a named group of guards, stored in Opik. Referencing policies by name keeps the checks an application runs configurable without a code change. Policies the workspace applies unconditionally are always included, whether or not they are named here.
The guards of all retrieved policies are checked together, as one flat set: which policy a guard came from is not preserved.
- Parameters:
names – Names of the policies to build the guardrail from. Every name must exist, a name that does not is an error rather than a check silently not running.
guardrail_timeout – Timeout in seconds for the guardrails backend calls.
- Returns:
Guardrail running the guards of the retrieved policies.
- Return type:
- Raises:
opik.rest_api.core.ApiError – If the policies cannot be retrieved, for example when one of
namesdoes not exist in the workspace.opik.exceptions.GuardrailPolicyError – If a policy holds a guard type this SDK version cannot run.
Example:
```python from opik.guardrails import Guardrail from opik import exceptions
guardrail = Guardrail.from_stored_policies(names=[“no_contact_information”])
- try:
guardrail.validate(“Call me at 555-0123”)
- except exceptions.GuardrailValidationFailed as e:
print(“Guardrail failed:”, e)
- validate(text: str) ValidationResponse¶
Validate text against all configured guardrails.
- Parameters:
text – Text to validate
- Returns:
API response containing validation results
- Return type:
- Raises:
opik.exceptions.GuardrailValidationFailed – If validation fails
opik.exceptions.GuardrailValidationError – If a guardrail cannot be evaluated (guardrails backend unreachable, timeout, or LLM judge provider failure). Guardrails fail closed, so this blocks the protected code path.