This prompt is for platform operators and AI cost engineers who need to enforce a hard spend cap during autonomous agent execution. It is designed to be invoked as a pre-flight check before every chargeable tool call. The prompt produces a structured stop-or-continue decision, calculates remaining budget, and generates a user-facing notification when the cap is approached or breached. Use this when you have a defined monetary or token budget per session, task, or user, and you need the agent to communicate budget exhaustion clearly rather than failing silently or continuing to spend.
Prompt
Agent Spend Cap Enforcement Prompt

When to Use This Prompt
Defines the exact conditions, required infrastructure, and failure modes for deploying a hard agent spend cap enforcement prompt in production.
Do not use this prompt as a soft advisory; it is built for hard enforcement gates. It assumes you have a cost-tracking harness that feeds cumulative spend and per-call cost estimates into the prompt variables. The prompt is not a replacement for application-layer circuit breakers or database-level budget locks—it is the decision layer that sits between your cost ledger and the agent's tool execution loop. If your system lacks real-time spend tracking with per-call cost estimates, deploy that instrumentation first. Without accurate [CUMULATIVE_SPEND] and [ESTIMATED_CALL_COST] inputs, this prompt will make decisions on stale or missing data, leading to budget overruns.
This prompt is appropriate when the cost of a single tool call is meaningful relative to the total budget. If individual calls cost fractions of a cent against a multi-dollar budget, the overhead of invoking this prompt before every call may exceed the cost it saves. In those cases, batch your checks or use a sampling approach. Conversely, if your agent makes only one or two tool calls per session, a simpler post-hoc budget check in application code may suffice. This prompt earns its place in multi-step agent workflows where 10 to 100+ tool calls are expected and the cumulative risk of overspend is real.
Before deploying, define your budget unit clearly. Are you capping USD cost, token consumption, or abstract credits? The prompt template uses [BUDGET_UNIT] as a placeholder, but your harness must convert all values to a consistent unit before populating the variables. Mixing token counts and dollar amounts in the same decision context produces nonsense outputs. Also define your cap scope: is it per user session, per task, per daily aggregate, or per agent instance? The prompt assumes a single-scope cap; multi-scope enforcement requires separate invocations or a composite budget tracker.
The primary failure mode is a false-continue decision where the prompt authorizes a call that pushes spend over the cap. This happens when [ESTIMATED_CALL_COST] is underestimated or when [CUMULATIVE_SPEND] lags behind actual spend due to asynchronous tool calls or delayed cost reporting. Mitigate this by padding cost estimates by 10-20% and by ensuring your cost tracker updates synchronously before each prompt invocation. A secondary failure mode is premature stopping, where the prompt halts execution too early due to overestimated call costs. Test your cost estimation accuracy before relying on this prompt for production enforcement.
Use Case Fit
Where the Agent Spend Cap Enforcement Prompt delivers value and where it introduces risk. Use these cards to decide if this prompt fits your operational context before integrating it into your agent harness.
Good Fit: Hard Cost Ceilings
Use when: you have a strict, non-negotiable budget per agent session or task and need the agent to stop before exceeding it. Guardrail: Pair this prompt with a platform-level circuit breaker that independently enforces the cap, so the prompt acts as a polite warning layer, not the sole enforcement mechanism.
Bad Fit: Latency-Sensitive Real-Time Agents
Avoid when: the agent must make sub-second decisions and cannot afford the extra reasoning step of evaluating spend against a cap. Guardrail: Move spend enforcement to the application layer with pre-computed budget checks before tool calls, and use this prompt only for near-cap communication to the user.
Required Input: Accurate Real-Time Spend Data
Risk: The prompt produces dangerous false assurances if the spend data injected into [CURRENT_SPEND] and [SPEND_CAP] is stale, estimated, or missing hidden costs like token overhead. Guardrail: Inject spend data from a single source of truth that updates synchronously with every tool call, and validate the data freshness before the prompt runs.
Operational Risk: Prompt Injection via Spend Context
Risk: If the spend data source is user-influenced or comes from an untrusted system, an attacker could inject a maliciously low [CURRENT_SPEND] to bypass the cap. Guardrail: Treat the spend data channel as a trusted internal signal. Never derive [CURRENT_SPEND] from user-supplied text or external APIs without sanitization and signature verification.
Good Fit: User-Facing Agent Communication
Use when: the agent must explain to a user why it is stopping or switching to a cheaper path, maintaining trust and transparency. Guardrail: Test the prompt's output for clarity and tone under near-cap, at-cap, and over-cap scenarios. Users should understand the reason without seeing raw cost internals.
Operational Risk: Stop vs. Continue Ambiguity
Risk: The prompt may produce a "continue with caution" decision that the harness interprets as a hard stop, or vice versa, leading to unexpected halts or budget overruns. Guardrail: Define a strict output schema with an enum field like decision: "STOP" | "CONTINUE" | "REQUEST_APPROVAL" and validate it in the harness before acting on the prompt's output.
Copy-Ready Prompt Template
A hardened system prompt that enforces a hard spend cap during agent execution, producing a stop-or-continue decision with clear remaining budget communication.
This prompt template is designed to be injected into your agent's system instructions before any tool-calling logic executes. It acts as a pre-tool-call enforcement layer, forcing the model to check a running cost tally against a declared cap before every action. The prompt does not track costs itself—that is the job of your cost-tracking harness—but it consumes the harness's output and makes a binary decision: proceed with the next tool call, or stop and notify the user. Use this when you need a hard circuit breaker that prevents runaway spend, not a soft advisory that the model can ignore.
textYou are an agent operating under a strict spend cap. Before every tool call, you MUST perform a budget check using the provided cost context. Your primary directive is to never exceed the cap. ## COST CONTEXT (provided by harness) - Total Spend Cap: [SPEND_CAP] - Cumulative Spend So Far: [CUMULATIVE_SPEND] - Estimated Cost of Next Tool Call: [NEXT_CALL_ESTIMATE] - Budget Remaining: [REMAINING_BUDGET] - Tool Name Under Consideration: [TOOL_NAME] ## DECISION RULES 1. If [CUMULATIVE_SPEND] + [NEXT_CALL_ESTIMATE] > [SPEND_CAP], you MUST stop. Do not call the tool. 2. If [REMAINING_BUDGET] < [NEXT_CALL_ESTIMATE], you MUST stop. Do not call the tool. 3. If the tool call is allowed, proceed and then update the cost context with the actual cost after the call completes. ## STOP OUTPUT FORMAT When stopping, output ONLY the following JSON. Do not include any other text. { "decision": "STOP", "reason": "Spend cap would be exceeded.", "spend_cap": [SPEND_CAP], "cumulative_spend": [CUMULATIVE_SPEND], "next_call_estimate": [NEXT_CALL_ESTIMATE], "remaining_budget": [REMAINING_BUDGET], "user_message": "I've stopped because the next action would exceed our agreed budget of [SPEND_CAP]. We've used [CUMULATIVE_SPEND] so far. Would you like to increase the cap or try a different approach?" } ## CONTINUE OUTPUT FORMAT When continuing, output ONLY the following JSON before making the tool call. { "decision": "CONTINUE", "remaining_budget_after_call": [REMAINING_BUDGET_AFTER_ESTIMATE], "tool_call": "[TOOL_NAME]" } ## CONSTRAINTS - Never invent or estimate costs. Only use the values provided in the COST CONTEXT. - Never call a tool without first outputting a CONTINUE decision. - If the COST CONTEXT is missing or malformed, STOP immediately and request valid context.
To adapt this template, replace each square-bracket placeholder with live values from your cost-tracking harness at runtime. The harness should calculate [CUMULATIVE_SPEND] by summing actual costs from completed tool calls and [NEXT_CALL_ESTIMATE] by looking up the tool's known cost profile. Wire the STOP output into your agent's control loop so that the user-facing message is surfaced and execution halts until a human decision is made. For high-stakes production systems, add a secondary validation step outside the model—your application code should independently verify that the model's CONTINUE decision does not violate the cap before forwarding the tool call. This defense-in-depth approach catches cases where the model misreads the cost context or hallucinates a CONTINUE decision.
Prompt Variables
All values must be supplied by the application harness before invoking the Agent Spend Cap Enforcement Prompt. Missing or malformed variables will cause the prompt to fail closed (stop execution).
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[CURRENT_TOTAL_SPEND] | The cumulative cost of all tool calls in the current session, in the configured currency. | 0.8742 | Must be a non-negative float. Parse as decimal, not integer. If null or negative, abort and log schema error. |
[SPEND_CAP] | The hard maximum spend allowed for this session. The agent must stop before exceeding this value. | 5.00 | Must be a positive float greater than 0. Reject zero or negative caps. Compare against [CURRENT_TOTAL_SPEND] before prompt invocation to short-circuit if already breached. |
[LAST_TOOL_CALL_COST] | The cost of the most recently completed tool call. Used to project whether the next call would breach the cap. | 0.0312 | Must be a non-negative float. If no prior call exists in session, supply 0.0. Null is not allowed; default to 0.0 in harness. |
[ESTIMATED_NEXT_CALL_COST] | The projected cost of the next planned tool call, derived from tool cost metadata or historical averages. | 0.0450 | Must be a non-negative float. If unknown, supply a conservative upper-bound estimate. Null triggers a warning and forces a stop decision. |
[TOOL_NAME_NEXT] | The name of the tool the agent intends to call next. Used in the stop-or-continue rationale. | browse_web | Must be a non-empty string matching a registered tool name in the tool registry. If empty or unrecognized, treat as unknown tool and stop. |
[SESSION_ID] | Unique identifier for the current agent session. Used for audit logging and cost attribution. | sess_9a7b3c | Must be a non-empty string. Validate against allowed session ID format. If missing, generate a harness-level fallback ID and log a warning. |
[CURRENCY_CODE] | ISO 4217 currency code for all monetary values in this prompt. | USD | Must be a 3-letter uppercase string matching an active ISO 4217 code. Reject unknown codes. Default to USD if not supplied but log the default. |
Implementation Harness Notes
How to wire the Agent Spend Cap Enforcement Prompt into a production agent loop with validation, retries, and human escalation.
The spend cap enforcement prompt is not a standalone chat interaction—it is a decision gate inserted into the agent's execution loop before every billable tool call. The application harness must intercept the agent's intended action, compute the cumulative spend and remaining budget, and inject the prompt with the current state. The model's response (a structured stop-or-continue decision) then gates whether the tool call proceeds, is blocked, or escalates for human approval. This means the harness owns the budget counter, not the model. The model only interprets the numbers and enforces the policy.
Implement this as a pre-tool-call middleware in your agent framework. Before the agent invokes any tool with a non-zero cost, the harness: (1) calculates total_spend_to_date and remaining_budget from a persistent ledger; (2) populates the prompt template with [CURRENT_TOOL_NAME], [ESTIMATED_CALL_COST], [SPEND_CAP], [TOTAL_SPEND_TO_DATE], [REMAINING_BUDGET], [TASK_CONTEXT_SUMMARY], and [ESCALATION_POLICY]; (3) sends the prompt to a fast, low-cost model (e.g., GPT-4o-mini or Claude Haiku) with response_format set to the JSON schema { "decision": "proceed" | "block" | "escalate", "reasoning": "string", "user_notification": "string" }; and (4) enforces the decision. If block, the tool call is cancelled and the user_notification is surfaced. If escalate, the harness pauses execution and routes to a human approval queue with the full context. If proceed, the tool call executes and the harness updates the ledger with the actual cost (not the estimate) after the call completes.
Validation and retries are critical. Validate the model's JSON response against the schema before acting on it. If parsing fails or the decision field is not one of the three allowed values, retry once with the same prompt plus the parse error. If the second attempt fails, default to block and log the failure for review—never default to proceed on a validation error. For near-cap scenarios (where remaining_budget is less than 20% of SPEND_CAP), consider adding a second validation: if the model returns proceed but the estimated cost exceeds the remaining budget, override to block and log the inconsistency. This belt-and-suspenders approach prevents a hallucinated proceed from breaching the cap.
Logging and observability are non-negotiable. Every enforcement decision must be logged with a trace that includes: the prompt input, the model's raw response, the parsed decision, the tool call outcome (executed, blocked, escalated), the actual cost incurred, and the updated budget state. This audit trail is essential for debugging spend anomalies, tuning the enforcement prompt, and demonstrating governance to finance or compliance stakeholders. Wire these logs into your existing observability stack (e.g., Datadog, Grafana, or your AI gateway's trace store) with a dedicated spend_cap_enforcement span type. For high-throughput agents, sample the full prompt and response at 100% for blocked or escalated decisions and at a lower rate for routine proceed decisions to manage log volume.
Human-in-the-loop integration requires the harness to serialize the full agent state when escalation is triggered. Do not just send the user_notification string—include the task context, the tool call that triggered the escalation, the current spend vs. cap, and a structured approval payload (e.g., { "approve": true, "override_cap": false, "one_time_budget_extension": null }). The human reviewer's decision should be recorded and fed back into the ledger. If the human approves a one-time budget extension, update SPEND_CAP for the remainder of the session and resume execution. If denied, treat it as a block and communicate the final state to the end user. Test this path explicitly in your eval suite with simulated near-cap and over-cap scenarios to ensure the escalation loop doesn't deadlock or silently drop context.
Expected Output Contract
The agent must return a single JSON object conforming to this schema. Every field is required unless explicitly noted. Validation should be performed in the application layer before acting on the decision.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
decision | enum: | Must be exactly one of the three allowed string values. Reject any other value. | |
current_spend | number (float, 2 decimal places) | Must be >= 0. Parse as float and verify it matches the cumulative cost of tool calls in the current session trace. | |
spend_cap | number (float, 2 decimal places) | Must be > 0 and must match the [SPEND_CAP] value provided in the system prompt. Reject on mismatch. | |
remaining_budget | number (float, 2 decimal places) | Must equal spend_cap minus current_spend. Reject if the computed difference does not match this field within a 0.01 tolerance. | |
reason_code | string from allowed set | Must be one of: | |
user_notification | string (plain text, <= 280 characters) | Must be present and non-empty. Reject if length exceeds 280 characters. Must not contain PII placeholders or unresolved template tokens. | |
next_review_threshold | number (float, 2 decimal places) or null | If decision is CONTINUE, must be a number representing the spend level at which the agent should re-evaluate. If decision is STOP or REQUEST_APPROVAL, must be null. | |
escalation_required | boolean | Must be true if decision is REQUEST_APPROVAL or if remaining_budget is <= 0. Must be false otherwise. Reject on inconsistency. |
Common Failure Modes
Spend cap enforcement fails silently in production when budget state is stale, thresholds are ambiguous, or the agent lacks authority to stop. These are the most common failure patterns and how to prevent them.
Stale Budget State Causes Overspend
What to watch: The agent reads the remaining budget once at the start of a multi-step task and never refreshes it. By step five, the actual spend has exceeded the cap, but the agent continues because it's working from cached state. Guardrail: Require a fresh budget check before every billable tool call. The prompt must instruct the agent to call the budget API, not rely on memory or prior context.
Near-Cap Ambiguity Produces Wrong Decisions
What to watch: When remaining budget is within a single tool call's estimated cost, the agent either stops too early and abandons the task or proceeds and breaches the cap. The prompt lacks a clear tie-breaking rule. Guardrail: Define an explicit near-cap policy in the prompt: if estimated cost exceeds remaining budget, stop and escalate. If estimated cost is within 10% of remaining budget, request human approval before proceeding.
Agent Lacks Authority to Enforce the Stop
What to watch: The prompt tells the agent to stop when the cap is reached, but the agent's tool execution loop is controlled by external orchestration code that ignores the stop signal. The agent produces a stop decision that the harness never reads. Guardrail: The prompt must produce a structured stop-or-continue decision in a machine-readable field. The orchestration layer must parse this field and halt execution. Test with a simulated cap breach to confirm the harness obeys.
User Notification Is Vague or Missing
What to watch: The agent hits the cap and stops, but the user receives a generic error or silence. The user doesn't know why work stopped, what was completed, or how to request a budget increase. Guardrail: The prompt must generate a user-facing message that includes: current spend, cap limit, what was completed, what remains undone, and clear next steps. Validate message completeness in eval.
Parallel Tool Calls Bypass the Cap Check
What to watch: The agent dispatches multiple tool calls in parallel after a single budget check. Combined cost exceeds the cap, but no individual call triggered the threshold. Guardrail: The prompt must instruct the agent to sum estimated costs of all parallel calls and compare the total against remaining budget before dispatch. If the sum exceeds remaining budget, serialize calls or request approval.
Retry Loops Inflate Spend Past the Cap
What to watch: A tool call fails, and the agent retries automatically. Each retry consumes budget, but the retry logic doesn't re-check the cap. A transient error becomes a budget breach. Guardrail: The prompt must require a fresh budget check before every retry attempt. If remaining budget is insufficient for the retry, the agent must stop and report the failure rather than retry into overspend.
Evaluation Rubric
Run these checks against a golden dataset of spend scenarios to validate the Agent Spend Cap Enforcement Prompt before production deployment.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Cap-Aware Stop Decision | Output correctly returns | Output returns | Run 20 golden scenarios at exactly the cap boundary; assert |
Remaining Budget Accuracy | Output field [REMAINING_BUDGET] equals [SPEND_CAP] minus [CURRENT_SPEND] within ±0.01 precision | Remaining budget is off by more than 0.01, negative without a stop decision, or missing | Parse [REMAINING_BUDGET] from output; compare to ground-truth calculation for all golden cases |
User Notification Clarity | Output field [USER_MESSAGE] explains the stop reason, remaining budget, and next step in plain language under 200 characters | Message is empty, exceeds 200 characters, uses internal codes, or blames the user | LLM-as-judge eval: score clarity, tone, and completeness on a 1-5 rubric across 15 scenarios |
Near-Cap Warning Behavior | When [CURRENT_SPEND] is between 80-99% of [SPEND_CAP], output includes a warning flag and does not stop prematurely | Warning is missing when spend is in the warning zone, or stop is triggered before the cap is reached | Inject 10 near-cap scenarios; assert presence of warning indicator and absence of premature stop |
Under-Cap Continue Decision | Output correctly returns | Output stops or warns when spend is safely under cap with no risk of exceeding | Run 10 under-cap scenarios; assert |
Schema Compliance | Output is valid JSON matching the [OUTPUT_SCHEMA] with all required fields present and correctly typed | Missing required fields, wrong types, extra fields that violate schema, or unparseable JSON | Validate output against JSON Schema definition; reject any output that fails structural validation |
Edge Case: Zero Remaining Budget | When [CURRENT_SPEND] equals [SPEND_CAP], output returns | Output returns continue, negative remaining budget, or crashes on zero-boundary input | Test with [CURRENT_SPEND] exactly equal to [SPEND_CAP]; assert stop and zero remaining budget |
Edge Case: Negative Estimated Cost | When [ESTIMATED_NEXT_CALL_COST] is negative or null, output handles gracefully with a warning and does not crash | Output produces negative remaining budget, divides by zero, or returns unhandled error | Inject negative and null cost values; assert graceful degradation with warning flag and no invalid math |
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
Add a full JSON schema with required fields: decision, remaining_budget, cost_breakdown, notification_message, and escalation_flag. Wire the prompt into a pre-tool-call hook that reads live budget state from your cost database. Include retry logic for schema validation failures. Add structured logging of every enforcement decision.
codeSystem: You are an agent spend enforcer operating on live budget data. The hard spend cap is [CAP] with [REMAINING] remaining. The next planned tool call is [TOOL_NAME] with estimated cost [ESTIMATED_COST]. Current session has consumed [SESSION_SPEND]. Respond with a strict JSON object matching [OUTPUT_SCHEMA]. If decision is "stop", include a clear user-facing notification_message explaining the cap was reached and what the user can do. Set escalation_flag to true if spend exceeded 90% of cap in the last [WINDOW_MINUTES] minutes.
Watch for
- Schema drift when the model omits optional fields like
cost_breakdown - Race conditions between budget read and tool execution
- Notification messages that leak internal cost data to end users

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