Guardrails AI
Trace Guardrails AI guards and validators with cetra from Python, with the model call they check.
Install
Section titled “Install”pip install "cetra-sdk[openai]" guardrails-aiSet up
Section titled “Set up”from typing import Any
import cetrafrom guardrails import Guard, OnFailActionfrom guardrails.validators import ( FailResult, PassResult, ValidationResult, Validator, register_validator,)
@register_validator(name="no-banned-word", data_type="string")class NoBannedWord(Validator): """Reject text that contains the word secret."""
def validate( self, value: Any, metadata: dict[str, Any], ) -> ValidationResult: if "secret" in value: return FailResult(error_message="contains banned word") return PassResult()
cetra.init(use_global_provider=True, instrument=["openai"])
guard = Guard(name="no-secrets").use(NoBannedWord(on_fail=OnFailAction.EXCEPTION))guard( model="gpt-4o-mini", messages=[{"role": "user", "content": "What is the capital of France?"}],)
cetra.flush()Guardrails writes its spans on the global tracer provider, so pass use_global_provider=True: cetra joins that provider instead of building its own. Call cetra.init() before you create the first guard. Define your validators locally with @register_validator, as in the sample; hub validators are separate, deprecated packages.
What you get
Section titled “What you get”- The guarded call is a
guardrailspan for the guard and one for the modelcall, and aguardrailspan per validator run, with the validator’s name and outcome. - The model call is an
llmspan nested under thecallspan, with the messages, the token counts and the cost, computed from the built-in prices. - The
callspan’s own token counts are not read, because its kind isguardrail: tokens count once, on thellmspan.
Limits
Section titled “Limits”- Pass the API key through
OPENAI_API_KEY: a key passed as an argument ends up in the recorded parameters. - Guardrails AI needs Python 3.13 or earlier.
- Guardrails sends usage metrics unless
enable_metricsis off in~/.guardrailsrc. - Guardrails writes its own spans; the OpenInference Guardrails instrumentation does not support current versions.
- Guardrails writes
user.id=unknownon its spans, so traces show the userunknownunless you set the user with cetra’s context (cetra.context(user_id=…)), which takes precedence. - The captured fixture does not include Guardrails’
stepspan: its input and output embed per-run ids that cannot be normalized. A live run shows it as anotherguardrailspan between the guard and the call. - The fixture was captured with guardrails-ai 0.11.0 and openinference-instrumentation-openai 0.1.69.
- If a field is missing, look at the span’s Attributes tab and compare it with Span attributes.
- Traces: read the trace as a tree and a timeline.
- Cost and tokens: how cost is computed from the token counts.
- Online rules: score these traces automatically.