For the complete documentation index, see llms.txt. This page is also available as Markdown.

Lakera Guard Guardrail Usage

Lakera Guard Guardrail Usage

Open In Colab

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:

  • valid is False when Lakera flags the message.

  • score is the highest detector confidence among the detected threats, mapped from Lakera's ordinal level to a float (l1_confident1.0l5_unlikely0.2); 0.0 when nothing was detected.

  • categories lists one CategoryResult per detector Lakera ran, with its name (the detector_type), whether it triggered, and the mapped confidence score.

  • extra carries the flagged flag, the payload locating any PII / profanity / regex matches, the request metadata, and a convenience detected_detector_types list. The full per-detector breakdown (and everything else Lakera returned) is preserved verbatim in raw.

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