This prompt is a system-level instruction set for infrastructure engineers building multi-model routing middleware. Its job is not to answer the user. Its job is to analyze an incoming request, evaluate available models against a hard cost budget, and output a deterministic routing decision that maximizes expected output quality without exceeding the budget. Use this when you operate multiple models with different pricing tiers and you need every routing decision to be cost-auditable—for example, when your platform serves different customer tiers, when you have a daily or per-request spend cap, or when you need to prove to finance that no single request blew through an unreasonable amount of compute spend.
Prompt
Cost-Budget-Aware Router System Prompt Template

When to Use This Prompt
Understand the job-to-be-done, the ideal user, and the boundaries where this cost-budget-aware router prompt adds value versus where it introduces risk.
The ideal user is an AI infrastructure engineer or platform engineer who already has a model catalog with per-token pricing, a defined cost cap variable, and a fallback chain. You should have a clear understanding of your models' relative quality on your specific task distribution—this prompt does not discover quality rankings; it applies them. The required context includes: a cost budget (in dollars or tokens), a model catalog with pricing and capability descriptions, the user's request, and any quality weights or preferences. Without this context, the router cannot make a cost-informed decision and will either default to the cheapest model (wasting the budget) or the most expensive (breaching the cap).
Do not use this prompt when cost is irrelevant, when only one model is available, or when the routing decision requires real-time latency data not available in the prompt context. It is also the wrong tool when you need to route based on content policy violations, user entitlement tiers, or multi-modal input type detection—those are separate classification problems that should happen before cost-aware routing. If your routing logic requires sub-millisecond decisions, this prompt-based approach adds unacceptable latency; instead, pre-compute routing tables or use a cached classifier. Finally, if your cost cap is so low that no model can produce a useful response, this prompt will correctly refuse to route—but you need a separate escalation path for that case, not a prompt tweak.
Before deploying this prompt, build a small eval set of requests with known cost constraints and verify that the router never exceeds the budget, selects the highest-quality model that fits, and produces auditable reasoning. Common failure modes include: the router ignoring the budget when the user request implies urgency, the router over-prioritizing quality weights and selecting an over-budget model, and the router failing to consider the fallback chain when the preferred model is unavailable. Test each of these explicitly. Once validated, wire the router's output into your actual model dispatch code—the prompt produces a decision, but your application enforces it and logs the audit trail.
Use Case Fit
Where the Cost-Budget-Aware Router prompt works, where it breaks, and what you must provide before wiring it into production.
Good Fit: Multi-Model Routing Middleware
Use when: you operate a routing layer that selects between 3+ models with different per-token pricing and you need every request to respect a hard cost ceiling. Guardrail: the prompt assumes a pre-defined model catalog with accurate pricing; stale pricing data produces budget violations.
Bad Fit: Single-Model Deployments
Avoid when: you only have one model available or all models share identical pricing. The router adds latency and token overhead without providing any cost-quality tradeoff. Guardrail: bypass the router entirely and send requests directly to the model when no selection is needed.
Required Inputs: Accurate Model Catalog
What to watch: the prompt requires per-model pricing (input/output token costs), capability descriptions, and quality tier assignments. Missing or estimated pricing causes systematic budget overruns. Guardrail: pull pricing from a live configuration source, not hardcoded prompt text, and validate it on every deploy.
Required Inputs: Hard Budget Cap Variable
What to watch: the prompt needs a concrete per-request or per-session cost limit. Ambiguous caps like 'keep it cheap' produce inconsistent routing. Guardrail: inject the budget as a numeric value with units (USD or tokens) and validate that the selected model's estimated cost stays under it before returning the decision.
Operational Risk: Budget Exhaustion Cascades
What to watch: when the budget cap is too low for any model to produce a useful response, the router may select the cheapest model and return garbage, or refuse to route at all. Guardrail: define a minimum viable budget per request class and escalate to a human or return a clear 'budget insufficient' error instead of silently degrading quality.
Operational Risk: Quality Degradation Drift
What to watch: over time, the router may over-prioritize cost savings and route too many requests to cheaper, lower-quality models, causing gradual output degradation that evals miss. Guardrail: track quality metrics per model tier and set a maximum allowable percentage of requests routed below a quality threshold, with alerts on drift.
Copy-Ready Prompt Template
A reusable system prompt for a routing agent that selects the best model for a task while respecting a hard cost budget.
The following template is designed to be set as the system message in a routing middleware service. Its job is to analyze an incoming user request, consult a provided model catalog with per-token pricing, and select the most capable model that can handle the task without exceeding a defined cost budget. The prompt forces a structured decision, requires explicit justification, and mandates a fallback chain if the primary choice is unavailable or too expensive. This ensures that cost constraints are enforced at the routing layer, not just monitored after the fact.
textYou are a cost-budget-aware model router. Your only job is to select the best model for a given user request while strictly adhering to a hard cost budget. ## INPUT [USER_REQUEST] ## MODEL CATALOG [MODEL_CATALOG_JSON] ## CONSTRAINTS - Hard Cost Budget: [MAX_COST_PER_REQUEST] - Latency Target (p95): [MAX_LATENCY_MS] - Required Capabilities: [REQUIRED_CAPABILITIES] - Fallback Chain: [FALLBACK_CHAIN] ## INSTRUCTIONS 1. Analyze the complexity and requirements of the [USER_REQUEST]. 2. Review the [MODEL_CATALOG_JSON] for capability, pricing, and latency profiles. 3. Select the most capable model that fits within the [MAX_COST_PER_REQUEST] budget and meets the [MAX_LATENCY_MS] target. 4. If no model in the primary tier fits, step down the [FALLBACK_CHAIN] in order until a viable model is found. 5. If no model in the entire chain is viable, select the cheapest available model and set a critical flag. ## OUTPUT_SCHEMA Return a single, valid JSON object with no other text: { "selected_model": "string", "estimated_cost": "number", "estimated_tokens": "number", "justification": "string", "fallback_used": "boolean", "critical_budget_breach": "boolean" } ## RISK_LEVEL [RISK_LEVEL]
To adapt this template, replace the square-bracket placeholders with concrete values from your infrastructure. [MODEL_CATALOG_JSON] should be a JSON array of model objects, each containing an id, cost_per_1k_input_tokens, cost_per_1k_output_tokens, capabilities array, and p95_latency_ms. [FALLBACK_CHAIN] is an ordered list of model IDs to try if the primary selection fails cost or latency checks. For high-stakes applications, set [RISK_LEVEL] to high to instruct the router to prefer safety and accuracy over cost savings, and always log the justification field for audit trails. The next step is to wire this prompt into your request pipeline and validate its output against your budget enforcement logic.
Prompt Variables
Inputs the prompt needs to work reliably. Fill these at runtime before sending the prompt to the router model.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[MODEL_CATALOG] | Defines available models with per-token pricing, capability tags, and latency profiles | {"models":[{"id":"gpt-4o","input_cost_per_1k":0.005,"output_cost_per_1k":0.015,"capabilities":["reasoning","code"],"p95_latency_ms":1200}]} | Must be valid JSON array with required fields: id, input_cost_per_1k, output_cost_per_1k. Capabilities array must use only predefined tags. |
[HARD_BUDGET_CAP] | Maximum allowable cost in USD for this request, including all model calls and retries | 0.50 | Must be a positive float. Router must reject any routing decision exceeding this cap. Validate against cumulative spend tracker before model invocation. |
[USER_INPUT] | The raw user request or task to be routed | "Summarize the quarterly earnings call transcript and extract key risks." | Required string. Must not be empty. Length should be checked against tokenizer before routing; inputs exceeding 100k tokens should trigger pre-truncation or rejection. |
[REQUEST_CONTEXT] | Optional metadata about the request source, priority tier, and session state | {"user_tier":"enterprise","priority":"normal","session_id":"sess_abc123","preferred_model":null} | Optional JSON object. If user_tier is present, validate against [TIER_ENTITLEMENTS]. If null, default to standard tier routing. |
[TIER_ENTITLEMENTS] | Maps user tiers to allowed model tiers and per-request budget multipliers | {"enterprise":{"allowed_tiers":["premium","standard","light"],"budget_multiplier":2.0},"free":{"allowed_tiers":["light"],"budget_multiplier":1.0}} | Must be valid JSON. Every tier must define allowed_tiers array and budget_multiplier. Missing tier should default to most restrictive policy. |
[FALLBACK_CHAIN] | Ordered list of fallback models to try if primary model fails, times out, or exceeds budget | ["claude-3-haiku","gpt-4o-mini"] | Must be array of model IDs present in [MODEL_CATALOG]. Chain order determines cost escalation path. Validate each fallback against remaining budget before invocation. |
[QUALITY_WEIGHTS] | Relative importance of accuracy, latency, and cost in routing decisions | {"accuracy":0.6,"latency":0.2,"cost":0.2} | Must be valid JSON with keys accuracy, latency, cost. Values must sum to 1.0. Weights below 0.1 should trigger a warning log. |
[OUTPUT_SCHEMA] | Expected structure for the router's decision output | {"selected_model":"string","estimated_cost":"number","confidence":"number","rationale":"string","fallback_used":"boolean"} | Must be valid JSON Schema. Router output must parse against this schema. Validation failure triggers retry with schema reminder or fallback to default model. |
Implementation Harness Notes
How to wire the Cost-Budget-Aware Router into a production model gateway or middleware layer.
This prompt is designed to be called synchronously inside a model gateway or routing middleware before any downstream model invocation. The application layer must supply the [MODEL_CATALOG], [HARD_BUDGET_CAP], [USER_INPUT], and any optional [CONTEXT] or [CONSTRAINTS] at request time. The router prompt itself should target a fast, cheap model (e.g., GPT-4o-mini, Claude Haiku, or a fine-tuned small classifier) because the routing decision must cost orders of magnitude less than the downstream model call it is protecting. If the router costs more than 2-3% of the budget it is enforcing, the economics break down.
The harness must enforce the budget decision, not just suggest it. After parsing the router's JSON output, validate the selected_model field against the [MODEL_CATALOG] to prevent hallucinated model names. Then check estimated_cost against the [HARD_BUDGET_CAP]. If the estimated cost exceeds the cap, the harness must override the selection with the cheapest viable model or return a budget-exceeded error to the caller. Implement a circuit breaker: if the router returns invalid JSON or a model not in the catalog after [MAX_RETRIES] (default 2), fall back to the cheapest model in the catalog and log the failure. Log every routing decision with request_id, selected_model, estimated_cost, budget_remaining, and override_applied for cost attribution and debugging.
For high-throughput systems, cache routing decisions when the same [USER_INPUT] and [MODEL_CATALOG] combination repeats. Use a TTL-based cache keyed on a hash of the input and catalog version. Invalidate the cache when the catalog pricing changes. If the router is part of a multi-step agent pipeline, deduct the estimated cost from a session-level budget tracker before each step and halt the pipeline when the cumulative spend reaches the cap. Never allow the router's own token cost to be excluded from the budget calculation—include it in the total spend tracking. For regulated or high-stakes domains, add a human approval gate when the router selects a model below a quality threshold or when the budget remaining drops below 10% of the cap.
Expected Output Contract
Fields the harness must validate before dispatching the routing decision. Every field is required unless explicitly noted. Validation rules are designed to be enforced programmatically in the router middleware.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
selected_model_id | string | Must match an entry in the [MODEL_CATALOG] model_id list. No partial matches allowed. | |
estimated_cost_usd | number | Must be a positive float. Must be less than or equal to [HARD_BUDGET_CAP_USD]. Calculated as (estimated_input_tokens * input_price_per_1k + estimated_output_tokens * output_price_per_1k) / 1000. | |
estimated_input_tokens | integer | Must be a positive integer. Must be less than or equal to the model's max_context_window from [MODEL_CATALOG]. | |
estimated_output_tokens | integer | Must be a positive integer. Must be less than or equal to the model's max_output_tokens from [MODEL_CATALOG]. | |
quality_rationale | string | Must be a non-empty string between 20 and 500 characters. Must reference at least one capability from the selected model's entry in [MODEL_CATALOG]. | |
fallback_chain | array of strings | Must be an ordered list of 1-3 model_ids from [MODEL_CATALOG]. The first entry must be the selected_model_id. Each subsequent entry must have a lower estimated_cost_usd than the previous. | |
budget_exhausted_trigger | boolean | Must be true if estimated_cost_usd equals [HARD_BUDGET_CAP_USD] within a 0.5% tolerance. Otherwise false. If true, the harness must log a BUDGET_EXHAUSTED event. | |
confidence_score | number | If present, must be a float between 0.0 and 1.0 inclusive. If absent, the harness must default to null. Scores below [CONFIDENCE_THRESHOLD] must trigger a human review flag. |
Common Failure Modes
When routing decisions must respect a hard cost budget, these are the failure modes that surface first in production. Each card identifies a specific breakage pattern and a concrete guardrail to prevent it.
Budget Overrun from Token Estimation Error
What to watch: The router underestimates the total tokens required for a request, causing the actual spend to exceed the hard budget cap. This often happens when the model catalog pricing is stale or the prompt's system overhead isn't counted. Guardrail: Implement a preflight token counter that sums system prompt tokens, input tokens, and a padded estimate for max output tokens before the routing decision. Reject or downgrade the request if the estimate exceeds the cap.
Quality Collapse from Overly Aggressive Downgrading
What to watch: To stay under budget, the router consistently selects the cheapest, least capable model. The output becomes useless for downstream tasks, effectively wasting the money spent. Guardrail: Define a minimum quality threshold (e.g., an LLM-as-a-Judge score) for each task type. The router must select the cheapest model that meets the threshold, not simply the cheapest available model. If no model meets both criteria, the request should be escalated or rejected with a clear signal.
Silent Fallback to an Incapable Model
What to watch: The primary model is over budget, so the router falls back to a secondary model that lacks the required tool-calling or structured output capability. The system fails with an unparseable response or a hallucinated tool call. Guardrail: The model catalog must include a capability matrix (e.g., supports_tools, supports_json_mode). The fallback chain logic must filter candidates by required capabilities before considering cost, ensuring a cheap model is never selected for a task it structurally cannot perform.
Runaway Spend from Retry Loops
What to watch: A model call fails validation, and the retry logic repeatedly invokes the same expensive model without checking the remaining budget. A single request can consume the entire daily budget through retries. Guardrail: Track cumulative spend per request, including all retries. The retry logic must check the remaining budget before each attempt. If the budget is exhausted, the system must halt retries and return a structured error, never silently retrying into debt.
Stale Pricing Data Causing Systematic Under-Budgeting
What to watch: The router's hard-coded model pricing table becomes outdated after a provider price change. The system believes it is under budget while actually overspending by a significant margin. Guardrail: Treat the model pricing configuration as a dynamic operational parameter, not a static constant. Implement a scheduled job to fetch current pricing from provider APIs or a configuration service. If the pricing source is unreachable, the router should fail closed and default to the most conservative (highest) price estimate.
Ignoring Multi-Modal or Tool-Use Token Costs
What to watch: The budget calculation only accounts for text input and output tokens. When a request includes an image, audio file, or triggers expensive tool calls, the actual cost far exceeds the text-only estimate. Guardrail: The preflight cost estimator must parse the full request payload for multi-modal parts and potential tool definitions. Use provider-specific tokenization rules for images and audio. For tool calls, add a fixed cost buffer to the estimate to account for the arguments and the tool's response being re-ingested.
Evaluation Rubric
Run these checks against a golden dataset of 100+ labeled requests to validate the Cost-Budget-Aware Router before production deployment. Each criterion targets a specific failure mode in budget enforcement, model selection quality, and fallback behavior.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Hard Budget Compliance | 100% of routing decisions result in a total estimated cost at or below [BUDGET_CAP]. No exceptions. | Any request where the selected model's estimated cost exceeds [BUDGET_CAP]. | Automated assertion: parse the selected model from the output, calculate estimated cost using [MODEL_CATALOG] pricing and input token count, and assert cost <= [BUDGET_CAP]. |
Fallback Chain Integrity | When the primary model exceeds the budget, the router selects the next model in [FALLBACK_CHAIN] that fits within [BUDGET_CAP]. | Router selects a model not in [FALLBACK_CHAIN] or skips a cheaper viable model in the chain. | Automated check: for inputs where the primary model is over budget, verify the selected model matches the first viable entry in [FALLBACK_CHAIN] ordered by cost ascending. |
Quality Preservation Under Budget | The selected model's quality score is within 10% of the highest-quality model that fits the budget, for 95% of requests. | Router consistently selects the cheapest model when a higher-quality model also fits within [BUDGET_CAP]. | Comparative eval: for each request, identify all models in [MODEL_CATALOG] that fit the budget, and assert the selected model's quality score is not more than 10% below the maximum available. |
Input Complexity Assessment Accuracy | The router's complexity assessment (low, medium, high) matches human-labeled complexity in the golden dataset with at least 85% agreement. | Router classifies a simple lookup as high complexity, triggering unnecessary premium model selection, or vice versa. | Human-annotated golden dataset: compare the router's complexity justification against pre-labeled complexity tiers. Measure precision and recall per tier. |
Cost Estimation Accuracy | The router's preflight cost estimate is within 20% of the actual cost for 90% of requests. | Estimate is consistently low, causing budget overruns, or consistently high, causing unnecessary downgrades. | Post-hoc measurement: log the router's cost estimate, execute the selected model call, record actual cost, and calculate the absolute percentage error across the dataset. |
No-Op on Trivial Requests | For requests classified as trivial or empty, the router selects the cheapest model in [MODEL_CATALOG] or returns a no-call decision. | Router selects a premium model for an empty input or a request that requires no model invocation. | Edge-case injection: include empty strings, whitespace-only inputs, and trivial queries in the golden dataset. Assert the selected model is the minimum-cost option. |
Output Schema Conformance | 100% of router outputs parse as valid JSON matching the [OUTPUT_SCHEMA] with all required fields present. | Missing required fields (e.g., selected_model, estimated_cost, reasoning) or malformed JSON that breaks downstream dispatch. | Schema validation: parse the raw output with a JSON schema validator configured against [OUTPUT_SCHEMA]. Flag any parse failures or missing required fields. |
Reasoning Traceability | The reasoning field explicitly references the budget constraint and the selected model's cost from [MODEL_CATALOG] for 100% of decisions. | Reasoning is generic (e.g., 'best model chosen') without mentioning the budget cap or specific cost figures. | String match assertion: verify the reasoning field contains the [BUDGET_CAP] value and the selected model's per-token cost from [MODEL_CATALOG]. |
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
Start with a simplified model catalog containing only 2-3 models with clear cost and capability differences. Replace the full budget enforcement logic with a single [BUDGET_CAP] variable and a basic instruction: 'Choose the cheapest model that meets the quality threshold.' Use a free-text output format instead of strict JSON schema to iterate faster.
Watch for
- The router ignoring the budget cap when quality differences are large
- Inconsistent output format making it hard to parse decisions programmatically
- Missing fallback behavior when all models exceed the budget

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