Inferensys

Prompt

Tool Call with Rate Limiting and Cost Awareness Prompt

A practical prompt playbook for teaching agents to batch calls, use caches, and optimize tool sequences under budget and rate constraints.
Developer demonstrating multi-agent tool use, agent tool selection interface on laptop, casual tech demo moment.
PROMPT PLAYBOOK

When to Use This Prompt

Teaches the model to make cost-aware and rate-limit-aware tool-calling decisions through few-shot examples rather than abstract rules.

This prompt is for agent developers whose systems operate under strict API constraints. It teaches the model to make cost-aware and rate-limit-aware tool-calling decisions through few-shot examples rather than abstract rules. Use it when your agent has access to multiple tools with different cost profiles, rate limits, or caching behaviors, and you need the model to batch requests, avoid redundant calls, and stay within a defined budget.

The prompt works by providing concrete demonstrations of good and bad tool-calling sequences under resource constraints. Each example shows the model how to reason about tool costs, identify batching opportunities, and respect rate limits before making a call. This is more effective than describing rules because the model learns the pattern of checking constraints before acting. The prompt template includes placeholders for your specific tools, their cost and rate-limit metadata, and example scenarios that match your application's typical workloads.

This prompt is not a substitute for application-layer rate limiting or circuit breakers. It works alongside those controls to reduce the likelihood of the model proposing call sequences that will fail or exceed cost thresholds. Do not use this prompt when your agent has only one tool, when all tools have identical cost and rate-limit profiles, or when you have already implemented deterministic batching logic in your application code. For high-stakes financial operations or compliance-sensitive workflows, always pair this prompt with human review gates and audit logging of actual tool calls made.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Tool Call with Rate Limiting and Cost Awareness Prompt delivers value and where it introduces risk. Use these cards to decide if this pattern fits your agent's operational constraints.

01

Good Fit: Budget-Constrained Agents

Use when: Your agent operates under a strict token or dollar budget per task and must prioritize high-value tool calls. The prompt's few-shot examples teach the model to batch independent calls and defer low-utility lookups. Guardrail: Pair with a budget-tracking wrapper that injects remaining budget into the prompt context so the model can adapt its strategy mid-execution.

02

Good Fit: Multi-Tool Environments with Tiered Costs

Use when: Your agent has access to tools with significantly different costs (e.g., a cheap cache lookup vs. an expensive external API call). The prompt demonstrates selecting the cheaper tool first and only escalating when necessary. Guardrail: Maintain a tool cost manifest and include per-tool cost annotations in the system prompt so the model's cost-awareness is grounded in real numbers, not assumptions.

03

Bad Fit: Single-Tool or Fixed-Sequence Workflows

Avoid when: The agent only has one tool or the tool call sequence is deterministic and non-negotiable. The cost-awareness examples add token overhead without providing any decision value. Guardrail: Use a simpler function-calling prompt without cost reasoning. Reserve this pattern for agents with genuine tool selection freedom.

04

Required Input: Tool Cost and Rate Limit Metadata

Risk: Without concrete cost and rate limit data in the prompt, the model will invent plausible but incorrect constraints, leading to overly conservative or reckless tool use. Guardrail: Always inject a structured tool manifest containing cost_per_call, rate_limit_remaining, cache_ttl, and batch_support fields. Validate this manifest before every agent turn.

05

Operational Risk: Stale Cost Data Drives Bad Decisions

Risk: If the cost or rate limit metadata injected into the prompt is outdated, the model will optimize for a reality that no longer exists—batching when the rate limit was already reset or avoiding a tool that is now cheap. Guardrail: Refresh tool metadata from live API headers or a cost service at the start of each agent turn. Log the metadata snapshot alongside the prompt for post-hoc debugging.

06

Operational Risk: Over-Batching Causes Timeouts

Risk: The model may aggressively batch independent calls to save cost, but a single batched call that exceeds a downstream timeout fails all constituent operations. Guardrail: Include a max_batch_size and max_batch_latency_ms constraint in the tool manifest. Add a negative example showing a batch that was too large and caused a timeout, teaching the model to split batches when necessary.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable few-shot prompt that teaches an agent to batch tool calls, select cache-aware operations, and order actions by cost when operating under API rate limits and budget constraints.

This template uses concrete worked examples to demonstrate the desired behavior rather than relying solely on abstract rules. The examples show the model how to analyze a set of pending tool calls, identify which can be batched into a single request, recognize when a cached result is still valid, and order the remaining calls from cheapest to most expensive. The square-bracket placeholders let you inject your own tool definitions, cost model, rate limit parameters, and the current task context. Copy the template, replace the placeholders with your production values, and test it against the eval criteria described in the testing section of this playbook.

code
SYSTEM:
You are an agent operating under strict API constraints. Before making any tool calls, you must analyze the requested operations and produce an execution plan that minimizes cost and respects rate limits. Follow these rules:
- Batch independent calls to the same endpoint into a single request when the API supports it.
- Check the [CACHE_STATE] before calling any read operation. If a valid cached result exists, use it instead of making a new call.
- Order remaining calls from lowest cost to highest cost according to [COST_MODEL].
- Never exceed [RATE_LIMIT] calls per [WINDOW].
- If the plan would exceed the budget [MAX_BUDGET], drop the lowest-priority calls and explain why.

USER:
[CURRENT_TASK]

Available tools and costs:
[TOOL_DEFINITIONS]

Current cache state:
[CACHE_STATE]

Rate limit remaining: [RATE_LIMIT_REMAINING] calls in the current [WINDOW] window.
Budget remaining: [BUDGET_REMAINING] of [MAX_BUDGET].

--- EXAMPLES ---

Example 1: Batching opportunity
Task: Get user profiles for IDs [101, 102, 103] and their last order dates.
Tools: getUserProfile (cost: 1, supports batch: yes, max batch: 10), getLastOrderDate (cost: 2, supports batch: no)
Cache: empty
Rate limit: 10 calls remaining
Budget: 15

Plan:
1. Batch call getUserProfile with ids=[101,102,103] (cost: 1, 1 call)
2. Call getLastOrderDate for user 101 (cost: 2, 1 call)
3. Call getLastOrderDate for user 102 (cost: 2, 1 call)
4. Call getLastOrderDate for user 103 (cost: 2, 1 call)
Total cost: 7, Total calls: 4

Example 2: Cache hit
Task: Get user profile for ID 101 and their account balance.
Tools: getUserProfile (cost: 1, supports batch: no), getAccountBalance (cost: 3, supports batch: no)
Cache: userProfile:101 = {"name": "Alice", "tier": "premium"} (cached 2 minutes ago, TTL: 5 minutes)
Rate limit: 5 calls remaining
Budget: 10

Plan:
1. Use cached userProfile:101 (cost: 0, 0 calls)
2. Call getAccountBalance for user 101 (cost: 3, 1 call)
Total cost: 3, Total calls: 1

Example 3: Budget exceeded
Task: Generate reports for Q1, Q2, Q3, Q4 and run fraud scan.
Tools: generateReport (cost: 5, supports batch: no), runFraudScan (cost: 8, supports batch: no)
Cache: empty
Rate limit: 10 calls remaining
Budget: 20

Plan:
1. Call generateReport for Q1 (cost: 5, 1 call)
2. Call generateReport for Q2 (cost: 5, 1 call)
3. Call generateReport for Q3 (cost: 5, 1 call)
Total cost: 15, Total calls: 3
Dropped: generateReport for Q4 (cost: 5, would exceed budget), runFraudScan (cost: 8, would exceed budget)
Reason: Remaining budget after Q1-Q3 is 5, insufficient for Q4 (5) or fraud scan (8). Fraud scan is highest cost and dropped first per cost-ordering rule.

--- END EXAMPLES ---

Now produce your execution plan for the current task. Output a JSON object with this schema:
[OUTPUT_SCHEMA]

To adapt this template, start by replacing [TOOL_DEFINITIONS] with your actual function schemas, including the cost field and supports_batch boolean for each tool. Define [COST_MODEL] as a simple mapping or a reference to the cost fields in your tool definitions. The [CACHE_STATE] placeholder should be populated at runtime with the current keys, values, timestamps, and TTLs from your cache layer. Replace [RATE_LIMIT] and [WINDOW] with your actual API tier limits, and wire [RATE_LIMIT_REMAINING] to a real-time counter in your application. The [OUTPUT_SCHEMA] should be a strict JSON schema that includes fields for the ordered plan steps, total cost, total calls, and any dropped items with reasons. Validate every model output against this schema before executing any tool calls. If the plan's calculated cost exceeds [MAX_BUDGET] or the call count exceeds the rate limit, reject the plan and request a revision from the model with the specific constraint violation included in the error message.

The few-shot examples are the engine of this prompt. They teach batching, cache awareness, and budget-constrained ordering more reliably than instructions alone. When you modify the examples, preserve the pattern of showing the task, the available tools with costs, the cache state, the constraints, and then the step-by-step plan with cost and call counts. Include at least one example that demonstrates dropping calls when the budget is exceeded, and one that shows a cache hit avoiding a call entirely. If your production tools have different batching semantics or cost structures, replace the examples with ones that match your actual API. Test the prompt with the eval harness described in the testing section to catch regressions when you change the examples or tool definitions.

IMPLEMENTATION TABLE

Prompt Variables

Required and optional inputs for the Tool Call with Rate Limiting and Cost Awareness Prompt. Each placeholder must be populated before the prompt is assembled and sent to the model. Validation notes describe how to check that the input is well-formed before execution.

PlaceholderPurposeExampleValidation Notes

[AVAILABLE_TOOLS]

List of tool definitions with cost, latency, and rate limit metadata per tool.

{"tools": [{"name": "search_index", "cost_estimate": "$0.002/call", "rate_limit": {"remaining": 95, "window_seconds": 60}}]}

Schema check: each tool object must include name, cost_estimate, and rate_limit fields. Rate limit remaining must be a non-negative integer.

[USER_OBJECTIVE]

The user's stated goal or task that may require one or more tool calls.

"Find the latest Q3 earnings reports for our top 5 competitors and summarize the revenue trends."

Non-empty string. Check for ambiguous pronouns or unresolved references. If objective requires external data, confirm at least one available tool can satisfy it.

[BUDGET_CONSTRAINT]

Maximum allowable cost for the entire tool-call sequence, expressed in the same unit as tool cost estimates.

"$0.05"

Parse as float. Must be greater than zero. Compare against cheapest single-tool cost to ensure at least one call is possible. If null, default to unbounded with a warning.

[RATE_LIMIT_WINDOW_SECONDS]

The sliding window duration for rate limit accounting across all tools.

60

Parse as positive integer. Must match the window used in [AVAILABLE_TOOLS] rate_limit metadata. Mismatch causes incorrect remaining-call calculations.

[MAX_CONCURRENT_CALLS]

Upper bound on parallel tool calls the system can execute simultaneously.

3

Parse as positive integer. Must not exceed the execution environment's actual concurrency limit. If set higher than infrastructure supports, parallel calls will queue or fail.

[TOOL_CALL_HISTORY]

Record of prior tool calls in the current session, including arguments, results, cost incurred, and rate limit impact.

[{"tool": "search_index", "cost_incurred": "$0.002", "timestamp": "2025-01-15T10:23:01Z"}]

Schema check: each entry must include tool name, cost_incurred, and timestamp. Sum cost_incurred across history and compare against [BUDGET_CONSTRAINT] to compute remaining budget. Null allowed for first turn.

[OUTPUT_SCHEMA]

Expected structure for the model's tool-call plan output, including fields for tool name, arguments, dependency ordering, and cost justification.

{"plan": [{"step": 1, "tool": "search_index", "args": {"query": "Q3 earnings 2025"}, "depends_on": [], "estimated_cost": "$0.002"}]}

Schema check: plan must be an array. Each step requires step number, tool name matching [AVAILABLE_TOOLS], args object, depends_on array of step numbers, and estimated_cost. Circular dependencies must be rejected.

[FAILURE_MODE_EXAMPLES]

Few-shot examples of incorrect tool-call plans demonstrating common failures: budget overrun, rate limit exhaustion, unnecessary sequential calls, and missed batching opportunities.

[{"bad_plan": "...", "failure_type": "budget_overrun", "correction": "..."}]

Schema check: each example must include bad_plan, failure_type from allowed enum, and correction. At least one example per failure category (budget, rate limit, batching, dependency). Null allowed if using instruction-only approach.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the tool-call prompt into an application with validation, retries, and cost-aware execution logic.

The prompt template is the brain, but the harness is the skeleton. To make this work in production, you need a thin application layer that enforces the rate limits and budget the prompt reasons about. The prompt generates a plan; the harness validates it, executes it, and feeds back results. Start by defining a ToolBudget object in your application code that tracks remaining calls per tool, total cost incurred, and a hard ceiling. Before executing any tool call the model proposes, check it against this budget. If the model suggests a call that would exceed a limit, do not execute it. Instead, inject a system message like SYSTEM: Tool call to [TOOL_NAME] blocked. Rate limit exceeded. Remaining budget: [BUDGET_STATE]. and re-prompt the model for an alternative plan. This turns the prompt's cost-awareness from a suggestion into a hard constraint.

The execution loop should follow a strict sequence: Plan → Validate → Execute → Observe → Repeat. After receiving the model's output, parse the proposed tool calls. Validate each one against the current ToolBudget. For calls that pass validation, execute them and capture the full response, including latency and any error codes. Append the results to the message history as structured tool messages. If any call fails with a retryable error (e.g., 429 rate limit, transient server error), do not immediately retry. Instead, surface the error to the model in the next turn and let the prompt's few-shot error-handling examples decide whether to retry with backoff, switch tools, or escalate. This respects the prompt's own decision logic for error recovery. Implement a maximum loop count (e.g., 5 agent turns) to prevent infinite planning spirals, and log every budget check, tool execution, and model re-prompt for observability.

For evaluation, build a test harness that replays recorded tool response sequences against the prompt. Your eval suite should check three specific failure modes this prompt is designed to prevent: budget-exceeding sequences (the model proposes a plan that would exceed cost or rate limits if executed unchecked), missed batching opportunities (the model makes N individual calls when a single batched call was available and within limits), and unnecessary calls (the model calls a tool when the required data already exists in the conversation context). Each test case should provide a mock ToolBudget state and a set of available tool definitions. The eval passes if the harness blocks all budget violations and the model's final plan uses no more than the available budget while achieving the stated goal. Run these evals in CI before any prompt or tool definition change.

IMPLEMENTATION TABLE

Expected Output Contract

Concrete fields, types, and validation rules for the agent's structured response when deciding whether to batch, cache, or call tools under rate and cost constraints.

Field or ElementType or FormatRequiredValidation Rule

decision

string enum: [call, batch, cache, defer, escalate]

Must match one of the allowed enum values exactly. No other values permitted.

selected_tools

array of objects

Each object must contain tool_name (string) and arguments (object). Array must not be empty if decision is call or batch.

selected_tools[].tool_name

string

Must match a tool name present in the provided [TOOL_LIST]. Hallucinated tool names are a hard failure.

selected_tools[].arguments

object

Must conform to the JSON Schema for the specified tool. Required fields must be present. No invented parameter values.

cost_estimate

object

Must contain estimated_cost (number), currency (string), and tokens (integer). estimated_cost must be a non-negative float.

rate_limit_check

object

Must contain remaining_calls (integer), window_seconds (integer), and would_exceed (boolean). remaining_calls must be >= 0.

batching_rationale

string

Required when decision is batch. Must explain which calls were grouped and why they are independent. Null allowed otherwise.

cache_utilization

array of objects

Required when decision is cache. Each object must have cache_key (string) and ttl_seconds (integer). Null allowed otherwise.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when using few-shot examples to teach tool calling with rate limiting and cost awareness, and how to guard against it.

01

Example-Induced Over-Batching

What to watch: The model learns from examples to always batch calls, even when a single urgent call is required. It delays execution waiting for batchable companions that never arrive. Guardrail: Include negative examples showing when immediate execution is required despite batching opportunities. Validate that time-sensitive tool calls are not queued.

02

Cost Optimization Hallucination

What to watch: The model invents cheaper tool alternatives not present in the actual tool list, mimicking cost-aware reasoning from examples without grounding in available tools. Guardrail: Add a tool grounding check that rejects any tool name not in the active tool registry. Include examples where the model must use the only available tool despite higher cost.

03

Rate Limit Counter Drift

What to watch: Examples that show explicit rate limit tracking cause the model to hallucinate counter values in production, leading to premature throttling or ignoring actual limits. Guardrail: Never put dynamic rate limit state in the prompt. Use tool response headers to signal limits. Test that the model respects actual 429 responses rather than self-imposed limits.

04

Cache-Aware Example Staleness

What to watch: Examples demonstrating cache-hit patterns become stale when the underlying cache semantics change, causing the model to skip necessary calls or make redundant ones. Guardrail: Version your examples alongside your tool definitions. Run regression tests that detect when cached vs. live call patterns diverge from expected behavior.

05

Budget Exhaustion Without Escalation

What to watch: The model continues selecting tools after exhausting the budget shown in examples, or stops prematurely when budget remains. Guardrail: Include a hard stop example where budget exhaustion triggers a structured escalation response. Validate that the model never exceeds a configurable cost ceiling in test scenarios.

06

Tool Ordering Priority Inversion

What to watch: Examples teaching cost-optimized ordering cause the model to reorder dependent calls incorrectly, breaking data dependencies to save tokens. Guardrail: Include dependency-constrained ordering examples where cost optimization is overridden by data flow requirements. Test that output correctness is never sacrificed for cost savings.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test whether the prompt reliably produces cost-aware, rate-limit-compliant tool call sequences before shipping to production.

CriterionPass StandardFailure SignalTest Method

Batch Detection

Model groups independent tool calls into a single batch when rate limits are specified

Sequential calls for independent operations; no batching attempt when [RATE_LIMIT] context is present

Run 10 multi-tool scenarios with independent calls; verify output contains single batch instruction for >=90% of cases

Cache-Aware Tool Selection

Model selects cached or cheaper tool variant when [CACHE_AVAILABLE] is true and freshness constraints allow

Always selects live/expensive tool despite cache availability and acceptable staleness window

Provide 5 scenarios with cache option and freshness tolerance; check tool selection against cost-optimal path

Budget Adherence

Total estimated cost of planned tool calls stays within [MAX_BUDGET] constraint

Planned sequence exceeds budget; no cost estimate provided; budget ignored in tool ordering

Inject [MAX_BUDGET] values; parse cost estimates from output; assert sum <= budget for 10 varied requests

Rate Limit Compliance

Tool call sequence respects [MAX_CALLS_PER_MINUTE] and [MAX_CONCURRENT] constraints

Output schedules more concurrent calls than allowed or exceeds per-minute limit without staggering

Validate call count and concurrency against constraints in 8 scenarios with tight limits

Unnecessary Call Elimination

Model skips tool calls when information is already available in [CONTEXT] or prior results

Redundant calls to tools for data already present; no justification for re-fetching

Seed context with pre-fetched data; verify model omits redundant calls in 7 of 10 cases

Cost-Optimized Ordering

Model orders tool calls to minimize cost when dependencies allow, using cheaper tools first for filtering

Expensive calls placed before cheap filtering calls; no cost-aware ordering logic evident

Provide dependency graph with cost annotations; check call order minimizes expected cost for 6 scenarios

Budget Exhaustion Handling

Model stops calling tools and reports findings when remaining budget is insufficient for next planned call

Continues calling tools past budget exhaustion; fails to report budget status; silent overspend

Set [MAX_BUDGET] to force mid-sequence exhaustion; verify graceful stop and status report in 5 tests

Tool Call Justification

Each tool call includes a brief rationale referencing cost, necessity, or rate limit awareness

No rationale provided; rationale doesn't reference constraints; generic justifications only

Parse rationale field from output; check for constraint-aware language in >=80% of calls across 10 scenarios

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base few-shot examples but strip the cost-tracking fields and budget enforcement logic. Use 2-3 simple examples showing tool selection with a comment about rate limits rather than structured cost metadata. Replace the [COST_BUDGET] and [RATE_LIMIT_REMAINING] placeholders with hardcoded generous values. Focus on getting the tool selection and batching logic right before adding constraint enforcement.

Prompt snippet

code
## Examples

User: Find all open issues in repo alpha and beta
Assistant: I'll batch these into one API call. [Tool: search_issues, Args: {repos: ["alpha", "beta"], state: "open"}]

Watch for

  • Model ignoring rate limit hints entirely when they're not structured as constraints
  • Batching logic that works in examples but fails on novel tool combinations
  • No cost feedback loop, so the model can't learn from its own expensive calls
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.