ELUVIXSovereign AI Router

Switchyard Routing Engine

Switchyard is the Layer 7 (L7) adaptive routing and tokenomics mitigation engine in Eluvix (@eluvix/router-core). Operating between client applications and heterogeneous LLM runtimes, Switchyard dynamically balances token cost, latency, capability, and model availability.


Architecture Overview

Switchyard decouples upstream model backends from client API consumers. Instead of hardcoding model endpoints or vendor-specific SDKs, clients target a virtual model identifier (e.g. auto, code, or specific model tags), and Switchyard resolves the optimal execution path in real time.

Incoming Chat Request (model: "auto")
                 β”‚
                 β–Ό
 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
 β”‚             Switchyard Engine                 β”‚
 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
 β”‚  1. Budget Guard: maxCostPerRequest check     β”‚
 β”‚  2. Anti-OOM: Token context estimation        β”‚
 β”‚  3. Prompt Profiler: Keyword & code scoring   β”‚
 β”‚  4. Latency Circuit Breaker: Spillover filter β”‚
 β”‚  5. Tier Selection: Execution strategy        β”‚
 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                        β”‚
         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
         β–Ό              β–Ό              β–Ό
   [Tier 1: $0]    [Tier 2: AGY]  [Tier 3: Cloud]
   Local vLLM /    Google Gemini  OpenAI o3-mini /
   Ollama          Antigravity    Claude 3.7 Sonnet

Routing Strategies

Switchyard provides six configurable execution strategies selectable per-graph or dynamically per-request:

1. Cost & Complexity Matrix (cost-complexity) (Default)

The primary intelligent routing mode. Switchyard computes an in-flight complexity score from prompt token counts, code blocks (```), structured schema definitions, and reasoning keywords.

  • Low Complexity (< Moderate threshold): Dispatches to local \$0 models (e.g. Llama 3 8B, Qwen 2.5 Coder 7B).
  • Moderate Complexity (between Moderate and Heavy): Routes to local high-parameter models or high-throughput CLI agents (Antigravity AGY).
  • High Complexity (> Heavy threshold or code-escalated): Escalates to frontier cloud models (gemini-4-carbon-high, OpenAI o3-mini, Anthropic Claude 3.7 Sonnet).

2. Online Contextual Thompson Bandit (thompson-bandit)

Self-optimizing multi-armed bandit strategy backed by persistent Beta posteriors (alpha, beta), EWMA TTFT/ITL latency, and 5%-per-hour decay in SQLite bandit_arms:

  • Samples (upstreamId, complexityTier) arms via exact Marsaglia-Tsang Gamma/Beta variates, combining empirical reliability with latency and \$0.00 sovereign local cost bonuses.
  • Automatically shifts traffic away from degraded or rate-limited providers within a handful of requests and gently re-probes recovered arms over time.

3. Strict Cost Escalation (cascade-cost)

Sequential tier progression designed to minimize cloud expenditures:

  • Always executes against local \$0 engines first.
  • If all local nodes fail, timeout, or report out-of-memory (OOM), Switchyard escalates sequentially to the next tier without dropping client requests.

4. Lowest Cost First (lowest-cost)

Sorts available upstreams strictly by estimated cost per 1k tokens. \$0 local nodes always take top priority; when local nodes are saturated or unavailable, the cheapest commercial API candidate is chosen.

5. Lowest Latency (lowest-latency)

Continuously tracks rolling round-trip response times in the local SQLite database (request_logs). Dispatches queries to the engine with the lowest measured ping and inference latency.

6. Round Robin (round-robin)

Distributes requests uniformly across all healthy upstreams meeting capability tags, ideal for load balancing multiple parallel local GPU workers.


Speculative Buffer-Verify Cascades, Vendor Aliasing & Distillation

1. Speculative Buffer-Verify Cascades (speculativeCascadeNode)

When speculativeCascade is wired via #draft and #verifier:

  1. Switchyard executes the fast \$0.00 local #draft engine first and buffers tokens internally while scoring structural completeness, refusal/hedging absence, tool JSON validity, and repetition entropy against minConfidence (default 0.75).
  2. If confidence passes, buffered tokens flush immediately over SSE (X-Eluvix-Cascade: draft-accepted)β€”eliminating corrupted half-streams.
  3. If confidence falls below minConfidence, Switchyard discards the draft buffer cleanly and streams from the #verifier frontier model (X-Eluvix-Cascade: verifier-escalated).

2. Capability-Tier Vendor Model Aliasing

External tools that hardcode vendor model strings (such as Claude Code or Codex CLI) are automatically mapped to sovereign capability tiers unless strictModelMatch: true is set:

  • claude-*-opus*, o1*, o3*, gpt-5* β†’ frontier
  • claude-*-sonnet*, gpt-4o, gemini-*-pro* β†’ heavy
  • claude-*-haiku*, gpt-4o-mini, gemini-*-flash* β†’ simple (eligible for \$0.00 local sovereign execution, emitting X-Eluvix-Model-Alias).

3. Async #shadow-student SFT & DPO Distillation Flywheel

When a #shadow-student handle is connected on speculativeCascadeNode, frontier teacher completions asynchronously mirror the prompt in fire-and-forget background mode (x-eluvix-hops incremented) to the local student model, scrub PII via PrivacyGuard, and persist { prompt, chosen, rejected } preference pairs to SQLite distillation_pairs for one-command export via GET /api/v1/export?format=sft|dpo.


Token Complexity & Prompt Profiling

Switchyard grades prompt difficulty using token boundaries configured in the Visual Routing Editor:

| Parameter | Default | Description | | :--- | :--- | :--- | | moderateThreshold | 300 tokens | Transition point from simple conversational queries to moderate tasks. | | heavyThreshold | 1,500 tokens | Transition point triggering high-parameter models or local reasoning engines. | | frontierThreshold | 6,000 tokens | Transition point requiring frontier cloud models. | | codeEscalation | true | Automatically escalates complexity when Markdown code fences (```) are detected. |


Resiliency & Fault Tolerance

Upstream Timeout (timeoutMs)

Per-target network timeout (default: 15,000ms). Requests exceeding this duration are aborted cleanly using AbortSignal.timeout(timeoutMs), triggering fallback to the next candidate tier.

Max Retries (retryCount)

Specifies the number of immediate retry attempts per target before considering the upstream unhealthy (default: 1).

Latency Spillover Circuit Breaker (spilloverThresholdMs)

Monitors recent telemetry logs. If a local engine's average response time exceeds the configured threshold (default: 3,000ms), Switchyard automatically spills subsequent traffic over to cloud or secondary tiers to prevent queuing bottlenecks.


Financial Governance & Modality Isolation

1. Max Cost per Request (maxCostPerRequest)

Enforces a strict financial spending cap per completion (e.g. \$0.05).

  • Switchyard estimates upstream cost using (prompt_tokens / 1000) * costPer1kTokens.
  • Any candidate engine exceeding this cap is automatically bypassed in favor of \$0 local models.
  • If no affordable candidate is found, Switchyard returns an explicit budget rejection, preventing runaway API bills from autonomous agent loops.

2. Rolling 24h Cloud Spend Guardrails (maxDailySpendUsd)

Tracks cumulative USD spend across a rolling 24-hour window in SQLite (getRollingSpendUsd(24)) and enforces maxDailySpendUsd according to budgetExhaustedAction:

  • prefer-local (Default): Soft-fails over from paid commercial APIs to \$0.00 local sovereign engines (Ollama, vLLM, RamaLama, Lemonade) and emits X-Eluvix-Budget-Fallback: local-sovereign alongside X-Eluvix-Rolling-24h-Spend-USD.
  • strict-local: Restricts candidates exclusively to \$0.00 local engines; returns HTTP 429 (X-Eluvix-Budget-Guard: DENIED_DAILY_SPEND_CAP) if no local engine is healthy.
  • reject: Immediately rejects requests with HTTP 429 until rolling 24-hour expenditure drops below the ceiling.

3. Modality-Aware Media Intent & Paperclip Org Bias (mediaIntentRouting, integrations.paperclip)

When mediaIntentRouting is enabled (default true), Switchyard classifies every model: "auto" prompt across text, code, vision-input, image-gen, video-gen, and mesh-3d:

  • Conversational, coding, tool-calling, and vision-input chat completions automatically exclude synthesis-only ComfyUI nodes.
  • Generative synthesis prompts automatically steer to matching ComfyUI workflow presets (flux-txt2img, wan21-txt2vid, hunyuan3d-mesh).

When Paperclip integration (integrations.paperclip) is enabled and HMAC-verified/scoped context arrives (eluvix/auto, eluvix/fast-local, eluvix/code-specialist, eluvix/heavy-reasoning, eluvix/frontier-verified):

  • Issue priority, remaining budget percentage, and sensitivity dynamically bias tier floors/ceilings and local-only egress (X-Eluvix-Paperclip-Bias), while per-key maxTier / maxCostPer1kUsd ceilings enforce strict upper bounds (key-tier-ceiling, key-cost-ceiling).
  • On eluvix/auto (or model: "auto" when agentStepTiering: true), intra-heartbeat trajectory analysis (classifyAgentTrajectoryStep) steps lightweight tool inspections down to fast-local, edits/patches to code-specialist, and stack-trace/test failure loops to heavy-reasoning (X-Eluvix-Step-Tier), clamped inside active Paperclip floor/ceiling bounds.

Configuration Example (bifrost.yaml & eluvix.json)

When compiled from the visual editor, Switchyard policies are exported as portable configurations:

version: 1.0
routing_strategy: cost-complexity
switchyard_balancer:
  strategy: cost-complexity
  timeout_ms: 15000
  retry_count: 1
  spillover_threshold_ms: 3000
  code_escalation: true
  max_cost_per_request: 0.05
  complexity_thresholds:
    moderate: 300
    heavy: 1500
    frontier: 6000