Layered LLM Selection and Task Routing: An Engineering Playbook

    Most production LLM traffic is simple and structured; a minority of requests need long-horizon reasoning. This article explains how to match model capability to task difficulty with a three-tier stack, routing signals, bounded upgrades, multi-step orchestration, cost controls, evaluation, and anti-patterns—so quality, latency, and spend stay predictable.

    1. Capability and cost are not the same curve

    In real R&D and content workflows, request mix is highly skewed. Most calls are regular work with clear format and steps: code review, implement-from-feedback, archiving, log summaries. A smaller share is hard: long chains, sustained reasoning, and multi-step execution—cross-module refactors, complex incident diagnosis, mechanical/3D design exploration, research-style analysis.

    Sending everything to the strongest model wastes money and latency on short jobs; the extra quality gain fades quickly. Sending everything to a cheap model causes hard tasks to fail and retry, and that hidden cost often exceeds calling a stronger model once. The engineering answer is not “pick the best model.” It is a layered model stack plus a routing layer so each request lands on a capability tier that matches its difficulty.

    2. A three-tier capability model

    A common pattern is to treat available models as three explicit tiers in configuration, not scattered in business code:

    • L1 lightweight: Templated, short-context, verifiable work—classification, extraction, formatting, simple Q&A. Optimize for throughput and low latency.
    • L2 daily default: Multi-step work with clear bounds—code review, iterate on review comments, document structuring, routine workflow orchestration. This is where most traffic should land.
    • L3 high capability: Long-horizon reasoning, heavy tool use, and high delivery bars—complex engineering changes, professional design delivery, deep research. Default style should be direct and concise, with less padding.

    Tiers make upgrade and downgrade paths explicit: L1 failures can escalate to L2; low-confidence L2 can escalate to L3; simple subtasks of L3 can drop down. Capability becomes a schedulable resource rather than a fixed cost.

    3. Task grading: where routing signals come from

    Routing quality follows signal quality. Combine three sources:

    1. Explicit labels: Callers tag task type and priority—fits known, fixed pipelines.
    2. Lightweight classifiers: An L1 model or small classifier scores difficulty and emits structured tags.
    3. Runtime feedback: Tool-call count, failed retries, schema/validation failures, latency over threshold—used for dynamic upgrade.

    Illustrative routing (placeholder APIs):

    1. def route(req, cfg):
    2. level = req.explicit_level or classify_difficulty(req) # L1/L2/L3
    3. if level == "L1" and req.context_tokens > cfg.l1_max_ctx:
    4. level = "L2"
    5. result = call_model(level, req, tools=req.tools)
    6. if not validate(result, req.schema):
    7. result = call_model(upgrade(level), req, tools=req.tools)
    8. emit_trace(req.id, level, result.usage, result.latency)
    9. return result

    Upgrades must be bounded: cap escalation count and total budget so retry storms cannot multiply cost.

    4. Multi-step work and multi-agent orchestration

    Daily-tier models usually complete work with tools: retrieval, commands, files, internal services. Three engineering rules:

    • Externalize state: Write intermediates to object storage or a workspace; keep only summaries and references in context so windows do not grow without bound.
    • Decouple asynchronously: Split long jobs into stages on a message queue, event-driven between stages, so you can replay failures and resume from checkpoints.
    • Separate roles: Split plan / execute / review across agent instances. Give the reviewer a higher tier than the executor as an internal quality gate.

    5. Cost control: cache, batching, and budgets

    Optimize with numbers, not intuition:

    • Prefix / context cache: Put stable system prompts, tool definitions, and spec docs in the request prefix so inference-side caching (often called context caching) can discount tokens. Hit rate depends on prefix stability—do not inject timestamps or random IDs at the front.
    • Batching: Merge offline jobs and trade latency for unit price.
    • Budget guards: Per product line, set token budgets and alerts; auto-downgrade to L1/L2 when exceeded.
    • Observability: Collect logs and alerts with at least six metrics: tier mix, cache hit rate, upgrade rate, cost per task, failure rate, plus latency/usage as needed.

    Vendor cache discounts and tiered pricing differ and change. Capacity planning should follow measured bills, not historical numbers.

    6. Evaluation: do not trust a single public leaderboard

    Public boards are a coarse filter. Decisions need your own eval set:

    1. Tiered eval sets: 100–300 real samples per L1/L2/L3, with gold answers and automatable assertions.
    2. Two axes: Quality (success rate, human scores) and efficiency (latency, tokens, cost per successful task).
    3. Regression gates: Run evals in CI when models or prompts change; block release on metric regressions.
    4. Canary and A/B: Ship new configs on small traffic and compare to baseline in the same period so mix differences do not pollute results.

    7. Common anti-patterns

    • Defaulting all traffic to the top tier “for safety.”
    • Embedding routing in business branches with no unified observability or tuning.
    • Unstable prompt prefixes so cache never hits.
    • Scoring quality only, then losing control of the bill.
    • Unbounded upgrades and retry loops on failing tasks.

    8. A practical rollout path

    First, wrap model calls behind a unified gateway that hides vendor differences. Second, add tier config and explicit task tags. Third, add validation, bounded upgrade, and budget guards. Fourth, build eval sets and canary gates. Fifth, use monitoring to retune tier boundaries and cache strategy.

    Baidu AI Cloud’s container platform, object storage, message queues, logging, and monitoring can host the gateway and eval pipeline; keep the model layer swappable so you are not locked to one implementation.

    The goal of layered selection is not “always use the cheapest model.” It is matching supply to task difficulty so quality, latency, and cost are all predictable, tunable, and regressable.