Guardrail

class opik.guardrails.guardrail.Guardrail(rules: List[Rule] | None = None, guardrail_timeout: int | None = None)

Bases: object

Client for Opik guardrails.

This class validates text against a set of rules, given in code or taken from the guardrail policies stored in your Opik workspace.

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 rules, stored in Opik. Referencing policies by name keeps the checks an application runs configurable without a code change. Every global policy of the workspace is included, whether or not it is named here.

The policies are read once, here: build the guardrail again to pick up a change made in the UI. The rules of all retrieved policies are checked together, as one flat set.

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 guardrail checks.

Returns:

Guardrail checking the rules of the named and global policies.

Return type:

Guardrail

Raises:
  • opik.rest_api.core.ApiError – If the policies cannot be retrieved, for example when guardrails are not available in the workspace.

  • opik.exceptions.GuardrailPolicyError – If one of names is not a non-empty string or does not exist in the workspace, or a policy holds a rule 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 rules.

Parameters:

text – Text to validate

Returns:

API response containing validation results

Return type:

ValidationResponse

Raises:
  • opik.exceptions.GuardrailValidationFailed – If validation fails

  • opik.exceptions.GuardrailValidationError – If the guardrail cannot be evaluated (backend unreachable, timeout, guardrails not available in the workspace, or an LLM judge provider failure). Guardrails fail closed, so this blocks the protected code path.