Inferensys

Prompt

Budget-Enforcement Router Prompt with Hard Cost Limits

A practical prompt playbook for using Budget-Enforcement Router Prompt with Hard Cost Limits in production AI workflows.
Wide-angle shot of a modern WeWork open floor plan with creative walls covered in AI system architecture diagrams, product team collaborating in standing desk area with industrial lighting.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the exact conditions, user, and system context where a hard-limit budget-enforcement router is the correct architectural choice, and when it is not.

This prompt is for infrastructure engineers who need a deterministic, auditable routing decision that guarantees a hard cost ceiling is never exceeded. It is designed for multi-model routing middleware where a request must be classified and dispatched to a model tier, and where exceeding a token or dollar budget is a compliance violation, not a performance degradation. Use this prompt when your system must produce a routing decision that includes an early termination trigger, an overage prevention rule, and a complete audit log entry.

The ideal user is an AI platform engineer operating a model gateway or internal router that dispatches requests to multiple model providers or tiers with different per-token pricing. Required context includes a pre-defined model catalog with exact per-token costs, a hard budget cap per request or per session, and a classification of the incoming request's complexity or required capability level. The prompt expects these as structured variables—it does not infer pricing or budget limits from natural language. The output is a machine-readable routing decision, not a recommendation for a human operator. Wire this directly into your gateway's dispatch logic, with the audit log entry written to your observability stack before the selected model is invoked.

Do not use this prompt for soft budget guidance, cost estimation, or latency-optimized routing where budget is a preference rather than a hard constraint. If your system can tolerate occasional budget overruns for quality improvement, use a cost-aware routing prompt with tradeoff weights instead. Do not use this prompt when the model catalog or pricing is dynamic and not available as structured input—the prompt cannot look up live pricing. Do not use this prompt as a standalone cost estimator; it routes, it does not forecast. If you need a preflight cost estimate before invocation, pair this with a cost-estimate preflight prompt and use the estimate as input to the routing decision.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Budget-Enforcement Router Prompt works, where it fails, and the operational prerequisites for safe deployment.

01

Good Fit: Hard Cost Ceilings

Use when: You have a non-negotiable per-request or daily token/dollar limit that must never be exceeded. The prompt is ideal for API products with strict COGS (Cost of Goods Sold) targets or freemium tiers where overages directly erode margin. Guardrail: Pair the prompt's decision with a circuit breaker in the application layer that independently enforces the limit, not just the model's output.

02

Bad Fit: Quality-Critical, Unbounded Analysis

Avoid when: The primary metric is accuracy or depth of reasoning, and the cost of a wrong answer far outweighs the compute cost. This prompt will aggressively terminate or downgrade to stay within budget, which is dangerous for medical review, legal analysis, or safety-critical code generation. Guardrail: Use a human-in-the-loop escalation path instead of a hard stop for high-stakes domains.

03

Required Input: Real-Time Pricing & Usage State

Risk: The prompt cannot enforce a budget if it lacks accurate, real-time data on current spend, token consumption, and per-model pricing. Stale or estimated data leads to premature termination or budget breaches. Guardrail: The application must inject [CURRENT_SPEND], [HARD_LIMIT], and a [MODEL_PRICING_TABLE] into the prompt context on every call, sourced from a live metering service.

04

Operational Risk: Premature Workflow Termination

Risk: A strict budget router can kill a multi-step agent workflow mid-task, leaving side effects (e.g., a half-filled database record) or a user with no result. Guardrail: Design workflows to be atomic or have a 'budget-exhausted' handler that safely rolls back state and returns a partial result with a clear 'incomplete' status code.

05

Operational Risk: Audit & Explainability Gaps

Risk: When a request is rejected or downgraded, users and internal teams need to know exactly why. A silent failure or a generic error message erodes trust and makes debugging impossible. Guardrail: The prompt must output a structured [AUDIT_LOG] containing the limit, current spend, decision rationale, and a unique trace ID for every routing decision.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template that enforces hard cost limits by routing requests to the most capable model within a strict budget, with explicit overage prevention and audit logging.

This prompt template is designed to be dropped directly into a model routing middleware layer. It receives a user request, a model catalog with per-token pricing, and a hard cost ceiling. The prompt's only job is to select a model and produce a routing decision that never exceeds the budget. It includes explicit rules for early termination when no model fits within the remaining budget, and it requires a structured audit log entry for every decision. Use this when you need a guaranteed cost ceiling with no exceptions—such as per-request caps in a multi-tenant SaaS product or daily spend limits on an internal AI platform.

text
You are a budget-enforcement router. Your only job is to select a model for the incoming request that maximizes response quality while guaranteeing the total estimated cost stays at or below the hard cost limit. You must never exceed the limit under any circumstance.

## INPUT

User Request:
[USER_REQUEST]

## MODEL CATALOG

Each available model includes its per-token pricing and a relative quality score (1-10).

[MODEL_CATALOG]

Format: model_id | input_cost_per_1k_tokens | output_cost_per_1k_tokens | quality_score | max_context_tokens | avg_output_tokens

## HARD COST LIMIT

Maximum allowed total cost for this request: [HARD_COST_LIMIT]

This is a hard ceiling. If no model can process this request within the limit, you must route to the designated fallback or reject the request. Never exceed this limit.

## ROUTING RULES

1. Estimate the total cost for each candidate model using this formula:
   total_cost = (estimated_input_tokens * input_cost_per_1k / 1000) + (estimated_output_tokens * output_cost_per_1k / 1000)
2. Estimate input tokens from the user request length. Use the model's avg_output_tokens as the output estimate unless the request explicitly demands a longer response.
3. Filter out any model whose estimated total cost exceeds the hard cost limit.
4. From the remaining models, select the one with the highest quality_score.
5. If no model fits within the budget, route to [FALLBACK_MODEL_ID] if it fits. If the fallback also exceeds the budget, reject with code NO_MODEL_WITHIN_BUDGET.
6. If the user request is empty or unprocessable, reject with code INVALID_INPUT.

## OVERAGE PREVENTION

- Round all cost estimates up to 4 decimal places.
- Add a 10% safety buffer to the estimated input tokens before calculating cost.
- If the estimated cost is within 5% of the hard limit, flag the decision with a COST_WARNING.

## OUTPUT SCHEMA

Return a JSON object with exactly these fields:

{
  "decision": "ROUTE" | "REJECT",
  "selected_model": string | null,
  "estimated_cost": number | null,
  "hard_cost_limit": number,
  "budget_remaining": number | null,
  "quality_score": number | null,
  "rejection_code": "NO_MODEL_WITHIN_BUDGET" | "INVALID_INPUT" | null,
  "cost_warning": boolean,
  "audit_log": {
    "timestamp": string,
    "request_id": string,
    "input_token_estimate": number,
    "output_token_estimate": number,
    "candidate_models_evaluated": number,
    "models_rejected_by_budget": array,
    "safety_buffer_applied": boolean,
    "routing_rule_version": "1.0"
  }
}

## CONSTRAINTS

- Do not include explanations outside the JSON.
- Do not invent model pricing or capabilities not in the catalog.
- If the hard cost limit is zero or negative, reject immediately.
- The audit_log must be complete even for rejected requests.

To adapt this template, replace the square-bracket placeholders with your runtime values. [MODEL_CATALOG] should be populated from a configuration store or database, not hardcoded—model pricing changes frequently. [HARD_COST_LIMIT] should come from your budget enforcement system, whether that's a per-request cap, a per-user daily allowance, or a tenant-level spend control. [FALLBACK_MODEL_ID] must reference a model that is always available and cheap enough to serve as a last resort; a lightweight open-weight model running locally is a common choice. The output schema is designed to be machine-readable by your routing middleware, so keep the field names stable across versions. If you change the routing rules, increment the routing_rule_version in the audit log to maintain traceability.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Budget-Enforcement Router Prompt. Every variable must be populated before the prompt is assembled and sent. Missing or malformed variables will cause the router to fail closed (reject the request) rather than risk a cost overrun.

PlaceholderPurposeExampleValidation Notes

[HARD_COST_LIMIT]

Absolute maximum cost allowed for this request in USD. The router must never exceed this value under any execution path.

0.05

Must be a positive float. Reject if <= 0. Validate precision to 4 decimal places. If null or missing, fail closed and log an audit event.

[MODEL_CATALOG]

Array of available models with their per-token pricing, capability tags, and quality scores. Used to evaluate routing options against the cost limit.

[{"id":"gpt-4o","input_cost_per_1k":0.0025,"output_cost_per_1k":0.01,"quality_score":0.92}]

Must be a non-empty JSON array. Each entry requires id, input_cost_per_1k, and output_cost_per_1k as positive floats. Reject if any model has missing pricing fields.

[USER_INPUT]

The raw user request or task description that needs to be routed. This is the payload whose processing cost must be constrained.

Summarize the attached 50-page quarterly report and extract all revenue figures by region.

Must be a non-empty string. If input exceeds [MAX_INPUT_TOKENS], truncate with a warning log before routing. Null or empty input triggers immediate rejection.

[MAX_INPUT_TOKENS]

Hard ceiling on input token count before routing is attempted. Prevents oversized payloads from consuming budget before a decision is made.

32000

Must be a positive integer. If the tokenized [USER_INPUT] exceeds this value, the request is rejected before any model call. Validate against the tokenizer of the primary model in [MODEL_CATALOG].

[ESTIMATED_OUTPUT_TOKENS]

Expected output token count used for cost projection. If unknown, use a conservative default defined in the system prompt.

4096

Must be a positive integer. If set to 0 or null, the router uses a default of 1024. Values above [MAX_OUTPUT_TOKENS] are clamped to the max. Log a warning when the default is used.

[MAX_OUTPUT_TOKENS]

Hard ceiling on output tokens for the selected model. Prevents runaway generation from breaching the cost limit.

8192

Must be a positive integer. This value is passed as the max_tokens parameter to the selected model's API call. Must be less than or equal to the model's context window.

[OVERAGE_PREVENTION_MODE]

Controls the router's behavior when projected cost approaches the hard limit. Options: 'reject', 'downgrade', 'truncate'.

reject

Must be one of the enumerated string values. If 'reject', the router fails closed. If 'downgrade', it selects the cheapest viable model. If 'truncate', it reduces [MAX_OUTPUT_TOKENS]. Invalid values default to 'reject' with an audit log.

[AUDIT_LOG_ENABLED]

Boolean flag controlling whether every routing decision is logged with cost projection, model selected, and limit check result.

Must be a boolean. When true, the router emits a structured audit log entry containing the request ID, timestamp, projected cost, actual cost, selected model, and limit compliance status. Required for production deployments.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Budget-Enforcement Router Prompt into a production application with validation, retries, logging, and hard-stop enforcement.

The Budget-Enforcement Router Prompt is designed to sit at a critical decision point in your request pipeline—after input classification but before model invocation. It receives a pre-assembled context containing the user request, available model catalog with per-token pricing, and the hard cost limit. The prompt's job is to return a single routing decision that never exceeds the budget. Implementation requires wrapping this prompt in a harness that enforces the hard limit at the application layer, not just trusting the model's output. The model can recommend a route, but your code must verify the projected cost against the budget before forwarding the request to the selected model.

Wire the prompt into a pre-invocation middleware function. The function should: (1) load the model catalog with current per-token pricing from your configuration store; (2) calculate the input token count for the user request using the target model's tokenizer; (3) assemble the prompt with [HARD_COST_LIMIT], [MODEL_CATALOG], [USER_REQUEST], and [INPUT_TOKEN_COUNT]; (4) call a fast, inexpensive model (e.g., GPT-4o-mini or Claude Haiku) to produce the routing decision; (5) parse the JSON output and validate that estimated_cost <= hard_cost_limit; (6) if validation fails, fall back to the cheapest available model that can handle the request type, log the discrepancy, and increment a budget_override_count metric. Never forward a request to a model whose projected cost exceeds the limit, even if the prompt's output claims otherwise. The application is the final enforcer.

Add retry logic for malformed JSON outputs. If the routing decision fails to parse, retry once with a stricter prompt variant that includes the previous raw output and an explicit instruction to return only valid JSON. If the second attempt also fails, route to the cheapest model and log a routing_parse_failure event. For audit logging, capture the full routing decision payload, the validated cost estimate, the selected model, the hard limit, and whether the decision was accepted, overridden, or fell back. This audit trail is essential for cost attribution, debugging budget breaches, and demonstrating compliance with spend governance policies. Store these logs in a structured format queryable by request ID and time window.

For high-throughput systems, consider caching routing decisions for identical or near-identical requests within a time window. If the same user request pattern appears repeatedly with the same budget constraint, reuse the prior routing decision rather than invoking the router prompt again. Invalidate the cache when the model catalog pricing changes or when the hard limit is adjusted. For multi-step agent workflows, invoke this prompt at each step where a new model call is required, and track cumulative spend against a session-level budget. If cumulative spend reaches 80% of the session budget, inject an additional constraint into the prompt that forces selection of the cheapest viable model for remaining steps. At 95%, terminate the session and return a budget-exhausted response to the user. Do not rely on the model to track cumulative spend—maintain that counter in application state.

IMPLEMENTATION TABLE

Expected Output Contract

The router prompt must return a single, machine-readable JSON object. Every field is required. Validation rules are designed for immediate parse-check enforcement in the routing middleware before any downstream model invocation occurs.

Field or ElementType or FormatRequiredValidation Rule

routing_decision

string (enum)

Must be one of: 'route_to_model', 'route_to_fallback', 'reject_request', 'escalate_for_review'. No other values allowed.

selected_model_id

string

Must match an entry in the [MODEL_CATALOG] model_id field. Null allowed only if routing_decision is 'reject_request' or 'escalate_for_review'.

estimated_tokens

integer

Must be a positive integer. Must not exceed [HARD_TOKEN_LIMIT]. If routing_decision is 'reject_request', value must be 0.

estimated_cost_usd

number (float)

Must be a positive float calculated as estimated_tokens * selected_model_price_per_token. Must not exceed [HARD_COST_LIMIT_USD]. Round to 6 decimal places.

cost_limit_breach

boolean

Must be true if estimated_cost_usd > [HARD_COST_LIMIT_USD] or estimated_tokens > [HARD_TOKEN_LIMIT]. If true, routing_decision must be 'reject_request' or 'escalate_for_review'.

justification_summary

string

Must be 1-3 sentences explaining the routing choice. Must reference the cost limit, token estimate, and model capability match. Must not exceed 300 characters.

audit_timestamp

string (ISO 8601)

Must be a valid UTC timestamp in ISO 8601 format with seconds precision. Example: '2025-03-15T14:30:00Z'. Must be generated at decision time.

fallback_chain_used

boolean

Must be true if the primary model was bypassed due to cost, availability, or capability mismatch. Must be false if the first-choice model was selected.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when enforcing hard cost limits in production and how to guard against it.

01

Silent Budget Overrun from Token Estimation Error

What to watch: The router estimates token usage before invocation, but the model generates more tokens than predicted, silently exceeding the hard cap. This is especially dangerous with streaming responses where mid-stream termination is messy. Guardrail: Add a preflight token-counting step that uses a conservative multiplier (e.g., 1.3x) on the estimated output tokens. Implement a hard server-side token limit (max_tokens) on the model call itself as a circuit breaker, not just a routing check.

02

Tool Call Costs Not Included in Budget Math

What to watch: The router enforces a budget on the primary model call but ignores the token cost of tool definitions, tool call arguments, and tool response payloads. Multi-step agent loops can burn through the budget in tool overhead alone. Guardrail: Budget calculations must include tool schema tokens, expected tool call tokens, and a cap on tool call rounds. Track cumulative spend across the entire request lifecycle, not just the final generation step.

03

Fallback Chain Causes Cascading Cost Spikes

What to watch: When the primary model fails or times out, the fallback chain retries with alternative models, each consuming tokens. A poorly designed fallback sequence can multiply costs without producing a successful result. Guardrail: Assign a separate, smaller budget for the entire fallback chain. Terminate the chain immediately when cumulative spend hits the fallback cap. Log every fallback attempt with cost attribution for audit.

04

Hard Cap Triggers Premature Termination on Valid Requests

What to watch: The budget limit is set too low for complex but legitimate requests, causing the router to abort mid-processing. Users receive truncated or empty responses with no explanation, degrading trust. Guardrail: Implement a soft-cap warning threshold (e.g., 80% of hard cap) that triggers a graceful degradation path—return a partial result with a clear explanation—rather than a hard abort. Monitor premature termination rates by request complexity tier.

05

Audit Log Drift Between Router Decision and Actual Spend

What to watch: The router logs a decision with an estimated cost, but the actual model invocation cost differs. Over time, audit logs become unreliable for cost attribution, billing, or compliance review. Guardrail: Log both the pre-invocation estimate and the post-invocation actual cost in the same trace. Reconcile discrepancies in a daily batch job. Flag any request where actual spend exceeds the estimate by more than 20% for review.

06

Race Condition on Shared Budget Counter

What to watch: In high-concurrency systems, multiple requests read and update a shared daily or per-user budget counter without proper locking, causing double-counting or missed enforcement. Guardrail: Use atomic decrement operations on the budget counter (e.g., Redis DECR with a floor check). If atomic operations aren't available, implement a short-lived distributed lock per budget key. Reject requests that would push the counter below zero before model invocation.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the Budget-Enforcement Router Prompt before production deployment. Each criterion validates a specific contract requirement. Run these tests against a golden dataset of 50-100 varied requests with known cost profiles.

CriterionPass StandardFailure SignalTest Method

Hard Cost Limit Compliance

100% of routing decisions produce a total estimated cost at or below [HARD_COST_LIMIT] across all selected models and tools

Any routing decision exceeds [HARD_COST_LIMIT] in the cost breakdown field

Automated assertion: parse cost_breakdown.total_estimated_cost from JSON output and assert total_estimated_cost <= [HARD_COST_LIMIT] for all test cases

Early Termination Trigger

When estimated cost reaches [TERMINATION_THRESHOLD] before routing completes, output includes termination_reason field and no model_selection

Output contains a model_selection when estimated cost exceeds [TERMINATION_THRESHOLD] or termination_reason is missing when threshold is breached

Inject test cases with inputs that force cost estimates above [TERMINATION_THRESHOLD]; assert termination_reason is present and model_selection is null

Audit Log Completeness

Every output includes audit_log with fields: timestamp, input_token_count, selected_models, cost_per_model, total_cost, budget_remaining, and decision_trace

Missing audit_log, missing required fields, or null values in required audit fields

Schema validation: assert audit_log exists and contains all required keys with non-null values; verify decision_trace is a non-empty array

Overage Prevention Rules

When budget_remaining after routing is less than [MINIMUM_RESERVE], output includes overage_prevention.applied: true and overage_prevention.action is not null

overage_prevention.applied is false when budget_remaining < [MINIMUM_RESERVE] or action field is null when applied is true

Boundary test: craft inputs where selected models leave budget_remaining below [MINIMUM_RESERVE]; assert overage_prevention.applied is true and action describes a concrete prevention measure

Fallback Chain Adherence

When primary model exceeds cost budget, fallback_chain is populated in order and selected model is the first fallback that fits within remaining budget

Primary model selected despite exceeding budget, fallback_chain is empty when primary fails budget check, or fallback order does not match configured [FALLBACK_CHAIN]

Inject test cases where primary model cost exceeds budget; assert selected_model matches first viable fallback and fallback_chain array matches configured order

Cost Breakdown Accuracy

cost_breakdown fields sum correctly: sum of per_model costs equals total_estimated_cost within 0.01 tolerance

total_estimated_cost does not equal sum of individual model costs, or cost_breakdown contains models not in selected_models

Arithmetic validation: parse all per_model cost values, sum them, assert Math.abs(sum - total_estimated_cost) < 0.01 for every output

No Silent Budget Bypass

Zero outputs contain a routing decision where cost_breakdown.total_estimated_cost is 0 or null while model_selection is non-null

model_selection contains entries but total_estimated_cost is 0, null, or missing

Null-check assertion: for all outputs where model_selection is not null, assert total_estimated_cost > 0 and is not null

Decision Trace Explainability

decision_trace array contains at least one entry per routing step with fields: step, model_considered, cost_estimate, decision, and reason

decision_trace is empty, missing required fields per step, or reason field contains generic text without specific cost justification

Content check: assert decision_trace.length > 0; for each trace entry, assert model_considered, cost_estimate, and reason are present; spot-check reason for cost-specific language

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a small model catalog (2-3 models with known per-token pricing). Use a simple JSON output schema with selected_model, estimated_cost, and within_budget fields. Skip audit logging and just log the decision to stdout. Set [HARD_COST_LIMIT] as a fixed dollar amount in the prompt body rather than pulling from config.

code
You are a budget-enforcement router. Given the input request and a hard cost limit of [HARD_COST_LIMIT], select the best model from [MODEL_CATALOG] that stays under budget.

Return JSON: {"selected_model": "...", "estimated_cost": 0.0, "within_budget": true}

Watch for

  • Models with missing or stale pricing in [MODEL_CATALOG] causing incorrect cost estimates
  • No handling for inputs that can't be served by any model within budget (empty selection)
  • Token estimation errors when input length is highly variable
Prasad Kumkar

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.