This prompt is designed for engineering teams running multi-step agent workflows where LLM token consumption directly impacts operating costs. It sits inside a monitoring layer that receives cumulative token counts and a plan estimate, then produces a structured cost variance report. Use it when you need an automated, readable alert that explains which steps are driving overruns and what to do about it, rather than a raw token counter. The ideal user is a platform engineer or AI operator responsible for cost governance who needs to detect budget anomalies before they become billing surprises.
Prompt
Cost Overrun Alert Prompt for Token Usage

When to Use This Prompt
Defines the job-to-be-done, ideal user, required context, and boundaries for the cost overrun alert prompt.
This prompt assumes you already have token accounting instrumentation in your agent runtime. It does not replace that instrumentation; it interprets its output. You should wire this prompt into a monitoring callback that fires when cumulative token consumption exceeds a configured threshold (e.g., 80% of plan estimate) or when a step's token delta is anomalous. The prompt requires three inputs: the original plan with per-step token estimates, the actual cumulative token counts per step, and the current execution state. Without accurate token instrumentation, this prompt will produce misleading variance reports.
Do not use this prompt for real-time per-token billing calculations, as it is designed for periodic aggregate reporting. Do not use it as a budgeting tool during plan creation—that belongs to a separate plan estimation prompt. Avoid using this prompt when the agent runtime lacks step-level token attribution, because the output will lack the granularity needed for actionable recommendations. If your workflow involves regulated data or financial commitments, always route the alert through a human review step before taking automated cost-mitigation actions such as aborting workflows or switching models.
Use Case Fit
Where the Cost Overrun Alert Prompt delivers value and where it introduces risk. Use these cards to decide if this prompt belongs in your agent monitoring stack.
Good Fit: Budgeted Agent Workflows
Use when: your agent executes multi-step plans with a known token budget per run or per task. The prompt compares cumulative consumption against estimates and flags variance early. Guardrail: set the alert threshold below your hard budget limit to leave room for recovery actions before the run is killed.
Bad Fit: Unbounded Creative Sessions
Avoid when: the workflow has no predefined cost ceiling or the value of completion outweighs token cost concerns. The prompt will generate noisy alerts that operators learn to ignore. Guardrail: only wire this prompt into workflows where a cost budget is an explicit constraint, not a soft preference.
Required Inputs
What you need: a plan with per-step token estimates, cumulative budget cap, and access to real-time token consumption counters from your model provider or proxy. Guardrail: if your platform cannot expose token counts per step, use a proxy layer that tracks usage before calling this prompt. Estimates without actuals produce misleading alerts.
Operational Risk: Alert Fatigue
What to watch: wiring this prompt into every agent run without tuning thresholds produces frequent low-severity alerts that operators mute. Guardrail: implement severity tiers. Use a warning threshold for early heads-up and a critical threshold that triggers paging. Only escalate when projected total exceeds budget by a configurable margin.
Operational Risk: Stale Estimates
What to watch: the prompt relies on per-step token estimates from the planning phase. If those estimates are systematically wrong, every alert is misleading. Guardrail: track estimate accuracy over time and feed actuals back into the planning prompt. If estimate error exceeds 30%, flag the plan itself for recalibration rather than trusting the alert.
Variant: Optimization Recommendation Mode
Use when: you want the alert to include actionable cost-reduction suggestions rather than just a variance report. Guardrail: add a secondary output field for optimization recommendations and validate that suggestions reference specific steps, not generic advice. Test that recommendations don't hallucinate tool names or step IDs that don't exist in the plan.
Copy-Ready Prompt Template
A production-ready prompt that monitors cumulative token consumption, compares it against plan estimates, and triggers a structured cost variance report when thresholds are breached.
This prompt is designed to be called by your monitoring harness at configurable intervals or after each agent step. It receives the current token accounting state and the original plan's cost estimates, then decides whether to generate an alert. The prompt is structured to produce a machine-readable JSON output that your harness can route to logging, dashboards, or paging systems. Replace every square-bracket placeholder with runtime values from your token accounting system and plan store before sending the request.
textSYSTEM: You are a cost monitoring agent for an LLM-powered workflow system. Your job is to compare actual cumulative token consumption against the plan's estimated budget and determine whether a cost overrun alert is warranted. You must be precise about token counts, conservative in your projections, and clear about which steps are driving variance. Never invent token counts. If data is missing, flag it as unknown rather than guessing. USER: Review the following token consumption data and plan estimates. Produce a structured cost variance report. ## PLAN ESTIMATES [PLAN_ESTIMATES_JSON] ## ACTUAL CONSUMPTION [ACTUAL_CONSUMPTION_JSON] ## THRESHOLDS - Warning threshold: [WARNING_PERCENT]% of total plan budget - Critical threshold: [CRITICAL_PERCENT]% of total plan budget - Projection confidence requires at least [MIN_COMPLETION_PERCENT]% of steps completed ## CONSTRAINTS - Report only on steps present in both the plan and actual consumption data. - If a step is missing from actuals, mark it as "not_started" with zero consumption. - If a step is missing from the plan, flag it as "unplanned_step" and include its consumption in the variance. - Project remaining cost using: (average tokens per completed step) × (remaining steps). - If fewer than [MIN_COMPLETION_PERCENT]% of steps are complete, set projection_confidence to "low" and note the limitation. - Do not hallucinate token counts or step names. ## OUTPUT SCHEMA Return a single JSON object with this structure: { "alert_level": "none" | "warning" | "critical", "total_plan_budget_tokens": number, "total_consumed_tokens": number, "projected_total_tokens": number | null, "budget_remaining_tokens": number, "percent_consumed": number, "percent_projected": number | null, "projection_confidence": "low" | "medium" | "high", "per_step_breakdown": [ { "step_id": string, "step_name": string, "estimated_tokens": number, "actual_tokens": number, "variance_tokens": number, "variance_percent": number, "status": "not_started" | "in_progress" | "completed" | "unplanned_step" } ], "top_variance_steps": [ { "step_id": string, "step_name": string, "variance_tokens": number, "explanation": string } ], "optimization_recommendations": [string], "should_alert": boolean, "alert_reason": string | null }
Adapt this template by adjusting the threshold values to match your organization's risk tolerance. For production deployments, ensure your harness validates the output JSON against the schema before acting on the alert. If the model returns malformed JSON, implement a retry with the validation error included as additional context. For high-cost workflows where a false negative could cause significant budget overruns, configure the harness to escalate to a human reviewer when projection_confidence is "low" and alert_level is "warning" or higher. Log every alert decision—including "none" outcomes—to build a traceable audit history of cost monitoring decisions.
Prompt Variables
All placeholders must be populated by your application layer before sending the prompt. Missing or invalid values will cause unreliable cost projections and alert thresholds.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[CURRENT_TOKEN_COUNT] | Total tokens consumed so far in the current plan execution | 142000 | Must be a positive integer. Parse from LLM usage metadata or token counter. Null not allowed. |
[PLAN_TOKEN_ESTIMATE] | Original estimated token budget for the full plan | 250000 | Must be a positive integer. Compare against [CURRENT_TOKEN_COUNT] to compute burn rate. Reject if less than 1. |
[STEPS_COMPLETED] | Number of plan steps fully executed | 7 | Integer between 0 and [TOTAL_PLAN_STEPS]. Must not exceed total steps. Validate against execution log. |
[TOTAL_PLAN_STEPS] | Total number of steps in the original plan | 12 | Positive integer. Must be greater than or equal to [STEPS_COMPLETED]. Reject if 0. |
[COST_THRESHOLD_PERCENT] | Percentage of estimated budget that triggers an alert | 85 | Integer between 1 and 200. Represents alert sensitivity. Values above 100 allow over-budget alerts. |
[PER_STEP_TOKEN_LOG] | JSON array of token counts per completed step | [{"step_id":"1","tokens":18000},{"step_id":"2","tokens":22000}] | Must be valid JSON array. Each object requires step_id string and tokens integer. Empty array allowed if no steps completed. |
[MODEL_PRICING_TIER] | Cost per 1K tokens for the active model | 0.003 | Positive float. Use actual pricing from model provider. Required for cost projection. Reject if 0 or negative. |
[CURRENCY_CODE] | ISO 4217 currency code for cost reporting | USD | Must be a valid 3-letter ISO currency code. Used for formatting cost variance report. Default to USD if null. |
Implementation Harness Notes
How to wire the cost overrun alert prompt into a production agent runtime with validation, retries, logging, and escalation.
The Cost Overrun Alert Prompt is designed to sit inside an agent monitoring loop, not as a standalone chat interaction. It should be invoked by a scheduler or hook that fires after each agent step completes, or at configurable token-consumption checkpoints (e.g., every 10,000 tokens consumed). The prompt expects a structured input payload containing the original plan with per-step token estimates, cumulative actual token usage, and the current step identifier. Wire this into your agent framework by capturing token counts from each model API response and accumulating them in a session-level cost tracker before passing them to the alert prompt.
Implement a pre-invocation guard that skips the prompt entirely if cumulative usage is below 50% of the total estimated budget. This avoids unnecessary inference cost for early-stage checks. When the guard passes, assemble the input payload with: the full plan array (each step with step_id, description, estimated_tokens), a cumulative_tokens_used integer, the current_step_id, and the cost_threshold_percentage that triggers an alert (e.g., 90). Validate this payload against a JSON Schema before calling the model. If validation fails, log the malformed input and fall back to a conservative alert that flags the step as unmonitored.
Model choice matters here. This prompt performs structured comparison and threshold arithmetic, not creative generation. Use a fast, cost-efficient model such as Claude 3.5 Haiku, GPT-4o-mini, or Gemini 1.5 Flash. The output schema must be strictly validated: expect a JSON object with alert_triggered (boolean), projected_total_tokens (integer), overrun_percentage (float), per_step_breakdown (array of objects with step_id, estimated, actual, variance), and optimization_recommendations (array of strings). If the model returns malformed JSON, retry once with a repair prompt that includes the raw output and the expected schema. After two failures, escalate to a human operator with the raw response and session context.
Log every invocation result to your observability stack, including the input token counts, output token counts, alert decision, and model latency. Tag logs with session_id, agent_run_id, and checkpoint_sequence_number so you can reconstruct the cost trajectory during post-mortems. If alert_triggered is true, publish an event to your notification bus. Downstream consumers—such as a Slack webhook, PagerDuty integration, or agent supervisor module—should receive the structured alert payload, not the raw prompt output. This decouples the detection prompt from the notification channel and lets you add or change alerting targets without touching the prompt logic.
Avoid wiring this prompt directly to an agent pause or abort action. The alert prompt detects and reports; a separate policy engine or human operator should decide whether to halt execution, reduce context, switch to a cheaper model, or continue. This separation prevents a single prompt output from triggering an unrecoverable workflow stop. Test the harness with synthetic token trajectories that simulate normal completion, gradual overrun, sudden spike, and estimate-free plans to verify that the guard, validation, retry, and logging paths all behave correctly before deploying to a live agent.
Expected Output Contract
Validation rules for the cost overrun alert response. Every field must be parseable by downstream monitoring dashboards and notification routers.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
alert_id | string (UUID v4) | Must match regex ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$ | |
alert_timestamp | ISO 8601 UTC | Must parse as valid datetime; must not be in the future; must be within 60s of generation time | |
alert_severity | enum: CRITICAL | WARNING | INFO | Must be one of the three allowed values; CRITICAL requires projected_overrun_pct > [THRESHOLD_CRITICAL] | |
current_token_total | integer | Must be >= 0; must equal sum of per_step_tokens.current_tokens across all steps | |
budget_token_limit | integer | Must be > 0; must match the [BUDGET_LIMIT] input parameter exactly | |
projected_total_tokens | integer | Must be >= current_token_total; must be derived from current burn rate * remaining steps estimate | |
projected_overrun_pct | float (0-100 or more) | Must be >= 0; must equal ((projected_total_tokens - budget_token_limit) / budget_token_limit) * 100 rounded to 1 decimal | |
overrun_triggered | boolean | Must be true if projected_overrun_pct > [OVERAGE_THRESHOLD_PCT]; must be false otherwise | |
per_step_breakdown | array of objects | Must contain one entry per step in [PLAN_STEPS]; each entry must have step_id, step_name, current_tokens, estimated_remaining_tokens, and status fields | |
per_step_breakdown[].step_id | string | Must match a step_id from the [PLAN_STEPS] input; no orphaned or missing step_ids allowed | |
per_step_breakdown[].current_tokens | integer | Must be >= 0; must not exceed current_token_total | |
per_step_breakdown[].estimated_remaining_tokens | integer | Must be >= 0; null allowed only if status is COMPLETED | |
per_step_breakdown[].status | enum: PENDING | IN_PROGRESS | COMPLETED | Must be one of the three allowed values; COMPLETED steps must have estimated_remaining_tokens = 0 | |
optimization_recommendations | array of strings | If present, each string must be <= 280 characters; must contain actionable suggestions, not generic advice | |
recommendation_priority | enum: REDUCE_CONTEXT | SUMMARIZE_HISTORY | DEFER_STEPS | SPLIT_WORKFLOW | HUMAN_REVIEW | Required if overrun_triggered is true; must be one of the allowed values | |
human_review_required | boolean | Must be true if alert_severity is CRITICAL or if projected_overrun_pct > [HUMAN_REVIEW_THRESHOLD]; must be false otherwise |
Common Failure Modes
Token-based cost overrun alerts fail silently, fire too late, or generate noise instead of actionable signals. These failure modes help you catch problems before your budget does.
Cumulative Drift vs. Spike Confusion
What to watch: The prompt treats a single expensive step as a budget emergency, or ignores slow cumulative drift across many cheap steps until the total is already over threshold. Guardrail: Track both per-step variance and cumulative burn rate. Require the alert to distinguish 'single-step spike' from 'trend-line overspend' with separate thresholds for each.
Projection Based on Stale Completion Estimates
What to watch: The prompt multiplies current cost by remaining steps using an initial plan that is already wrong. If the agent replanned or skipped steps, the projection is garbage. Guardrail: Require the prompt to consume the latest plan state and actual completed-step costs, not the original estimate. Validate that projected remaining steps match the current plan length before computing the forecast.
Threshold Alert Storms
What to watch: Once the projected cost crosses the threshold, every subsequent monitoring check re-fires the same alert, flooding the operator with duplicate notifications. Guardrail: Include a stateful suppression rule in the prompt output schema. Require the alert to include a 'previously alerted' flag and only escalate when the severity level changes or the projected overrun amount increases by more than a configurable delta.
Ignoring Token Type Cost Differentials
What to watch: The prompt treats all tokens as equal cost, but input tokens, output tokens, and cached tokens have different pricing. A prompt-heavy plan with low output can look safe while quietly burning budget on long context windows. Guardrail: Require the cost model to accept per-token-type pricing multipliers. The alert must break down projected cost by input, output, and cache-read tokens before comparing against the budget threshold.
Optimization Recommendations That Increase Cost
What to watch: The prompt suggests 'optimizations' like adding more few-shot examples, requesting chain-of-thought, or expanding context to improve accuracy—each of which increases token consumption. Guardrail: Constrain the optimization section to only recommend cost-reducing changes. Add a validator that rejects any recommendation whose estimated token impact is positive. If no cost-reducing options exist, the prompt must explicitly state that and recommend escalation instead.
Silent Failure When Token Counters Are Unavailable
What to watch: The agent runtime fails to provide actual token counts for some steps, but the prompt still produces a confident-looking report using zeros or estimates without flagging the data gap. Guardrail: Require the prompt to distinguish 'measured' from 'estimated' token counts per step. If any step lacks measured counts, the alert must include a data-quality warning and widen the confidence interval on the projection. Add an eval check that fails the output if any step reports zero tokens without an explicit 'unavailable' marker.
Evaluation Rubric
Run these checks against a golden dataset of 20-30 plan/actual pairs with known outcomes. Each pair includes a plan with estimated token budgets and an actual execution trace with cumulative token consumption. Tests validate that the alert prompt correctly identifies overruns, suppresses false alarms, and produces actionable variance reports.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Overrun Detection Sensitivity | Alert triggers when projected total exceeds [THRESHOLD_PERCENT] of plan estimate | Alert fires below threshold or fails to fire above threshold | Run 10 pairs with known overrun percentages; measure precision/recall at threshold boundary |
False Positive Suppression | No alert when projected total is within [THRESHOLD_PERCENT] of plan estimate | Alert fires on within-budget executions | Run 10 pairs with actuals at 80-95% of budget; count false alerts |
Per-Step Cost Attribution | Every step in the execution trace appears in the variance report with a cost delta | Missing steps, aggregated steps without per-step breakdown, or steps attributed to wrong plan phase | Parse output JSON; verify step count matches input trace; check each step has non-null cost_delta |
Projection Accuracy | Projected total cost is within 15% of actual final cost when execution is at least 50% complete | Projection deviates more than 15% from actual final cost | Run mid-execution traces at 50%, 70%, 90% completion; compare projected_total to actual_total |
Optimization Recommendation Relevance | At least one optimization recommendation references a specific step with high token consumption | Generic advice with no step reference, or recommendations for steps within budget | Parse recommendations array; verify at least one entry links to a step_id with above-average cost |
Threshold Boundary Handling | Alert decision is deterministic at exact threshold boundary; no oscillation between alert/suppress on identical inputs | Different alert decisions on repeated runs with same input | Run same plan/actual pair at exact threshold value 5 times; verify consistent alert_triggered boolean |
Schema Compliance | Output matches [OUTPUT_SCHEMA] exactly: all required fields present, no extra fields, correct types | Missing required fields, type mismatches, or hallucinated fields not in schema | Validate output against JSON Schema; reject any output that fails structural validation |
Budget Exhaustion Severity Classification | Alert includes severity field matching actual overrun magnitude: 'warning' for 100-120%, 'critical' for 120-150%, 'exceeded' for >150% | Severity misclassified relative to actual overrun percentage | Run pairs at each severity boundary; verify severity field matches defined ranges |
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 the base prompt and a simple threshold check. Use a single [COST_LIMIT] variable and ask the model to compare current token consumption against it. Skip structured output initially—accept a natural-language alert. Test with a few hardcoded usage snapshots.
Watch for
- The model may hallucinate token counts if you don't supply actual usage data in [TOKEN_USAGE_SNAPSHOT]
- Without a schema, alerts will be inconsistent and hard to parse programmatically
- Threshold-only logic misses rate-of-spend problems (e.g., a slow leak that will exceed budget in 10 more steps)

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