Skip to content
Blog

Dynamic Model Routing in ADK by Task Complexity

Building a router that sends each task to the right model — complexity signals, ADK's routing primitives, failover with error context, and evaluation to keep routing honest.

Published on • November 25, 2026

AI Assistant

A single model for every request is a compromise wearing a lab coat: trivial classification overpays for intelligence it doesn’t need, and hard analysis underperforms because it was forced through the cheap tier. Dynamic model routing replaces the compromise with a decision: assess each task’s complexity, then send it to the model best suited to that class of work.

ADK treats model selection as configuration you can make programmatic — from a simple conditional in an agent factory up to dedicated routing connectors that handle model failover. This post builds the decision logic first, then wires it in.

Step 1: decide what “complexity” means operationally

Model the signal before the mechanism. Useful, cheap-to-compute complexity signals for ADK tasks:

SignalCheap versionWhat it suggests
Intent classa small model or rule tags the intentknown simple intents → Flash tier
Constraint countnumber of requirements in the requestmore interacting constraints → Pro
Evidence volumebytes/pages/documents to synthesizelarge synthesis → Pro (long context)
Ambiguitymissing slots the task can’t proceed withoutambiguous → Pro or clarify-first
Policy riskcategory (billing change, legal, safety)high risk → Pro + guardrails
Historical failuretask type’s eval success ratefailing type → escalate tier

Keep the signal set small and explainable — three to five signals, each logged with the routing decision. An opaque router can’t be debugged when it routes wrongly at 3 a.m.

Step 2: the routing strategies

Strategy A — deterministic router (start here). A function maps signals → model string. Trivial, testable, fully explainable:

PRO_TIER = "gemini-pro-latest"
FLASH_TIER = "gemini-flash-latest"

def choose_model(*, intent: str, doc_count: int, risk: str) -> str:
    if risk in {"legal", "billing_change", "safety"}:
        return PRO_TIER
    if intent in {"faq", "classify", "extract"}:
        return FLASH_TIER
    if doc_count >= 5:
        return PRO_TIER
    return FLASH_TIER

Strategy B — model-per-agent (structural). Different agents for different jobs, each pinned to its tier; a supervisor or classifier routes between agents rather than swapping one agent’s model. This is the swarm pattern — see design patterns — and is the easiest to evaluate because each agent’s behavior is stable.

Strategy C — router connector with failover. ADK’s routing layer (experimental RoutedLlm in TypeScript, with equivalents evolving across languages) goes further: route by policy and fail over on provider errors, exposing structured failure information like errorContext.failedKeys so the caller knows which model and which configuration keys broke. That’s routing as resilience, not just cost control.

# Conceptual: policy + failover
router = RoutedModel(
    default=FLASH_TIER,
    routes=[
        Route(when=lambda t: t.metadata.get("risk") == "high", model=PRO_TIER),
    ],
    fallbacks=[FLASH_TIER],   # failover path when a model errors
)

Strategy D — escalate on doubt. Run the cheap tier; on a structured doubt signal (low confidence, failed self-check, validation error) rerun that step on the premium tier. The pattern from the tier comparison post, and often the best cost/quality ratio available.

Step 3: wire it into ADK

The cleanest integration point is the agent factory — one composition function that decides the model before constructing the agent:

def build_task_agent(task: TaskProfile) -> Agent:
    model = choose_model(
        intent=task.intent,
        doc_count=task.doc_count,
        risk=task.risk_class,
    )
    return Agent(
        model=model,
        name=f"task_agent_{task.intent}",
        instruction=task.instruction,
        tools=task.tools,
        output_schema=task.output_model,   # typed handoff for evaluation
    )

Two integration rules:

  1. Routing happens before invocation, never mid-generation. Swapping models halfway through a turn loses context and confuses state; decide at task boundaries.
  2. Log the decision. Every run should record {signals, chosen_model, reason} in session metadata — future-you needs to answer “why did this go to Pro?”

Step 4: keep routing honest with evaluation

A router is a classifier, and like any classifier it drifts:

  • Per-tier eval suites. Run the same representative scenario set through each tier; where the cheap tier matches the premium tier within noise, route down permanently.
  • Log mismatches. When a routed-down task escalates or fails, capture it as a candidate signal — the router’s false negatives are your next feature.
  • A/B the policy. Route a canary slice by new rules, compare cost per successful task and success rate before full rollout.
  • Re-baseline quarterly. Model generations shift tier capability; routing tables age.

The metric that decides everything: cost per successful task by route. Cost per call lies; a cheap model that fails and escalates twice costs more than a premium model that succeeds once.

Anti-patterns

  • ❌ Routing on raw prompt length alone (length ≠ complexity; long transcripts can be simple).
  • ❌ Per-token mid-response switching — incoherent and state-hostile.
  • ❌ An ML router trained before you’ve exhausted rules — rules you can read are rules you can fix.
  • ❌ Silent failover — if the fallback fires, it must be logged; hidden failovers hide outages.
  • ❌ One shared model string constant duplicated across files — route policy belongs in one module.

Where to go next

Routing amplifies the levers around it: tiers are compared in Flash vs Pro, sampling behavior per route in GenerateContentConfig, and the non-Gemini destinations in LiteLLM third-party models and local Ollama models.

References