Metadata-Version: 2.4
Name: ai-guardrail-lite
Version: 0.1.0
Summary: Deterministic AI input guardrails for Python
License-Expression: MIT
Project-URL: Homepage, https://github.com/mkkotcherla/ai-guardrail-lite-python
Project-URL: Source, https://github.com/mkkotcherla/ai-guardrail-lite-python
Project-URL: Issues, https://github.com/mkkotcherla/ai-guardrail-lite-python/issues
Project-URL: Security, https://github.com/mkkotcherla/ai-guardrail-lite-python/security/policy
Keywords: ai,guardrails,redaction,pii,prompt-injection
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# 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

```python
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

```python
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

```sh
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](https://github.com/mkkotcherla/ai-guardrail-lite/tree/v0.1.0)
