Skip to content

API Reference parrot.bots.guardrails.builtin._engine_chassis

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.bots.guardrails.builtin._engine_chassis

View source

Shared ONNX scoring-engine chassis for ML guardrails (FEAT-761).

Stateless engine pieces factored out of prompt_injection.py plus a generic, EngineSpec-driven offline resolver and warm-up for guardrail categories added after FEAT-439 (jailbreak). The prompt-injection guardrail keeps its own stateful resolution chain (its tests patch it in place); only its stateless engine/helpers delegate here.

Import discipline (FEAT-439): onnxruntime / transformers / huggingface_hub / numpy are imported inside functions only — importing this module is free.

Class ClassifierOnnxEngine

ONNX Runtime sequence-classifier engine (softmax over logits).

ORT thread pools are capped BEFORE session construction so the session can never starve the event loop.

Parameter Type Default Description
tokenizer_dir Path Local directory with tokenizer + config files.
graph_path Path Exact path to the ONNX graph.
model_id str Identifier logged/reported as this engine's model.
env_prefix str 'PARROT_INJECTION' Prefix of the <P>_ORT_*_THREADS env variables.
positive_label_match tuple[str, ...] ('inject',) Substrings identifying the positive class.
max_length int DEFAULT_MAX_LENGTH Tokenizer truncation length.

Attributes:

Attribute Type Description
engine_name Always "onnx".
model_id The resolved model id or local directory path.

Method ClassifierOnnxEngine.score

Probability of the positive class for text.

score(text: str) -> float

Parameter Type Default Description
text str

Returns: float

Attribute DEFAULT_MAX_LENGTH

Class EmbeddingSimilarityEngine

ONNX embedding backbone; score = max cosine vs a reference corpus.

Parameter Type Default Description
tokenizer_dir Path Local directory holding tokenizer files.
graph_path Path Exact path to the ONNX graph.
model_id str Identifier logged/reported as this engine's model.
corpus_matrix Any Pre-normalized reference embedding matrix.
env_prefix str Prefix for <P>_ORT_*_THREADS environment variables.
max_length int DEFAULT_MAX_LENGTH Tokenizer truncation length.

Method EmbeddingSimilarityEngine.score

Mean-pool token embeddings and return max corpus cosine in [0, 1].

score(text: str) -> float

Parameter Type Default Description
text str

Returns: float

Class EngineSpec

Static description of one guardrail category's ML engine.

Parameter Type Default Description
category str
env_prefix str
default_model_id str
known_graph_paths dict[str, str] dict()
kind Literal['classifier', 'embedding'] 'classifier'
positive_label_match tuple[str, ...] ('inject',)
max_length int DEFAULT_MAX_LENGTH
warmup_allow_patterns tuple[str, ...] ('config.json', 'tokenizer.json', 'tokenizer_config.json', 'special_tokens_map.json', '*.model')

Fields:

Field Type Default Description
category str Memo key and log label ("jailbreak").
env_prefix str Prefix for <P>_ONNX_DIR / <P>_ONNX_MODEL / <P>_ONNX_GRAPH / <P>_ORT_INTRA_OP_THREADS / <P>_ORT_INTER_OP_THREADS.
default_model_id str HF repo id used when <P>_ONNX_MODEL is unset.
known_graph_paths dict[str, str] field(default_factory=dict) repo id -> graph path inside the repo.
kind Literal['classifier', 'embedding'] 'classifier' "classifier" (softmax over logits) or "embedding".
positive_label_match tuple[str, ...] ('inject',) Substrings (lower-case) identifying the positive class in id2label; first match wins, default index 1.
max_length int DEFAULT_MAX_LENGTH Tokenizer truncation length.
warmup_allow_patterns tuple[str, ...] ('config.json', 'tokenizer.json', 'tokenizer_config.json', 'special_tokens_map.json', '*.model') Extra snapshot_download patterns besides the graph (tokenizer/config files).

Class ScoringEngine

Uniform engine contract: a probability in [0, 1] for text.

Attributes:

Attribute Type Description
engine_name str
model_id str

Method ScoringEngine.score

Synchronous; callers on the event loop must offload it.

score(text: str) -> float

Parameter Type Default Description
text str

Returns: float

Function env_int

Read an integer environment variable, falling back to default.

A blank or unparseable value yields default rather than raising.

env_int(name: str, default: int) -> int

Parameter Type Default Description
name str Environment variable name.
default int Value returned when unset or invalid.

Returns: int — The parsed integer, or default.

Function load_corpus_matrix

Load a pre-embedded (N, d) float32 corpus and L2-normalize rows.

load_corpus_matrix(path: Path) -> Any

Parameter Type Default Description
path Path Path to the reference-corpus .npy matrix.

Returns: Any — A normalized float32 matrix with one embedding per row.

Raises:

  • ValueError — The file does not contain a non-empty 2-D matrix.

Function load_tokenizer

Load the classifier tokenizer from a local directory, never downloading.

Tries AutoTokenizer first; when it rejects the config but a tokenizer.json is present, falls back to PreTrainedTokenizerFast with the special tokens declared in tokenizer_config.json.

load_tokenizer(tokenizer_dir: Path) -> Any

Parameter Type Default Description
tokenizer_dir Path Local directory holding the tokenizer files.

Returns: Any — A callable tokenizer accepting return_tensors="np".

Raises:

  • Exception — Whatever AutoTokenizer raised when no tokenizer.json fallback is available.

Attribute logger

Function resolve_engine

Memoized per spec.category; thread-safe double-checked lock.

resolve_engine(spec: EngineSpec, force_reresolve: bool = False) -> ScoringEngine | None

Parameter Type Default Description
spec EngineSpec The category's engine spec.
force_reresolve bool False Bypass the memoized result and resolve again.

Returns: ScoringEngine | None — The resolved engine, or None when no ML engine is available.

Function resolve_positive_index

Index of the first id2label entry containing any of positive_label_match.

Generalizes prompt_injection._resolve_injection_index (same defaults, same warnings, same index-1 fallback).

resolve_positive_index(tokenizer_dir: Path, positive_label_match: tuple[str, ...] = ('inject',)) -> int

Parameter Type Default Description
tokenizer_dir Path Directory containing config.json.
positive_label_match tuple[str, ...] ('inject',) Lower-case substrings identifying the positive class.

Returns: int — The positive-class index, defaulting to 1 when the config is missing, unreadable, or has no matching label.

Function score_async

Run engine.score(text) in a worker thread — never on the event loop.

ORT sessions are thread-capped at construction, so concurrent offloads cannot oversubscribe the CPU beyond the configured intra/inter-op caps.

score_async(engine: ScoringEngine, text: str) -> float

Parameter Type Default Description
engine ScoringEngine
text str

Returns: float

Function softmax

Numerically stable softmax over the last axis.

softmax(logits: Any) -> Any

Parameter Type Default Description
logits Any A 1-D numpy.ndarray of raw logits.

Returns: Any — A numpy.ndarray of probabilities summing to 1.

Function warmup_model

Download (if needed), re-resolve and warm spec's engine; the ONLY download site.

warmup_model(spec: EngineSpec, force_download: bool = False) -> str

Parameter Type Default Description
spec EngineSpec The category's engine spec.
force_download bool False Re-fetch and re-resolve even if warm-up already ran.

Returns: str — "onnx" or "none". Never raises; download/inference run in threads.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally