API Documentation
Enterprise-grade routing, reliability, and deep observability for your AI stack. The complete reference for integrating with MLRouter programmatically.
1. Authentication
MLRouter authenticates API requests primarily via API Keys passed in the Authorization: Bearer header. Valid key formats include:
mlr-: The primary API Key format.mas-: Legacy internal keys for standard API access.sk-mlr-: Legacy public OpenRouter-compatible keys.mlr-mgmt-: Management keys for administrative operations.
You can create and manage your API Keys in Settings -> API Keys.
import OpenAI from "openai";const client = new OpenAI({ baseURL: "https://www.mlrouter.com/v1", apiKey: "mlr-your-api-key",});javascript2. Core Concepts
API Keys
Scoped API keys with their own spend caps, routing strategy, and guardrails, configured on the Routing page. Rotate or revoke them without touching your provider credentials.
Routing Strategies
Route each request by cost, latency, or capability - with automatic fallback to a healthy provider when one degrades.
Guardrails
Enforce allowed/blocked models, per-request token ceilings, and spend limits to keep AI usage predictable and secure.
TokenDrift
Continuously benchmark models so you know when quality drifts - and can re-route to a better option before it hits production.
Presets
Reusable configuration templates defining system prompts, default parameters, and allowed model subsets for consistent application behavior.
Fallback Chains
Ordered sequences of alternative models and providers to seamlessly transition to if a primary request fails or times out.
Data Policies
Ensure compliance by attaching policies (like zero-data-retention or HIPAA) to provider keys, dynamically filtering out non-compliant routes.
Classifiers
Real-time evaluators that analyze prompts and responses for specific intents, PII, or toxicity, seamlessly triggering alerts or blocks.
Memory & Sessions
Automatic persistent conversation tracking (mcp-persist) providing stateful context across multi-turn chat sessions.
3. Chat Completions
/v1/chat/completionsOpenAI-compatible chat completions. Accepts standard request bodies, handles streaming, and intelligently routes requests to the best available provider based on your active routing strategy.
models(string[])An array of model IDs to use as an explicit, request-scoped fallback chain.
allow_fallbacks(boolean)Defaults to true. If false, returns an error immediately on primary model failure instead of trying fallbacks.
stream(boolean)Set to true to receive partial message deltas via Server-Sent Events (SSE).
Idempotency-Key(HTTP header)Makes retries safe for 24 hours. Reusing a key with a different JSON body returns 422; a completed retry replays the stored response without dispatch or billing.
X-MLR-Max-Cost(HTTP header (USD))Per-request worst-case cost ceiling with up to four decimal places. The request is refused before provider dispatch when its estimate is higher.
mlrouter.max_cost(string | number)Body equivalent of X-MLR-Max-Cost. mlrouter.max_cost_credits is also accepted as an exact integer-credit ceiling.
x_mas_routing_strategy(string)Overrides the virtual key's routing strategy for this single request (e.g., 'cost', 'latency'). Can also be passed as the X-MAS-Routing-Strategy HTTP header.
4. Models
/v1/modelsLists every model available to your workspace, including context windows, pricing details, and live provider health scores.
/v1/models/:id/benchmarksRetrieves TokenDrift benchmark scores and performance history for a specific model.
/v1/models/sync-statusReturns the synchronization status of the upstream model catalog.
5. Embeddings & Audio
/v1/embeddingsGenerates vector embeddings for the provided input text, compatible with the OpenAI /v1/embeddings spec.
/v1/audio/modelsLists available audio generation and transcription models.
/v1/audio/speechGenerates spoken audio from text (TTS).
/v1/audio/transcriptionsTranscribes audio into text (STT).
6. API Keys Management
/v1/api-keysLists all API keys in the workspace.
/v1/api-keysCreates a new API key. Returns the unmasked key exactly once.
/v1/api-keys/:idRevokes an API key.
Routing & Governance (PATCH)
/v1/api-keys/:id/strategyUpdates the routing strategy associated with the key.
/v1/api-keys/:id/spend-capModifies the spend limit constraints and reset period for the key.
/v1/api-keys/:id/rate-limitUpdates the requests-per-minute limit for the key.
/v1/api-keys/:id/guardrailAttaches or removes a guardrail policy for the key.
/v1/api-keys/:id/compressionToggles opt-in LLMLingua-2 prompt compression for the key. Body: { prompt_compression: boolean }.
/v1/api-keys/:id/cost-safetyConfigures the integer-credit request ceiling, exact response cache TTL, semantic-cache interface, and provider prompt-cache passthrough.
Key Sub-resources (GET)
/v1/api-keys/:id/spendRetrieves current spend accumulation against the key's cap.
Routing and governance for a key are configured on the Routing page. Key creation and revocation are handled separately in Settings -> API Keys.
7. Presets
/v1/presetsLists all configuration presets available in the workspace.
/v1/presetsCreates a new preset containing default parameters and system prompts.
/v1/presets/:idRetrieves details of a specific preset.
/v1/presets/:idCreates an immutable revision; pass publish=true to publish it immediately.
/v1/presets/:id/revisionsLists immutable revision history, authors, and change messages.
/v1/presets/:id/diff?from=&to=Returns the field-level diff between two revisions.
/v1/presets/:id/publishMoves the published pointer to revision_id.
/v1/presets/:id/rollbackCopies an older revision into a new revision and publishes it.
/v1/presets/:id/splitSets sticky A/B weights in integer basis points.
/v1/presets/:id/analyticsReports request, cost, latency, and error metrics per revision.
/v1/presets/:idDeletes a preset.
Shadow traffic
/v1/shadow-configsLists this workspace's shadow evaluations and budget state.
/v1/shadow-configsCreates a sampled, budget-capped candidate evaluation.
/v1/shadow-configs/:idPauses, resumes, or changes sampling and budget settings.
/v1/shadow-configs/:id/reportReturns per-arm wins, cost and latency deltas, and disagreements.
/v1/shadow-configs/:id/promotePromotes a confirmed candidate to the linked preset or workspace default.
8. Guardrails & Classifiers
Guardrails
/v1/guardrailsLists all configured guardrails.
/v1/guardrailsCreates a new guardrail policy.
/v1/guardrails/:idRetrieves a specific guardrail policy.
/v1/guardrails/:idUpdates a guardrail policy.
/v1/guardrails/:idRemoves a guardrail policy.
Classifiers
/v1/classifiersLists all prompt/response classifiers.
/v1/classifiersCreates a new classifier.
/v1/classifiers/:idRetrieves a specific classifier.
/v1/classifiers/:idUpdates a classifier.
/v1/classifiers/:idRemoves a classifier.
9. TokenDrift
Endpoints proxied to the TokenDrift service for quality and safety analysis.
/compareCompares tokenizer efficiency and cost across multiple models for a given prompt.
text(string)The prompt text to tokenize and compare.
models(string[])Model IDs to compare token counts and estimated cost across.
/migration-safetyAnalyzes tokenizer/vocabulary risk when migrating from one model to another using a set of representative prompts.
source_model(string)The model currently in use.
target_model(string)The model being considered for migration.
sample_prompts(string[])Representative prompts (one per line) used to estimate migration risk.
/drift-checkChecks whether a model's tokenizer output has drifted from an expected reference token count for a given text.
model(string)The model to check.
reference_text(string)The reference text to re-tokenize and compare.
reference_token_count(number)The previously-recorded token count for reference_text, used to detect drift.
10. Requests & Observability
/v1/requestsQueries request logs with support for date-range and filtering query parameters.
/v1/analytics/cacheRetrieves overall semantic cache hit rates and metrics.
/v1/analytics/cache-breakdownProvides a detailed breakdown of cache performance by model.
/v1/analytics/cache-savingsCalculates estimated USD savings generated by cache hits.
/v1/analytics/tokensReturns token usage metrics aggregated over time.
/v1/analytics/heatmapGenerates a latency/error heatmap for visual analysis.
11. BYOK Provider Keys
Bring your own key (BYOK) routes your workspace's requests with a credential from your provider account. Open Settings → Provider Keys, choose the provider, paste the key, and select Verify and connect. MLRouter makes a minimal authenticated models-list request and shows the result before the key can serve traffic.
Security model
- • AES-256-GCM encryption at rest; plaintext is never returned by any API.
- • Only the provider and last four characters are displayed after save.
- • Keys are provider-bound and sent only to validated first-party hosts; redirects are refused.
- • Shadow, eval, and background use is off until you explicitly opt in.
Billing
Your provider bills model tokens directly. MLRouter charges only the configured per-request platform fee, shown as a separate line. If you enable platform fallback and your key is rejected, that request uses normal platform billing and is markedplatform_fallback.
Troubleshooting verification
API
/v1/provider-keysLists masked metadata, state, verification history, opt-ins, and data policies.
/v1/provider-keysVerifies, encrypts, and connects a key. Requires recent identity reverification.
/v1/provider-keys/:id/verifyRuns a rate-limited live verification using the stored credential.
/v1/provider-keys/:id/rotateVerifies a replacement, then atomically switches traffic to it.
/v1/provider-keys/:idUpdates enabled state, fallback/background opt-ins, or data policies.
/v1/provider-keys/:idPermanently removes the encrypted key and policy row.
12. Notifications
/v1/notificationsFetches all workspace notifications (e.g., budget alerts, billing events).
/v1/notifications/:id/readMarks a specific notification as read.
/v1/notifications/read-allMarks all pending notifications in the workspace as read.
13. Memory & Sessions
/v1/memory/sessionsRetrieves a paginated list of all active chat sessions in the persistent memory store.
/v1/memory/sessions/:idFetches full conversational history and state for a specific session ID.
14. Billing
/v1/billing/balanceCurrent workspace spend balance and limit.
/v1/billing/usageHistorical spend and usage charts.
/v1/billing/planCurrent active subscription plan details.
/v1/billing/creditsAvailable prepaid credit balance.
/v1/billing/transactionsHistory of purchases and credit adjustments.
/v1/billing/packagesAvailable prepaid credit packages with fee breakdowns.
/v1/billing/checkoutGenerates a Stripe checkout session for purchases.
/v1/billing/portalGenerates a Stripe billing portal link for subscription management.
/v1/billing/topupInitiates a manual credit top-up.
/v1/billing/subscribeSubscribes the workspace to a premium tier.
/v1/billing/promoApplies a promotional code to the workspace balance.
15. Public Status
/public/statusUnauthenticated endpoint providing global provider health status and uptime metrics.
16. Response Headers
Every response from /v1/chat/completions carries X-MLR-* headers explaining how the request was routed.
X-MLR-Resolved-ModelThe concrete model the request was routed to.X-MLR-Routing-StrategyWhich strategy selected the provider (cost, latency, …).X-MLR-Fallback-ProviderSet when the primary provider was unavailable and a fallback served the request.X-MLR-Credential-ModeCredential that served the request: platform, byok, or platform_fallback.X-MLR-Estimated-Cost-USDEstimated cost of the request in USD.X-MLR-Health-ScoreHealth score (0–100) of the provider that served the request.X-MLR-Trace-IDCorrelation id for finding this request in observability.