Lakera Guard Guardrail Usage
Lakera Guard Guardrail Usage
import os
from getpass import getpass
def ensure_env_var(name: str) -> None:
"""Prompt for an environment variable if not already set."""
if name not in os.environ:
print(f"{name} not found in environment!")
value = getpass(f"Please enter your {name}: ")
os.environ[name] = value
print(f"{name} set for this session!")
else:
print(f"{name} found in environment.")
for var in ["LAKERA_API_KEY"]:
ensure_env_var(var)Basic Usage
Output should look like:
validisFalsewhen Lakera flags the message.scoreis the highest detector confidence among the detected threats, mapped from Lakera's ordinal level to a float (l1_confident→1.0…l5_unlikely→0.2);0.0when nothing was detected.categorieslists oneCategoryResultper detector Lakera ran, with itsname(thedetector_type), whether ittriggered, and the mapped confidencescore.extracarries theflaggedflag, thepayloadlocating any PII / profanity / regex matches, the requestmetadata, and a conveniencedetected_detector_typeslist. The full per-detectorbreakdown(and everything else Lakera returned) is preserved verbatim inraw.
When the input contains PII, profanity, or a custom-regex match, the payload list locates each one (start / end offsets, matched text, detector_type, and labels):
Validating whole conversations
Lakera Guard natively understands chat-message lists, so you can screen a full conversation (including system and assistant turns) in one call:
Advanced Usage
For more information, please see our docs.
Per-project policies
Lakera projects let you configure which categories to flag, severity thresholds, and custom rules in the Lakera dashboard. Pass the project ID and the project's policy is applied to every request:
Controlling what Lakera returns
The richer outputs are opt-in request flags, exposed as constructor parameters. They default to breakdown=True and payload=True so you get the full picture; set them to False to minimize the response, enable dev_info for Lakera build details, or attach metadata (e.g. user_id, session_id) for observability:
Last updated