

Based on Dragos Research: AI inference providers failed to detect hacking and prompt theft. This guide implements defensive monitoring, anomaly detection, and secure inference patterns to address these gaps.
| Service | Purpose | Setup Link |
|---|---|---|
| AI Inference Provider (OpenAI, Anthropic, Cohere, or self-hosted) | Target inference endpoints to monitor | OpenAI • Anthropic • Cohere |
| Observability Platform (Datadog, Grafana Cloud, or self-hosted Prometheus/Grafana) | Metrics, logs, traces aggregation | Datadog • Grafana Cloud |
| SIEM/Log Aggregation (Splunk, Elastic, or Loki) | Security event correlation | Elastic Cloud • Splunk |
| Secrets Manager (AWS Secrets Manager, HashiCorp Vault, 1Password) | API key rotation & storage | AWS Secrets Manager • Vault |
# Python 3.11+ required
python3 --version # >= 3.11.0
# Node.js 20+ required
node --version # >= 20.0.0
# Docker for containerized deployment
docker --version
# Infrastructure as Code (optional)
terraform --version # >= 1.6.0
# Create isolated environment
python3 -m venv .venv
source .venv/bin/activate
# Upgrade packaging tools
pip install --upgrade pip setuptools wheel
# Core dependencies
pip install \
openai>=1.12.0 \
anthropic>=0.18.0 \
cohere>=4.37 \
httpx>=0.26.0 \
pydantic>=2.5.0 \
pydantic-settings>=2.1.0 \
prometheus-client>=0.19.0 \
structlog>=24.1.0 \
python-json-logger>=2.0.7 \
tenacity>=8.2.3 \
cryptography>=42.0.0 \
python-dotenv>=1.0.0
# Security & monitoring
pip install \
opentelemetry-api>=1.22.0 \
opentelemetry-sdk>=1.22.0 \
opentelemetry-exporter-otlp>=1.22.0 \
opentelemetry-instrumentation-openai>=0.42b0 \
opentelemetry-instrumentation-httpx>=0.42b0 \
bandit[toml]>=1.7.7 \
safety>=2.3.5
# Development tools
pip install \
pytest>=7.4.0 \
pytest-asyncio>=0.23.0 \
pytest-cov>=4.1.0 \
ruff>=0.1.14 \
mypy>=1.7.0 \
pre-commit>=3.6.0
# Initialize project
npm init -y
# Core dependencies
npm install \
openai@^4.52.0 \
@anthropic-ai/sdk@^0.24.0 \
cohere-ai@^7.8.0 \
axios@^1.7.0 \
zod@^3.23.0 \
pino@^9.0.0 \
pino-pretty@^11.0.0 \
prom-client@^15.1.0 \
@opentelemetry/api@^1.8.0 \
@opentelemetry/sdk-node@^0.52.0 \
@opentelemetry/auto-instrumentations-node@^0.44.0 \
@opentelemetry/exporter-trace-otlp-grpc@^0.52.0 \
@opentelemetry/exporter-metrics-otlp-grpc@^0.52.0 \
@opentelemetry/resources@^1.24.0 \
@opentelemetry/semantic-conventions@^1.24.0
# Development dependencies
npm install -D \
typescript@^5.4.0 \
tsx@^4.11.0 \
vitest@^1.6.0 \
@types/node@^20.12.0 \
eslint@^8.57.0 \
@typescript-eslint/eslint-plugin@^7.0.0 \
@typescript-eslint/parser@^7.0.0 \
prettier@^3.2.0 \
husky@^9.0.0
.env.example (copy to .env and fill in)
# AI Provider API Keys (rotate regularly!)
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
COHERE_API_KEY=...
# Observability
OTEL_EXPORTER_OTLP_ENDPOINT=https://otel.your-domain.com:4317
OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer <token>"
OTEL_SERVICE_NAME=icarax-ai-inference-monitor
OTEL_RESOURCE_ATTRIBUTES="deployment.environment=production,service.namespace=security"
# Prometheus/Grafana
PROMETHEUS_PUSHGATEWAY_URL=https://pushgateway.your-domain.com
GRAFANA_API_KEY=...
# Security
ENCRYPTION_KEY=base64-encoded-32-byte-key
AUDIT_LOG_WEBHOOK=https://siem.your-domain.com/api/events
ALERT_WEBHOOK=https://alerts.your-domain.com/webhook
# Rate limiting & thresholds
MAX_PROMPT_LENGTH=32000
MAX_TOKENS_PER_MINUTE=100000
ANOMALY_THRESHOLD_SCORE=0.85
PROMPT_SIMILARITY_THRESHOLD=0.92
pyproject.toml (Python project config)
[project]
name = "icarax-inference-security"
version = "1.0.0"
description = "AI Inference Security Monitoring & Prompt Theft Detection"
requires-python = ">=3.11"
dependencies = [
"openai>=1.12.0",
"anthropic>=0.18.0",
"cohere>=4.37",
"httpx>=0.26.0",
"pydantic>=2.5.0",
"pydantic-settings>=2.1.0",
"prometheus-client>=0.19.0",
"structlog>=24.1.0",
"python-json-logger>=2.0.7",
"tenacity>=8.2.3",
"cryptography>=42.0.0",
"python-dotenv>=1.0.0",
"opentelemetry-api>=1.22.0",
"opentelemetry-sdk>=1.22.0",
"opentelemetry-exporter-otlp>=1.22.0",
"opentelemetry-instrumentation-openai>=0.42b0",
"opentelemetry-instrumentation-httpx>=0.42b0",
]
[project.optional-dependencies]
dev = [
"pytest>=7.4.0",
"pytest-asyncio>=0.23.0",
"pytest-cov>=4.1.0",
"ruff>=0.1.14",
"mypy>=1.7.0",
"pre-commit>=3.6.0",
"bandit[toml]>=1.7.7",
"safety>=2.3.5",
]
[tool.ruff]
line-length = 100
target-version = "py311"
select = ["E", "F", "I", "W", "UP", "B", "C4", "SIM", "T20", "PTH", "ERA", "PD", "PGH", "PL", "TRY", "NPY", "RSE", "RET", "FLY", "INP", "ASYNC", "ARG", "TCH", "INT", "PIE", "TID", "LOG", "EXE", "FURB", "PERF", "QF", "COM", "ISC", "ICN", "PT", "REF", "SLF", "SLOT", "T10", "ERA001", "PTH118", "PTH120", "B006", "B007", "B008", "B009", "B011", "B015", "S101", "S102", "S103", "S104", "S105", "S106", "S107", "S108", "S109", "S110", "S112", "S113", "S201", "S301", "S302", "S303", "S304", "S305", "S306", "S307", "S308", "S309", "S310", "S311", "S312", "S313", "S314", "S315", "S316", "S317", "S318", "S319", "S320", "S321", "S322", "S323", "S324", "S401", "S402", "S403", "S404", "S405", "S406", "S407", "S408", "S409", "S410", "S501", "S502", "S503", "S504", "S505", "S506", "S507", "S508", "S601", "S602", "S603", "S604", "S605", "S606", "S607", "S607", "S608", "S701", "S702", "S703", "S704", "S705", "S706", "S707", "S708", "S709", "S710", "S711", "S712", "S713", "S714", "S715", "S716", "S717", "S718", "S719", "S720", "S721", "S722", "S723", "S724", "S725", "S726", "S727", "S728", "S729", "S730", "S731", "S732", "S733", "S734", "S735", "S736", "S737", "S738", "S739", "S740", "S741", "S742", "S743", "S744", "S745", "S746", "S747", "S748", "S749", "S750", "S751", "S752", "S753", "S754", "S755", "S756", "S757", "S758", "S759", "S760", "S761", "S762", "S763", "S764", "S765", "S766", "S767", "S768", "S769", "S770", "S771", "S772", "S773", "S774", "S775", "S776", "S777", "S777", "S778", "S779", "S780", "S781", "S782", "S783", "S784", "S785", "S786", "S787", "S788", "S789", "S790", "S791", "S792", "S793", "S794", "S795", "S796", "S797", "S798", "S799", "S800", "S801", "S802", "S803", "S804", "S805", "S806", "S807", "S808", "S809", "S810", "S811", "S812", "S813", "S814", "S815", "S816", "S817", "S818", "S819", "S820", "S821", "S822", "S823", "S824", "S825", "S826", "S827", "S828", "S829", "S830", "S831", "S832", "S833", "S834", "S835", "S836", "S837", "S838", "S839", "S840", "S841", "S842", "S843", "S844", "S844", "S845", "S846", "S847", "S848", "S849", "S850", "S851", "S852", "S853", "S854", "S855", "S856", "S857", "S858", "S859", "S860", "S861", "S862", "S863", "S864", "S865", "S866", "S867", "S868", "S869", "S870", "S871", "S872", "S873", "S874", "S875", "S876", "S877", "S878", "S879", "S880", "S881", "S882", "S883", "S884", "S885", "S886", "S887", "S888", "S889", "S890", "S891", "S892", "S893", "S894", "S895", "S896", "S897", "S898", "S899", "S900", "S901", "S902", "S903", "S904", "S905", "S906", "S907", "S908", "S909", "S910", "S911", "S912", "S913", "S914", "S915", "S916", "S917", "S918", "S919", "S920", "S921", "S922", "S923", "S923", "S924", "S925", "S926", "S927", "S928", "S929", "S930", "S931", "S932", "S933", "S934", "S935", "S936", "S937", "S938", "S939", "S940", "S941", "S942", "S943", "S944", "S945", "S946", "S947", "S948", "S949", "S950", "S951", "S952", "S953", "S954", "S955", "S956", "S957", "S958", "S959", "S960", "S961", "S962", "S963", "S964", "S965", "S966", "S967", "S968", "S969", "S970", "S971", "S972", "S973", "S974", "S977", "S978", "S979", "S980", "S981", "S982", "S983", "S984", "S985", "S986", "S987", "S988", "S989", "S990", "S991", "S992", "S993", "S994", "S995", "S996", "S997", "S998", "S999"]
ignore = ["S101", "S603", "S607"]
[tool.mypy]
python_version = "3.11"
strict = true
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
disallow_incomplete_defs = true
check_untyped_defs = true
no_implicit_optional = true
tsconfig.json (TypeScript config)
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"exactOptionalPropertyTypes": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "**/*.test.ts"]
}
# src/icarax/inference/client.py
"""
Secure AI Inference Client with built-in security monitoring.
Implements prompt theft detection, anomaly scoring, and audit logging.
"""
from __future__ import annotations
import hashlib
import hmac
import json
import time
import uuid
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
from typing import Any, AsyncIterator, Literal, Optional
from contextlib import asynccontextmanager
import httpx
import structlog
from pydantic import BaseModel, Field, SecretStr, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
from prometheus_client import Counter, Histogram, Gauge, CollectorRegistry
from tenacity import (
retry,
stop_after_attempt,
wait_exponential_jitter,
retry_if_exception_type,
)
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
logger = structlog.get_logger(__name__)
# =============================================================================
# Metrics Definitions
# =============================================================================
REGISTRY = CollectorRegistry()
INFERENCE_REQUESTS_TOTAL = Counter(
"inference_requests_total",
"Total inference requests",
["provider", "model", "status"],
registry=REGISTRY,
)
INFERENCE_LATENCY_SECONDS = Histogram(
"inference_latency_seconds",
"Inference request latency",
["provider", "model"],
buckets=(0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0),
registry=REGISTRY,
)
INFERENCE_TOKENS_TOTAL = Counter(
"inference_tokens_total",
"Total tokens processed",
["provider", "model", "type"], # type: prompt, completion, total
registry=REGISTRY,
)
ANOMALY_DETECTIONS_TOTAL = Counter(
"anomaly_detections_total",
"Total anomaly detections",
["anomaly_type", "severity"],
registry=REGISTRY,
)
PROMPT_SIMILARITY_SCORE = Histogram(
"prompt_similarity_score",
"Prompt similarity score against known patterns",
buckets=(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 0.99, 1.0),
registry=REGISTRY,
)
ACTIVE_CONNECTIONS = Gauge(
"active_inference_connections",
"Active inference connections",
["provider"],
registry=REGISTRY,
)
# =============================================================================
# Configuration
# =============================================================================
class Provider(str, Enum):
OPENAI = "openai"
ANTHROPIC = "anthropic"
COHERE = "cohere"
CUSTOM = "custom"
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
case_sensitive=False,
extra="ignore",
)
# API Keys (SecretStr prevents logging)
openai_api_key: Optional[SecretStr] = None
anthropic_api_key: Optional[SecretStr] = None
cohere_api_key: Optional[SecretStr] = None
custom_api_key: Optional[SecretStr] = None
custom_base_url: Optional[str] = None
# Security
encryption_key: SecretStr
audit_log_webhook: Optional[str] = None
alert_webhook: Optional[str] = None
# Thresholds
max_prompt_length: int = 32000
max_tokens_per_minute: int = 100000
anomaly_threshold_score: float = 0.85
prompt_similarity_threshold: float = 0.92
# Timeouts
request_timeout: float = 60.0
connect_timeout: float = 10.0
# Retry
max_retries: int = 3
retry_base_delay: float = 1.0
# Observability
otel_endpoint: Optional[str] = None
otel_headers: Optional[str] = None
service_name: str = "icarax-inference-monitor"
settings = Settings() # type: ignore[call-arg]
# =============================================================================
# Data Models
# =============================================================================
class MessageRole(str, Enum):
SYSTEM = "system"
USER = "user"
ASSISTANT = "assistant"
TOOL = "tool"
class ChatMessage(BaseModel):
role: MessageRole
content: str
name: Optional[str] = None
tool_calls: Optional[list[dict[str, Any]]] = None
tool_call_id: Optional[str] = None
@field_validator("content")
@classmethod
def validate_content_length(cls, v: str) -> str:
if len(v) > settings.max_prompt_length:
raise ValueError(f"Content exceeds max length of {settings.max_prompt_length}")
return v
class InferenceRequest(BaseModel):
model: str
messages: list[ChatMessage]
temperature: float = Field(default=0.7, ge=0.0, le=2.0)
max_tokens: Optional[int] = Field(default=None, ge=1, le=128000)
top_p: float = Field(default=1.0, ge=0.0, le=1.0)
frequency_penalty: float = Field(default=0.0, ge=-2.0, le=2.0)
presence_penalty: float = Field(default=0.0, ge=-2.0, le=2.0)
stream: bool = False
user_id: Optional[str] = None
session_id: Optional[str] = None
metadata: dict[str, Any] = Field(default_factory=dict)
class TokenUsage(BaseModel):
prompt_tokens: int = 0
completion_tokens: int = 0
total_tokens: int = 0
class InferenceResponse(BaseModel):
id: str
model: str
provider: Provider
choices: list[dict[str, Any]]
usage: TokenUsage
created: int = Field(default_factory=lambda: int(time.time()))
latency_ms: float
request_id: str
anomaly_score: float = 0.0
anomalies_detected: list[str] = Field(default_factory=list)
class AnomalyType(str, Enum):
PROMPT_INJECTION = "prompt_injection"
PROMPT_THEFT = "prompt_theft"
UNUSUAL_PATTERN = "unusual_pattern"
RATE_ANOMALY = "rate_anomaly"
GEOGRAPHIC_ANOMALY = "geographic_anomaly"
MODEL_EXTRACTION = "model_extraction"
DATA_EXFILTRATION = "data_exfiltration"
class SecurityEvent(BaseModel):
event_id: str = Field(default_factory=lambda: str(uuid.uuid4()))
timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
event_type: AnomalyType
severity: Literal["low", "medium", "high", "critical"]
provider: Provider
model: str
request_id: str
user_id: Optional[str] = None
session_id: Optional[str] = None
anomaly_score: float
details: dict[str, Any] = Field(default_factory=dict)
raw_prompt_hash: Optional[str] = None # SHA-256 of prompt for correlation
mitigated: bool = False
mitigation_actions: list[str] = Field(default_factory=list)
# =============================================================================
# Encryption Utilities
# =============================================================================
class EncryptionService:
"""Handles encryption/decryption of sensitive data at rest."""
def __init__(self, key: SecretStr) -> None:
self._fernet = self._create_fernet(key.get_secret_value())
@staticmethod
def _create_fernet(key: str) -> Fernet:
# Derive key from provided secret
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=b"icarax-salt-v1", # In production, use random salt per deployment
iterations=100000,
)
derived_key = kdf.derive(key.encode())
return Fernet(base64.urlsafe_b64encode(derived_key))
def encrypt(self, data: str) -> str:
return self._fernet.encrypt(data.encode()).decode()
def decrypt(self, encrypted: str) -> str:
return self._fernet.decrypt(encrypted.encode()).decode()
# =============================================================================
# Anomaly Detection Engine
# =============================================================================
class AnomalyDetector:
"""
Detects anomalous patterns in inference requests.
Implements multiple detection strategies for prompt theft and injection.
"""
def __init__(self) -> None:
self._known_prompts: dict[str, list[str]] = {} # user_id -> recent prompts
self._prompt_embeddings: dict[str, list[float]] = {} # For similarity detection
self._rate_limiter: dict[str, list[float]] = {} # user_id -> timestamps
self._injection_patterns = self._load_injection_patterns()
@staticmethod
def _load_injection_patterns() -> list[dict[str, Any]]:
"""Load known prompt injection patterns."""
return [
{
"name": "ignore_previous_instructions",
"pattern": r"(?i)ignore\s+(?:previous|above|all)\s+instructions?",
"severity": "high",
"type": AnomalyType.PROMPT_INJECTION,
},
{
"name": "system_prompt_extraction",
"pattern": r"(?i)(?:show|print|display|output|reveal)\s+(?:the\s+)?(?:system|initial|original)\s+prompt",
"severity": "critical",
"type": AnomalyType.PROMPT_THEFT,
},
{
"name": "role_manipulation",
"pattern": r"(?i)you\s+are\s+(?:now|now\s+a)\s+(?:developer|admin|root|system)",
"severity": "high",
"type": AnomalyType.PROMPT_INJECTION,
},
{
"name": "data_exfiltration",
"pattern": r"(?i)(?:send|post|transmit|exfiltrate)\s+(?:data|info|secrets|keys|tokens)",
"severity": "critical",
"type": AnomalyType.DATA_EXFILTRATION,
},
{
"name": "model_extraction",
"pattern": r"(?i)(?:repeat|output|print)\s+(?:your|the)\s+(?:weights|parameters|architecture|training)",
"severity": "high",
"type": AnomalyType.MODEL_EXTRACTION,
},
{
"name": "encoding_bypass",
"pattern": r"(?i)(?:base64|rot13|hex|unicode|encode|decode)\s+(?:this|the\s+following)",
"severity": "medium",
"type": AnomalyType.PROMPT_INJECTION,
},
]
def analyze(self, request: InferenceRequest, user_id: str) -> tuple[float, list[SecurityEvent]]:
"""
Analyze request for anomalies.
Returns (anomaly_score, list_of_security_events).
"""
events: list[SecurityEvent] = []
scores: list[float] = []
# 1. Prompt injection detection
injection_score, injection_events = self._detect_prompt_injection(request, user_id)
scores.append(injection_score)
events.extend(injection_events)
# 2. Prompt theft / similarity detection
theft_score, theft_events = self._detect_prompt_theft(request, user_id)
scores.append(theft_score)
events.extend(theft_events)
# 3. Rate anomaly detection
rate_score, rate_events = self._detect_rate_anomaly(request, user_id)
scores.append(rate_score)
events.extend(rate_events)
# 4. Unusual pattern detection (structural)
pattern_score, pattern_events = self._detect_unusual_patterns(request)
scores.append(pattern_score)
events.extend(pattern_events)
# Overall anomaly score (weighted max)
overall_score = max(scores) if scores else 0.0
# Update tracking
self._update_tracking(request, user_id)
return overall_score, events
def _detect_prompt_injection(
self, request: InferenceRequest, user_id: str
) -> tuple[float, list[SecurityEvent]]:
import re
events: list[SecurityEvent] = []
max_score = 0.0
full_prompt = "\n".join(msg.content for msg in request.messages)
for pattern_def in self._injection_patterns:
matches = list(re.finditer(pattern_def["pattern"], full_prompt))
if matches:
score = 0.9 if pattern_def["severity"] == "critical" else 0.7
max_score = max(max_score, score)
event = SecurityEvent(
event_type=pattern_def["type"],
severity=pattern_def["severity"], # type: ignore[arg-type]
provider=Provider.OPENAI, # Will be overridden by caller
model=request.model,
request_id=request.metadata.get("request_id", "unknown"),
user_id=user_id,
session
---
## Next Steps
1. **Get API Access** - Sign up at the official website
2. **Try the Examples** - Run the code snippets above
3. **Read the Docs** - Check official documentation
4. **Join Communities** - Discord, Reddit, GitHub discussions
5. **Experiment** - Build something cool!
## Further Reading
- [TechCrunch AI](https://techcrunch.com/category/artificial-intelligence/)
- [The Verge](https://www.theverge.com/technology)
- [Wired AI](https://www.wired.com/tag/artificial-intelligence/)
- [Medium AI](https://medium.com/topic/artificial-intelligence)
**Source:** [Security Week AI](https://www.securityweek.com/ai-inference-providers-failed-to-detect-hacking-and-prompt-theft-says-dragos/)
---
*Follow ICARAX for more AI insights and tutorials.*
