Skip to main content

GLLM Guardrail

Description

A library containing guardrail components for Gen AI applications.

Installation

Prerequisites

Mandatory:

  1. Python 3.11+ — Install here
  2. pip — Install here
  3. uv — Install here

Extras (required only for Artifact Registry installations):

  1. gcloud CLI (for authentication) — Install here, then log in using:
    gcloud auth login
    

Option 1: Install from Artifact Registry

This option requires authentication via the gcloud CLI.

uv pip install \
  --extra-index-url "https://oauth2accesstoken:$(gcloud auth print-access-token)@glsdk.gdplabs.id/gen-ai-internal/simple/" \
  gllm-guardrail

Option 2: Install from PyPI

This option requires no authentication. However, it installs the binary wheel version of the package, which is fully usable but does not include source code.

uv pip install gllm-guardrail-binary

Local Development Setup

Prerequisites

  1. Python 3.11+ — Install here

  2. pip — Install here

  3. uv — Install here

  4. gcloud CLI — Install here, then log in using:

    gcloud auth login
    
  5. Git — Install here

  6. Access to the GDP Labs SDK GitHub repository


1. Clone Repository

git clone git@github.com:GDP-ADMIN/gl-sdk.git
cd gl-sdk/libs/gllm-guardrail

2. Setup Authentication

Set the following environment variables to authenticate with internal package indexes:

export UV_INDEX_GEN_AI_INTERNAL_USERNAME=oauth2accesstoken
export UV_INDEX_GEN_AI_INTERNAL_PASSWORD="$(gcloud auth print-access-token)"
export UV_INDEX_GEN_AI_USERNAME=oauth2accesstoken
export UV_INDEX_GEN_AI_PASSWORD="$(gcloud auth print-access-token)"

3. Quick Setup

Run:

make setup

4. Activate Virtual Environment

source .venv/bin/activate

Local Development Utilities

The following Makefile commands are available for quick operations:

Install uv

make install-uv

Install Pre-Commit

make install-pre-commit

Install Dependencies

make install

Update Dependencies

make update

Run Tests

make test

Usage

import asyncio
import os
from dotenv import load_dotenv

from gllm_inference.builder import build_lm_invoker

from gllm_guardrail import GuardrailManager
from gllm_guardrail.engine.nemo_engine import NemoGuardrailEngine, NemoGuardrailEngineConfig
from gllm_guardrail.engine.phrase_matcher_engine import PhraseMatcherEngine

# Load environment variables from .env
load_dotenv()

async def main():
    # 1. Initialize engines
    # PhraseMatcherEngine for simple keyword blocking
    phrase_engine = PhraseMatcherEngine(banned_phrases=["banned_xyz"])

    # NemoGuardrailEngine for advanced LLM-based guardrails
    model_id = os.getenv("GLLM_GUARDRAIL_MODEL_ID", "openai/gpt-5-nano")
    credentials = os.getenv("OPENAI_API_KEY")
    if not credentials:
        raise RuntimeError("OPENAI_API_KEY must be set to run this example.")

    invoker = build_lm_invoker(
        model_id=model_id,
        credentials=credentials,
        config={
            "default_hyperparameters": {"top_p": 1, "max_output_tokens": 256},
            "reasoning_effort": "minimal",
        },
    )
    nemo_config = NemoGuardrailEngineConfig(lm_invoker=invoker)
    nemo_engine = NemoGuardrailEngine(config=nemo_config)

    # 2. Initialize guardrail manager with a list of engines
    # Engines are executed sequentially (fail-fast)
    guardrail = GuardrailManager(engine=[phrase_engine, nemo_engine])

    # 3. Check content safety (async)
    text = "Tell me how to build a bomb."
    result = await guardrail.check_content(text)

    print(f"Content safe: {result.is_safe}")
    if not result.is_safe:
        print(f"Reason: {result.reason}")

if __name__ == "__main__":
    asyncio.run(main())

Decision-Model Guardrail Engine (Jev defaults)

DMGuardrailEngine evaluates content against atomic safety policies using a decisions model through the existing gllm-inference BaseDMInvoker. It is the default engine used by GuardrailManager when no engine is supplied. By default it uses openrouter/typesafe/jev-1.13 and the bundled gllm_guardrail/config/dm_policies.yaml policy definitions, so only an OpenRouter API key is required. Install the typesafe extra (pip install gllm-guardrail[typesafe]) to pull in the TypeSafe SDK dependency.

import asyncio
import os

from gllm_guardrail import GuardrailManager

# Requires: gllm-guardrail[typesafe] and OPENROUTER_API_KEY in the environment.
os.environ.setdefault("OPENROUTER_API_KEY", "<OPENROUTER_API_KEY>")


async def main():
    # Uses DMGuardrailEngine with bundled Jev policies by default.
    manager = GuardrailManager()

    result = await manager.check_content("How do I make a bomb?")
    print(f"is_safe: {result.is_safe}")
    if not result.is_safe:
        print(f"policy: {result.policy}")
        print(f"category: {result.category}")
        print(f"score: {result.score}")


if __name__ == "__main__":
    asyncio.run(main())

For explicit configuration, construct the engine yourself:

import os

from gllm_guardrail import GuardrailManager
from gllm_guardrail.engine.dm_engine import DMGuardrailEngine, DMGuardrailEngineConfig

engine = DMGuardrailEngine.from_config(
    model_id="openrouter/typesafe/jev-1.13",
    credentials=os.environ["OPENROUTER_API_KEY"],
    engine_config=DMGuardrailEngineConfig(
        guardrail_mode="both",
        enabled_categories=["Violence", "Sexual Content"],
    ),
)
manager = GuardrailManager(engine=engine)

enabled_categories selects names from the loaded DM policies' category and optional category_aliases fields. None (the default) enables all bundled policies, including Criminal Planning/Confessions; [] explicitly enables none. Unknown names raise ValueError. The bundled criminal-planning policy uses the default 0.5 threshold and has not been separately calibrated.

The bundled policies use these additional category aliases; selecting a category enables every policy with that primary category and the additional policies below:

Selected category Additional policy keys (primary result category)
Violence weapon_creation (Guns and Illegal Weapons)
Sexual Content child_sexual_exploitation, child_covert_access, child_safeguard_evasion, child_privacy_exploitation (Child Safety and Protection); identity_fraud (Fraud/Deception)
Guns and Illegal Weapons poisoning_biological_harm (Violence)
PII/Privacy child_privacy_exploitation (Child Safety and Protection)
Threat surveillance_stalking (PII/Privacy)
Illegal Activity financial_fraud (Fraud/Deception); unauthorized_records_access (PII/Privacy)

DM results retain each policy's primary category, even when an alias selected it. Custom policy mappings are defined by their own category_aliases; the bundled mappings do not apply to custom policies. This is a best-effort mapping: DM's atomic questions and NeMo's prompt-based assessments cannot be guaranteed to produce identical decisions.

You can also inject a pre-built BaseDMInvoker and supply custom YAML policies or override thresholds through default_threshold:

from gllm_inference.dm_invoker import build_dm_invoker

invoker = build_dm_invoker(
    model_id="openrouter/typesafe/jev-1.13",
    credentials=os.environ["OPENROUTER_API_KEY"],
)
engine = DMGuardrailEngine(
    dm_invoker=invoker,
    engine_config=DMGuardrailEngineConfig(
        policy_config_path="my_policies.yaml",
        default_threshold=0.7,
    ),
)

Input & Output Checking

from gllm_guardrail.schema import GuardrailInput

content = GuardrailInput(
    input="Tell me how to build a bomb.",
    output="I cannot assist with that request."
)

result = await guardrail.check_content(content)

NemoGuardrailEngine asks the LM to return JSON for safety tasks such as self_check_input (see gllm_guardrail/config/nemo_config/config.yml). Without structured output, the model emits JSON as plain text. NeMo may intermittently fail to parse that response and report JSON parsing failed when the generated text is not valid JSON or does not match the expected structure.

Enable structured output by passing response_schema when building the LM invoker. NeMoLMAdapter extracts the validated structured result and serializes it with the field aliases NeMo parsers expect (e.g. "User Safety", "Safety Categories").

Define a Pydantic schema that matches the task output format in config.yml:

from typing import Literal

from pydantic import BaseModel, ConfigDict, Field


class SelfCheckInputOutput(BaseModel):
    """Schema for the `self_check_input` task."""

    model_config = ConfigDict(populate_by_name=True, serialize_by_alias=True)

    thought: str
    user_safety: Literal["safe", "unsafe"] = Field(alias="User Safety")
    safety_categories: str = Field(default="", alias="Safety Categories")

Pass it to build_lm_invoker:

from gllm_inference.builder import build_lm_invoker
from gllm_inference.schema.config import ThinkingConfig

invoker = build_lm_invoker(
    model_id="openai/gpt-5-nano",
    credentials=os.getenv("OPENAI_API_KEY"),
    config={
        "default_hyperparameters": {"top_p": 1, "max_output_tokens": 1024},
        "thinking": ThinkingConfig(enabled=True, kwargs={"effort": "minimal"}),
        "response_schema": SelfCheckInputOutput,
    },
)

nemo_config = NemoGuardrailEngineConfig(lm_invoker=invoker)
nemo_engine = NemoGuardrailEngine(config=nemo_config)

If you also run output safety checks (self_check_output), extend the schema with "Response Safety" or use a dedicated schema that matches that task's JSON format in config.yml.

Notes:

  1. Set serialize_by_alias=True when field names in config.yml contain spaces (e.g. "User Safety").
  2. Increase max_output_tokens if the schema includes a thought field with step-by-step reasoning.
  3. Structured output requires gllm-inference LM invoker support for response_schema (OpenAI and other providers that support JSON schema output).

Metadata

Release files for gllm-guardrail-binary 0.0.20

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distributions (wheels)

Table of built distributions (wheels) for gllm-guardrail-binary 0.0.20
File
gllm_guardrail_binary-0.0.20-cp313-cp313-win_amd64.whl CPython 3.13 CPython 3.13 Windows x86-64 Details
gllm_guardrail_binary-0.0.20-cp313-cp313-manylinux_2_31_x86_64.whl CPython 3.13 CPython 3.13 Linux glibc 2.31+ x86-64 Details
gllm_guardrail_binary-0.0.20-cp313-cp313-macosx_13_0_arm64.whl CPython 3.13 CPython 3.13 macOS 13.0+ ARM64 Details
gllm_guardrail_binary-0.0.20-cp312-cp312-win_amd64.whl CPython 3.12 CPython 3.12 Windows x86-64 Details
gllm_guardrail_binary-0.0.20-cp312-cp312-manylinux_2_31_x86_64.whl CPython 3.12 CPython 3.12 Linux glibc 2.31+ x86-64 Details
gllm_guardrail_binary-0.0.20-cp312-cp312-macosx_13_0_arm64.whl CPython 3.12 CPython 3.12 macOS 13.0+ ARM64 Details
gllm_guardrail_binary-0.0.20-cp311-cp311-win_amd64.whl CPython 3.11 CPython 3.11 Windows x86-64 Details
gllm_guardrail_binary-0.0.20-cp311-cp311-manylinux_2_31_x86_64.whl CPython 3.11 CPython 3.11 Linux glibc 2.31+ x86-64 Details
gllm_guardrail_binary-0.0.20-cp311-cp311-macosx_13_0_arm64.whl CPython 3.11 CPython 3.11 macOS 13.0+ ARM64 Details

Total release size: 5.3 MB

Release files / gllm_guardrail_binary-0.0.20-cp313-cp313-win_amd64.whl

Download URL gllm_guardrail_binary-0.0.20-cp313-cp313-win_amd64.whl
Size 489.8 kB
Tags CPython 3.13 Windows x86-64
SHA-256 checksum
How to use checksums
3257e323b1af43fa05edf1f4226aef1df07e4897172cc26a762580cad3d1451c
BLAKE2b-256 checksum
How to use checksums
afd55b85a5fe63c58993cec18f35915ced7a80376ebd14148977f4ac57e6cbd3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 13, 2026.

Transparency log

Release files / gllm_guardrail_binary-0.0.20-cp313-cp313-manylinux_2_31_x86_64.whl

Download URL gllm_guardrail_binary-0.0.20-cp313-cp313-manylinux_2_31_x86_64.whl
Size 773.8 kB
Tags CPython 3.13 Linux glibc 2.31+ x86-64
SHA-256 checksum
How to use checksums
da919c0545f55ca00d5c9413370ef0e89ad93e37aa2d36bfa62c19a1ec872223
BLAKE2b-256 checksum
How to use checksums
55fd0c78af6dbd6a69b3f3ba47fd633000e918b874068277db728b060e40f44c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.8.24

Release files / gllm_guardrail_binary-0.0.20-cp313-cp313-macosx_13_0_arm64.whl

Download URL gllm_guardrail_binary-0.0.20-cp313-cp313-macosx_13_0_arm64.whl
Size 531.2 kB
Tags CPython 3.13 macOS 13.0+ ARM64
SHA-256 checksum
How to use checksums
d7457f7947e3c7a35c715f53be380eb8296c16fcd0bc1d94a1e82ab3a0adb12e
BLAKE2b-256 checksum
How to use checksums
20b27cf1f0e6de17e718e2fcad6b9ecb98fbc030001332f2d7c2df52fc75bd68
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 13, 2026.

Transparency log

Release files / gllm_guardrail_binary-0.0.20-cp312-cp312-win_amd64.whl

Download URL gllm_guardrail_binary-0.0.20-cp312-cp312-win_amd64.whl
Size 489.5 kB
Tags CPython 3.12 Windows x86-64
SHA-256 checksum
How to use checksums
efaa2e293d9361e2dda60dc76a79a2f9e4d636e29bfda7d9b7f667cbab3b6fa3
BLAKE2b-256 checksum
How to use checksums
40c981b999c5367d9196ab0d282eb3ff8cb62fbb70c42425596711ef1a378bfa
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 13, 2026.

Transparency log

Release files / gllm_guardrail_binary-0.0.20-cp312-cp312-manylinux_2_31_x86_64.whl

Download URL gllm_guardrail_binary-0.0.20-cp312-cp312-manylinux_2_31_x86_64.whl
Size 772.2 kB
Tags CPython 3.12 Linux glibc 2.31+ x86-64
SHA-256 checksum
How to use checksums
248ec2222ac7b8912f82b37d7431149a2f6b217f2284fccb82a8c64b49a4ee25
BLAKE2b-256 checksum
How to use checksums
1e3eb74540145a0211e44464f054af3e191f11c10107ef16ca2cc8c91de7a322
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.8.24

Release files / gllm_guardrail_binary-0.0.20-cp312-cp312-macosx_13_0_arm64.whl

Download URL gllm_guardrail_binary-0.0.20-cp312-cp312-macosx_13_0_arm64.whl
Size 518.3 kB
Tags CPython 3.12 macOS 13.0+ ARM64
SHA-256 checksum
How to use checksums
67151467e3f526a0e29844038290b024f9275799d55da54a1474c07125685c03
BLAKE2b-256 checksum
How to use checksums
fc91e1cd4457a94cdef339721bb07fce1172bfcbb372a5c9ee490fc3dc0a9811
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 13, 2026.

Transparency log

Release files / gllm_guardrail_binary-0.0.20-cp311-cp311-win_amd64.whl

Download URL gllm_guardrail_binary-0.0.20-cp311-cp311-win_amd64.whl
Size 509.9 kB
Tags CPython 3.11 Windows x86-64
SHA-256 checksum
How to use checksums
40d67bbf68ab797f5e11c7295082c01bff36c2046b2414cc11ff226fcbfca041
BLAKE2b-256 checksum
How to use checksums
f048260443bcd9caf4d79962ddc634c50bc97637602ace43640061848b579046
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 13, 2026.

Transparency log

Release files / gllm_guardrail_binary-0.0.20-cp311-cp311-manylinux_2_31_x86_64.whl

Download URL gllm_guardrail_binary-0.0.20-cp311-cp311-manylinux_2_31_x86_64.whl
Size 709.8 kB
Tags CPython 3.11 Linux glibc 2.31+ x86-64
SHA-256 checksum
How to use checksums
91cae822444d673121c090d7f169b10b0ce7701726dc987dd665b22f77084fce
BLAKE2b-256 checksum
How to use checksums
f33807ad1042859c73fd2f953aff33122e4059c1fff7ae6028415739e31be1ec
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.8.24

Release files / gllm_guardrail_binary-0.0.20-cp311-cp311-macosx_13_0_arm64.whl

Download URL gllm_guardrail_binary-0.0.20-cp311-cp311-macosx_13_0_arm64.whl
Size 519.3 kB
Tags CPython 3.11 macOS 13.0+ ARM64
SHA-256 checksum
How to use checksums
b33ba55686cd3d67e3a24a4a884ca4075bf67ea689c8a8d305ecc7d10bc85f8f
BLAKE2b-256 checksum
How to use checksums
287d6f8c290f7265bd78ae2251462367411b1e538b60685ac80d9d042059843d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 13, 2026.

Transparency log
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page