AiCredits
Model Tiering

How to Reduce LLM API Costs by 60% with Model Tiering: A Python Router Guide

Model tiering with deepseek-v4-flash and deepseek-v4-pro: a verifiable cascade router that cuts LLM spend without hurting quality. Runnable Python code.

Published 2026-10-17 Updated 2026-10-17 8 min

Why Model Tiering Beats Model Shopping

Most teams try to cut their LLM bill by hunting for a cheaper model. That works exactly once. The cheaper model handles your easy traffic beautifully and falls apart on the hard slice, so you end up keeping a second vendor, a second SDK, and a second bill — and you've added a routing decision anyway, just with worse tooling.

Model tiering is a different move. You keep one API surface, one SDK, one key, and you decide per request which tier the work actually deserves. On AiCredits that means two models behind one OpenAI-compatible endpoint: deepseek-v4-flash as the fast default for the bulk of your traffic, and deepseek-v4-pro for the requests that genuinely need more capability. Pro costs more than flash, so the whole game is making sure you only reach for it when flash would have failed.

The number in the headline is a target, not a promise. Savings depend entirely on your traffic mix — how much of your workload is extractable, classifiable, or otherwise checkable. The only savings figure worth quoting is the one you measure in your own logs, and this post shows you how to log it.

The Real Routing Axis Is Verifiability, Not Difficulty

People route on how hard a request feels. That's a bad gate: difficulty isn't measurable, and your intuition about it drifts as your product changes. Route on something you can actually determine — whether the answer can be checked cheaply.

If the output is verifiable, it belongs on the cheap tier. Valid JSON matching a schema, a value that appears in the source document, a classification from a fixed label set, a transformation a regex can sanity-check — all of these let a deterministic verifier catch a bad flash response before your user ever sees it. If the output isn't verifiable (open-ended planning, trade-off analysis, debugging an unfamiliar stack), you don't have a safety net, and that's exactly when deepseek-v4-pro earns its higher cost.

  • Layer 1 — Free heuristics: length thresholds and keyword signals. Costs nothing, adds no latency, and should catch the obvious pro-shaped requests before any tokens are spent.

  • Layer 2 — Cascade with a deterministic verifier: run flash first, validate with code you already trust (JSON parsing, schema checks, unit tests, lookup against the source), and escalate once if validation fails.

  • Layer 3 — Sampled audit: send a small random sample of flash outputs to pro offline and compare. This measures whether your gate is still calibrated, without paying for a router model on every live request.

A Runnable Cascade Router

Here's the whole pattern in one file. It needs Python 3.10+ for the union type syntax and the OpenAI SDK. Export your key first: export AICREDITS_API_KEY=...

The verifier is the important part, not the router. The gate decides what starts on flash; the verifier decides what gets promoted to pro. Without the verifier, you're just hoping.

import json
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
)

FLASH = "deepseek-v4-flash"   # default tier: the bulk of your traffic
PRO = "deepseek-v4-pro"       # escape hatch: hard, unverifiable work

REASONING_SIGNALS = (
    "step by step", "root cause", "trade-off", "refactor",
    "design a", "why does", "prove",
)

def needs_pro(prompt: str) -> bool:
    """Free gate: no tokens, no network call, no added latency."""
    if len(prompt) > 6000:
        return True
    low = prompt.lower()
    return any(sig in low for sig in REASONING_SIGNALS)

def call(model: str, prompt: str, json_schema: dict | None = None) -> str:
    kwargs = {}
    if json_schema is not None:
        kwargs["response_format"] = {"type": "json_object"}
    resp = client.chat.completions.create(
        model=model,
        messages=[
            {"role": "system", "content": "You are a precise assistant. Reply with JSON only when the user asks for JSON."},
            {"role": "user", "content": prompt},
        ],
        max_tokens=800,
        **kwargs,
    )
    return resp.choices[0].message.content

def schema_ok(text: str, json_schema: dict) -> bool:
    """Deterministic verifier. This is what makes cheap-tier output safe."""
    try:
        data = json.loads(text)
    except json.JSONDecodeError:
        return False
    return all(key in data for key in json_schema.get("required", []))

def tiered_answer(prompt: str, json_schema: dict | None = None) -> tuple[str, str]:
    if needs_pro(prompt):
        return call(PRO, prompt, json_schema), PRO

    draft = call(FLASH, prompt, json_schema)
    if json_schema is not None and not schema_ok(draft, json_schema):
        return call(PRO, prompt, json_schema), PRO  # single, capped escalation
    return draft, FLASH

if __name__ == "__main__":
    schema = {"required": ["title", "summary"]}
    answer, used = tiered_answer(
        "Summarize this changelog entry as JSON with keys title and summary: "
        "Fixed a race condition in the cache warmer.",
        json_schema=schema,
    )
    print(used, answer)

Two details worth keeping. First, when you ask for JSON mode, include the literal word "JSON" in the prompt — the example above does, and skipping it is the most common cause of an empty or malformed response. Second, if you call tiered_answer without a schema, nothing gets verified, so the cascade can't protect you. For free-text output, add a cheap structural check (non-empty, correct number of items, required section headings present) or accept that those calls are unverified and route them by heuristic alone.

Escalate once, never in a loop. A retry loop on failures can cost more than simply calling deepseek-v4-pro the first time, and it multiplies your worst-case latency exactly when users are most annoyed.

Where Tiering Silently Leaks Money

  • Escalating on most requests. If flash fails often, you pay for flash and pro. That's the signal to raise the gate threshold or move that entire task class to pro and stop pretending.

  • Paying a model to route. A classifier call to decide which model to call doubles the cost of short prompts and adds a round trip. Use heuristics live, sample an LLM judge offline.

  • Unbounded output. On long-form generation, output tokens dominate the bill. A max_tokens ceiling is the cheapest optimization in this article.

  • Unstable prompts. Prompt caching rewards a stable prefix: cache hits cost less, and if you inject a timestamp or a shuffled instruction block at the top of every request, you pay full rate every time. Put the fixed instructions first, the variable content last.

  • Ignoring batch timing. Non-urgent bulk work can be queued for off-peak windows, which cost less than peak. Backfills, re-embeddings, and nightly enrichment jobs belong there.

  • Oversized context. Stuffing a whole document into every call when a trimmed section would do costs you on every single request.

Measure Escalation Rate, Not Vibes

The one number that tells you whether your tiering is working is the share of requests that ended up on pro after starting on flash. If it's tiny, your gate is doing its job. If it's large, your flash prompts are underspecified and you should fix the prompt before adding more routing logic.

from collections import Counter

routes = Counter()

def run_batch(prompts: list[str], json_schema: dict) -> list[str]:
    answers = []
    for prompt in prompts:
        answer, model_used = tiered_answer(prompt, json_schema)
        routes[model_used] += 1
        answers.append(answer)
    total = sum(routes.values()) or 1
    print(
        f"flash={routes[FLASH]} pro={routes[PRO]} "
        f"escalation_rate={routes[PRO] / total:.2f}"
    )
    return answers

Which Tier Does What

TierReach for it whenCheap verifier existsAvoid when
deepseek-v4-flashExtraction, classification, summarization, formatting, drafting, high-volume batch workUsually yes: schema checks, regex, equality against source text, unit testsThe task needs multi-step reasoning and you cannot check the answer cheaply
deepseek-v4-proPlanning, debugging, trade-off analysis, long-context synthesis, anything with no ground truthRarely — use sampling and human review insteadYou are running large volumes of near-identical simple calls

Keys, Payment, and One Base URL

AiCredits sells DeepSeek API credits to developers outside China, payable by card or PayPal with no Chinese phone number or bank account required. Because the endpoint is OpenAI-compatible at https://api.aicreditsapi.com/v1, tiering is a one-line model swap in code you already have — the same client, the same call signature, a different model string. Current rates live at aicreditsapi.com/pricing, and off-peak windows cost less than peak, which is worth knowing before you schedule a large backfill.

If you want a ready-made deterministic verifier rather than writing schema checks by hand, code linting tools are a natural fit — a linter is exactly the kind of cheap, trustworthy check that lets you keep more traffic on the fast tier without shipping broken output.

FAQ

Does model tiering really cut LLM API costs significantly?

It depends on your traffic mix. The savings come from how much of your workload is verifiable, because verifiable work can stay on deepseek-v4-flash and escalate only when a check fails. Track your own escalation rate and compute the difference against a pro-only baseline on the same prompts — that's the honest number.

Won't routing to a cheaper model hurt output quality?

Not if the output is verifiable. The verifier catches bad responses before they reach users, and the fallback is a single escalation to deepseek-v4-pro. Quality problems show up when you send unverifiable, reasoning-heavy work to the cheap tier with no check at all.

Should I use an LLM to decide which model to use?

Not on the live path. A routing model call adds cost and latency to every request, which is worst on exactly the short prompts where savings matter most. Use free heuristics live and sample an LLM judge offline to audit whether your gate is still calibrated.

How do I buy DeepSeek API credits from outside China?

AiCredits sells credits to international developers with payment by card or PayPal — no Chinese phone number or bank account needed. Keys work against an OpenAI-compatible base URL, so existing code needs only a base_url and model change. See aicreditsapi.com/pricing for current rates.

Does prompt caching affect the tiering math?

Yes. Cache hits cost less than a cold request, so keep the stable part of your prompt (system instructions, shared context) at the front and the variable part at the end. Unstable prefixes mean you pay full rate on every call even when most of the prompt is identical.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

💻Code Explainer

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×