model-routing-strategy
Use this skill when implementing model selection for LLM applications. Activate when the user needs to choose between different AI models, implement cost-efficient model routing, balance quality vs cost, or build intelligent model selection systems.
What this skill does
# Model Routing Strategy
Dynamically select the optimal model for each task to balance quality, cost, and latency.
## When to Use
- Building applications using multiple LLM providers
- Optimizing costs while maintaining quality
- Need different model capabilities for different tasks
- Implementing fallback strategies
- A/B testing model performance
## Model Comparison Matrix
### Capability vs Cost
| Capability | Best Models | Cost Tier |
|------------|-------------|-----------|
| Complex reasoning | Claude Opus, o1 | $$$ |
| General tasks | Claude Sonnet, GPT-4o | $$ |
| Simple tasks | Claude Haiku, GPT-4o-mini | $ |
| Code generation | Claude Sonnet, GPT-4o | $$ |
| Creative writing | Claude Opus, GPT-4 | $$$ |
| Extraction/Classification | Claude Haiku, GPT-4o-mini | $ |
### Latency Comparison
| Model | Typical Latency (TTFB) |
|-------|------------------------|
| Claude Haiku | 200-400ms |
| Claude Sonnet | 400-800ms |
| Claude Opus | 800-1500ms |
| GPT-4o-mini | 200-400ms |
| GPT-4o | 400-700ms |
| GPT-4 Turbo | 500-1000ms |
## Routing Strategies
### Strategy 1: Complexity-Based Routing
```typescript
type Complexity = 'simple' | 'medium' | 'complex';
interface Task {
prompt: string;
requirements: {
needsReasoning: boolean;
needsCreativity: boolean;
needsAccuracy: boolean;
maxLatencyMs?: number;
maxCostUSD?: number;
};
}
function assessComplexity(task: Task): Complexity {
const prompt = task.prompt.toLowerCase();
// Complex indicators
const complexPatterns = [
/analyze.*and.*compare/,
/explain.*step.*by.*step/,
/write.*comprehensive/,
/evaluate.*trade.*offs/,
/design.*architecture/,
/debug.*complex/,
/review.*security/
];
// Simple indicators
const simplePatterns = [
/summarize.*briefly/,
/extract.*from/,
/classify.*as/,
/format.*as.*json/,
/translate.*to/,
/fix.*typo/
];
if (complexPatterns.some(p => p.test(prompt)) ||
task.requirements.needsReasoning ||
task.requirements.needsCreativity) {
return 'complex';
}
if (simplePatterns.some(p => p.test(prompt))) {
return 'simple';
}
return 'medium';
}
function selectModel(complexity: Complexity): string {
const modelMap = {
simple: 'claude-haiku-4-5', // $0.25/$1.25 per 1M
medium: 'claude-sonnet-4-6', // $3/$15 per 1M
complex: 'claude-opus-4-6' // $15/$75 per 1M
};
return modelMap[complexity];
}
```
### Strategy 2: Cost-Constrained Routing
```typescript
interface ModelOption {
name: string;
provider: string;
inputCostPer1K: number;
outputCostPer1K: number;
qualityScore: number; // 0-1
avgLatencyMs: number;
}
const models: ModelOption[] = [
{ name: 'claude-opus-4-6', provider: 'anthropic', inputCostPer1K: 0.015, outputCostPer1K: 0.075, qualityScore: 0.98, avgLatencyMs: 1200 },
{ name: 'claude-sonnet-4-6', provider: 'anthropic', inputCostPer1K: 0.003, outputCostPer1K: 0.015, qualityScore: 0.95, avgLatencyMs: 600 },
{ name: 'claude-haiku-4-5', provider: 'anthropic', inputCostPer1K: 0.00025, outputCostPer1K: 0.00125, qualityScore: 0.85, avgLatencyMs: 300 },
{ name: 'gpt-4o', provider: 'openai', inputCostPer1K: 0.005, outputCostPer1K: 0.015, qualityScore: 0.94, avgLatencyMs: 550 },
{ name: 'gpt-4o-mini', provider: 'openai', inputCostPer1K: 0.00015, outputCostPer1K: 0.0006, qualityScore: 0.82, avgLatencyMs: 300 },
];
function selectWithinBudget(
estimatedInputTokens: number,
estimatedOutputTokens: number,
maxCost: number,
minQuality: number = 0.8
): ModelOption | null {
const viable = models
.filter(m => {
const cost = (estimatedInputTokens / 1000) * m.inputCostPer1K +
(estimatedOutputTokens / 1000) * m.outputCostPer1K;
return cost <= maxCost && m.qualityScore >= minQuality;
})
.sort((a, b) => b.qualityScore - a.qualityScore); // Best quality within budget
return viable[0] || null;
}
```
### Strategy 3: Latency-Optimized Routing
```typescript
function selectForLatency(
maxLatencyMs: number,
minQuality: number = 0.8
): ModelOption | null {
return models
.filter(m => m.avgLatencyMs <= maxLatencyMs && m.qualityScore >= minQuality)
.sort((a, b) => b.qualityScore - a.qualityScore)[0] || null;
}
// For real-time applications
const realtimeModel = selectForLatency(500, 0.8); // Haiku or GPT-4o-mini
// For batch processing
const batchModel = selectForLatency(2000, 0.95); // Sonnet or Opus
```
### Strategy 4: Task-Type Routing
```typescript
type TaskType = 'code' | 'creative' | 'analysis' | 'extraction' | 'chat' | 'classification';
const taskModelMap: Record<TaskType, string[]> = {
code: ['claude-sonnet-4-6', 'gpt-4o', 'claude-opus-4-6'],
creative: ['claude-opus-4-6', 'gpt-4', 'claude-sonnet-4-6'],
analysis: ['claude-opus-4-6', 'o1', 'claude-sonnet-4-6'],
extraction: ['claude-haiku-4-5', 'gpt-4o-mini', 'claude-sonnet-4-6'],
chat: ['claude-sonnet-4-6', 'gpt-4o', 'claude-haiku-4-5'],
classification: ['claude-haiku-4-5', 'gpt-4o-mini', 'claude-sonnet-4-6']
};
function selectForTaskType(taskType: TaskType, budget: 'low' | 'medium' | 'high'): string {
const candidates = taskModelMap[taskType];
const budgetIndex = { low: 2, medium: 1, high: 0 };
return candidates[Math.min(budgetIndex[budget], candidates.length - 1)];
}
```
## Fallback Chains
```typescript
interface FallbackChain {
primary: string;
fallbacks: string[];
retryConfig: {
maxRetries: number;
backoffMs: number;
};
}
const chains: Record<string, FallbackChain> = {
highQuality: {
primary: 'claude-opus-4-6',
fallbacks: ['claude-sonnet-4-6', 'gpt-4o', 'claude-haiku-4-5'],
retryConfig: { maxRetries: 3, backoffMs: 1000 }
},
costEffective: {
primary: 'claude-haiku-4-5',
fallbacks: ['gpt-4o-mini', 'claude-sonnet-4-6'],
retryConfig: { maxRetries: 2, backoffMs: 500 }
}
};
async function executeWithFallback(
chain: FallbackChain,
prompt: string
): Promise<string> {
const allModels = [chain.primary, ...chain.fallbacks];
for (let i = 0; i < allModels.length; i++) {
const model = allModels[i];
try {
return await callModel(model, prompt);
} catch (error) {
console.log(`Model ${model} failed, trying fallback...`);
if (i < allModels.length - 1) {
await sleep(chain.retryConfig.backoffMs * (i + 1));
}
}
}
throw new Error('All models in fallback chain failed');
}
```
## Dynamic Routing with Learning
```typescript
interface ModelPerformance {
model: string;
successRate: number;
avgLatency: number;
avgQuality: number; // From human feedback or automated eval
totalCalls: number;
}
class AdaptiveRouter {
private performance = new Map<string, ModelPerformance>();
recordOutcome(
model: string,
success: boolean,
latencyMs: number,
qualityScore?: number
): void {
const perf = this.performance.get(model) || {
model,
successRate: 1,
avgLatency: latencyMs,
avgQuality: 0.9,
totalCalls: 0
};
// Exponential moving average
const alpha = 0.1;
perf.successRate = alpha * (success ? 1 : 0) + (1 - alpha) * perf.successRate;
perf.avgLatency = alpha * latencyMs + (1 - alpha) * perf.avgLatency;
if (qualityScore !== undefined) {
perf.avgQuality = alpha * qualityScore + (1 - alpha) * perf.avgQuality;
}
perf.totalCalls++;
this.performance.set(model, perf);
}
selectBest(
candidates: string[],
weights: { quality: number; latency: number; reliability: number }
): string {
let bestScore = -Infinity;
let bestModel = candidates[0];
for (const model of candidates) {
const perf = this.performance.get(model);
if (!perf) continue;
const score =
weights.quality * perf.avgQuality +
weights.reliability * perf.successRate +
weights.latency * (1 - perf.avgLatency / 5000); // Normalize to 0-1
if (score > bestScore) {
bestScoRelated in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.