Router (dispatcher): classify first, then send each request to the right specialist

A router reads each request, picks one label, and sends it to a specialist path. Use it when one system serves very different kinds of request and one prompt cannot serve them all well.

Router in 60 seconds

  • What: a small step that reads a request, outputs one label with a confidence, and sends the request to the matching specialist path.
  • Who decides the path: your code acts on the label. The model only classifies; it does not wander.
  • Best for: support desks, internal help tools, and any system where billing, technical, and general questions need different prompts, tools, or models.
  • Weak spots: wrong labels send the request to the wrong place, and requests that need two specialists do not fit one label.
  • Origin: RouteLLM (Ong et al., 2024) learns a router from preference data that sends each query to a stronger or a weaker model.

Where this type fits

Orchestration patterns are grouped by who decides the path. The router belongs to the group where your code decides: pipeline, router, parallel fan-out, and state graph. The model supplies a label, but a plain if or lookup table turns that label into an action. See the orchestration hub for the full comparison.

The problem it solves

Imagine one assistant that answers billing questions, debugs API errors, and chats about opening hours. To serve all three, its prompt grows long and its tool list grows wide. Billing rules sit next to code samples. The model sees forty tools when it needs three. Answers get slower, cost more, and mix up topics. A change to the billing section can quietly break the technical section.

A second problem is cost. Most traffic is easy: simple lookups and greetings. A few requests are hard. If every request goes to the largest model, you pay the top price for work a small model handles well. If every request goes to the small model, the hard ones fail.

A router fixes both. It splits traffic early. Each specialist gets a short, focused prompt and only its own tools. Easy requests go to cheap paths and hard ones go to strong paths. You can also test, version, and own each specialist separately.

How it works

  • Receive the request. Include only what the classifier needs: the latest message and perhaps a short summary of earlier turns.
  • Classify. Ask a small model, or a trained classifier, to return a label from a fixed list plus a confidence score. Use structured output so the label is always one of the allowed values.
  • Check confidence. If the score is below a threshold, or the label is not in the list, use the safe default path.
  • Dispatch. A lookup table maps the label to a handler: a prompt, a tool set, and a model choice.
  • Run the specialist. The chosen path does the real work and produces the response.
  • Log the decision. Record the label, the confidence, and the path taken so you can audit and improve routing later.
The classifier chooses one path, low confidence falls back to the general specialist, and every decision is logged.

The diagram shows one decision point and no loop. That is the point of the pattern. The classifier runs once, the label picks a path, and the specialist owns the rest. Because the decision is one small call, it adds little delay, especially when the classifier is a small model.

The safe default matters more than it looks. When the classifier is unsure, the request should go to a path that can cope with anything, even if it is not the best fit. A general specialist, or a handoff to a person, is better than a confident wrong answer.

A worked example

Acme runs a support assistant with three paths: billing, technical, and general. Customer message: "I was charged twice for March and now the export button gives a 500 error."

  • Input: the message above, plus the account plan name.
  • Classifier output: {"label": "billing", "confidence": 0.54}. The message mixes two topics, so confidence is low.
  • Threshold check: the threshold is 0.7. 0.54 is below it, so the router ignores the label and picks the safe default, general.
  • General specialist: it replies that it will open two tickets, one for the double charge and one for the export error, and asks for the invoice number.
  • Log entry: {"label": "billing", "confidence": 0.54, "path": "general", "reason": "low_confidence"}.

Next week the team reads the log, sees many mixed messages, and decides to split them before routing. That is a change to the router, not to any specialist.

Building it

A router with a confidence threshold and a safe default (illustrative) (python)
from dataclasses import dataclass

ALLOWED = {"billing", "technical", "general"}
DEFAULT = "general"
MIN_CONFIDENCE = 0.7   # tune on labelled examples, not by guesswork

@dataclass
class Decision:
    label: str
    confidence: float

def classify(message: str) -> Decision:
    # Placeholder: a small model or trained classifier that returns
    # structured output such as {"label": "...", "confidence": 0.0 to 1.0}.
    raw = llm.generate_json(
        prompt=CLASSIFIER_PROMPT, input=message, timeout_s=3,
    )
    return Decision(raw.get("label", ""), float(raw.get("confidence", 0)))

def choose_path(decision: Decision) -> tuple[str, str]:
    # Never trust the label blindly. Check it is allowed and confident.
    if decision.label not in ALLOWED:
        return DEFAULT, "invalid_label"
    if decision.confidence < MIN_CONFIDENCE:
        return DEFAULT, "low_confidence"
    return decision.label, "ok"

HANDLERS = {
    "billing":   lambda m: run_specialist(BILLING_PROMPT, billing_tools, m),
    "technical": lambda m: run_specialist(TECH_PROMPT, tech_tools, m),
    "general":   lambda m: run_specialist(GENERAL_PROMPT, [], m),
}

def handle(message: str) -> str:
    try:
        decision = classify(message)
    except Exception:
        # If the classifier fails or times out, the request still gets served.
        decision = Decision("", 0.0)
    path, reason = choose_path(decision)
    log.info("route", label=decision.label, conf=decision.confidence,
             path=path, reason=reason)
    return HANDLERS[path](message)

Everything outside classify and run_specialist is ordinary code. llm, log, the prompts, the tool lists, and run_specialist are placeholders for your own components.

Design decisions

  • Classifier choice: start with a small model and a short prompt that lists the labels with two examples each. Move to a trained classifier once you have a few thousand labelled requests, because it is faster and cheaper per call.
  • Label design: keep three to eight labels that are mutually exclusive and match real ownership. If two labels always go to the same team, merge them.
  • Safe default: always define one. Make it a path that is safe for any request, such as a general specialist or a person.
  • Threshold: set it from data. Plot accuracy against confidence on labelled examples and pick the point where wrong routes become costly. Start at 0.7 and adjust.
  • Latency: keep the classifier call under a second, with a timeout and a fallback to the default. Run it on the smallest model that meets your accuracy target.
  • Access control: the router decides the path, so it must not decide permissions. Check the user's rights inside each specialist, not from the label.
  • Versioning: version the label list and the classifier prompt together. Log the version with every decision so old logs stay readable.

Measuring it

  • Routing accuracy: label a sample of real requests by hand. Accuracy is correct routes divided by total sampled. Track it per label, not just overall.
  • Confusion matrix: count how often each true label is sent to each path. It shows which pairs of specialists are being mixed up.
  • Fallback rate: the share of requests sent to the default for low confidence. A rising rate means traffic has drifted away from your labels.
  • Cost per request by path: total spend on each path divided by its requests. Compare against a baseline where everything uses one strong model.
  • End-to-end quality by path: a graded sample of final answers per specialist, so you can tell a routing fault from a specialist fault.
  • Router latency: the median and 95th percentile of the classification call alone.
Per-label accuracy from a labelled sample (illustrative) (python)
from collections import Counter

def routing_report(samples):
    # samples: list of (true_label, predicted_label) pairs from human review
    totals, correct = Counter(), Counter()
    for true, pred in samples:
        totals[true] += 1
        correct[true] += int(true == pred)
    return {lab: correct[lab] / totals[lab] for lab in totals}

When to use it, and when not to

SituationUse this type?Why
Support desk with billing, technical, and general questionsYesEach topic needs its own prompt and tools, and the labels are clear.
Mixed traffic where most requests are easyYesSend easy requests to a small model and hard ones to a strong model to cut cost.
One narrow task such as summarising invoicesNoThere is only one path, so a router adds a call and nothing else.
Requests that routinely need two specialists at onceNot aloneUse parallel fan-out or a supervisor so more than one path can run.
Requests where the path depends on earlier resultsNot aloneA state graph can decide again after each step.
High-risk actions such as paymentsWith careRoute, then add a human checkpoint inside the specialist.

Trade-offs

DimensionEffectWhat to do about it
QualitySpecialists with short, focused prompts usually do better. A wrong route does much worse than a general answer.Use a safe default and a confidence threshold, and review the confusion matrix every week.
LatencyAdds one classification call before any real work.Use a small model, set a timeout, and start the default path if it is exceeded.
CostSmall models handle most traffic, so average cost falls. The classifier call is a small fixed extra.Compare spend per path against an all-strong-model baseline.
ComplexityMore prompts and tool sets to maintain, plus a label list to govern.Give each path a named owner and its own tests.
Failure modesLabel drift, ambiguous requests, and silent misroutes that look like specialist failures.Log every decision with its confidence and sample logs for human review.

A pipeline runs every request through the same stages in order. A router runs each request through one stage chosen from several. They combine well: route first, then run a pipeline inside each specialist.

A supervisor with workers also picks who does the work, but a model makes that choice repeatedly and can use several workers on one request. A router chooses once and its choice is a plain label your code acts on, which is easier to test and cheaper to run.

What this means for your role

Common mistakes

Further reading

A router is a small piece that earns its place by keeping specialists focused. Keep its job narrow, give it a safe default, and measure its mistakes.

Search topics

↑↓ to move · Enter to open · Esc to close