Skip to main content

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 Python 3.10+ License: MIT Runtime dependencies: 0

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.

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

Quick start

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.

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

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)

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

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

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

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

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

Further reading

MIT licensed. Maintained by Kotcherla Murali Krishna.

Metadata

Release files for llm-output-guard-lite 0.1.1

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

Source distribution (sdist)

Source distribution for llm-output-guard-lite 0.1.1
File Size Uploaded Provenance Actions
llm_output_guard_lite-0.1.1.tar.gz 23.6 kB Without provenance Details for llm_output_guard_lite-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for llm-output-guard-lite 0.1.1
File Interpreter ABI Platform Actions
llm_output_guard_lite-0.1.1-py3-none-any.whl Python 3 none any Details for llm_output_guard_lite-0.1.1-py3-none-any.whl

Total release size: 51.8 kB

Release files / llm_output_guard_lite-0.1.1.tar.gz

Download URL llm_output_guard_lite-0.1.1.tar.gz
Size 23.6 kB
Tags Source
SHA-256 checksum
How to use checksums
15a91ef6132afb4023c521eeb3ebd0d73790bfcaa242b48cdc5d5613584bfeed
BLAKE2b-256 checksum
How to use checksums
39ea3330089aaf2eba283663b67945f6d003c0a6829ba1f059598961e617579d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.8

Release files / llm_output_guard_lite-0.1.1-py3-none-any.whl

Download URL llm_output_guard_lite-0.1.1-py3-none-any.whl
Size 28.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
bbbf00f738e315dbf7c48be07b98d2e34c1bb21b8591e2dd0d6699114d07577a
BLAKE2b-256 checksum
How to use checksums
84bf85fbb80712329761f18c5bd83a004f36bf4916522d3426b11bfccd5e8153
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.8

Security for llm-output-guard-lite 0.1.1

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.1 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