Skip to main content

Installation

pip install raxe

Basic Usage

from raxe import Raxe

# Initialize
raxe = Raxe()

# Scan a prompt
result = raxe.scan("Ignore all previous instructions")

# Check for threats
if result.has_threats:
    print(f"Threat detected!")
    print(f"Severity: {result.severity}")
    print(f"Total detections: {result.total_detections}")

ScanPipelineResult Object

The scan() method returns a ScanPipelineResult:
result = raxe.scan("test prompt")

# Boolean evaluation - True when SAFE
if result:  # True when no threats
    print("Safe to proceed")
else:
    print("Threat detected")

# Properties
result.has_threats        # bool: True if any threat detected
result.severity           # str | None: "critical", "high", "medium", "low", "info"
result.total_detections   # int: Number of detections (L1 + L2)
result.detections         # list[Detection]: All L1 detections
result.duration_ms        # float: Total scan time in milliseconds
result.should_block       # bool: True if policy says to block
result.l1_detections      # int: Count of L1 detections
result.l2_detections      # int: Count of L2 predictions
result.text_hash          # str: SHA256 hash of scanned text

Detection Object

Each detection contains:
for detection in result.detections:
    detection.rule_id      # str: "pi-001"
    detection.rule_version # str: "1.0.0"
    detection.severity     # Severity: Severity.HIGH
    detection.confidence   # float: 0.95
    detection.category     # str: "PI"
    detection.matches      # list[Match]: Matched text spans

Match Object

for detection in result.detections:
    for match in detection.matches:
        match.matched_text   # str: The matched content
        match.start          # int: Start position
        match.end            # int: End position

Configuration Options

from raxe import Raxe

raxe = Raxe(
    # API key (optional - reads from config or env if not provided)
    api_key="raxe_...",

    # Telemetry
    telemetry=True,        # Enable privacy-preserving telemetry

    # Detection layers
    l2_enabled=True,       # Enable ML detection (L2)

    # L2 voting preset
    voting_preset="balanced",  # balanced, high_security, low_fp
)

Decorator Pattern

Protect functions automatically:
from raxe import Raxe

raxe = Raxe()

@raxe.protect
def generate_response(prompt: str) -> str:
    """Scanned before execution"""
    return llm.generate(prompt)

# Usage
try:
    response = generate_response(user_input)
except RaxeBlockedError as e:
    print(f"Blocked: {e.severity}")

Custom Threat Handling

from raxe import Raxe

raxe = Raxe()

def process_with_custom_logic(user_input: str) -> str:
    result = raxe.scan(user_input)

    if result.has_threats:
        severity = result.severity

        if severity == "critical":
            # Block and alert
            alert_security_team(result)
            return "Request blocked."

        elif severity == "high":
            # Log and proceed with caution
            log_suspicious_activity(result)
            return generate_with_guardrails(user_input)

        else:
            # Low/Medium - just log
            log_detection(result)

    return generate_normally(user_input)

Context Manager

Ensures proper cleanup:
from raxe import Raxe

with Raxe() as raxe:
    result = raxe.scan("test prompt")
    # Process result...
# Telemetry automatically flushed on exit

Error Handling

from raxe import Raxe
from raxe.sdk.exceptions import RaxeBlockedError, RaxeException

raxe = Raxe()

try:
    result = raxe.scan(user_input, block_on_threat=True)
except RaxeBlockedError as e:
    # Threat was blocked by policy
    print(f"Blocked: {e.result.severity}")
    print(f"Detections: {e.result.total_detections}")
except RaxeException as e:
    # Other RAXE errors
    print(f"Error: {e}")

Filtering Detections

from raxe.domain.rules.models import Severity

result = raxe.scan(user_input)

# Filter by category
pi_threats = [d for d in result.detections if d.category == "prompt_injection"]
pii_threats = [d for d in result.detections if d.category == "pii"]

# Filter by severity (using enum)
critical = [d for d in result.detections if d.severity == Severity.CRITICAL]

# Filter by confidence
high_confidence = [d for d in result.detections if d.confidence >= 0.9]

Multi-Tenant Scanning

For multi-customer deployments, pass tenant_id and app_id to resolve tenant-specific policies:
from raxe import Raxe

raxe = Raxe()

# Scan with tenant context
result = raxe.scan(
    "Ignore all previous instructions",
    tenant_id="acme",      # Customer tenant
    app_id="chatbot",      # App within tenant
)

# Policy attribution for billing/audit
print(f"Policy: {result.metadata['effective_policy_id']}")
print(f"Mode: {result.metadata['effective_policy_mode']}")
print(f"Source: {result.metadata['resolution_source']}")

Override Policy Per-Request

# Override the tenant/app default policy
result = raxe.scan(
    prompt,
    tenant_id="acme",
    app_id="chatbot",
    policy_id="strict"  # Force strict mode for this request
)
See Multi-Tenant Policies for full documentation.

Thread Safety

The Raxe client is thread-safe:
from concurrent.futures import ThreadPoolExecutor
from raxe import Raxe

raxe = Raxe()  # Single instance

def scan_prompt(prompt: str):
    return raxe.scan(prompt)

with ThreadPoolExecutor(max_workers=10) as executor:
    results = list(executor.map(scan_prompt, prompts))