Skip to content

API Reference parrot.bots.guardrails.builtin.prompt_injection

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

parrot.bots.guardrails.builtin.prompt_injection

View source

PromptInjectionGuardrail — the legacy _sanitize_question flow as a plugin.

Encapsulates the prompt-injection detection/mitigation flow previously hardcoded in AbstractBot._sanitize_question (bots/abstract.py:1866-1971) as a self-contained INPUT Guardrail. See sdd/specs/guardrails-infrastructure.spec.md §3 Module 2 (FEAT-396).

Critical constraint: this module owns the pytector/torch import boundary — entirely. pytector is detected via importlib.util.find_spec and, if available, the process-wide shared detector singleton below is used — lazily, only inside __init__, and only when THIS guardrail is actually instantiated (i.e. only when a bot registers "prompt_injection", via the explicit guardrails=[...] kwarg or the legacy injection_detection flag). Neither this module nor parrot.bots.guardrails import pytector/torch at module import time.

FEAT-396 (TASK-2028): the singleton used to live in parrot.bots.abstract (loaded unconditionally whenever pytector was installed, regardless of injection_detection) — it has been moved here in full, so the pytector import boundary has exactly one owner.

FEAT-439 (TASK-2307): the same import-boundary discipline now also covers onnxruntime/transformers/huggingface_hub for the ONNX scoring engine — all imported lazily, only inside the engine-construction functions below, never at module import time.

FEAT-439 (TASK-2309): warmup_injection_model() is the ONLY code path in this feature permitted to download the ONNX graph (~560 MB fp32 for the default wolf-defender model, ~700 MB for DeBERTa v2). There is no generic "warm up all models" bot/host hook to attach this to (unlike embeddings' AbstractBot.warmup_embeddings, which is embedding-specific and wired into exactly one call site) — long-lived hosts call await warmup_injection_model() explicitly at startup, e.g.::

from parrot.bots.guardrails.builtin.prompt_injection import (
    warmup_injection_model,
)
await warmup_injection_model()

Alias ClassifierOnnxEngine

Re-exported from parrot.bots.guardrails.builtin._engine_chassis.ClassifierOnnxEngine.

Alias Guardrail

Re-exported from parrot.bots.guardrails.base.Guardrail.

Alias GuardrailAction

Re-exported from parrot.bots.guardrails.base.GuardrailAction.

Alias GuardrailContext

Re-exported from parrot.bots.guardrails.base.GuardrailContext.

Alias GuardrailResult

Re-exported from parrot.bots.guardrails.base.GuardrailResult.

Alias GuardrailStage

Re-exported from parrot.bots.guardrails.base.GuardrailStage.

Alias InjectionScoringEngine

Re-exported from parrot.security.prompt_injection.InjectionScoringEngine.

Alias PromptInjectionDetector

Re-exported from parrot.security.prompt_injection.PromptInjectionDetector.

Class PromptInjectionGuardrail

INPUT guardrail wrapping the prompt-injection detection/mitigation flow.

Mirrors AbstractBot._sanitize_question exactly: 1. Trusted-source bypass (ctx.extras["trusted_source"]). 2. strict_mode bypass. 3. Framework-pattern stripping before scanning. 4. pytector detection (if installed) else the regex/keyword engine. 5. Security-event logging for any detected threat. 6. BLOCK (category reason only) when block_on_threat and severity is CRITICAL/HIGH; otherwise TRANSFORM — the flagged input is wrapped in an untrusted-content marker, exactly as _wrap_flagged_input does today.

Parameter Type Default Description
strict_mode bool True When False, check() is a no-op PASS (mirrors the legacy strict_mode ctor flag).
block_on_threat bool False When True, CRITICAL/HIGH threats produce BLOCK; otherwise they produce a TRANSFORM (wrapped) result. Also selects on_error (fail_closed vs fail_open).
injection_probability_threshold float 0.98 Minimum pytector probability required to treat input as an injection.
scan_tool_output bool False When True, also inspect TOOL_OUTPUT content. Threats at that stage always produce TRANSFORM, never BLOCK.
**kwargs Any {} Accepted and ignored, for forward-compat with extra policy keys passed via guardrails=[{"name": ..., ...}].

Attributes:

Attribute Type Description
stages set
strict_mode Mirrors the legacy strict_mode ctor flag.
block_on_threat Mirrors the legacy block_on_threat ctor flag.
injection_probability_threshold Mirrors the legacy pytector probability threshold.

Method PromptInjectionGuardrail.check

Run the prompt-injection flow against content.

check(content: str, ctx: GuardrailContext) -> GuardrailResult

Parameter Type Default Description
content str The user input to inspect.
ctx GuardrailContext Call context. ctx.extras["trusted_source"] (bool) skips the check entirely (agent-to-agent calls); ctx.extras ["chatbot_id"] and ctx.extras["context"] are forwarded to security-event logging when present.

Returns: GuardrailResult — PASS when clean (or bypassed); TRANSFORM with the untrusted-content-wrapped text for non-blocking threats; BLOCK (category reason only, never content) for blocking threats.

Alias SecurityEventLogger

Re-exported from parrot.security.prompt_injection.SecurityEventLogger.

Alias ThreatLevel

Re-exported from parrot.security.prompt_injection.ThreatLevel.

Alias env_int

Re-exported from parrot.bots.guardrails.builtin._engine_chassis.env_int.

Alias load_tokenizer

Re-exported from parrot.bots.guardrails.builtin._engine_chassis.load_tokenizer.

Attribute logger

Alias max_threat_level

Re-exported from parrot.security.prompt_injection.max_threat_level.

Alias resolve_positive_index

Re-exported from parrot.bots.guardrails.builtin._engine_chassis.resolve_positive_index.

Alias score_async

Re-exported from parrot.bots.guardrails.builtin._engine_chassis.score_async.

Alias softmax

Re-exported from parrot.bots.guardrails.builtin._engine_chassis.softmax.

Function warmup_injection_model

Resolve, (down)load, and warm the injection classifier.

The ONLY code path permitted to download the model. Downloads, session construction, and the dummy inference all run via asyncio.to_thread so warm-up itself never blocks the event loop. Safe to call multiple times; subsequent calls (without force_download) are a fast no-op. Concurrent callers serialize on an internal lock, so at most one download happens even under concurrent invocation. Never raises: a failed download or resolution step logs loudly and returns whatever engine still resolves ("pytector" or "regex") — hosts must start even fully offline.

warmup_injection_model(force_download: bool = False) -> str

Parameter Type Default Description
force_download bool False Re-fetch the graph and re-resolve even if warm-up already ran.

Returns: str — The name of the engine that ended up selected: "onnx", "pytector", or "regex".

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