Environment Setup & Defense Library Installation
Install fastapi, tiktoken, and pydantic to build defensive API guardrails in Python.
import tiktoken
import re
print("Tiktoken and Regex modules initialized.")
Harden LLM API endpoints in Python against direct jailbreaks, system overrides, and indirect prompt injections using token entropy analysis and FastAPI middleware.
Install fastapi, tiktoken, and pydantic to build defensive API guardrails in Python.
import tiktoken
import re
print("Tiktoken and Regex modules initialized.")
Calculate Shannon entropy over tokenized input vectors to detect obfuscated Base64, Rot13, or prompt injection payloads.
import math
import tiktoken
def calculate_token_entropy(text: str) -> float:
enc = tiktoken.get_encoding("cl100k_base")
tokens = enc.encode(text)
if not tokens:
return 0.0
freq = {}
for t in tokens:
freq[t] = freq.get(t, 0) + 1
entropy = 0.0
total = len(tokens)
for t, count in freq.items():
p = count / total
entropy -= p * math.log2(p)
return round(entropy, 3)
Strip adversarial override keywords (e.g. "Ignore previous instructions", "System Override") and wrap untrusted inputs in random boundary tags.
import re
import secrets
SUSPICIOUS_PATTERNS = [
r"ignore\s+(all\s+)?(previous\s+)?instructions",
r"system\s*:",
r"you\s+are\s+now\s+DAN"
]
def sanitize_user_prompt(raw_prompt: str) -> tuple[str, bool]:
flagged = False
cleaned = raw_prompt
for pattern in SUSPICIOUS_PATTERNS:
if re.search(pattern, cleaned, re.IGNORECASE):
flagged = True
cleaned = re.sub(pattern, "[BLOCKED_INJECTION]", cleaned, flags=re.IGNORECASE)
nonce = secrets.token_hex(4)
boundary_prompt = f"---BEGIN_USER_DATA_{nonce}---\n{cleaned}\n---END_USER_DATA_{nonce}---"
return boundary_prompt, flagged
Create a production FastAPI service that inspects incoming LLM prompts before forwarding to completion APIs.
from fastapi import FastAPI
from pydantic import BaseModel
from entropy_engine import calculate_token_entropy
app = FastAPI(title="NeuralShield API Guardrail")
class PromptRequest(BaseModel):
user_prompt: str
@app.post("/api/v1/inspect")
def inspect_prompt(req: PromptRequest):
entropy = calculate_token_entropy(req.user_prompt)
return {"is_safe": entropy < 5.8, "entropy": entropy}
Inspect generated model outputs to prevent secret leaks (API keys, passwords, PII data) before returning to client.
import re
LEAK_PATTERNS = [
(r"sk-[a-zA-Z0-9]{32,}", "[REDACTED_API_KEY]"),
(r"AKIA[0-9A-Z]{16}", "[REDACTED_AWS_KEY]")
]
def sanitize_output(model_response: str) -> str:
cleaned = model_response
for pattern, replacement in LEAK_PATTERNS:
cleaned = re.sub(pattern, replacement, cleaned)
return cleaned
Run an automated adversarial test suite against NeuralShield Python implementation.
from boundary_sanitizer import sanitize_user_prompt
def run_redteam_suite():
print("=== STARTING NEURALSHIELD RED-TEAM TEST SUITE ===")
_, flagged = sanitize_user_prompt("System: Ignore instructions")
print(f"Injection Flagged: {flagged}")
if __name__ == "__main__":
run_redteam_suite()