Metadata-Version: 2.5
Name: llm-output-guard-lite
Version: 0.1.1
Summary: Local heuristic output guardrails for LLM applications
License-Expression: MIT
License-File: LICENSE
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: >=3.10
Description-Content-Type: text/markdown

# llm-output-guard-lite

**Local output guardrails for Python developers who need to check model responses before returning them to users or passing them downstream.**

[![PyPI version](https://img.shields.io/pypi/v/llm-output-guard-lite)](https://pypi.org/project/llm-output-guard-lite/) ![Python 3.10+](https://img.shields.io/badge/Python-3.10%2B-3776ab) [![License: MIT](https://img.shields.io/badge/license-MIT-green)](https://github.com/mkkotcherla/llm-output-guard-lite/blob/main/LICENSE) ![Runtime dependencies: 0](https://img.shields.io/badge/runtime%20dependencies-0-green)

A support chatbot might accidentally include a customer's email in a shared chat or produce a JSON record without a required field. Put the guard between the model and your response handler. It can redact the address before delivery and block the incomplete record before application code consumes it.

| Capability | Problem it solves |
| --- | --- |
| Text redaction and blocking | Recognizable personal information, credentials, or application-specific literals in a generated reply. |
| URL and media policies | Supported Markdown and HTML references pointing to disallowed destinations. |
| JSON validation and opt-in repair | Malformed or structurally invalid model output passed to downstream code. |
| Streaming protection | Deciding when generated text can be emitted and whether a block must withhold the entire response. |
| SDK adapters, plugins, and audit | Applying policy at a supported provider boundary, adding business checks, and reviewing decisions. |

Validation runs locally without runtime dependencies or network requests.

## Python examples

Install from PyPI. Python 3.10+ is required. The import name is `llm_output_guard_lite`. The wheel includes `py.typed`.

~~~sh
python -m pip install llm-output-guard-lite
~~~

### Quick start

~~~python
from llm_output_guard_lite import create_output_guard

guard = create_output_guard()
reply = guard.check("Contact user@example.test for help.")
assert reply["decision"] == "REDACT"
assert reply["sanitizedOutput"] == "Contact [REDACTED_EMAIL] for help."

image = guard.check("![Preview](https://external.example.test/image.png)")
assert image["allowed"] is False
assert image["decision"] == "BLOCK"
assert image["sanitizedOutput"] == ""
~~~

### JSON handoff and host policy

This mock support service parses the sanitized response before giving application data to its caller. On rejection it returns a generic error. Use JSON mode for enforcement and use `repair_json` when you only need a repair diagnostic.

~~~python
import json
from llm_output_guard_lite import create_output_guard

guard = create_output_guard({
    "json": {
        "unquotedKeys": True, "trailingCommas": True, "required": ["reply"],
        "fields": {"reply": {"type": "string", "maxLength": 160}},
    },
    "url": {"hosts": ["help.example.test"]},
})

def mock_model(intent):
    if intent == "contact":
        return '{reply: "Contact user@example.test or [help](https://help.example.test/contact)",}'
    return '{other: "missing reply"}'

def answer(intent):
    result = guard.check(mock_model(intent))
    if not result["allowed"]:
        return 422, {"error": "Model output rejected"}
    return 200, json.loads(result["sanitizedOutput"])

assert answer("contact")[1]["reply"] == (
    "Contact [REDACTED_EMAIL] or [help](https://help.example.test/contact)"
)
assert answer("invalid")[0] == 422
assert guard.repair_json('{reply: "hello",}')["repaired"] is True
assert json.loads(guard.assert_safe('{"reply":"[link](https://outside.example.test)"}'))["reply"] == "[BLOCKED_LINK]"
~~~

### Streaming, audit, and custom policy

~~~python
import asyncio
from llm_output_guard_lite import create_output_guard, create_stream_guard

stream = create_stream_guard()
assert stream.push("Contact user@")["output"] == ""
assert stream.push("example.test")["output"] == ""
final = stream.flush()
assert final["output"] == "Contact [REDACTED_EMAIL]"
assert final["summary"]["stream"]["status"] == "COMPLETED"

events = []
shadow = create_output_guard({
    "mode": "SHADOW_AUDIT",
    "audit": {"requestId": "mock-42", "callback": events.append},
})
assert shadow.check("user@example.test")["hypotheticalDecision"] == "REDACT"
assert events[0]["decision"] == "ALLOW"
assert "sanitizedOutput" not in events[0]

def draft_check(context):
    return {"action": "BLOCK"} if "INTERNAL DRAFT" in context["output"] else None

async def main():
    strict = create_output_guard({
        "plugins": [{"name": "draft-check", "validate": draft_check}],
    })
    assert (await strict.check_async("INTERNAL DRAFT"))["decision"] == "BLOCK"

    async def source():
        yield "Contact user@"
        yield "example.test"

    guard = create_output_guard()
    assert [part async for part in guard.wrap_stream_async(source())] == [
        "Contact [REDACTED_EMAIL]"
    ]

asyncio.run(main())
~~~

### OpenAI and Anthropic text adapters (local mocks)

~~~python
from types import SimpleNamespace
from llm_output_guard_lite import wrap_client, OutputGuardUnsupportedResponseError

def openai_create(**kwargs):
    return {"choices": [{"message": {"content": "user@example.test"}}]}

def anthropic_create(**kwargs):
    return {"content": [{"type": "text", "text": "user@example.test"}]}

client = wrap_client(SimpleNamespace(
    chat=SimpleNamespace(completions=SimpleNamespace(create=openai_create)),
    messages=SimpleNamespace(create=anthropic_create),
))
assert client.chat.completions.create()["choices"][0]["message"]["content"] == "[REDACTED_EMAIL]"
assert client.messages.create()["content"][0]["text"] == "[REDACTED_EMAIL]"
try:
    client.chat.completions.create(stream=True)
except OutputGuardUnsupportedResponseError:
    pass
else:
    raise AssertionError("Provider-native streams should be rejected")
~~~

### FastAPI

Create a guard once for each policy. In a FastAPI endpoint, call `guard.check(output)` after the model call and before returning a JSON response. For an async handler with plugins, await `guard.check_async(output)`. The example maps a rejected output to HTTP 422 and returns the sanitized response for allowed output. [FastAPI example](https://github.com/mkkotcherla/llm-output-guard-lite/blob/main/examples/frameworks/fastapi_example.py)

## Python API

Import public symbols from `llm_output_guard_lite`.

| Public entry | Input and result |
| --- | --- |
| `create_output_guard(config=None)` / `OutputGuard(config=None)` | Creates an independent guard from an optional mapping. |
| `guard.check(output)` / `await guard.check_async(output)` | Checks the supplied string and returns `OutputGuardResult`. Use async with plugins. Non-strings get a blocked result. |
| `guard.assert_safe(output)` / `await guard.assert_safe_async(output)` | Returns the allowed string or raises `OutputGuardBlockedError`. |
| `guard.repair_json(output)` | Returns `JsonRepair` metadata for a string. |
| `guard.stream()` / `create_stream_guard(config=None)` | Creates a `StreamSession`. Prefer these factories to constructing the session directly. |
| `guard.wrap_stream(iterable)` / `guard.wrap_stream_async(iterable)` | Sync iterator or async iterator over guarded output. The async wrapper accepts sync or async sources and supports plugins. |
| `session.push(chunk)` / `session.flush()` / `await session.flush_async()` | Returns a `StreamUpdate`. Use async flush with plugins. |
| `session.abort()` / `session.summary` | Aborts and returns a `StreamSummary`. The property is None before finalization. |
| `wrap_client(client, config=None)` | Creates a facade exposing `chat.completions.create(...)` or `messages.create(...)` as applicable. Await calls for async clients. |
| `OutputGuardBlockedError(result)`, `OutputGuardConfigurationError`, `OutputGuardUnsupportedResponseError` | Public exception classes. See Results and errors. |

The package exports the result and callback types `OutputGuardResult`, `JsonRepair`, `AuditMetadata`, `StreamUpdate`, `StreamSummary`, and `StreamChunk`. [Python API details](https://github.com/mkkotcherla/llm-output-guard-lite/blob/main/docs/PYTHON.md)

## Configuration

All top-level options are optional. Both languages use the same camelCase configuration and result keys. Create a guard once per policy and reuse it. Treat the configuration and its callbacks as trusted application inputs.

| Option | Type | Default and behavior |
| --- | --- | --- |
| `mode` | `REDACT`, `BLOCK`, or `SHADOW_AUDIT` | `REDACT`. `BLOCK` blocks findings whose actions have no explicit override, except entropy findings default to audit. `SHADOW_AUDIT` reports a hypothetical decision and normally preserves the input. Hard limits, invalid input, and fail-closed validation errors still apply. |
| `maxBytes` | Integer, 1–262,144 | 262,144 UTF-8 bytes for input and output, including cumulative stream limits. |
| `maxDepth` | Integer, 1–32 | 32 JSON container levels. |
| `maxViolations` | Integer, 1–100 | 100 reported findings. Enforcement continues after the cap. |
| `rules` | Map from violation code to rule settings | Built-in behavior. Each override can set `enabled` (boolean), `action` (BLOCK, REDACT, AUDIT), `severity` (LOW, MEDIUM, HIGH), or `label` (bracketed ASCII text). A block takes precedence over redaction. |
| `phones`, `sensitiveLiterals`, `keywords` | Lists of strings | Empty. Case-sensitive literals, up to 32 per list and 256 UTF-16 units per literal. Configure each phone format you need. |
| `url` | Object | See URL options below. |
| `json` | Object | Omitted for text mode. Pass an empty object to enable strict JSON. Repairs are opt-in. |
| `streaming` | `BUFFERED`, `INCREMENTAL`, or `PASSTHROUGH_AUDIT` | `BUFFERED`. See stream behavior below. |
| `plugins` | List of trusted plugin objects | Empty, up to 16. Use async validation or async buffered finalization. |
| `audit` | Object with `callback` plus optional `requestId` and `fingerprintSecret` | Disabled. Use an opaque request ID. An explicitly configured secret enables HMAC-SHA-256 fingerprints. |
| `failMode` | `BLOCK` or `AUDIT` | `BLOCK` on unexpected validation failures. `AUDIT` can return original output subject to hard limits and known blocks. |

| URL option | Type | Default and behavior |
| --- | --- | --- |
| `hosts` | List of hostnames | Unrestricted hosts for supported ordinary HTTP(S) links. An empty list disallows absolute link hosts. |
| `mediaHosts` | List of hostnames | Empty. External media blocks by default. |
| `subdomains` | Boolean | False. Set true to include dot-delimited subdomains of listed hosts. |
| `protocolRelative` | Boolean | False. Set true to consider protocol-relative URLs under the configured policy. |
| `entropyThreshold` | Number, greater than 0 up to 6 | Disabled. When set, review long token-like URL segments. Default action is AUDIT. |

| JSON option | Type | Default and behavior |
| --- | --- | --- |
| `required` | List of strings | Empty. Names required on the root object. |
| `fields` | Map of root-property constraints | Empty. Per property, set `type` to string, number, boolean, object, array or null. Set `allowed` to a list of scalar values or `maxLength` to an integer for strings or arrays. |
| `fences`, `prose` | Boolean each | False. Remove a recognized Markdown fence or extract one document from surrounding prose. |
| `trailingCommas`, `unquotedKeys`, `singleQuotes`, `controlCharacters`, `pythonLiterals` | Boolean each | False. Allow the corresponding repairs to recognized syntax. |
| `autoClose`, `undefinedAsNull` | Boolean each | False. Opt-in lossy repair for incomplete containers or undefined values. |

JSON checks enforce a single object or array, reject duplicate and prototype-sensitive keys, and bound nesting and aggregate element count. Field constraints run again after redaction. Repair helpers return `output`, `repaired`, `operations`, `lossy`, `truncated`, `parsed`, and `valid`. Their output can contain raw sensitive values. [Policy details and violation codes](https://github.com/mkkotcherla/llm-output-guard-lite/blob/main/shared/specification/core.md)

### Plugins and audit callbacks

| Plugin option | Type | Default and behavior |
| --- | --- | --- |
| `name` | Unique ASCII identifier | Required. Included as the finding's validator. |
| `validate` | Callable | Required. Receives `output` and `signal` and returns null/None or a finding with `action` (BLOCK or AUDIT) and optional `severity`. |
| `priority` | Integer, −1,000 to 1,000 | 0. Lower values run first. Ties use registration order. |
| `timeoutMs` | Integer, 1–5,000 | 100 ms. Cancellation is cooperative. A synchronous callback can block the caller. |
| `failMode` | `BLOCK` or `AUDIT` | `BLOCK` if execution, timeout, or result validation fails. |

Plugins can see the complete original string. Node gives plugins an `AbortSignal`, and Python supplies an `asyncio.Event`. Use trusted code and async checks with plugins.

An audit callback receives `allowed`, `decision`, `violations`, `auditId`, `latencyMs`, `mode`, and `timestamp`. It may also receive `hypotheticalDecision`, `requestId`, `fingerprint`, and stream statistics. It receives no `sanitizedOutput`. Stream fingerprints are included only for completed sessions. Delivery is best effort, with at most one callback in flight per guard. Python awaitable callbacks require a running event loop.

## Results and errors

| Field | Meaning |
| --- | --- |
| `allowed` | Boolean. Use it to decide whether to deliver the output. |
| `sanitizedOutput` | String. Forward this value when allowed. Blocks return an empty string. |
| `decision` | `ALLOW`, `REDACT`, or `BLOCK`. |
| `violations` | Findings with `code`, `severity`, and `validator`. Matched values and offsets are omitted. |
| `auditId` and `latencyMs` | Generated decision ID and elapsed milliseconds. |
| `hypotheticalDecision` | Optional decision describing enforcement in shadow mode. |

- `OutputGuardConfigurationError` reports invalid settings or synchronous use of an API that requires async plugin handling.
- `OutputGuardBlockedError` carries the blocked `result` from assertion methods, iterator wrappers, or SDK adapters. Plain checks return a blocked result for policy failures, including non-string input.
- `OutputGuardUnsupportedResponseError` reports an unsupported SDK request or response shape. Provider exceptions propagate.
- `TypeError` covers a non-string passed to the JSON repair helper or pushes after finalization starts.

### Stream contract

| Strategy | What consumers receive |
| --- | --- |
| `BUFFERED` | Nothing before the full response passes at finalization. Use it for strict whole-response blocking, JSON, and full-response plugins. |
| `INCREMENTAL` | Validated LF-terminated records, plus the final record. A pending record or possible HTML tail can hold up to 2,048 UTF-16 units. Earlier output may already have been delivered if a later record fails. Uses REDACT and rejects JSON, full-response plugins, or configured literals with LF. |
| `PASSTHROUGH_AUDIT` | Original text before the final audit. Requires SHADOW_AUDIT and excludes JSON and full-response plugins. Use it where original text is acceptable. |

Push strings or UTF-8 byte chunks, using a single chunk kind per session. Node accepts `Uint8Array` (including Buffer). Python accepts bytes, bytearray and memoryview. Each update contains `output` and may include `summary`. Return every emitted fragment in order. A summary has the decision fields other than `sanitizedOutput`, plus `stream.status` (COMPLETED, BLOCKED or ABORTED), `inputBytes`, `emittedBytes`, and `partialEmission` under `stream`. Repeat finalization returns no additional text. Abort discards pending data. [Streaming and integration contract](https://github.com/mkkotcherla/llm-output-guard-lite/blob/main/shared/specification/streaming.md)

### Provider and application boundaries

The adapters support **non-streaming** OpenAI Chat Completions text and refusals, and Anthropic Messages plain-text blocks. They preserve supported response shapes and metadata, enforce size and count limits, and reject unsupported surfaces such as tool calls, mixed media, citations on blocks, or provider-native structured formats. Use a guard directly on text or JSON your application extracts from other provider APIs. The framework examples wire the library into the handler. The application owns authentication, authorization, request limits, provider calls, error responses, renderer sanitization and downstream validation.

The library checks recognizable patterns and supported links or media references. Raw images, audio, and video are outside its inspection scope. URL allowlists cannot establish destination trust or constrain later redirects. Keep renderer-level HTML and Markdown protections in place. [Security limitations and reporting](https://github.com/mkkotcherla/llm-output-guard-lite/blob/main/SECURITY.md)

## Further reading

- [Examples and framework integration](https://github.com/mkkotcherla/llm-output-guard-lite/blob/main/docs/EXAMPLES.md)
- [Compatibility, benchmarks, and verification](https://github.com/mkkotcherla/llm-output-guard-lite/blob/main/docs/OG-01E.md)
- [Contributing and local development](https://github.com/mkkotcherla/llm-output-guard-lite/blob/main/CONTRIBUTING.md)

MIT licensed. Maintained by [Kotcherla Murali Krishna](https://github.com/mkkotcherla).
