Back to Community & Earn Hub

Semantic Routing & Model Cascading in Production: Cutting LLM API Bills by 74% Without Losing Frontier Reasoning Quality

@aditya_verma11 hours ago·2 min read 1880 views
Semantic Routing & Model Cascading in Production: Cutting LLM API Bills by 74% Without Losing Frontier Reasoning Quality

The Single-Model Fallacy in Production AI

Most engineering teams start with a single frontier model endpoint (claude-3-5-sonnet or gpt-4o) for every single LLM call in their application.

When you audit production traces, however, traffic is heavily skewed:

  • ~55% of requests are straightforward: intent classification, JSON reformatting, summarizing short tickets, or answering FAQ lookups.
  • ~30% are moderate complexity: single-file code edits or SQL generation against known schemas.
  • ~15% genuinely require deep frontier reasoning: multi-file architecture planning, subtle race-condition debugging, or ambiguous edge cases.

Paying frontier per-token pricing for the easy 55% is pure waste.


Architecture: Semantic Router + Confidence Cascade

A production-grade cascade combines pre-inference semantic routing (vector similarity against curated anchor utterances in <5ms) with post-inference confidence escalation:

text
                     ┌──────────────────────────┐
                     │    Incoming User Query   │
                     └─────────────┬────────────┘
                                   │
                                   ▼
                     ┌──────────────────────────┐
                     │ Semantic Router (<5ms)   │
                     │ (bge-small-en-v1.5)      │
                     └──────┬────────────┬──────┘
                            │            │
            Simple / Known  │            │ Complex / High-Stakes
                            ▼            ▼
             ┌──────────────────┐    ┌──────────────────────┐
             │  Local 8B (vLLM) │    │ Frontier Model API   │
             └────────┬─────────┘    └──────────────────────┘
                      │
         Check logprob / JSON confidence
                      │
         ┌────────────┴────────────┐
         │ High Confidence         │ Low Confidence (Escalate)
         ▼                         ▼
   Return Fast (~120ms)      Fallback to Frontier Model

Python Production Implementation

Here is a clean, async router and cascade implementation using FastEmbed for sub-5ms local embeddings and OpenAI-compatible clients:

python
import numpy as np
from fastembed import TextEmbedding

class SemanticCascadeRouter:
    def __init__(self, complex_anchors: list[str], threshold: float = 0.78):
        self.embedder = TextEmbedding(model_name="BAAI/bge-small-en-v1.5")
        self.threshold = threshold
        # Pre-compute normalized anchor vectors once at startup
        self.complex_vecs = np.array(list(self.embedder.embed(complex_anchors)))

    def route(self, query: str) -> str:
        q_vec = next(self.embedder.embed([query]))
        # Cosine similarity (FastEmbed outputs L2-normalized vectors)
        max_sim = float(np.max(self.complex_vecs @ q_vec))
        return "frontier" if max_sim >= self.threshold else "local_8b"


async def generate_with_cascade(router: SemanticCascadeRouter, query: str, local_client, frontier_client):
    tier = router.route(query)

    if tier == "local_8b":
        resp = await local_client.chat.completions.create(
            model="Qwen/Qwen2.5-7B-Instruct",
            messages=[{"role": "user", "content": query}],
            logprobs=True,
            max_tokens=512,
        )
        choice = resp.choices[0]
        # Compute mean token probability; escalate if uncertain
        avg_logprob = sum(t.logprob for t in choice.logprobs.content) / max(1, len(choice.logprobs.content))
        if np.exp(avg_logprob) >= 0.72:
            return {"model": "local_8b", "text": choice.message.content}

    # Escalate to frontier model
    resp = await frontier_client.chat.completions.create(
        model="claude-3-5-sonnet",
        messages=[{"role": "user", "content": query}],
        max_tokens=1024,
    )
    return {"model": "frontier", "text": resp.choices[0].message.content}

Production Results

Across 100,000 production agent turns:

  • 68% resolved cleanly by the local 8B model on the first pass.
  • 9% escalated via the logprobs safety net.
  • 23% routed directly to the frontier model.
  • Net Impact: 74% reduction in monthly API spend and 2.8x faster median TTFT, with zero measurable drop in CSAT or eval pass rates.
2 Comments

Discussion

@sneha_patel10 hours ago

Using logprobs as a post-inference confidence gate is such a smart safety net. Even if the semantic router misclassifies a deceptively short query as 'simple', low token logprobs catch the uncertainty and escalate cleanly before returning a hallucination to the user.

@tanvi_kulkarni11 hours ago

BAAI/bge-small-en-v1.5 via FastEmbed runs on CPU in ~3ms with zero GPU contention. Pairing that in front of our vLLM endpoints cut our monthly frontier API spend by over 70% in the first week.

Join the developer discussion

Sign in or create a free account to comment (+10 pts) and tag helpful AIStoreHub repositories.