This prompt is for platform operators and AI cost engineers who need an agent to choose between multiple available tools by weighing each tool's capability against its estimated invocation cost. The core job-to-be-done is preventing runaway spend in production agent systems where unconstrained tool selection leads to expensive API calls, unnecessary data processing, or premium-tier service usage when cheaper alternatives would suffice. The ideal user is someone embedding cost metadata directly into the agent's decision layer—not just setting hard caps, but making cost a first-class dimension of tool choice alongside accuracy, latency, and capability fit.
Prompt
Cost-Aware Tool Selection System Prompt

When to Use This Prompt
Define the job, reader, and constraints for the Cost-Aware Tool Selection System Prompt.
Use this prompt when your agent has access to a tool registry that includes cost-per-call estimates, token consumption projections, or tiered pricing metadata. It is most effective in scenarios where multiple tools can satisfy the same intent at different price points—for example, a local embedding model versus a paid vector search API, or a cached database lookup versus a live third-party enrichment call. The prompt requires that cost metadata is available at decision time, either injected into the system prompt as part of the tool descriptions or accessible through a pre-flight cost estimation tool. Do not use this prompt when all tools have identical cost profiles, when cost information is unavailable or unreliable, or when the primary constraint is latency rather than spend.
This prompt is insufficient on its own for hard spend enforcement. It influences tool selection but does not guarantee budget compliance—pair it with a separate spend-cap enforcement mechanism, circuit breakers, and cost logging. It is also not a replacement for rate-limit handling or retry logic. In high-stakes financial or compliance workflows, always route final tool selections through a human approval gate when estimated costs exceed predefined thresholds. Before deploying, validate the prompt against a test harness that simulates budget pressure, tool unavailability, and cost-estimation errors to ensure the agent degrades gracefully rather than defaulting to the most expensive available option.
Use Case Fit
Where the Cost-Aware Tool Selection prompt delivers value and where it introduces risk. Use this to decide if the prompt belongs in your agent's system instructions.
Good Fit: Multi-Tool Agent with Variable Pricing
Use when: your agent has access to multiple tools that can accomplish the same goal at different price points (e.g., GPT-4 vs. Claude Haiku for summarization, or a paid API vs. a local model). Guardrail: Provide explicit per-tool cost metadata in the system prompt so the model can make informed trade-offs rather than guessing.
Bad Fit: Single-Tool or Fixed-Cost Environments
Avoid when: the agent only has one tool available or all tools have identical cost profiles. The cost-awareness instructions add token overhead without changing behavior. Guardrail: Feature-flag this prompt so it only activates when multiple tools with distinct costs are registered in the tool registry.
Required Input: Accurate Cost Metadata
Risk: If per-call cost estimates are stale, missing, or measured in inconsistent units, the model will optimize for a phantom objective. Guardrail: Inject cost metadata from a live pricing service at prompt assembly time. Validate that every tool in the active set has a non-null cost field before sending the system prompt.
Operational Risk: Cost Optimization Over Quality
Risk: The model may over-index on cost minimization and select cheaper tools that produce lower-quality outputs, degrading the user experience. Guardrail: Include a minimum quality threshold in the prompt (e.g., 'Never sacrifice accuracy for cost savings on compliance-critical tasks') and log cost-vs-quality metrics for review.
Operational Risk: Budget Exhaustion Deadlocks
Risk: When the remaining budget is too low for any capable tool, the agent may loop, refuse all actions, or select an inappropriate fallback. Guardrail: Define an explicit budget-exhaustion policy in the prompt that triggers a structured escalation to a human operator with remaining budget and task state.
Bad Fit: Latency-Sensitive Real-Time Systems
Avoid when: response time is the primary constraint and cost is secondary. The additional reasoning step for cost comparison adds latency. Guardrail: If latency SLA is below 500ms, disable cost-aware selection and use a static routing table instead. Reserve this prompt for batch or async workloads where the trade-off calculation is worthwhile.
Copy-Ready Prompt Template
A reusable system prompt that makes an agent weigh tool capability against estimated call cost before every selection.
This template embeds cost metadata directly into the agent's tool-selection reasoning loop. Instead of treating cost as an afterthought, the prompt forces the model to compare candidate tools on both functional fit and estimated spend before emitting a tool call. The placeholders let you inject your own tool catalog, cost model, budget constraints, and risk tolerance without rewriting the selection logic.
textYou are an agent that selects and invokes tools to accomplish user tasks. Before every tool call, you must evaluate candidate tools against two dimensions: functional suitability and estimated cost. ## TOOL CATALOG [TOOLS] ## COST MODEL Each tool entry includes an `estimated_cost` field expressed in [COST_UNIT]. This is the expected cost of a single invocation under normal parameters. Actual cost may vary with input size, output size, and server-side pricing. ## BUDGET CONSTRAINTS - Per-task budget cap: [BUDGET_CAP] [COST_UNIT] - Per-call soft threshold: [SOFT_THRESHOLD] [COST_UNIT] (exceeding this requires explicit justification) - Rate limit window: [RATE_WINDOW] with max [RATE_LIMIT] calls per window - If remaining budget falls below [MIN_REMAINING], prefer the cheapest viable tool or escalate to human review ## SELECTION RULES 1. Identify all tools that can satisfy the current step's functional requirements. 2. Rank them by `estimated_cost` ascending. 3. Select the lowest-cost tool that meets the functional requirement, unless a higher-cost tool provides a materially better outcome (higher accuracy, richer response, lower latency) that justifies the additional spend. 4. If you select a tool above the soft threshold, include a one-sentence justification in your reasoning. 5. If no tool fits within the remaining budget, respond with: `BUDGET_EXHAUSTED: [remaining_budget] [COST_UNIT] remaining, need [required_cost] [COST_UNIT] for cheapest viable tool.` Do not invoke the tool. 6. Track cumulative spend across all calls in the current task. Report it after each call as: `SPEND_TRACKER: [cumulative_spend] / [BUDGET_CAP] [COST_UNIT]`. ## OUTPUT FORMAT For every tool call, output a JSON block: { "tool": "<tool_name>", "arguments": { ... }, "estimated_cost": <number>, "cost_justification": "<optional, required if cost exceeds soft threshold>", "cumulative_spend": <number>, "budget_remaining": <number> } ## FALLBACK AND ESCALATION - If the primary tool fails with a rate-limit error (HTTP 429), apply the backoff specified in the Retry-After header. Do not retry before the window expires. - If three consecutive calls to the same tool fail, switch to the next cheapest viable alternative. - If cumulative spend reaches [ESCALATION_THRESHOLD]% of the budget cap, pause and request human approval before proceeding. ## CONSTRAINTS [CONSTRAINTS] ## EXAMPLES [EXAMPLES] ## RISK LEVEL [RISK_LEVEL]
To adapt this template, replace each square-bracket placeholder with concrete values from your production environment. The [TOOLS] placeholder should contain a structured list of tool definitions, each with a name, description, parameter schema, and estimated_cost field. Derive [COST_UNIT] from your pricing model—use tokens, dollars, credits, or an abstract cost score. Set [BUDGET_CAP] based on observed per-task spend baselines, and tune [SOFT_THRESHOLD] to flag calls that deserve scrutiny without blocking them outright. The [ESCALATION_THRESHOLD] should be high enough to avoid alert fatigue but low enough to prevent budget overruns before a human can intervene. If your tools have widely varying costs, add a cost_tier field (low/medium/high) to the tool catalog and adjust the selection rules to prefer lower tiers when budget pressure is high. Before deploying, run this prompt through a harness that simulates budget exhaustion, rate-limit responses, and tool failures to verify the agent degrades gracefully rather than looping or hallucinating.
Prompt Variables
Required and optional inputs for the Cost-Aware Tool Selection System Prompt. Each variable must be populated before the prompt is assembled and sent to the model. Missing or malformed variables will cause the agent to ignore cost constraints or select inappropriate tools.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TOOL_CATALOG] | JSON array of available tools with cost metadata, capability descriptions, and argument schemas | [{"name": "web_search", "cost_per_call_usd": 0.005, "capabilities": ["real-time-info"], "schema": {...}}] | Validate JSON parse succeeds. Each object must have name, cost_per_call_usd, and capabilities fields. Reject if cost_per_call_usd is negative or missing. |
[TASK_DESCRIPTION] | Natural language description of the user's goal or query that requires tool selection | Find the latest quarterly earnings for the top 3 cloud providers and summarize them | Non-empty string required. Reject if null or whitespace-only. Length should be under 2000 tokens to avoid diluting cost-awareness instructions. |
[BUDGET_CAP_USD] | Maximum total cost allowed for all tool calls in this task, expressed in USD | 0.05 | Must be a positive float. Reject if zero, negative, or non-numeric. If null, agent should assume no budget constraint and log a warning. |
[COST_WEIGHT] | Float between 0 and 1 controlling how aggressively the agent prioritizes cost over capability in selection decisions | 0.7 | Must be a float in range [0.0, 1.0]. 0 means ignore cost entirely. 1 means minimize cost regardless of capability gap. Reject out-of-range values. |
[FALLBACK_BEHAVIOR] | Enum specifying what the agent should do when no tool fits within budget: 'error', 'select_cheapest', or 'request_approval' | select_cheapest | Must be one of the three allowed enum values. Reject unrecognized strings. If 'request_approval', ensure [APPROVAL_GATE_URL] is also provided. |
[APPROVAL_GATE_URL] | Optional webhook URL for triggering human approval when budget would be exceeded and fallback is 'request_approval' | If [FALLBACK_BEHAVIOR] is 'request_approval', this field is required and must be a valid HTTPS URL. Parse check for URL scheme and hostname. Null allowed otherwise. | |
[RATE_LIMIT_STATE] | Optional JSON object describing current rate limit status per tool, including remaining calls and reset timestamps | {"web_search": {"remaining": 8, "resets_at_utc": "2025-01-15T14:30:00Z"}} | If provided, validate JSON parse. Each key must match a tool name in [TOOL_CATALOG]. Remaining must be a non-negative integer. Null allowed if rate limits are not tracked. |
Implementation Harness Notes
How to wire the cost-aware tool selection prompt into a production agent loop with validation, logging, and budget enforcement.
The Cost-Aware Tool Selection System Prompt is designed to sit inside an agent's tool-calling step, not as a standalone chat interface. It receives a list of available tools annotated with estimated costs (in tokens, dollars, or latency), the current task context, and any remaining budget constraints. The prompt's job is to return a structured tool selection that balances capability against cost. In production, this prompt is typically invoked by an agent framework (LangGraph, AutoGen, custom loop) immediately after the planner decides a tool call is needed but before the call is executed. The model never directly invokes the tool; it only produces a selection decision that the harness validates and then executes.
Wire this prompt into your agent loop with a pre-execution validation layer. Before executing the selected tool, validate that: (1) the selected tool exists in the available tool registry, (2) the estimated cost does not exceed the remaining session or task budget, (3) the tool's required arguments are present and type-correct, and (4) the selection rationale references actual tool capabilities rather than hallucinated features. If validation fails, log the rejection reason, increment a cost_selection_failure metric, and either retry with the failure message fed back into the prompt or fall back to the cheapest viable tool. For high-stakes domains (finance, healthcare, infrastructure), insert a human approval gate when the selected tool exceeds a cost threshold or when the model's confidence in the selection appears low—detectable by checking if the rationale is vague or contradicts the tool's documented capabilities.
Log every tool selection decision as a structured event: {timestamp, session_id, task_id, available_tools, budget_remaining, selected_tool, estimated_cost, rationale, validation_passed, actual_cost_post_execution}. This log becomes your cost attribution and debugging backbone. Compare estimated_cost against actual_cost_post_execution to detect systematic under- or over-estimation. If the model consistently selects expensive tools when cheaper equivalents succeed, you may need to adjust cost metadata, add few-shot examples of cost-conscious selection, or tighten the budget constraint language. For model choice, prefer models with strong instruction-following and structured output support (GPT-4o, Claude 3.5 Sonnet, or fine-tuned variants). Avoid using this prompt with models that struggle to reason about trade-offs or that hallucinate tool names—test with a golden set of tool registries and budget scenarios before deployment. Implement a circuit breaker: if three consecutive tool selections fail validation, abort the agent step, log the escalation, and surface the decision to a human operator or fallback workflow.
Expected Output Contract
Validate the structured output of the Cost-Aware Tool Selection System Prompt. Each field must be parsed and checked before the agent proceeds with tool execution.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
selected_tool | string | Must match a tool name from the provided [TOOL_REGISTRY]. Reject if hallucinated. | |
estimated_cost | number | Must be a non-negative float. Reject if null or negative. Compare against [TOOL_COST_MAP] for consistency. | |
cost_currency | string | Must be one of ['USD', 'token', 'credit']. Reject if missing or not in enum. | |
justification | string | Must contain a cost-vs-capability rationale. Reject if empty, generic, or missing reference to [BUDGET_CAP]. | |
alternative_tools_considered | array of strings | Must list at least one alternative tool name from [TOOL_REGISTRY]. Reject if empty or contains hallucinated names. | |
budget_remaining_after_call | number | Must be less than or equal to [BUDGET_CAP] minus estimated_cost. Reject if negative or exceeds cap. | |
fallback_tool | string or null | Must be a tool name from [TOOL_REGISTRY] or null. If not null, estimated_cost must be lower than selected_tool cost. | |
confidence_score | number | If present, must be between 0.0 and 1.0. Reject if out of range. Used for cost-vs-accuracy trade-off logging. |
Common Failure Modes
Cost-aware tool selection fails in predictable ways under production pressure. These are the most common failure modes and the guardrails that prevent them.
Cost Metadata Staleness
What to watch: The model selects tools based on outdated cost estimates embedded in the system prompt, leading to budget overruns when actual API pricing has changed. Guardrail: Inject cost metadata at runtime from a live pricing source rather than hardcoding it. Validate cost estimates against actual charges weekly and trigger a prompt refresh when drift exceeds 10%.
Cheapest-Tool Bias
What to watch: Under budget pressure, the model consistently selects the lowest-cost tool even when it lacks the capability to complete the task correctly, producing silent failures that look successful. Guardrail: Include minimum capability requirements in the tool selection criteria. Add an eval that compares task completion accuracy against tool cost tier and flags when cheap-tool accuracy drops below threshold.
Budget Exhaustion Mid-Task
What to watch: The agent spends most of the budget on early steps and runs out before completing critical later steps, leaving the task in an unrecoverable partial state. Guardrail: Require the agent to produce a per-step budget allocation before execution begins. Implement a hard stop with a structured partial-result handoff when remaining budget falls below the cheapest viable completion path.
Cost-Ignorant Fallback Selection
What to watch: When a primary tool fails or is rate-limited, the fallback selection logic ignores cost constraints and picks an expensive alternative that blows through the remaining budget. Guardrail: Define fallback chains with explicit cost ceilings per tier. Test fallback paths under simulated primary-tool failure and verify that the selected fallback respects the original budget envelope.
Hidden Cost Amplification in Loops
What to watch: A single tool call appears cheap, but the agent calls it in a tight loop—retrying, paginating, or exploring—and cumulative cost explodes without any single call triggering a threshold. Guardrail: Track cumulative per-tool spend within a session, not just per-call cost. Set a per-tool session cap and require explicit re-authorization when the cap is approached. Test with loop-inducing scenarios.
Cost vs. Accuracy Trade-Off Blindness
What to watch: The model cannot reliably estimate whether a more expensive tool will actually produce a better outcome, so it either overspends for marginal gains or underspends and misses critical accuracy requirements. Guardrail: Maintain a historical correlation table of tool cost vs. outcome quality for common task types. Inject this evidence into the selection prompt so the model can ground its trade-off decisions in observed data rather than guessing.
Evaluation Rubric
Criteria for evaluating the quality and safety of cost-aware tool selections before shipping to production. Use these checks in an eval harness or LLM-as-judge pipeline.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Budget Constraint Adherence | Selected tool's estimated cost does not exceed the remaining [BUDGET_CAP] for the current task or step. | Tool selection exceeds remaining budget without explicit user override or escalation. | Inject a near-exhausted budget state and verify the agent selects a cheaper alternative or requests approval. |
Cost-Benefit Justification | When a more expensive tool is selected over a cheaper alternative, the response includes a specific capability gap the cheaper tool cannot fill. | Expensive tool selected with generic reasoning or no comparison to cheaper alternatives listed in [TOOL_CATALOG]. | Provide two tools with overlapping capabilities but different costs; verify the agent articulates the trade-off when choosing the costlier option. |
Fallback Invocation | When the primary tool would exceed a rate limit or budget, the agent selects the next-best tool from the [FALLBACK_CHAIN] without hallucinating unsupported capabilities. | Agent ignores the fallback chain, retries the blocked tool, or invents a tool not in the catalog. | Simulate a 429 rate limit on the primary tool and check that the agent selects a valid fallback from the provided list within one response. |
Rate Limit Header Compliance | Agent respects a simulated Retry-After header by not scheduling the same tool call before the specified window elapses. | Agent retries immediately, schedules a call within the forbidden window, or ignores the header entirely. | Provide a tool response with a 429 status and Retry-After: 30; verify the agent's next plan delays the retry by at least 30 seconds. |
Runaway Loop Prevention | Agent terminates or escalates after [MAX_CONSECUTIVE_CALLS] to the same tool without state change, rather than continuing indefinitely. | Agent makes more than the configured maximum consecutive calls with identical or non-progressing arguments. | Feed a tool that returns the same non-progressing result repeatedly; verify the agent stops and reports the stall within the configured limit. |
Cost Logging Completeness | Every tool call in the agent's execution trace is accompanied by a structured cost record matching the [COST_LOG_SCHEMA]. | Missing cost records, null required fields, or cost attributed to the wrong tool or step. | Run a multi-step scenario and validate the output trace against the cost log schema; flag any missing or malformed records. |
Spend Cap Enforcement | Agent stops execution and communicates remaining budget when the next planned call would exceed the [HARD_SPEND_CAP]. | Agent exceeds the hard cap, continues without warning, or stops without communicating the reason. | Set a hard cap just below the cost of the next required tool call; verify the agent halts and outputs a clear budget-exhaustion message. |
User-Facing Cost Communication | When budget or rate limits force a change in plan, the agent produces a user-visible message explaining the constraint and the alternative chosen. | Agent silently downgrades tool selection or produces a cryptic internal error without user-facing explanation. | Trigger a budget-forced fallback and check that the output includes a message suitable for display to an end user, not just an internal log line. |
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 system prompt and a hardcoded cost table. Use a single model call with no retries or validation. Replace the [TOOL_CATALOG_JSON] placeholder with a small set of 3-5 tools with estimated costs. Skip the [BUDGET_CAP] constraint initially to observe default selection behavior.
Watch for
- The model ignoring cost metadata when capability differences are small
- Hallucinated cost estimates if you omit the catalog entirely
- No logging of actual spend, making it impossible to validate selection quality

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