REST API Reference
Complete reference for the DriftRail API. All endpoints require authentication via API key.
SDK Quick Start
pip install driftrail
from driftrail import DriftRail, DriftRailEnterprise
# Basic client
client = DriftRail(api_key="dr_live_...", app_id="my-app")
client.ingest(model="gpt-4o", provider="openai",
input={"prompt": "..."}, output={"text": "..."})
# Inline guardrails
result = client.guard(output=response, mode="strict")
# Enterprise client (120+ methods)
enterprise = DriftRailEnterprise(api_key="...", app_id="...")
enterprise.get_drift_score()
enterprise.start_trace(app_id="my-app", name="chat")
enterprise.create_prompt(name="Support Bot", content="...")
View on PyPI →
npm install @drift_rail/sdk
import { DriftRail } from '@drift_rail/sdk';
const client = new DriftRail({
apiKey: 'dr_live_...',
appId: 'my-app'
});
await client.ingest({
model: 'gpt-4o',
provider: 'openai',
input: { prompt: '...' },
output: { text: '...' }
});
// Inline guardrails
const result = await client.guard({ output, mode: 'strict' });
View on npm →
Full Documentation: See Python SDK docs and Node.js SDK docs for complete usage guides.
Base URL
Authentication
Include your API key in the Authorization header:
Authorization: Bearer dr_live_your_api_key_here
Alternative: Use X-API-Key header.
Key Formats
| Environment | Prefix | Example |
|---|---|---|
| Production | dr_live_ | dr_live_a1b2c3d4... |
| Staging | dr_test_ | dr_test_e5f6g7h8... |
| Development | dr_test_ | dr_test_i9j0k1l2... |
Rate Limits
| Plan | Requests/min | Burst |
|---|---|---|
| Starter | 60 | 100 |
| Growth | 300 | 500 |
| Pro | 1,000 | 2,000 |
| Enterprise | Custom | Custom |
Per-key rate limits can be configured via the API Keys endpoint.
Error Codes
400Bad Request - Invalid parameters401Unauthorized - Invalid or missing API key403Forbidden - Insufficient permissions or scope404Not Found - Resource doesn't exist415Unsupported Media Type - Use application/json429Too Many Requests - Rate limit exceeded500Internal Server ErrorInline Guard
Real-time content safety check. Blocks dangerous outputs before they reach users. <50ms latency.
/api/guard
Critical Path
Request Body
{
"output": "The LLM response to check",
"input": "Optional user prompt for context",
"mode": "strict",
"timeout_ms": 100,
"skip_classification": false
}
Response
{
"allowed": true,
"action": "allow",
"output": "The LLM response to check",
"triggered": [],
"classification": {
"risk_score": 15,
"pii": { "detected": false, "types": [] },
"toxicity": { "detected": false, "severity": "none" },
"prompt_injection": { "detected": false, "risk": "none" }
},
"latency_ms": 42,
"fallback": false
}
Fail-Open: If classification times out, allowed: true and fallback: true are returned.
Ingest
Log an LLM inference event for async classification and monitoring.
/ingest
Request Body
{
"model": "gpt-5",
"provider": "openai",
"input": {
"prompt": "What is the capital of France?",
"messages": [{ "role": "user", "content": "..." }],
"retrievedSources": [{ "id": "doc-1", "content": "..." }]
},
"output": {
"text": "The capital of France is Paris.",
"toolCalls": []
},
"metadata": {
"latencyMs": 420,
"tokensIn": 25,
"tokensOut": 12,
"temperature": 0.7
}
}
Response (202 Accepted)
{
"success": true,
"event_id": "evt_a1b2c3d4...",
"job_id": "job_e5f6g7h8..."
}
Events
Query logged inference events with optional filters.
/api/events
Query Parameters
Classifications
List classification results with risk scores and detected issues.
/api/classifications
List all classifications with filters for risk score and time range.
/api/classifications/distribution
Get risk distribution statistics (low, medium, high counts).
/api/classifications/high-risk
Get high-risk events above threshold (default: 70).
Stats
Get aggregated statistics for your application.
/api/stats
Query param: period = 1h, 24h, 7d, 30d
{
"period": "24h",
"events": { "total": 5000, "by_environment": {...} },
"models": [{ "model": "gpt-5", "count": 3000 }],
"risk": { "low": 4200, "medium": 650, "high": 150 },
"latency": { "avg_ms": 520, "p95_ms": 1200 },
"alerts": { "critical": 1, "warning": 3, "info": 8 }
}
API Keys
Manage API keys with scoping, IP allowlisting, expiration, and usage analytics.
/api/keys
List all API keys with usage stats.
/api/keys
Create new API key with optional scopes, IP restrictions, expiration.
{
"name": "Production API",
"environment": "prod",
"scopes": ["read", "write", "ingest", "guard"],
"allowed_ips": ["192.168.1.0/24"],
"expires_at": "2025-12-31T23:59:59Z",
"rate_limit_override": 500
}
/api/keys/rotate
Rotate a key with optional grace period.
/api/keys/usage
Get usage overview across all keys.
/api/keys?key_id=xxx
Revoke an API key.
Scopes: read, write, ingest, guard, admin, * (all)
Guardrails
Configure rule-based guardrails for content filtering.
/api/guardrails
List all guardrails.
/api/guardrails
Create a guardrail rule.
{
"name": "Block PII",
"rule_type": "block_pii",
"action": "block",
"config": { "types": ["email", "phone", "ssn"] }
}
/api/guardrails/check
Test content against guardrails.
Rule Types: block_high_risk, block_pii, block_toxicity, block_prompt_injection, custom_regex, custom_keywords
Actions: flag, block, redact, warn
Detections
Configure detection types, custom classifiers, and risk scoring.
/api/detections/types
List available detection types for your tier.
/api/detections/settings
Update enabled detections.
/api/detections/custom
Pro+
Add custom detection with your own prompt.
/api/detections/framework
Pro+
Upload a compliance framework PDF and auto-generate custom detections.
{
"pdf_base64": "JVBERi0xLjQK...",
"framework_name": "My Custom Framework",
"focus_areas": ["data privacy", "security"],
"max_controls": 30,
"auto_save": false
}
Response
{
"success": true,
"framework": {
"name": "GDPR Compliance Framework",
"description": "EU data protection requirements",
"summary": "Document covers data subject rights..."
},
"controls": [
{
"control_id": "GDPR-7.1",
"name": "Data Subject Access Rights",
"description": "Users must be able to access their data",
"category": "Data Rights",
"evidence_type": "system_check",
"keywords": ["access request", "data export"]
}
],
"detections": [
{
"id": "gdpr_data_subject_access_rights",
"name": "GDPR: Data Subject Access Rights",
"prompt": "Detect violations of compliance control..."
}
],
"latency_ms": 3500
}
Supported: PDF up to 50MB. Works with GDPR, HIPAA, SOC2, PCI-DSS, or any custom compliance framework.
/api/detections/test
Pro+
Test a custom detection prompt against sample content.
/api/detections/risk-config
Get current risk scoring configuration.
/api/detections/risk-config
Pro+
Update risk scoring configuration.
{
"config": {
"weights": {
"hallucination": 0.25,
"policy_violation": 0.25,
"toxicity": 0.20,
"pii_detection": 0.15,
"prompt_injection": 0.15
},
"thresholds": {
"low_max": 35,
"medium_max": 65
},
"compounding": {
"enabled": true,
"factor": 1.15,
"max_multiplier": 1.6
},
"min_confidence": 0.6
}
}
/api/detections/risk-preview
Preview risk score calculation with sample detections.
{
"detections": [
{ "detection_id": "hallucination", "result": { "hallucination_risk": "medium" }, "confidence": 0.85 },
{ "detection_id": "pii_detection", "result": { "exposure": "low" }, "confidence": 0.9 }
],
"config": { ... } // optional, uses tenant config if omitted
}
Risk Scoring Algorithm
- • Weighted - Each detection type has configurable weight (0-1)
- • Confidence-adjusted - Scores scaled by sqrt(confidence)
- • Compounding - Multiple significant detections increase score
- • Thresholds - Custom low/medium/high boundaries
Webhooks
Register webhook endpoints for real-time notifications.
/api/webhooks
Register a webhook (HTTPS required).
{
"url": "https://your-app.com/webhook",
"events": ["alert.critical", "classification.high_risk"]
}
Events: alert.created, alert.critical, usage.threshold, classification.high_risk
Integrations
Connect to Slack, Teams, or Discord for notifications.
/api/integrations
Create integration.
{
"type": "slack",
"webhook_url": "https://hooks.slack.com/...",
"channel_name": "#ai-alerts",
"events": ["alert.critical", "incident.created"]
}
/api/integrations/test
Test a webhook URL before saving.
Types: slack, teams, discord
Projects
Organize your AI applications into projects with separate keys and guardrails.
/api/projects
List all projects.
/api/projects
Create a new project.
/api/projects/:id/keys
List project API keys.
/api/projects/:id/guardrails
List project-specific guardrails.
/api/projects/:id/usage
Get project usage statistics.
Incidents
Track and manage AI safety incidents.
/api/incidents
List incidents with status/severity filters.
/api/incidents
Create an incident.
{
"title": "High hallucination rate detected",
"description": "Hallucination rate spiked to 15%",
"severity": "high",
"incident_type": "hallucination_spike"
}
/api/incidents/:id/status
Update incident status (open, investigating, mitigating, resolved, closed).
/api/incidents/stats
Get incident statistics including MTTR.
Compliance
Manage compliance frameworks, analyze content for violations, and handle GDPR data subject requests.
/api/compliance/status
Get compliance framework status (HIPAA, SOC2, GDPR, PCI-DSS).
/api/compliance/settings
Update compliance settings.
{
"hipaa_enabled": true,
"gdpr_enabled": true,
"pii_auto_redact": true,
"pii_redaction_level": "standard",
"data_region": "eu"
}
/api/compliance/analyze
RAG-Augmented
Analyze LLM interactions for compliance violations using AI-powered analysis with embedded regulatory knowledge (HIPAA, GDPR, PCI DSS, SOC 2).
Request Body
{
"input": "User prompt text",
"output": "AI response text",
"frameworks": ["hipaa", "gdpr", "pci_dss", "soc2"],
"context": { "industry": "healthcare", "region": "eu" }
}
Response
{
"compliant": false,
"overallRisk": "high",
"violations": [{
"framework": "hipaa",
"requirement": "§164.514",
"severity": "high",
"description": "PHI identifier exposed",
"recommendation": "Apply Safe Harbor de-identification"
}],
"piiDetected": { "types": ["ssn"], "count": 1 },
"latencyMs": 245
}
/api/compliance/analyze/batch
Batch analyze up to 100 interactions. Returns individual results plus summary statistics.
/api/compliance/analyze/check
Quick heuristic check if content requires compliance review (no LLM call, instant response).
/api/compliance/dsar
Create GDPR Data Subject Access Request.
Model Comparison
Compare model performance and run A/B tests.
/api/models/leaderboard
Get model performance leaderboard. Metrics: avg_risk_score, avg_latency_ms, hallucination_rate, error_rate.
/api/models/comparisons
Create A/B test comparison between two models.
/api/models/performance/:model
Get performance history for a specific model.
Exports
Export data for compliance audits and analysis.
/api/exports
Create an export job.
{
"export_type": "events",
"format": "json",
"date_from": "2026-01-01T00:00:00Z",
"date_to": "2026-01-31T23:59:59Z"
}
/api/exports/download/:id
Download completed export file.
Types: events, classifications, audit_logs, incidents, full_audit
Formats: json, csv, pdf
Brand Safety
Protect your brand with content rules and competitor monitoring.
/api/brand-safety/rules
Create a brand safety rule.
{
"name": "Block Competitor Mentions",
"rule_type": "competitor_mentions",
"config": { "terms": ["CompetitorA", "CompetitorB"] },
"action": "flag",
"severity": "medium"
}
/api/brand-safety/check
Check text against brand safety rules.
Rule Types: blocked_terms, competitor_mentions, sentiment_threshold, topic_restriction, custom_regex
Retention
Configure data retention policies for compliance.
/api/retention
Create a retention policy.
{
"name": "Production Events - 90 days",
"data_type": "inference_events",
"retention_days": 90,
"environment_filter": ["prod"]
}
/api/retention/summary
Get retention summary with deletion stats.
Audit Logs
Search, stream, and export audit logs. Configure SIEM integration.
/api/logs
Search logs with filters (level, action, actor, resource, time range).
/api/logs/stats
Get log statistics by level and action.
/api/logs/export
Configure SIEM export (Splunk, Datadog, etc.).
/api/logs/sampling
Configure log sampling for high-volume environments.
/api/logs/retention
Configure log retention with optional archiving.
AI Playground
Test AI models with real-time DriftRail safety monitoring.
/api-playground
Get usage limits and available models.
/api-playground
Send a message and get AI response with detections.
{
"messages": [
{ "role": "system", "content": "You are a helpful assistant." },
{ "role": "user", "content": "What is the capital of France?" }
],
"model": "gemini-flash-lite-latest",
"runDetections": true
}
Limits: Starter: 25/mo, Growth: 500/mo, Pro: 2,500/mo, Enterprise: 10,000+/mo
Alerts
Monitor and manage drift alerts. Alerts are automatically generated when anomalies are detected in your AI system's behavior.
Alert Types
Severity Levels
/api/alerts
List alerts with filtering and pagination.
Query Parameters
Response
{
"alerts": [
{
"alert_id": "a1b2c3d4-...",
"app_id": "my-chatbot",
"model": "gpt-4",
"alert_type": "risk_increase",
"severity": "critical",
"current_value": 85.5,
"baseline_value": 25.0,
"deviation_percent": 242.0,
"details": {
"affected_events": 150,
"time_window": "1h"
},
"created_at": "2025-01-03T10:30:00Z",
"acknowledged_at": null,
"acknowledged_by": null,
"resolved_at": null,
"resolution_notes": null
}
],
"summary": {
"critical": 2,
"warning": 5,
"info": 12
}
}
/api/alerts
Acknowledge or resolve an alert.
Request Body
// Acknowledge an alert
{
"alert_id": "a1b2c3d4-...",
"action": "acknowledge"
}
// Resolve an alert with notes
{
"alert_id": "a1b2c3d4-...",
"action": "resolve",
"notes": "False positive - expected behavior during deployment"
}
Response
{
"success": true
}
/api/alerts/metrics
New
Get real-time drift metrics with health score. Compares current 24h metrics against 7-day baselines.
Query Parameters
Response
{
"health_score": 92.5,
"current": {
"risk_distribution": 25.3,
"latency": 450,
"token_usage": 1250,
"error_rate": 0.5,
"hallucination_rate": 2.1,
"volume": 15000
},
"baselines": {
"risk_distribution": 22.1,
"latency": 420,
"token_usage": 1180,
"error_rate": 0.3,
"hallucination_rate": 1.8,
"volume": 14500
},
"last_updated": "2026-01-03T10:30:00Z"
}
/api/alerts/baselines
New
List active drift baselines. Baselines are automatically created and refreshed.
Response
{
"baselines": [
{
"baseline_id": "b1c2d3e4-...",
"app_id": "my-chatbot",
"model": "gpt-4o",
"valid_from": "2026-01-01T00:00:00Z",
"valid_until": null,
"avg_risk_score": 22.5,
"sample_count": 50000,
"risk_distribution": {"low": 85, "medium": 12, "high": 3}
}
]
}
/api/alerts/baselines
New
Refresh a drift baseline with current data from the last 7 days.
Request Body
{
"baseline_id": "b1c2d3e4-...",
"action": "refresh"
}
Response
{
"success": true,
"baseline": {
"baseline_id": "new-uuid",
"app_id": "my-chatbot",
"valid_from": "2026-01-03T10:30:00Z",
"avg_risk_score": 23.1,
"sample_count": 52000
}
}
/api/alerts/trends
New
Get historical drift trends over time.
Query Parameters
Response
{
"trends": [
{
"date": "2026-01-03",
"avg_deviation": 5.2,
"alert_count": 3,
"metrics": {
"risk": 24.5,
"latency": 445,
"volume": 15200
}
}
]
}
Enhanced Alert Types
Drift detection now monitors 6 metric types with automatic baseline comparison.
risk_score_drift
latency_drift
error_rate_drift
hallucination_drift
volume_drift
token_drift
Webhook Events
Alerts trigger webhook notifications. Configure webhooks to receive real-time alerts.
alert.created
alert.critical
See Webhooks and Integrations for Slack/Teams setup.
Executive Dashboard
Aggregated metrics for C-level reporting with KPI tracking, cost analysis, and trend comparisons.
/api/executive
Pro+
Get executive-level metrics with period comparisons.
Query Parameters
Response
{
"period": "7d",
"health_score": 92.5,
"summary": {
"total_events": 150000,
"total_events_change": 12.5,
"high_risk_events": 450,
"high_risk_change": -5.2,
"avg_latency_ms": 420,
"sla_compliance_percent": 99.2
},
"cost_metrics": {
"estimated_cost_usd": 1250.00,
"cost_change": 8.3,
"monthly_budget_usd": 5000,
"budget_used_percent": 25,
"tokens_used": 5000000,
"cost_per_event": 0.0083
},
"incident_metrics": {
"open_incidents": 2,
"critical_incidents": 0,
"mttr_hours": 2.5,
"incidents_this_period": 5
},
"risk_trends": [...],
"volume_trends": [...],
"model_breakdown": [...],
"compliance_status": {...},
"kpi_status": [...]
}
/api/executive/kpi-targets
Get configured KPI targets for the tenant.
/api/executive/kpi-targets
Update KPI targets.
{
"risk_score_target": 25,
"latency_target_ms": 500,
"sla_target_percent": 99.5,
"cost_budget_usd": 5000,
"mttr_target_hours": 4
}
/api/executive/export
Export executive report.
{
"period": "30d",
"format": "pdf" // json, csv, pdf
}
Model Analytics
Deep analytics on model performance, environment comparisons, and model switches.
/api/model-analytics/summary
Get analytics summary with model performance overview.
/api/model-analytics/history
Get historical logs filtered by model, environment, or API key.
/api/model-analytics/switches
Get model switch history (when models changed in production).
/api/model-analytics/switches/detect
Auto-detect model switches from inference patterns.
/api/model-analytics/environments
Compare metrics across environments (prod vs staging vs dev).
/api/model-analytics/environments/capture
Capture a snapshot of current environment metrics.
/api/model-analytics/benchmarks
Get model benchmark data with performance rankings.
/api/model-analytics/api-keys
Get per-API-key analytics showing usage patterns.
Benchmarks
Compare your AI metrics against industry benchmarks.
/api/benchmarks
Get benchmark comparison report for your industry.
Response
{
"industry": "fintech",
"your_metrics": {
"avg_risk_score": 22.5,
"avg_latency_ms": 450,
"hallucination_rate": 2.1,
"pii_exposure_rate": 0.5
},
"industry_benchmarks": {
"avg_risk_score": { "p25": 18, "p50": 28, "p75": 42 },
"avg_latency_ms": { "p25": 320, "p50": 480, "p75": 720 },
"hallucination_rate": { "p25": 1.5, "p50": 3.2, "p75": 5.8 }
},
"percentile_rankings": {
"risk_score": 35,
"latency": 42,
"safety": 78
}
}
/api/benchmarks/industries
List available industries for benchmarking.
/api/benchmarks
Update your tenant's industry for benchmark comparison.
{
"industry": "healthcare"
}
Industries: fintech, healthcare, ecommerce, saas, legal, education, media, gaming, enterprise
Billing
Manage subscriptions, view usage, and upgrade plans.
/api/billing/plans
List available subscription plans with pricing.
/api/billing/subscription
Get current subscription and usage details.
{
"plan": "growth",
"status": "active",
"current_period_start": "2026-01-01T00:00:00Z",
"current_period_end": "2026-02-01T00:00:00Z",
"usage": {
"events_ingested": 45000,
"events_limit": 100000,
"percent_used": 45,
"api_keys_used": 3,
"api_keys_limit": 10
},
"features": {
"custom_detections": true,
"compliance_reports": true,
"sla_guarantee": "99.9%"
}
}
/api/billing/usage
Get usage history across billing periods.
/api/billing/upgrade
Upgrade to a higher plan tier.
{
"plan_tier": "pro",
"billing_cycle": "monthly"
}
/api/billing/downgrade
Downgrade to a lower plan (takes effect next billing cycle).
Playground Sessions
Save, manage, and share AI playground conversations and templates.
/api/playground/sessions
List saved playground sessions.
/api/playground/sessions
Create a new session.
{
"name": "Customer Support Test",
"model": "gemini-flash-lite-latest",
"system_prompt": "You are a helpful customer support agent."
}
/api/playground/sessions/:id
Get session with all messages.
/api/playground/sessions/:id/messages
Add a message to the session.
/api/playground/templates
List reusable conversation templates.
/api/playground/templates
Create a template from a session.
{
"name": "PII Detection Test",
"description": "Template for testing PII detection",
"system_prompt": "You are a helpful assistant.",
"starter_messages": [
{ "role": "user", "content": "My SSN is 123-45-6789" }
]
}
/api/playground/templates/:id/use
Create a new session from a template.
AI Assistant
AI-powered chat assistant with full dashboard context. Ask questions about your data, get insights, and receive recommendations.
/api-assistant
Get session history or list all sessions.
/api-assistant
Send a message to the assistant.
Request
{
"message": "What's my current risk score trend?",
"session_id": "optional-uuid"
}
Response
{
"message": "Your risk score has decreased by 12% over the past week...",
"session_id": "uuid",
"history": [
{ "role": "user", "content": "What's my current risk score trend?" },
{ "role": "assistant", "content": "Your risk score has decreased..." }
]
}
/api-assistant
Clear session and start fresh.
Example Questions
- • "What's causing my high risk score today?"
- • "Compare GPT-4 vs Claude performance this week"
- • "Show me PII detection trends"
- • "Why did I get a drift alert yesterday?"
Compliance Reports
Generate and export compliance audit reports for SOC2, GDPR, HIPAA, and custom frameworks.
/api/compliance/reports
Generate a new compliance report.
{
"framework": "soc2",
"report_type": "full",
"date_from": "2026-01-01T00:00:00Z",
"date_to": "2026-01-31T23:59:59Z",
"include_evidence": true
}
/api/compliance/reports
List generated compliance reports.
/api/compliance/reports/:id
Get specific report details.
/api/compliance/reports/:id/export
Export report in various formats.
/api/compliance/frameworks
List custom compliance frameworks.
/api/compliance/frameworks
Create a custom compliance framework.
/api/compliance/frameworks/analyze
Analyze a PDF document to extract compliance controls.
Frameworks: soc2, gdpr, hipaa, pci_dss, iso27001, nist, custom
Health Check
Public health endpoint for monitoring and uptime checks. No authentication required.
/health
Public
Get system health status.
Response
{
"status": "healthy",
"timestamp": "2026-01-06T10:30:00Z",
"version": "1.0.0",
"checks": {
"database": { "status": "pass", "latencyMs": 5 },
"ai": { "status": "pass" },
"auth": { "status": "pass" }
}
}
OpenTelemetry
Export traces in OTLP format for integration with your observability stack.
/api/otel
Export spans in OpenTelemetry Protocol (OTLP) format.
Query Parameters
Response
{
"resourceSpans": [{
"resource": {
"attributes": [
{ "key": "service.name", "value": { "stringValue": "driftrail" } }
]
},
"scopeSpans": [{
"spans": [{
"traceId": "abc123...",
"spanId": "def456...",
"name": "ingest",
"startTimeUnixNano": "1704534600000000000",
"endTimeUnixNano": "1704534600500000000",
"attributes": [
{ "key": "model", "value": { "stringValue": "gpt-4o" } },
{ "key": "risk_score", "value": { "intValue": 25 } }
]
}]
}]
}]
}
/api/otel
Push spans to an external OTEL collector.
Compatible with: Jaeger, Zipkin, Grafana Tempo, Datadog, Honeycomb, New Relic