Implementation:Evidentlyai Evidently Guard Decorator
| Knowledge Sources | |
|---|---|
| Domains | Guardrails, Decorators, LLM_Safety |
| Last Updated | 2026-02-14 12:00 GMT |
Overview
guardrails/decorators.py provides the @guard decorator that wraps a function with guardrail validation, automatically intercepting a specified input argument and running it through one or more guardrails before the function executes.
Description
The module exposes a single decorator factory, guard(), which accepts:
- A single
GuardrailBaseinstance or a list of them. - An
input_argparameter name (default"input") indicating which function argument to validate.
When the decorated function is called, the decorator:
- Uses
inspect.signatureto bind the positional and keyword arguments to parameter names. - Extracts the value of
input_argfrom the bound arguments. - If a list of guards is provided, calls
validate_guards(fromevidently.guardrails.core) to validate the input against all guards. - If a single guard is provided, calls
guard.validate()directly. - If
tracelyis installed and a current tracing span exists, sets the guardrails as context values on the span for observability integration. - If validation passes, the original function is called normally.
This enables declarative, non-invasive guardrail enforcement on LLM pipeline functions.
Usage
Use the @guard decorator to protect functions (e.g., LLM call wrappers) with input validation guardrails. It is particularly useful in production pipelines where you want to ensure inputs meet safety or quality criteria before processing.
Code Reference
Source Location
- Repository: Evidentlyai_Evidently
- File:
src/evidently/guardrails/decorators.py
Signature
def guard(
guard: Union[GuardrailBase, List[GuardrailBase]],
input_arg: str = "input",
) -> Callable:
...
Import
from evidently.guardrails.decorators import guard
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| guard | Union[GuardrailBase, List[GuardrailBase]] |
Yes | A single guardrail or list of guardrails to validate against. |
| input_arg | str |
No (default "input") | The name of the decorated function's parameter to validate. |
Outputs
| Name | Type | Description |
|---|---|---|
| return | Callable |
A decorator that wraps the target function with guardrail validation. |
Usage Examples
from evidently.guardrails.decorators import guard
from evidently.guardrails.core import GuardrailBase, GuardException
class ProfanityGuard(GuardrailBase):
def validate(self, data: str):
banned = ["badword"]
for word in banned:
if word in data.lower():
raise GuardException(self, f"Profanity detected: {word}")
# Apply guard to a function, validating the 'prompt' argument
@guard(ProfanityGuard(), input_arg="prompt")
def call_llm(prompt: str) -> str:
return "LLM response"
# Multiple guards
@guard([ProfanityGuard()], input_arg="prompt")
def call_llm_multi(prompt: str) -> str:
return "LLM response"