This prompt is for infrastructure teams managing token budgets across model tiers. It produces a cost-aware routing decision that maps task complexity to model capability within defined budget constraints. Use it when you operate multiple model endpoints at different price points and need a deterministic, auditable way to select the cheapest model that can handle the task reliably. The ideal user is an AI infrastructure engineer or platform developer who has already instrumented their application with a model router and needs a classification step that makes a structured decision before any downstream model invocation occurs. You must have a defined model tier list with known capability profiles and per-token costs; this prompt does not discover or recommend models.
Prompt
Cost-Optimized Model Selection Prompt

When to Use This Prompt
Defines the precise operational context for using the cost-optimized model selection prompt, identifying the ideal user, required inputs, and critical boundaries where the prompt should not be applied.
This is not a general-purpose model recommendation prompt. Do not use it when you lack concrete cost data, when your model tiers have overlapping or undefined capabilities, or when the task requires subjective quality judgments that your tier definitions cannot capture. The prompt assumes you have already profiled your models against representative workloads and can express their strengths as discrete capability classes (e.g., 'handles complex reasoning,' 'handles simple extraction,' 'handles creative generation'). It also assumes you have a budget policy—whether a hard per-request cost ceiling, a daily token budget, or a cost-priority weighting—that can be expressed as a constraint. Without these inputs, the prompt will produce unreliable routing decisions that may appear reasonable but fail under production load.
The prompt works as a classification step inside a model router. It receives a task description and budget parameters, then returns a structured routing decision before any downstream model invocation occurs. This means you should wire it into your request pipeline after authentication and input validation but before the model call. The output should be treated as a machine-readable routing instruction, not a user-facing explanation. Validate the output against your actual model registry before executing the route; if the prompt selects a model that doesn't exist or exceeds budget, your router should fall back to a safe default and log the discrepancy for review. Common failure modes include over-classifying simple tasks to expensive models out of caution, under-classifying complex tasks to cheap models that produce unusable output, and failing to account for input token costs when calculating total request cost.
Use Case Fit
Where the Cost-Optimized Model Selection Prompt works and where it introduces unacceptable risk. Use these cards to decide if this prompt fits your architecture before integrating it into a model router.
Good Fit: Tiered Model Architectures
Use when: You operate multiple model tiers (e.g., lightweight, standard, premium) and need a deterministic, cost-aware dispatch layer. Guardrail: Define explicit complexity-to-tier mapping rules in the prompt to prevent the router from defaulting to the most expensive model for trivial tasks.
Bad Fit: Latency-Critical Real-Time Systems
Avoid when: Your system has a strict sub-100ms routing budget. Adding an LLM call for model selection introduces latency overhead that may violate your SLA. Guardrail: Use a rule-based classifier or cached routing table for latency-sensitive paths, and reserve this prompt for asynchronous or batch workloads.
Required Inputs
What you need: A defined task description, a catalog of available models with their cost-per-token and capability profiles, and a maximum budget constraint. Guardrail: Validate that the model catalog is complete and up-to-date before every routing call. A missing model entry will cause the prompt to make uninformed decisions.
Operational Risk: Budget Overrun by Death by a Thousand Cuts
What to watch: The prompt correctly routes individual low-complexity tasks to cheap models, but a surge in request volume still causes a budget overrun. Guardrail: Implement a circuit breaker on the aggregate token spend. If the total cost exceeds a threshold within a time window, force all traffic to the cheapest available model or a static fallback.
Operational Risk: Complexity Misclassification
What to watch: A task that appears simple (e.g., a short user query) but requires deep reasoning is routed to a cheap, less capable model, producing a low-quality or incorrect output. Guardrail: Add a lightweight confidence score to the routing decision. If confidence is below a threshold, escalate to a human reviewer or a more capable model for a second opinion.
Operational Risk: Cost Optimization Drift
What to watch: Over time, the router becomes overly aggressive in selecting the cheapest model, degrading output quality in ways that are not immediately obvious. Guardrail: Continuously evaluate a sample of routed outputs against quality benchmarks. If quality scores drop below an acceptable threshold, automatically tighten the cost-quality trade-off parameters in the prompt.
Copy-Ready Prompt Template
A reusable prompt that maps task complexity to model capability within token budget constraints, producing a cost-aware routing decision.
This prompt template is designed to be dropped directly into your model router or classification middleware. It forces the routing model to consider three dimensions simultaneously: task complexity, required capability tier, and token budget. The output is a structured decision that your application can parse and execute without additional interpretation. Replace each square-bracket placeholder with your actual values before sending to the routing model.
textYou are a cost-aware model router. Your job is to select the most cost-effective model that can reliably complete the task within the stated constraints. ## TASK TO ROUTE [USER_INPUT] ## AVAILABLE MODELS [MODEL_CATALOG] ## TOKEN BUDGET Maximum budget: [MAX_TOKENS] tokens Cost per 1K tokens for each model: [MODEL_PRICING] ## TASK COMPLEXITY INDICATORS - Requires reasoning depth: [REASONING_DEPTH low/medium/high] - Requires external tool use: [TOOLS_REQUIRED true/false] - Requires structured output: [STRUCTURED_OUTPUT true/false] - Domain specificity: [DOMAIN_SPECIFICITY general/domain/niche] - Latency tolerance: [LATENCY_TOLERANCE real-time/near-real-time/batch] ## ROUTING RULES 1. Select the cheapest model that meets all task requirements. 2. If no model fits within budget, select the closest fit and flag the budget overrun. 3. If task complexity is ambiguous, default to the safer (more capable) model and flag for review. 4. Never route PII or regulated data to models outside approved zones. ## OUTPUT FORMAT Return a JSON object with these exact fields: { "selected_model": "model_id", "confidence": 0.0-1.0, "estimated_tokens": integer, "estimated_cost": "$X.XXXX", "budget_compliant": true/false, "budget_overrun_amount": "$X.XXXX or null", "fallback_model": "model_id or null", "routing_reasoning": "Brief explanation of the decision", "flags": ["budget_overrun", "complexity_ambiguous", "requires_review"] }
To adapt this template, start by populating [MODEL_CATALOG] with your actual model inventory. Include model IDs, capability descriptions, context window sizes, and per-token pricing. The [MODEL_PRICING] field should mirror your current rate card. If you use dynamic pricing or spot instances, update this field at runtime from your cost API. The complexity indicators should be pre-computed by an upstream classification step or set to sensible defaults based on your workload profile. If you lack a pre-classifier, remove the complexity indicators and let the routing model infer complexity from [USER_INPUT] alone, but expect higher variance in routing decisions.
Before deploying, run this prompt through your eval harness with at least 50 labeled examples covering: obvious cheap-model cases, obvious expensive-model cases, edge cases near budget boundaries, and inputs that should trigger the requires_review flag. Measure precision and recall on budget-compliant routing decisions. If the router consistently over-selects expensive models, tighten the routing rules or add few-shot examples showing correct cheap-model selections. If it under-selects and produces failures, loosen the safety default in rule 3 or increase the budget. Wire the output JSON into your application's model dispatch layer, and log every routing decision with the actual cost incurred so you can detect drift between estimated and actual token consumption.
Prompt Variables
Inputs the prompt needs to work reliably. Validate each before sending.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TASK_DESCRIPTION] | The user's request or task to be routed | Summarize the Q3 financial report and identify top 3 risks | Must be non-empty string; check length > 10 chars; reject empty or whitespace-only inputs |
[AVAILABLE_MODELS] | JSON array of model options with capabilities and per-token costs | [{"name":"gpt-4o","cost_per_1k_input":0.005,"cost_per_1k_output":0.015,"capabilities":["reasoning","structured_output"]}] | Must be valid JSON array with at least 1 model; each model requires name, cost_per_1k_input, cost_per_1k_output, and capabilities fields |
[BUDGET_CONSTRAINTS] | Maximum allowed cost for this request in USD | 0.05 | Must be positive float; reject zero or negative values; parse as decimal with 4-digit precision |
[LATENCY_REQUIREMENT] | Maximum acceptable response time in milliseconds | 2000 | Must be positive integer; reject values below 100ms; null allowed if latency is unconstrained |
[TASK_COMPLEXITY_HINT] | Optional pre-assessed complexity level to bias routing | high | Must be one of [low, medium, high] or null; reject unrecognized values; null triggers internal complexity assessment |
[OUTPUT_FORMAT_REQUIREMENT] | Required output structure or schema constraint | json_object | Must be one of [text, json_object, json_array, function_call] or null; null defaults to text |
[PREVIOUS_ROUTING_DECISIONS] | Optional array of recent routing decisions for consistency checking | [{"task_hash":"abc123","model_selected":"gpt-4o-mini","cost":0.002}] | Must be valid JSON array or null; each entry requires task_hash, model_selected, and cost fields; null allowed for first request in session |
Implementation Harness Notes
How to wire the cost-optimized model selection prompt into a production routing middleware with validation, retries, and budget enforcement.
The Cost-Optimized Model Selection Prompt is designed to sit inside a model routing middleware—a thin service that receives a task payload, invokes the prompt against a fast, cheap classifier model, and uses the structured output to dispatch the actual work to the appropriate model tier. This harness is not a standalone chatbot. It is a decision function that must return a deterministic, validatable routing decision within a strict latency budget. The primary integration point is a select_model() function that wraps the LLM call, parses the JSON response, validates the decision against current budget state and rate limits, and returns a model identifier plus reasoning trace to the upstream orchestrator.
Validation and state checks are the most critical part of this harness. Before accepting the LLM's routing decision, validate that: (1) the selected model exists in the current inventory and is not in a degraded state; (2) the estimated token cost of the selected model does not exceed the remaining budget for the tenant, session, or time window; (3) the complexity score is internally consistent with the model tier (a complexity: high task routed to a lightweight model should trigger a review log entry); and (4) the output schema is parseable with all required fields present. Implement a validate_routing_decision() function that checks these invariants and returns either an approved decision or a fallback override. If validation fails, fall back to a conservative default model (e.g., the cheapest capable model) and increment a budget_override_count metric. Log every override with the original LLM decision, the validation failure reason, and the fallback applied.
Retry logic should be minimal and bounded. The classifier model call should have a single retry on timeout or malformed JSON, with a short backoff (100-300ms). Do not retry on budget-exceeded decisions—those are policy violations, not transient errors. If the classifier model returns an unparseable response after one retry, route to the default model and emit a routing_parse_failure alert. Observability requires logging: the input task summary (not full content, to control log costs), the raw LLM routing decision, the validated decision, the current budget state, the selected model, and the latency of the routing call itself. These logs feed into cost dashboards that track budget utilization, unnecessary expensive-model usage, and routing decision accuracy over time.
Model choice for the router itself matters. Use the cheapest fast model that reliably produces valid JSON for this task—typically a lightweight model like GPT-4o-mini, Claude Haiku, or Gemini Flash. The router model should cost less than 1% of the average downstream task cost to justify its existence. If the router model's cost approaches 5% of downstream costs, the routing logic is too expensive and should be replaced with a rule-based classifier or cached decisions for repetitive task patterns. Budget state must be passed into the prompt's [BUDGET_CONTEXT] placeholder as a structured object containing: remaining budget, budget period, current spend rate, and any hard caps. Do not rely on the LLM to fetch or calculate budget state—provide it explicitly from your application's budget tracker.
Testing this harness requires a suite of task payloads with known complexity levels and budget scenarios. Test cases should include: tasks clearly appropriate for cheap models, tasks clearly requiring expensive models, borderline tasks where either choice is defensible, and budget-exhausted scenarios where the only valid decision is the cheapest model or a rejection. Measure routing accuracy against human-labeled complexity assessments, but also measure cost efficiency: what percentage of tasks are routed to the cheapest model that can handle them? A router that always selects the most expensive model is failing its core purpose, even if each individual decision seems defensible. Run these tests in CI before deploying prompt changes, and gate deployments on cost-efficiency regression thresholds.
What to avoid: Do not use this prompt for real-time streaming decisions where the routing latency budget is under 200ms—the LLM call overhead will violate that constraint. Do not pass raw user content into the routing prompt if it contains PII; extract a task summary or complexity signal first. Do not let the router model select itself for downstream work. And do not treat the complexity score as a quality metric for anything other than routing—it is a cost-control signal, not an evaluation of output correctness. The next step after implementing this harness is to deploy a shadow mode where routing decisions are logged but not enforced, letting you measure cost savings potential before cutting over production traffic.
Expected Output Contract
Defines the required JSON structure for the cost-optimized model routing decision. Every field must be validated before the routing instruction is executed downstream.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
selected_model | string | Must match an entry in the [MODEL_CATALOG] enum. No free-form model names allowed. | |
cost_tier | string | Must be one of: 'budget', 'standard', 'premium'. Must align with selected_model's tier in [MODEL_CATALOG]. | |
estimated_tokens | integer | Must be a positive integer. Must not exceed the [TOKEN_BUDGET] for the selected cost_tier. | |
estimated_cost_usd | number | Must be a positive float. Calculated as estimated_tokens * model_rate. Must be less than or equal to [MAX_COST_USD]. | |
complexity_score | integer | Must be an integer between 1 and 5. A score of 4 or 5 routed to 'budget' tier must trigger a retry with a higher tier. | |
reasoning | string | Must be a non-empty string. Must explicitly justify why the selected_model is sufficient for the complexity_score. Must not contain placeholder text. | |
fallback_model | string | If not null, must match an entry in [MODEL_CATALOG]. Must be a higher cost_tier than selected_model. Required if complexity_score >= 4 and selected_model is 'budget'. | |
requires_human_review | boolean | Must be true if the input contains [REGULATED_TERMS] or if complexity_score is 5 and confidence is below [CONFIDENCE_THRESHOLD]. Otherwise false. |
Common Failure Modes
What breaks first when a cost-optimized model selection prompt is deployed in production, and how to prevent budget overruns, quality degradation, and silent misrouting.
Expensive Model Overuse for Simple Tasks
What to watch: The prompt routes trivial classification, summarization, or formatting tasks to a frontier model, burning budget with zero quality gain. This often happens when task complexity heuristics are too coarse or missing. Guardrail: Implement a complexity pre-check that classifies tasks into tiers (simple, moderate, complex) before model selection. Log cost-per-request and set a threshold alert when the percentage of simple tasks hitting expensive models exceeds 10%.
Budget Exhaustion from Batch or Streaming Workloads
What to watch: A single batch job or high-volume stream consumes the entire token budget because the prompt lacks per-session or per-workload cost caps. Guardrail: Add a [BUDGET_REMAINING] variable to the prompt context and instruct the model to select cheaper tiers when the remaining budget falls below a defined threshold. Enforce a hard circuit breaker in the application layer that blocks calls when the budget is exhausted, regardless of the model's decision.
Complex Tasks Routed to Underpowered Models
What to watch: Multi-step reasoning, code generation, or structured data extraction requests are sent to a small, fast model to save cost, resulting in hallucinated outputs, malformed JSON, or incomplete answers that require expensive retries. Guardrail: Define explicit complexity triggers (e.g., multi-hop reasoning, nested JSON output, code generation) that force a minimum model tier. Test the prompt with a golden set of complex queries and measure the retry rate caused by inadequate model selection.
Prompt Drift on Cost-Quality Trade-Off Language
What to watch: Vague instructions like 'prefer cheaper models' or 'use the smallest model possible' cause inconsistent routing as the model interprets cost-sensitivity differently across inputs. Guardrail: Replace subjective language with a concrete decision matrix in the prompt: map task types and complexity scores to specific model names or tiers. Use few-shot examples that demonstrate the exact boundary between choosing a small model and escalating to a larger one.
Ignoring Latency Constraints in Cost Calculations
What to watch: The prompt optimizes purely for token cost and selects a slow, cheap model for a user-facing synchronous request, violating latency SLOs and degrading user experience. Guardrail: Include a [LATENCY_BUDGET_MS] input variable and instruct the prompt to treat it as a hard constraint. Validate routing decisions in eval by measuring end-to-end latency and flagging any decision where a cheaper model would have met the latency target but wasn't selected.
Hallucinated Model Names or Capabilities
What to watch: The prompt invents a model name, assumes a model has capabilities it lacks (e.g., vision, tool-use), or routes to a deprecated model version, causing runtime errors. Guardrail: Provide a closed list of available models with their capabilities and costs as a structured [MODEL_CATALOG] variable. Add a post-routing validation step that rejects any decision containing a model name not present in the catalog before the API call is made.
Evaluation Rubric
Use this rubric to test the cost-optimized model selection prompt before production deployment. Each criterion targets a specific failure mode that wastes budget or degrades output quality.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Cost Tier Selection Accuracy | Prompt routes simple tasks (greetings, FAQs) to [BUDGET_MODEL] and complex tasks (reasoning, code generation) to [PREMIUM_MODEL] with ≥90% agreement against a labeled golden dataset. | Simple tasks consistently routed to [PREMIUM_MODEL] or complex tasks routed to [BUDGET_MODEL] in ≥15% of test cases. | Run 50 labeled examples (25 simple, 25 complex) through the prompt. Measure agreement with expected tier. Flag any systematic misclassification pattern. |
Budget Constraint Adherence | Routing decisions never exceed the per-request [MAX_COST_BUDGET] when a cheaper capable model is available. Total cost of 100 test runs stays within 110% of optimal routing cost. | Prompt selects [PREMIUM_MODEL] when [BUDGET_MODEL] would have produced an acceptable output, or total batch cost exceeds 130% of optimal. | Calculate the cost of each routing decision against a pre-computed optimal routing baseline. Track cumulative cost over 100 varied test inputs. Fail if cost exceeds threshold. |
Fallback Chain Completeness | When [PRIMARY_MODEL] is unavailable or returns an error, the prompt produces a valid fallback decision within the fallback chain without hallucinating unavailable models. | Prompt returns a model name not in the approved [MODEL_CATALOG], skips a tier in the fallback chain, or returns null without explanation. | Inject simulated model unavailability errors for each tier. Verify the fallback output matches the next available model in the defined chain. Check for hallucinated model names. |
Confidence Score Calibration | The prompt outputs a [CONFIDENCE_SCORE] between 0.0 and 1.0. Low-confidence scores (<0.7) correlate with genuinely ambiguous or edge-case inputs. | High confidence (>0.85) assigned to inputs that produce incorrect routing, or low confidence assigned to straightforward classification tasks. | Plot confidence scores against routing accuracy for 100 test cases. Calculate Expected Calibration Error (ECE). Fail if ECE > 0.15 or if any high-confidence bucket has accuracy below 80%. |
Output Schema Compliance | Every response strictly matches the [OUTPUT_SCHEMA] with all required fields present, correct types, and valid enum values for model selection. | Missing required fields, incorrect types (e.g., string instead of float for confidence), or model names outside the approved [MODEL_CATALOG] enum. | Validate 100 responses against the JSON schema. Fail if any response has schema violations. Automate this check in CI/CD pipeline with a schema validator. |
Latency Overhead Acceptability | The routing decision itself adds less than [MAX_ROUTING_LATENCY_MS] to the total request pipeline in 95% of cases. | Routing prompt latency exceeds threshold in more than 5% of requests, or routing latency is greater than the execution time of the selected model. | Measure end-to-end latency of the routing prompt in isolation across 100 requests under typical load. Calculate p95 latency. Fail if p95 exceeds the configured threshold. |
Budget Overrun Pattern Detection | No single input category (e.g., 'summarization') consumes more than [CATEGORY_BUDGET_SHARE] of the total token budget without explicit justification in the reasoning trace. | A specific task category consistently triggers [PREMIUM_MODEL] selection despite [BUDGET_MODEL] producing acceptable outputs for that category in evaluation. | Group 100 routing decisions by task category. Calculate cost per category. Flag any category exceeding its expected budget share by more than 20% without valid complexity justification in the [REASONING] field. |
Edge Case Handling | Prompt handles empty input, extremely long input, non-English input, and adversarial input by routing to a safe fallback or returning a structured error without crashing. | Prompt returns unparseable output, exceeds its own token limit, or selects an inappropriate model for clearly out-of-distribution inputs. | Run a test suite of 20 edge cases including empty strings, 100k-character inputs, mixed-language queries, and prompt injection attempts. Verify output is always valid JSON with a safe routing decision or structured error. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a single model tier and a simplified budget constraint. Replace the detailed [MODEL_CATALOG] with a hardcoded list of 2-3 models. Skip the [COST_PER_1K_TOKENS] variables and use relative labels like 'cheap', 'mid', 'expensive'. Focus on getting the routing logic right before tuning cost parameters.
Watch for
- The model always picking the cheapest option regardless of task complexity
- Ignoring the [TASK_COMPLEXITY] field and defaulting to a single model
- Budget calculations that are directionally correct but numerically wrong

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us