Overview
Builds an intelligent LLM router that chooses the cheapest/fastest/ most appropriate model or prompt for each incoming request. Covers routing strategies (complexity classifier, embedding similarity, regex/rules, cascading), model tier design, fallback logic, caching, and a complete, production-ready Python router implementation supporting OpenAI + Anthropic + local models.
When to Use This Skill
- High LLM spend and you want to reduce cost without hurting quality too much.
- Different queries have very different complexity (simple FAQ vs deep reasoning).
- You have access to multiple models (cheap fast ones + expensive smart ones) and want to use the right one per task.
- Building a multi-model gateway or agent that needs to be cost-aware.
Prerequisites
- Access to at least two LLMs with different cost/quality/latency profiles.
- A way to classify or score incoming queries (or willingness to build one).
- (Recommended) Embedding model for similarity-based routing.
- Logging of token usage and quality signals.
Steps
Define model tiers:
- Tier 0 (free/fast): small local model, rule-based, or cached answers.
- Tier 1 (cheap): GPT-4o-mini, Claude 3 Haiku, Gemini Flash, etc.
- Tier 2 (smart/expensive): GPT-4o, Claude 3.5 Sonnet, o1, etc.
- Document cost per 1M tokens and typical latency for each.
Routing strategies (pick one or combine):
- Rules / regex: Simple, zero-cost (e.g., "if query contains 'code' → coding model").
- Complexity classifier: Fine-tune or prompt a small model to output "simple | medium | complex".
- Embedding similarity: Embed the query and route based on similarity to known hard/easy example sets.
- Cascading: Always try cheap model first; if confidence low or output fails validation, escalate to expensive model.
- Task type: Route coding questions to a coding-specialized model, math to a math model, etc.
Fallback & escalation:
- If cheap model returns low-quality (detected by length, refusal, validation failure, or a judge), retry with next tier.
- Always have a "best effort" expensive fallback.
Caching:
- Exact match cache for identical queries.
- Semantic cache (embed query, retrieve similar past answers if similarity > threshold).
- TTL and invalidation strategy.
Implementation:
- Clean
Router class with route(query) -> model_name and complete(query, **kwargs).
- Pluggable classifiers and caches.
- Logging of every decision + cost.
- Optional: async support.
Output:
- Complete
llm_router.py with multiple strategies implemented.
- Example model tier config (JSON or dataclass).
- Complexity classifier prompt or fine-tuning dataset sketch.
- Caching implementation (exact + semantic).
- Dashboard or log analysis script to see routing distribution and savings.
Examples
A full router that:
- Uses a small classifier (or LLM judge) to label complexity.
- Routes simple queries to Haiku / 4o-mini.
- Routes complex reasoning to Sonnet / 4o.
- Falls back on validation failure.
- Uses semantic cache for repeated questions.
With usage example and cost savings simulation.
Edge Cases & Error Handling
- Classifier is wrong: The cascade/fallback catches most mistakes.
- Cache poisoning: Only cache when the answer was high-quality (validated or judged good).
- Cost tracking: Always log
model, input_tokens, output_tokens, cost for every call.
Verification
- The router code runs and makes decisions.
- On a test set of easy/medium/hard queries, it routes the majority of easy ones to cheap models and hard ones to expensive models.
- Quality on the test set is close to "always use expensive" while cost is significantly lower.
- Fallback triggers correctly on low-quality cheap outputs.
- Cache hits reduce cost/latency on repeated queries.
- Success: You have a measurable reduction in LLM spend with acceptable quality impact, and the system is easy to tune and monitor.
References
1---2name: llm-router-builder3description: Builds an LLM router that selects the right model or prompt based on task complexity, cost, or latency. Use when optimizing AI API costs or routing queries to specialized models.4license: Apache-2.05---67## Overview89Builds an intelligent LLM router that chooses the cheapest/fastest/ most appropriate model or prompt for each incoming request. Covers routing strategies (complexity classifier, embedding similarity, regex/rules, cascading), model tier design, fallback logic, caching, and a complete, production-ready Python router implementation supporting OpenAI + Anthropic + local models.1011## When to Use This Skill1213- High LLM spend and you want to reduce cost without hurting quality too much.14- Different queries have very different complexity (simple FAQ vs deep reasoning).15- You have access to multiple models (cheap fast ones + expensive smart ones) and want to use the right one per task.16- Building a multi-model gateway or agent that needs to be cost-aware.1718## Prerequisites1920- Access to at least two LLMs with different cost/quality/latency profiles.21- A way to classify or score incoming queries (or willingness to build one).22- (Recommended) Embedding model for similarity-based routing.23- Logging of token usage and quality signals.2425## Steps26271. **Define model tiers**:28 - Tier 0 (free/fast): small local model, rule-based, or cached answers.29 - Tier 1 (cheap): GPT-4o-mini, Claude 3 Haiku, Gemini Flash, etc.30 - Tier 2 (smart/expensive): GPT-4o, Claude 3.5 Sonnet, o1, etc.31 - Document cost per 1M tokens and typical latency for each.32332. **Routing strategies** (pick one or combine):34 - **Rules / regex**: Simple, zero-cost (e.g., "if query contains 'code' → coding model").35 - **Complexity classifier**: Fine-tune or prompt a small model to output "simple | medium | complex".36 - **Embedding similarity**: Embed the query and route based on similarity to known hard/easy example sets.37 - **Cascading**: Always try cheap model first; if confidence low or output fails validation, escalate to expensive model.38 - **Task type**: Route coding questions to a coding-specialized model, math to a math model, etc.39403. **Fallback & escalation**:41 - If cheap model returns low-quality (detected by length, refusal, validation failure, or a judge), retry with next tier.42 - Always have a "best effort" expensive fallback.43444. **Caching**:45 - Exact match cache for identical queries.46 - Semantic cache (embed query, retrieve similar past answers if similarity > threshold).47 - TTL and invalidation strategy.48495. **Implementation**:50 - Clean `Router` class with `route(query) -> model_name` and `complete(query, **kwargs)`.51 - Pluggable classifiers and caches.52 - Logging of every decision + cost.53 - Optional: async support.54556. **Output**:56 - Complete `llm_router.py` with multiple strategies implemented.57 - Example model tier config (JSON or dataclass).58 - Complexity classifier prompt or fine-tuning dataset sketch.59 - Caching implementation (exact + semantic).60 - Dashboard or log analysis script to see routing distribution and savings.6162## Examples6364A full router that:65- Uses a small classifier (or LLM judge) to label complexity.66- Routes simple queries to Haiku / 4o-mini.67- Routes complex reasoning to Sonnet / 4o.68- Falls back on validation failure.69- Uses semantic cache for repeated questions.70With usage example and cost savings simulation.7172## Edge Cases & Error Handling7374- **Classifier is wrong**: The cascade/fallback catches most mistakes.75- **Cache poisoning**: Only cache when the answer was high-quality (validated or judged good).76- **Cost tracking**: Always log `model`, `input_tokens`, `output_tokens`, `cost` for every call.7778## Verification79801. The router code runs and makes decisions.812. On a test set of easy/medium/hard queries, it routes the majority of easy ones to cheap models and hard ones to expensive models.823. Quality on the test set is close to "always use expensive" while cost is significantly lower.834. Fallback triggers correctly on low-quality cheap outputs.845. Cache hits reduce cost/latency on repeated queries.856. Success: You have a measurable reduction in LLM spend with acceptable quality impact, and the system is easy to tune and monitor.8687## References8889- [LLM Routing Papers & Techniques](https://arxiv.org/abs/2406.18665)90- [Semantic Caching](https://python.langchain.com/docs/integrations/caches/)91- [OpenAI + Anthropic SDKs](https://github.com/anthropics)92- [LiteLLM](https://github.com/BerriAI/litellm) (great for multi-provider abstraction)