Implements model selection for LLM applications, dynamically choosing between AI models to balance quality, cost, and latency. Covers complexity-based routing, cost-constrained routing, and fallback strategies.
Ships in llmops-guardian. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Dynamically select the optimal model for each task to balance quality, cost, and latency.
Providers ship new models and retire old ones often, so route by tier in code and map tiers to concrete model IDs in config.
| Tier | Typical use | Relative cost |
|---|---|---|
| Large / most capable | Complex reasoning, long-horizon agent work, hard code changes | $$$ |
| Medium / balanced | General tasks, most code generation, chat | $$ |
| Small / fast | Extraction, classification, routing, short summaries | $ |
Which model belongs in which tier for your workload is an empirical question: measure quality with your own evals (see the cost-quality-tradeoff skill) and latency with your own production telemetry. Look up current model IDs and prices on each provider's models and pricing pages (Anthropic: https://platform.claude.com/docs/en/about-claude/models/overview).
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 = {
// Map tiers to current model IDs from config; prices change, so look them
// up on the provider pricing page instead of hard-coding them here.
simple: SMALL_MODEL_ID,
medium: MEDIUM_MODEL_ID,
complex: LARGE_MODEL_ID
};
return modelMap[complexity];
}
interface ModelOption {
name: string;
provider: string;
inputCostPer1K: number;
outputCostPer1K: number;
qualityScore: number; // 0-1
avgLatencyMs: number;
}
// PLACEHOLDER values. Load prices from the provider pricing pages, qualityScore
// from YOUR eval suite on YOUR tasks, and avgLatencyMs from your own production
// measurements. Do not copy published leaderboard numbers into routing logic.
const models: ModelOption[] = [
{ name: LARGE_MODEL_ID, provider: 'anthropic', inputCostPer1K: 0.005, outputCostPer1K: 0.025, qualityScore: 0.95, avgLatencyMs: 1200 },
{ name: MEDIUM_MODEL_ID, provider: 'anthropic', inputCostPer1K: 0.003, outputCostPer1K: 0.015, qualityScore: 0.9, avgLatencyMs: 600 },
{ name: SMALL_MODEL_ID, provider: 'anthropic', inputCostPer1K: 0.001, outputCostPer1K: 0.005, qualityScore: 0.8, avgLatencyMs: 300 },
{ name: ALT_PROVIDER_MODEL_ID, provider: 'openai', inputCostPer1K: 0.002, outputCostPer1K: 0.008, qualityScore: 0.85, avgLatencyMs: 500 },
];
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;
}
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); // your fastest tier that meets the quality bar
// For batch processing
const batchModel = selectForLatency(2000, 0.95); // a higher-quality tier
type TaskType = 'code' | 'creative' | 'analysis' | 'extraction' | 'chat' | 'classification';
const taskModelMap: Record<TaskType, string[]> = {
// Ordered [high budget, medium budget, low budget]; validate with your evals
code: [LARGE_MODEL_ID, MEDIUM_MODEL_ID, SMALL_MODEL_ID],
creative: [LARGE_MODEL_ID, MEDIUM_MODEL_ID, SMALL_MODEL_ID],
analysis: [LARGE_MODEL_ID, MEDIUM_MODEL_ID, SMALL_MODEL_ID],
extraction: [MEDIUM_MODEL_ID, SMALL_MODEL_ID, SMALL_MODEL_ID],
chat: [MEDIUM_MODEL_ID, SMALL_MODEL_ID, SMALL_MODEL_ID],
classification: [MEDIUM_MODEL_ID, SMALL_MODEL_ID, SMALL_MODEL_ID]
};
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)];
}
interface FallbackChain {
primary: string;
fallbacks: string[];
retryConfig: {
maxRetries: number;
backoffMs: number;
};
}
const chains: Record<string, FallbackChain> = {
highQuality: {
primary: LARGE_MODEL_ID,
fallbacks: [MEDIUM_MODEL_ID, ALT_PROVIDER_MODEL_ID, SMALL_MODEL_ID],
retryConfig: { maxRetries: 3, backoffMs: 1000 }
},
costEffective: {
primary: SMALL_MODEL_ID,
fallbacks: [ALT_PROVIDER_MODEL_ID, MEDIUM_MODEL_ID],
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');
}
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) {
bestScore = score;
bestModel = model;
}
}
return bestModel;
}
}
interface ABTest {
name: string;
variants: { model: string; weight: number }[];
metrics: string[];
}
class ModelABTester {
private tests = new Map<string, ABTest>();
private results = new Map<string, { model: string; metric: string; value: number }[]>();
selectVariant(testName: string, userId: string): string {
const test = this.tests.get(testName);
if (!test) throw new Error(`Test ${testName} not found`);
// Deterministic selection based on userId
const hash = this.hashUserId(userId);
let cumWeight = 0;
for (const variant of test.variants) {
cumWeight += variant.weight;
if (hash < cumWeight) {
return variant.model;
}
}
return test.variants[0].model;
}
recordMetric(testName: string, model: string, metric: string, value: number): void {
const results = this.results.get(testName) || [];
results.push({ model, metric, value });
this.results.set(testName, results);
}
getResults(testName: string): Record<string, Record<string, { avg: number; count: number }>> {
const results = this.results.get(testName) || [];
// Aggregate by model and metric
// ...
}
}
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
Other plugins' skills for the same job
7 skills in this plugin
/ai-audit-loggingUse this skill when implementing audit logging for AI systems. Activate when the user needs to track
AI decisions for compliance, implement audit trails for LLM usage, meet regulatory requirements
(EU AI Act, SOC2), or create accountability records for AI-generated content.
/llm-fallback-chainsUse this skill when implementing fallback strategies for LLM applications. Activate when the user needs
graceful degradation for AI services, multi-provider failover, handling LLM outages, or building
resilient AI systems.
/llm-rate-limitingUse this skill when implementing rate limiting for LLM APIs. Activate when the user needs to prevent
API quota exhaustion, implement backoff strategies, handle rate limit errors, or manage concurrent
LLM requests.
/prompt-caching-patternsUse this skill when implementing caching for LLM applications. Activate when the user wants to reduce
API costs through caching, implement semantic caching, cache LLM responses, optimize repeated prompts,
or set up efficient caching strategies for AI applications.
/prompt-injection-guardUse this skill when securing AI applications against prompt injection. Activate when the user needs to
prevent prompt injection attacks, validate AI inputs, implement input sanitization, or protect against
adversarial prompts.
/token-cost-analyzerUse this skill when analyzing and optimizing LLM API costs. Activate when the user wants to reduce
AI API spending, understand token usage, audit LLM costs, optimize prompts for cost efficiency,
or track and report on AI expenditure.
3 plugins in one repository ship this exact skill · first indexed Nov 5, 2026
/llmops-guardian:model-routing-strategyfrom llmops-guardian
npx claudepluginhub latestaiagents/agent-skills --plugin llmops-guardian