Skip to content

API Reference parrot.security.prompt_injection

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

parrot.security.prompt_injection

View source

Prompt Injection Detection and Protection.

Class InjectionScoringEngine

Public contract of a resolved ML prompt-injection scorer.

score returns an injection probability in [0, 1]. Implementations are thread-safe and must be called off the event loop (asyncio.to_thread).

Attributes:

Attribute Type Description
engine_name str
model_id str

Method InjectionScoringEngine.score

Return the injection probability for text.

score(text: str) -> float

Parameter Type Default Description
text str

Returns: float

Class PromptInjectionDetector

Detects and mitigates prompt injection attempts in user questions.

Parameter Type Default Description
logger Optional[logging.Logger] None
allowlist Optional[List[re.Pattern]] None

Attributes:

Attribute Type Description
DEFAULT_FRAMEWORK_ALLOWLIST List[re.Pattern]
framework_allowlist List[re.Pattern]

Method PromptInjectionDetector.add_framework_allowlist

Register an additional framework-added pattern to pre-strip.

Accepts either a compiled :class:re.Pattern or a raw regex string (compiled with re.IGNORECASE | re.DOTALL).

add_framework_allowlist(pattern: re.Pattern | str) -> None

Parameter Type Default Description
pattern re.Pattern | str

Method PromptInjectionDetector.strip_framework_patterns

Remove framework-injected patterns before scanning.

Returned text is what the detectors should scan; the original text must still flow to the LLM untouched. This prevents false positives when the wrapper itself injects XML metadata that resembles role impersonation to an ML classifier.

strip_framework_patterns(text: str) -> str

Parameter Type Default Description
text str

Returns: str

Method PromptInjectionDetector.detect_threats

Scan text for prompt injection patterns.

Framework-injected metadata (see :attr:DEFAULT_FRAMEWORK_ALLOWLIST) is stripped before scanning so that our own enrichments don't trigger the detector.

detect_threats(text: str) -> List[Dict[str, Any]]

Parameter Type Default Description
text str

Returns: List[Dict[str, Any]] — List of detected threats with details

Method PromptInjectionDetector.sanitize

Sanitize text by replacing detected patterns.

sanitize(text: str, strict: bool = True, replacement: str = '[FILTERED_CONTENT]') -> Tuple[str, List[Dict[str, Any]]]

Parameter Type Default Description
text str Input text to sanitize
strict bool True If True, replace patterns; if False, only detect
replacement str '[FILTERED_CONTENT]' Text to use for replacements

Returns: Tuple[str, List[Dict[str, Any]]] — Tuple of (sanitized_text, detected_threats)

Class PromptInjectionException

Raised when a critical prompt injection is detected in strict mode.

Parameter Type Default Description
message str
threats List[Dict]
original_input str

Class SecurityEventLogger

Logs security events with session tracking.

Parameter Type Default Description
db_pool None
logger Optional[logging.Logger] None

Method SecurityEventLogger.log_injection_attempt

Log a detected prompt injection attempt.

log_injection_attempt(user_id: str, session_id: str, chatbot_id: str, threats: List[Dict[str, Any]], original_input: str, sanitized_input: str, metadata: Optional[Dict[str, Any]] = None)

Parameter Type Default Description
user_id str
session_id str
chatbot_id str
threats List[Dict[str, Any]]
original_input str
sanitized_input str
metadata Optional[Dict[str, Any]] None

Method SecurityEventLogger.log_security_category_event

Log a security detection WITHOUT any input/output/prompt text (FEAT-761).

Used by the jailbreak and prompt-leakage guardrails, whose offending content may be the system prompt itself. The signature deliberately has no content parameter. Never raises (DB failures are logged).

log_security_category_event(*, category: str, severity: ThreatLevel, score: Optional[float] = None, user_id: Optional[str] = None, session_id: Optional[str] = None, chatbot_id: Optional[str] = None, counts: Optional[Dict[str, int]] = None) -> None

Parameter Type Default Description
category str Detection category ("jailbreak", "prompt_leakage").
severity ThreatLevel Highest severity of the detection.
score Optional[float] None Optional model/matcher score in [0, 1].
user_id Optional[str] None Requesting user, "anonymous" when unknown.
session_id Optional[str] None Session, "unknown" when unknown.
chatbot_id Optional[str] None Bot identifier.
counts Optional[Dict[str, int]] None Non-content counters (e.g. {"matched_segments": 2}).

Attribute THREAT_LEVEL_ORDER

Type: Dict[ThreatLevel, int]

Class ThreatLevel

Severity levels for detected threats.

Function get_injection_scoring_engine

Return the process-wide ML engine the PromptInjectionGuardrail uses, or None (regex only).

The resolution chain lives in parrot.bots.guardrails.builtin.prompt_injection, which owns the pytector/onnxruntime import boundary; it is imported lazily here so parrot.security never imports parrot.bots at module import time. Import and resolution run with stdout redirected to stderr: pytector prints a "Loading Hugging Face model …" banner on first use, and a caller serving a stdio JSON-RPC channel (parrot mcp-local) must never see it on stdout. Never raises.

get_injection_scoring_engine(force_reresolve: bool = False) -> Optional[InjectionScoringEngine]

Parameter Type Default Description
force_reresolve bool False

Returns: Optional[InjectionScoringEngine]

Attribute logger

Function max_threat_level

Return the highest-severity level across threats.

max_threat_level(threats: List[Dict[str, Any]], default: ThreatLevel = ThreatLevel.LOW) -> ThreatLevel

Parameter Type Default Description
threats List[Dict[str, Any]] Threat dicts as produced by :meth:PromptInjectionDetector.detect_threats / :meth:PromptInjectionDetector.sanitize, or by any other detector. Each may carry a 'level' key holding a :class:ThreatLevel or its string value.
default ThreatLevel ThreatLevel.LOW Level returned for an empty list, and the rank assigned to a threat whose 'level' is missing or unrecognized.

Returns: ThreatLevel — The member of :class:ThreatLevel with the highest data:THREAT_LEVEL_ORDER rank. Never raises, for any input shape: this runs on a fail-open guardrail path, where an exception means the threat is silently dropped.

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