Hierarchical Model Routing and Long-Running Agent Engineering Practices
This article explains how to move from a single "strongest model" strategy to a hierarchical model routing system for LLM applications. It covers how to tier models by capability and cost, how to classify tasks into complex, everyday, and high-frequency categories, and how to orchestrate long-running agents with tool output preprocessing, multi-agent coordination, budget control, and observability. The goal is to balance task quality, latency, and cost in production.
1. Background: From “Using the Strongest Model” to “Routing Models”
When teams first adopt large language model capabilities, they often use a simple strategy: send every task to the strongest, largest model available. This works in validation, but it quickly creates three problems in production.
The first problem is cost control. Complex models are typically priced per token, and their unit price is usually much higher than lighter tiers. When many simple requests (format conversion, field extraction, short-text classification) also go through the flagship model, the bill grows linearly or even non-linearly.
The second problem is unpredictable latency. Flagship models often come with longer inference chains and slower first-token responses, which is not friendly to interactive applications or high-frequency batch processing.
The third problem is capability mismatch. Using a strong model for simple tasks does not bring proportional gains. Instead, it consumes quota and concurrency resources that long-running tasks need.
A more reasonable engineering approach is to build a three-layer structure: capability tiering + task routing + execution orchestration. First, divide models into tiers by capability and cost. Second, classify tasks by complexity and frequency. Finally, use an orchestration layer to connect tool calls, context management, and multi-agent collaboration into an observable execution chain.
2. Capability Tiering: Treat Models as a Schedulable Resource Pool
The core of tiering is not labeling models, but defining clear routing rules and fallback strategies. A common industry practice is to divide models into three tiers:
- Flagship tier: used for complex coding, long-chain agent tasks, knowledge work, security analysis, scientific computing, and other high-difficulty scenarios;
- Balanced tier: used for daily development, routine code completion, document generation, structured extraction, and other medium-complexity tasks;
- High-frequency tier: used for classification, rewriting, summarization, routing decisions, lightweight processing after cache hits, and other high-frequency, low-complexity tasks.
When implementing this, it is recommended to define “admission conditions” and “exit conditions” for each tier. For example:
routing_policy:default_tier: balancedescalate_rules:- when: "task.type == 'code_agent' and task.steps > 8"to: flagship- when: "tool_error_rate > 0.2"to: flagshipdegrade_rules:- when: "task.type in ['classify','rewrite','extract'] and input_tokens < 2000"to: high_freqobservability:log_fields: [tier, task_type, tokens_in, tokens_out, latency_ms, cost_est]
The routing layer needs to be tied to an observability system. Only by logging each request’s tier, token consumption, latency, and failure reasons into logging and monitoring services can you continuously optimize routing rules instead of tuning them by intuition.
3. Task Classification: Criteria for Complex, Everyday, and High-Frequency Tasks
After tiering, the key is how to classify tasks accurately. It is recommended to score tasks from four dimensions:
- Step complexity: whether multi-round tool calls are needed, and whether backtracking and self-verification are required;
- Context size: whether the input is very long, and whether cross-file or cross-document retrieval is needed;
- Cost of errors: whether an error would cause rollback costs, data risk, or security impact;
- Call frequency: whether it is triggered at millisecond-level high frequency.
An executable scoring example:
def choose_tier(task):score = 0score += 2 if task.needs_multi_tool else 0score += 2 if task.input_tokens > 8000 else 0score += 2 if task.risk_level == "high" else 0score -= 1 if task.qps > 50 else 0if score >= 4: return "flagship"if score >= 2: return "balanced"return "high_freq"
It is important to note that classification rules should support gradual rollout and rollback. In the early stage of launch, a “shadow mode” can be used: new rules only record results without taking effect, running in parallel with old rules for a period. After comparing success rates, latency, and costs, you can switch to the new rules.
4. Tool Output Preprocessing: The First Line of Defense for Long-Task Stability
Long-task failures are often not because the model “doesn’t know how to do it,” but because tool returns pollute the context. Common noise includes: overly long logs, repeated stack traces, binary fragments, incomplete pagination, and redundant fields. Without preprocessing, the model will allocate attention to irrelevant information, causing plan drift.
Engineering practice recommends adding a layer of “result cleaning and compression” before all tool results enter the model:
- Structure first: convert unstructured output into tables or key-value structures, keeping only necessary fields;
- Truncation and summarization: extract key lines from very long text first, then pass it to the model;
- Deduplication and sorting: merge duplicate errors, and sort by time or severity;
- Error normalization: unify failure formats from different tools into a
code/message/retryabletriple.
Example:
def normalize_tool_output(raw):items = parse(raw)items = dedupe(items, key="fingerprint")items = sort_by(items, key="severity", reverse=True)return {"summary": summarize(items, max_lines=20),"errors": [e for e in items if e.retryable],"truncated": len(items) > 20}
Preprocessed tool output can significantly reduce invalid tokens and make subsequent plan generation more focused.
5. Long-Task Orchestration: When to Enable Multi-Agent Systems
Multi-agent systems are not the default option. They should only be enabled when a task meets the following conditions: the goal can be decomposed into parallel subgoals, subtasks have low coupling, and different roles (planner, executor, reviewer) need to cross-validate.
A general orchestration framework is as follows:
- Planner: decomposes the goal into a subtask graph (DAG) with dependencies;
- Executor: schedules to different models by tier, calls tools, and produces intermediate results;
- Reviewer: validates key nodes; if validation fails, it triggers a retry or escalation to a higher tier;
- Aggregator: merges results, generates final deliverables and execution traces.
Pseudo-code example:
plan = planner(goal)for node in topo_sort(plan):tier = route(node)result = executor(tier, node, tools)if reviewer.reject(result):result = executor("flagship", node, tools, retry=1)artifacts.append(result)return aggregator(artifacts)
The key engineering point is “budget control”: set maximum steps, maximum tokens, and maximum wall-clock time for each subtask. When the limit is exceeded, the system should downgrade or terminate to prevent long tasks from expanding indefinitely.
6. Context Governance and Caching: Key to Reducing Costs
The benefits of hierarchical scheduling need to be combined with context governance to be realized. It is recommended to:
- Only inject context fragments relevant to the current subtask, avoiding dumping the entire library;
- Design stable prefixes (system prompts, tool descriptions) to be cache-friendly, using cache read discounts to reduce repeated costs;
- Store intermediate artifacts in object storage and use references instead of full text to reduce repeated transfers;
- Use message queues to decouple long tasks and change synchronous waiting to asynchronous callbacks.
Example structure:
{"task_id": "t-1024","tier": "balanced","context_refs": ["obj://ctx/plan.md", "obj://ctx/api.json"],"budget": {"steps": 12, "tokens": 60000, "wall_clock_s": 900}}
7. Observability and Evaluation: Data-Driven Routing Optimization
Without evaluation, there is no optimization. It is recommended to establish three types of metrics:
- Quality metrics: task success rate, manual review pass rate, regression test pass rate;
- Efficiency metrics: first-token latency, total duration, average steps;
- Cost metrics: token consumption per task, cache hit rate, cost per successful task.
The evaluation set should cover “simple/medium/complex” tiers and retain real failure samples for regression. Every time routing thresholds or prompts are adjusted, A/B testing should be done on a fixed evaluation set, and the cost-quality curve should be observed, rather than looking at a single run score.
8. Implementation Roadmap
- Phase 1: Connect logs and monitoring, establish token/latency/cost baselines;
- Phase 2: Launch three-tier routing and shadow mode, verify routing accuracy;
- Phase 3: Add tool output preprocessing and budget control to stabilize long tasks;
- Phase 4: Enable multi-agent orchestration when conditions are met, and implement gradual rollout and rollback;
- Phase 5: Use evaluation sets to drive continuous optimization, forming an iterative culture of “scheduling as strategy.”
9. Conclusion
Model capability tiering and task hierarchical scheduling are essentially about upgrading “calling models” to “managing compute resources.” When teams can assign tasks to appropriate tiers based on complexity, frequency, and risk, and combine them with tool output cleaning, context governance, budget constraints, and observable evaluation, they can achieve a sustainable balance between quality, latency, and cost. This is also a necessary path from “single-point strongest” to “system optimum.”
