KAITO Guardrail Core
kaito-guardrail-core provides KAITO-owned scanners and standard-library-only
streaming utilities. guardrail_core.streaming.sse and
guardrail_core.streaming.openai frame SSE events and parse/build OpenAI chat
chunks; they do not scan or enforce policy.
guardrail_core.streaming.window provides a policy-independent text window for
scan-before-release buffering.
Scanner configuration (0.2.0)
guardrail_core.config exposes scanner schemas, along with
parse_scanner_config() and build_scanner(). Applications
own policy loading and failure handling; they must not recreate a scanner registry.
The following example configures all eight supported scanner types:
from guardrail_core.config import build_scanner, parse_scanner_config
scanner_configs = [
{
"type": "ban_substrings",
"substrings": ["secret"],
"match_type": "word",
"case_sensitive": False,
"contains_all": False,
"action": "redact",
},
{"type": "invisible_text", "action": "redact"},
{
"type": "regex",
"patterns": [r"\bINTERNAL-\d+\b"],
"is_blocked": True,
"match_type": "search",
"action": "block",
},
{
"type": "json",
"required_elements": 1,
"repair": True,
"action": "redact",
},
{
"type": "reading_time",
"max_time": 2.0,
"truncate": True,
"action": "redact",
},
{
"type": "token_limit",
"limit": 4096,
"encoding_name": "cl100k_base",
"action": "block",
},
{"type": "secrets", "redact_mode": "all", "action": "redact"},
{
"type": "sensitive",
"detectors": ["email", "phone", "credit_card", "ip_address"],
"action": "redact",
},
]
scanners = [build_scanner(parse_scanner_config(raw)) for raw in scanner_configs]
result = scanners[0].scan("", "a secret")
assert result.output == "a [REDACTED]"
These are independent configuration examples, not a recommended scanner chain:
choose scanners appropriate to the content (for example, json expects JSON).
Entries use a flattened mapping with type, optional action (block or
redact), and scanner-specific fields. The default action is block. Type and
field names accept snake_case, camelCase, and hyphenated spelling. Scanner order
and policy-level actions remain the caller's responsibility.
The strict parser rejects unknown scanners, unknown or duplicate normalized
fields, invalid actions, and malformed scanner settings with ValueError.
It does not log and skip invalid entries. Construction exceptions from
build_scanner() propagate unchanged. The schema classes retain their existing
from_dict() and build() methods.
Configuration and construction stay in guardrail_core.config; sensitive-data
detection and redaction live in an internal scanner module. Consumers continue
to use the same configuration APIs.
Streaming scanner adapter
ScannerWindowAdapter connects configured scanners to StreamingBufferWindow.
Redactors run before blockers, preserving relative order within each group.
It handles word-boundary context, derives the minimum holdback, and verifies
Secrets redaction before release.
Configurations, including nested lists, are copied at construction; later caller
changes do not affect the adapter.
from guardrail_core.config import parse_scanner_config
from guardrail_core.streaming.scanners import ScannerWindowAdapter
from guardrail_core.streaming.window import StreamingBufferWindow
scanner = ScannerWindowAdapter([
parse_scanner_config({
"type": "ban_substrings",
"substrings": ["secret"],
"action": "redact",
}),
])
window = StreamingBufferWindow(scanner, holdback_len=scanner.holdback_len)
| Scanner | Supported actions | Restrictions |
|---|---|---|
ban_substrings |
block, redact |
word or str; contains_all=False |
invisible_text |
block, redact |
None |
secrets |
block, redact |
Redaction requires redact_mode="all" |
sensitive |
block, redact |
Email, phone, credit card, IPv4 |
Unsupported configurations raise StreamingPolicyError before construction.
Construction errors propagate; scan exceptions are wrapped by the window in
WindowScanError.
Holdback defaults to at least 256 Unicode code points and increases for longer substrings. Smaller explicit bounds are rejected. Detection is limited to the retained window; arbitrary-length Secrets/Sensitive matches are not guaranteed.
Release only chunks returned by the window. Flush only after validated normal completion; discard the window on failure or cancellation. Consumers own stream lifecycle, transport, and refusal responses.
Installation and development
This repository starts from
kaito-project/kaito main at 74d6eeeefe314e91f5c636de10c5b5c21cb21b64.
The original source remains in KAITO during the transition. The distribution
name and import paths are unchanged. Version 0.2.0 introduced the shared scanner
configuration APIs; 0.2.1 extracts the shared streaming scanner adapter. No package is
published by this change. After merge and publication of 0.2.1, production-stack
should pin kaito-guardrail-core==0.2.1.
Install the published package:
python -m pip install kaito-guardrail-core
For local development:
python -m venv .venv
source .venv/bin/activate
python -m pip install -e . -r requirements-dev.txt
python -m build
python -m twine check --strict dist/*
python -m pytest tests
python -m ruff check --output-format=github .
python -m ruff format --check .
CI tests the installed wheel outside the source tree in a fresh environment on
Python 3.12 through 3.14. The distribution name is kaito-guardrail-core;
Python imports use guardrail_core.
The tokenizer dependency uses tiktoken 0.12.0, which provides Python 3.14 wheels.
The older 0.11.0 release cannot build its PyO3 extension on Python 3.14.
Streaming window
guardrail_core.streaming.window retains output tails to detect cross-chunk
matches, releasing only scanner-approved prefixes.
holdback_len is measured in Unicode code points and must be sufficient for the
scanner's cross-chunk matching requirements.
flowchart TD
Feed["feed(text)"] --> Buffer["Buffer text"]
Buffer -->|Exceeds holdback| Scan["Scan entire buffer"]
Buffer -->|Within holdback| Hold["Retain tail"]
Scan -->|Allow / redact| Emit["Release approved prefix; retain tail"]
Scan -->|Block| Block["Discard buffer; stop output"]
Scan -->|Error| Error["Discard buffer; raise WindowScanError"]
EOF["Normal EOF: flush()"] --> Final["Scan remaining text"]
Final -->|Allow / redact| Release["Release remaining text"]
Final -->|Block| Block
Final -->|Error| Error
Fail["Parse failure / cancellation"] --> Discard["Discard window; do not flush"]
Example (prints hello world; replace print with downstream emission):
from guardrail_core.streaming.window import (
StreamingBufferWindow,
WindowScanError,
WindowScanResult,
)
class Scanner:
def scan(
self, text: str, *, flush: bool = False, preceding_char: str = ""
) -> WindowScanResult:
return WindowScanResult(blocked="secret" in text)
window = StreamingBufferWindow(Scanner(), holdback_len=len("secret") - 1)
chunks = ["hello ", "world"]
try:
for text in chunks:
result = window.feed(text)
print("".join(result.chunks), end="")
if result.blocked:
print("[blocked]")
break
else:
result = window.flush()
print("[blocked]" if result.blocked else "".join(result.chunks), end="")
except WindowScanError:
print("[scan failed]")
Use chunks = ["safe se", "cret"] to exercise cross-chunk blocking. Parse errors
and cancellation must propagate without entering the normal-EOF else branch.
Scanner is illustrative; replace it with your scanner adapter. The caller is
responsible for closing the upstream stream and generating product-specific
refusal responses.
Byte-oriented SSE framing
from guardrail_core.streaming.sse import SSEFramer
from guardrail_core.streaming.openai import parse_openai_chat_sse_event
framer = SSEFramer(max_event_bytes=1024 * 1024)
for chunk in [b'data: {"choices":[]}\r', b"\n\r", b"\n"]:
for event in framer.feed(chunk):
result = parse_openai_chat_sse_event(event)
print(result.status, result.payload)
for event in framer.finish():
print(event.data)
Call feed(bytes) in stream order and finish() exactly once at EOF. Both return
lists of complete SSEEvent objects. LF, CRLF, CR, mixed endings, and arbitrary
byte boundaries are supported. Complete events use strict UTF-8 decoding.
EOF never supplies a missing event terminator.
event.raw_bytes: exact received bytes, including line endings and the terminating blank line, suitable for lossless forwarding.event.raw: decoded event body, excluding its final line ending and blank line.event.lines: body lines, including comments and non-data fields.event.data: joined data fields, orNonewhen no data fields exist.SSEEvent.from_raw(text): parse an already decoded event body, without framing; itsraw_bytesdefaults to the UTF-8 encoding of that body.
Errors and resource bounds
SSEFramingError is a ValueError with these subclasses:
| Exception | Meaning |
|---|---|
SSEDecodeError |
A complete event is not valid UTF-8; the original decode error is chained. |
SSEIncompleteEventError |
EOF left an unterminated event, including an incomplete UTF-8 sequence. |
SSEEventTooLargeError |
An event exceeded max_event_bytes (default 1 MiB). |
max_event_bytes must be a positive integer and counts wire bytes, including
delimiters, per event. Invalid limits and non-byte input raise ValueError/TypeError.
On failure, error.raw_bytes contains the failing event's buffered bytes (at most
the limit); error.completed_events retains earlier complete events from the same
call. Callers choose whether to forward them and how to handle failure.
After a framing error or finish(), the framer is unusable; further calls raise
ValueError.
OpenAI parsing contract
parse_openai_chat_sse_event(event) returns OpenAIChatChunkParseResult, retaining
RAGEngine's status names and convenience fields:
| Input | OpenAIChatChunkParseStatus |
|---|---|
| No data field, empty data, or whitespace-only data | NO_DATA |
Data equal to [DONE] after stripping whitespace |
DONE |
| Invalid JSON | MALFORMED_JSON, with error |
| Non-object payload, non-list choices, or non-object choice | INVALID_PAYLOAD, with error |
| Missing/non-integer choice index (including bool) | INVALID_PAYLOAD, with error |
| Missing/null delta | PARSED, treating delta as an empty object |
| Non-object, non-null delta | INVALID_PAYLOAD, with error |
| Missing/null content | PARSED, no text |
| Non-string, non-null content or finish_reason | INVALID_PAYLOAD, with error |
Missing choices |
PARSED, treating choices as an empty list |
| Valid choices, including empty, role-only, and multi-choice chunks | PARSED |
All choices are retained in order, including role-only and tool-call-only chunks;
indexes need not be zero or contiguous. Use parsed_choices for aligned content
and finish reasons, not the filtered contents/finish_reasons lists.
payload preserves the original fields, including invalid object payloads.
SSE builders
The functions in guardrail_core.streaming.openai return UTF-8-encodable strings
with LF delimiters, matching RAGEngine:
build_openai_chat_delta_sse_chunk(content, *, choice_index=0)build_openai_chat_finish_reason_sse_chunk(*, finish_reason="content_filter", choice_index=0)build_sse_done_chunk()build_sse_data_chunk(payload)for arbitrary JSON object fields and choices
Text builders create new minimal chunks; use the generic builder with a retained
payload to preserve metadata, or forward event.raw_bytes for byte-exact replay.
Publishing
Build from the repository root, using pyproject.toml for metadata and version.
Wheels exclude tests; source distributions include tests and build inputs.
Publisher setup
Confirm maintainer access and configure:
- A project or pending publisher on both TestPyPI and PyPI for
kaito-guardrail-core. - A GitHub Trusted Publisher on each index: owner
kaito-project, repositorykaito-guardrail-core, workflow filenamerelease-guardrail-core.yaml, and the corresponding GitHub environment below. Publishing uses GitHub OIDC, not an API token. - GitHub environments
guardrail-core-testpypiandguardrail-core-pypi, restricted tomain. Require maintainer approval forguardrail-core-pypibefore enabling production publishing.
Trusted Publishers and GitHub environments from kaito-project/kaito do not
transfer automatically. Configure them for this repository before running a
release, and coordinate with KAITO maintainers so only one repository publishes
the package. Version 0.1.1 is already published; do not republish it.
Release workflow
After the intended package version merges into main, run the
Release KAITO Guardrail Core workflow:
- Select
main. Setrelease_versionto the metadata version andrelease_committo its full lowercase 40-character SHA onmain; the package tag must not exist. - Build and validate the source distribution and wheel; test the installed wheel outside the source checkout.
- Publish to TestPyPI and verify the downloaded wheel byte-for-byte. Install its dependencies separately from PyPI; do not mix indexes.
- Approve
guardrail-core-pypi, then publish the same stored artifacts to PyPI without rebuilding. - Create
kaito-guardrail-core-v<version>and a GitHub Release for that source commit, attaching the artifacts. Do not mark it as the repository's latest release.
Recovery
For transient failures, rerun only failed jobs in the same run to reuse artifacts. Never overwrite an existing version or rebuild different content under it. Coordinate partial-upload recovery with maintainers; bump the version in a new PR before the next release.
Consumer adoption
Consumers must pin a version already published on production PyPI. Production images install requirements, not library source; editable installs are for development.
Metadata
Release files for kaito-guardrail-core 0.2.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| kaito_guardrail_core-0.2.1.tar.gz | 53.0 kB | With provenance | Details for kaito_guardrail_core-0.2.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| kaito_guardrail_core-0.2.1-py3-none-any.whl | Python 3 | none | any | Details for kaito_guardrail_core-0.2.1-py3-none-any.whl |
Total release size: 89.8 kB
Release files / kaito_guardrail_core-0.2.1.tar.gz
| Download URL | kaito_guardrail_core-0.2.1.tar.gz |
|---|---|
| Size | 53.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
97b0c5f6a637b54af7ec7233b24c268515bfe2880619a9d488c4639e35c25f7d
|
|
BLAKE2b-256 checksum How to use checksums |
a4c7beca3ebfa28e0a003228b06dd9a6578bf6f054b1127f7ca6b56cfdf9e442
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.7
|
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 Nov 4, 2026.
Transparency logRelease files / kaito_guardrail_core-0.2.1-py3-none-any.whl
| Download URL | kaito_guardrail_core-0.2.1-py3-none-any.whl |
|---|---|
| Size | 36.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
cd432e4a7234ab2edffb98a4414994ebabf3b8ec44afc6ac093ac74af2fd333b
|
|
BLAKE2b-256 checksum How to use checksums |
7f772420e945f757f758372e1e11f248655e80787edebb388b77ea0459baff21
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.7
|
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 Nov 4, 2026.
Transparency logSecurity for kaito-guardrail-core 0.2.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.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for kaito_guardrail_core-0.2.1.tar.gz
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 Nov 4, 2026.
Transparency logA 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.