Skip to main content

ai-guardrail-lite for Python

Deterministic input checks for Python applications. Validate user text before sending it to any AI provider or local model. The library runs locally with zero runtime dependencies or network calls.

Python 3.11 or later is required. This is a local release candidate. After PyPI publication, install with python -m pip install ai-guardrail-lite.

Quickstart

import asyncio
from ai_guardrail_lite import Config, create_guardrail

guard = create_guardrail(Config(mode="REDACT"))

async def main():
    result = await guard.check("Contact person@example.test")
    if result.allowed:
        print(result.sanitized_prompt)  # Contact [REDACTED_EMAIL]

asyncio.run(main())

Reuse the guard in an async request handler and send sanitized_prompt downstream only when allowed is true. Use await guard.check_parts([...]) to enforce cumulative budgets, preserve ordered text fields in sanitized_parts, and validate each field independently. An empty sequence is allowed.

Configuration

Setting Behavior
mode BLOCK is the default. REDACT replaces supported spans and blocks other blocking findings. SHADOW_AUDIT lets policy findings through unchanged and reports the hypothetical redaction-mode decision. Hard limits and fail-closed failures apply in every mode.
blocked_keywords, keyword_exceptions Case-insensitive, Unicode word-delimited phrases. An exception must contain the specific blocked occurrence.
pii, phone Detects email, formatted US SSNs, Luhn-qualified cards and phone numbers. Choose "us", "international", or False for phone detection.
secrets, base64 Both enabled by default. Checks typical secret shapes and up to eight plausible Base64 candidates of up to 2,048 encoded characters. Decoding is one level deep.
injection English-language rules override, extraction, jailbreak, role, and obfuscated default to "block". Select "warning", "info", or False per rule. Set the whole setting to False to disable heuristic injection checks.
limits Limits defaults to 65,536 UTF-8 bytes, 65,536 UTF-16 code units, 65,536 estimated tokens, 128 fields, 4× per-field inspection expansion, and 32 reported violations. The token estimate is bytes divided by four rounded up per field.
timeout_ms, fail_mode Default 500 ms cooperative validation deadline. FAIL_CLOSED denies validation failures. FAIL_OPEN allows them while preserving other blocking decisions.
plugins Trusted synchronous or asynchronous callbacks run per field in ascending priority, with ties in registration order. Optional per-plugin timeout and failure mode override apply.
on_audit, fingerprint_secret Optional callback receives immutable metadata. An optional secret enables HMAC-SHA-256 fingerprints for inspected originals. Async callbacks are detached and their errors isolated.

A blocked result has empty sanitized fields. Findings contain a stable code, validator ID and severity. Hard-limit codes include INPUT_MALFORMED, INPUT_LIMIT, INSPECTION_LIMIT and TOKEN_LIMIT. See the Node reference for built-in detector codes. Python rejects lone surrogate code points as malformed and uses Python string offsets for custom spans. Asynchronous plugin timeouts request task cancellation. Use one persistent event loop for asynchronous plugins and audit callbacks. The Python port exposes the core API and can be integrated in any Python server or SDK call site.

Custom validator

from ai_guardrail_lite import Config, Context, Plugin, PluginFinding, Redaction, create_guardrail

def internal_tag(ctx: Context) -> tuple[PluginFinding, ...]:
    tag = "INTERNAL_ONLY"
    offset = ctx.prompt.find(tag)
    if offset < 0:
        return ()
    return (PluginFinding("INTERNAL_TAG", redaction=Redaction(
        offset, offset + len(tag), "[REDACTED_TAG]"
    )),)

guard = create_guardrail(Config(mode="REDACT", plugins=(Plugin("internal-tag", 10, internal_tag),)))

Security boundaries

Heuristics can miss malicious text or flag benign text. Treat results as one layer alongside application authorization, input-size controls, permission checks and output validation. The port does not inspect output, tool calls, browser components, or non-text content. Detectors are language and region limited. Values found only after normalization or Base64 decoding may be blocked when an exact original redaction span is unavailable.

Plugins can see original and inspected text. Review them as trusted code and use static names, violation codes, and labels. Async cancellation cannot interrupt CPU-bound plugins or stop a plugin that suppresses cancellation. Audit callbacks should handle their own backpressure. Token estimates are approximate.

Development

python -m venv .venv
. .venv/bin/activate
python -m pip install -e .
python -m unittest discover -s tests -v
python examples/standalone.py
python examples/plugin.py
python -m pip install build twine
python -m build
python -m twine check --strict dist/*

Node source and behavior reference

Metadata

Release files for ai-guardrail-lite 0.1.0

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

Source distribution (sdist)

Source distribution for ai-guardrail-lite 0.1.0
File Size Uploaded Provenance Actions
ai_guardrail_lite-0.1.0.tar.gz 18.0 kB Without provenance Details for ai_guardrail_lite-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ai-guardrail-lite 0.1.0
File Interpreter ABI Platform Actions
ai_guardrail_lite-0.1.0-py3-none-any.whl Python 3 none any Details for ai_guardrail_lite-0.1.0-py3-none-any.whl

Total release size: 31.2 kB

Release files / ai_guardrail_lite-0.1.0.tar.gz

Download URL ai_guardrail_lite-0.1.0.tar.gz
Size 18.0 kB
Tags Source
SHA-256 checksum
How to use checksums
9ca28f5d9076fecf8e9eb03ed537de5234e32c57a4f70eeb1751714158d6ae89
BLAKE2b-256 checksum
How to use checksums
ce17aef9ab894169a96da27d1659a38b7849e100fde969e37639bc24910edad3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.8

Release files / ai_guardrail_lite-0.1.0-py3-none-any.whl

Download URL ai_guardrail_lite-0.1.0-py3-none-any.whl
Size 13.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cd525f7bab3dd8f548f3978c3ecedfe5c4ea40322107660da211e128590bb878
BLAKE2b-256 checksum
How to use checksums
e55149a4fd44b55cf115c0d3935d87fb9b69d6656b626da26d558624ef6079c3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.8

Security for ai-guardrail-lite 0.1.0

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

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