Inferensys

Prompt

Tool-Call Cost Attribution Prompt per Tool

A practical prompt playbook for using Tool-Call Cost Attribution Prompt per Tool in production AI workflows.
Developer demonstrating multi-agent tool use, agent tool selection interface on laptop, casual tech demo moment.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job-to-be-done, the ideal user, and the boundaries for the Tool-Call Cost Attribution Prompt per Tool.

This prompt is designed for FinOps engineers and platform teams who need to move beyond aggregate cost monitoring and understand exactly which tools are driving inference spend within a production agent trace. The core job-to-be-done is post-hoc cost attribution: taking a raw trace containing multiple tool calls, their descriptions, arguments, and outputs, and producing a per-tool cost breakdown. This breakdown must separate token consumption into tool description tokens (the schema overhead), argument tokens (the input), and output tokens, then assign a cost based on the model's pricing tier. The output is a structured report that ranks tools by cost, identifies the most expensive calls, and highlights optimization targets such as tools with oversized descriptions or verbose outputs. The ideal user is someone who already has access to production trace data and needs to make budget planning, tool rationalization, or context-window optimization decisions based on real usage patterns rather than assumptions.

Use this prompt when you have exported a single agent trace or a batch of traces from your observability platform and need a detailed cost attribution before making engineering decisions. The prompt expects a structured [TRACE_INPUT] containing the model identifier, per-token pricing, and a list of tool calls with their full schemas, arguments, and outputs. It is not designed for real-time cost estimation during a live request; that requires a lightweight token-counting function in your application code, not an LLM call. This prompt is also not a replacement for aggregate cost dashboards—it is a diagnostic tool for deep-diving into specific traces to find optimization opportunities. Do not use this prompt when you need sub-millisecond latency or when the trace contains sensitive data that should not be sent to an external model; in those cases, pre-process the trace to redact sensitive fields or use a local model. The prompt assumes you have already resolved the model's per-token pricing (input and output) and included it in the input context; it will not fetch or guess pricing tiers.

Before running this prompt, ensure your trace data includes the full tool call payload: the tool's name, its JSON Schema description (the part that consumes description tokens), the arguments passed, and the complete tool output. Missing any of these components will produce an incomplete or misleading cost report. After receiving the output, validate that the token counts are plausible by spot-checking against a known tokenizer for your model. The report should be treated as a starting point for optimization conversations—pair it with latency data and error rates to prioritize which tools to refactor, simplify, or replace. If the report identifies a tool whose description tokens exceed its argument and output tokens combined, that tool's schema is likely too verbose and should be trimmed before the next deployment.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Use these cards to decide if the Tool-Call Cost Attribution Prompt per Tool fits your current trace analysis workflow.

01

Good Fit: Post-Run Cost Diagnostics

Use when: you have a completed trace with tool-call spans and need to attribute token and latency costs to individual tools for optimization targeting. Guardrail: ensure traces include per-span token counts and timing metadata before running attribution.

02

Bad Fit: Real-Time Budget Enforcement

Avoid when: you need to halt execution mid-trace based on cost thresholds. This prompt analyzes completed traces, not live streams. Guardrail: pair with a circuit breaker or token limiter in the agent harness for runtime enforcement.

03

Required Inputs: Tokenized Trace Spans

What to watch: the prompt requires per-tool-call token counts (description tokens, argument tokens, output tokens) and latency measurements. Guardrail: validate that your tracing system captures these fields before invoking the prompt; otherwise, output will be incomplete or hallucinated.

04

Operational Risk: Missing Tool Description Tokens

What to watch: many tracing systems omit the token cost of tool descriptions sent in the system prompt. Guardrail: pre-process traces to estimate or inject tool description token counts, or flag tools where this data is absent in the final report.

05

Operational Risk: Cost Model Drift

What to watch: per-token pricing changes across model versions or providers can invalidate cached cost reports. Guardrail: always include the model ID and pricing date in the attribution report, and re-run attribution when pricing changes.

06

Variant: Aggregated vs. Per-Session Attribution

Use when: you need to decide between per-session tool-cost breakdowns or cross-session aggregation. Guardrail: run per-session attribution for debugging specific traces; run aggregated attribution for monthly FinOps reporting and tool deprecation decisions.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt that attributes token and latency costs to each tool call in an agent trace and returns a structured JSON cost report.

This prompt template is designed for FinOps engineers and platform developers who need to attribute costs to individual tool calls within a production agent trace. It takes a raw trace, a pricing table, and an output schema, and returns a per-tool cost breakdown. Use this when you need to identify which tools are driving your inference spend, so you can target optimization efforts at the most expensive calls.

code
You are a cost attribution analyst for an AI platform. Your task is to analyze the provided agent trace and attribute token and latency costs to each tool call.

[TRACE]
[PRICING]

Instructions:
1. Parse the trace to identify every distinct tool call. A tool call includes the tool description tokens sent to the model, the argument tokens, and the output tokens returned by the tool.
2. For each tool call, calculate the token count for:
   - `tool_description_tokens`: Tokens used to describe the tool's schema and purpose in the system prompt or function manifest.
   - `argument_tokens`: Tokens in the arguments the model generated for the call.
   - `output_tokens`: Tokens in the tool's response that were fed back into the model's context.
3. Using the provided [PRICING] table, calculate the cost for each token category based on the model used for that step.
4. Sum the costs to get a `total_cost` for each tool call.
5. Calculate the `latency_ms` for each tool call from the trace timestamps.
6. Return the results as a single JSON object matching the [OUTPUT_SCHEMA].

[OUTPUT_SCHEMA]
{
  "trace_id": "string",
  "total_trace_cost": "number",
  "total_trace_latency_ms": "number",
  "tool_calls": [
    {
      "tool_name": "string",
      "call_index": "integer",
      "tool_description_tokens": "integer",
      "argument_tokens": "integer",
      "output_tokens": "integer",
      "total_tokens": "integer",
      "cost": "number",
      "latency_ms": "number"
    }
  ]
}

[CONSTRAINTS]
- Do not estimate or interpolate costs. Use only the provided [PRICING] table.
- If a token count cannot be determined from the trace, set the field to null and add a `warnings` array to the output object explaining the gap.
- Round all costs to 6 decimal places.
- If the trace contains no tool calls, return an empty `tool_calls` array with `total_trace_cost` and `total_trace_latency_ms` set to 0.

To adapt this template, replace the [TRACE] placeholder with your raw agent trace data, typically a JSON object containing model requests, tool call events, and timestamps. The [PRICING] placeholder should be a table mapping model names to per-token costs. If your trace format differs, adjust the parsing instructions in step 1. For high-stakes financial reporting, always validate the output against a known trace with pre-calculated costs before trusting the prompt in an automated pipeline.

IMPLEMENTATION TABLE

Prompt Variables

Inputs required for the Tool-Call Cost Attribution Prompt per Tool. Provide these variables to produce a per-tool cost breakdown from a production trace.

PlaceholderPurposeExampleValidation Notes

[TRACE_JSON]

Full trace object containing tool-call events with token usage, latency, and model metadata

{"trace_id": "abc123", "events": [{"type": "tool_call", "tool_name": "search", "input_tokens": 150, "output_tokens": 80, "latency_ms": 320}]}

Must be valid JSON. Parse check required. Reject if events array is missing or empty.

[TOOL_MANIFEST]

Tool definitions including name, description, and parameter schemas for calculating description token overhead

{"tools": [{"name": "search", "description": "Search the knowledge base", "parameters": {...}}]}

Must include description field for each tool. Schema validation required. Null allowed if description tokens are not needed.

[MODEL_PRICING]

Per-token pricing configuration for the model used in the trace

{"model": "gpt-4o", "input_cost_per_1k": 0.005, "output_cost_per_1k": 0.015}

Must include input_cost_per_1k and output_cost_per_1k as positive floats. Schema check required.

[COST_CURRENCY]

Currency code for cost reporting

USD

Must be a valid ISO 4217 currency code. Default to USD if null.

[LATENCY_UNIT]

Unit for latency measurements in the output report

milliseconds

Must be one of: milliseconds, seconds. Default to milliseconds if null.

[INCLUDE_DESCRIPTION_TOKENS]

Boolean flag to include tool description tokens in cost attribution

Must be true or false. Default to false if null. Affects whether manifest descriptions are tokenized and costed.

[GROUP_BY]

Aggregation key for cost grouping

tool_name

Must be one of: tool_name, trace_id, session_id. Default to tool_name if null.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Tool-Call Cost Attribution Prompt into a production observability pipeline for automated cost analysis.

This prompt is designed to operate on a single, pre-processed trace object. The primary integration point is a post-processing step within your observability pipeline, triggered after a trace is completed and exported. The application harness is responsible for extracting the relevant trace segment, formatting it into the [TRACE_JSON] input, and injecting the [TOOL_MANIFEST] and [PRICING_CONFIG] before calling the model. Do not send raw, full-trace blobs; pre-filter to include only the tool_calls array, their arguments, outputs, and associated usage metadata to keep the prompt focused and token-efficient.

The harness must enforce a strict validation contract on the model's output. Parse the generated JSON report and validate that every tool_name in the cost_breakdown array exists in the provided [TOOL_MANIFEST]. Reject any report that attributes cost to hallucinated or non-existent tools. Implement a retry loop with a maximum of two attempts: if validation fails, append the validation error to the prompt context and re-request the report. Log all validation failures and retries as a cost_attribution_error metric. For high-stakes FinOps workflows, route reports with a total_cost variance greater than 5% from the trace's own recorded cost to a human review queue before ingestion into your billing system.

Model choice matters here. Use a model with strong JSON mode and long-context handling, such as gpt-4o or claude-3-opus, because the prompt requires precise arithmetic across many tokens and strict schema adherence. Cache the [TOOL_MANIFEST] and [PRICING_CONFIG] as a reusable system prefix to reduce per-request latency and cost. Finally, store the validated cost report as a structured log event keyed by trace_id, enabling downstream aggregation into per-tool cost dashboards. Avoid running this prompt on every trace in real-time; sample high-cost or anomalous traces first to control inference spend.

IMPLEMENTATION TABLE

Expected Output Contract

Validation rules for the per-tool cost attribution JSON output. Use this contract to parse, validate, and store cost reports before feeding them into dashboards or optimization workflows.

Field or ElementType or FormatRequiredValidation Rule

trace_id

string (UUID)

Must match the input trace identifier exactly. Reject if missing or mismatched.

analysis_timestamp

ISO 8601 UTC string

Must parse as a valid datetime. Reject if in the future or unparseable.

total_cost_estimate

object

Must contain input_tokens, output_tokens, total_tokens, and latency_ms fields. All values must be non-negative numbers.

tool_costs

array of objects

Must contain at least one entry if tool calls exist in the trace. Reject if empty when tool_calls_present is true.

tool_costs[].tool_name

string

Must match a tool name from the agent's tool manifest. Reject unknown tool names.

tool_costs[].call_count

integer >= 0

Must equal the count of invocations for this tool in the trace. Reject on mismatch.

tool_costs[].description_tokens

integer >= 0

Must not exceed the total input tokens for the trace. Flag if zero when tool has a non-empty description.

tool_costs[].argument_tokens

integer >= 0

Sum across all tools must not exceed total input tokens. Reject if negative.

tool_costs[].output_tokens

integer >= 0

Sum across all tools must not exceed total output tokens. Reject if negative.

tool_costs[].latency_ms

integer >= 0

Sum across all tools must not exceed total latency. Flag if a single tool exceeds 80% of total latency without annotation.

tool_costs[].cost_attribution

object

Must contain currency (ISO 4217 code) and amount (decimal string). Reject if currency is missing or amount is unparseable.

tool_costs[].optimization_target

boolean

Must be true if this tool ranks in the top 3 by cost or latency. Flag if a high-cost tool is not marked.

warnings

array of strings

If present, each entry must be a non-empty string. Null allowed. Flag if warnings array contains duplicate messages.

tool_calls_present

boolean

Must be true if the trace contains any tool-call events. Reject if false when tool_costs array is non-empty.

PRACTICAL GUARDRAILS

Common Failure Modes

Token and latency cost attribution breaks when traces are incomplete, tool boundaries are fuzzy, or attribution logic double-counts shared overhead. These failure modes help FinOps engineers trust the per-tool report before acting on it.

01

Shared Prefix Overhead Misattribution

What to watch: System prompts, tool definitions, and shared context are tokenized once but influence every tool call. Naive attribution assigns the full system prompt cost to the first tool call, inflating its cost and hiding the true per-tool distribution. Guardrail: Amortize shared prefix tokens across all tool calls proportionally by their individual prompt token consumption, and flag reports where the first tool call exceeds 40% of total cost.

02

Truncated or Missing Tool Output Tokens

What to watch: When a tool response exceeds the model's context window or is truncated by a proxy, the trace may show zero or partial output tokens. The attribution report silently undercounts the tool's cost, making expensive tools appear cheap. Guardrail: Validate that every tool call in the trace has a non-zero output_tokens field and a complete finish_reason. Flag any tool with missing output tokens for manual cost estimation.

03

Tool Description Token Bloat Masking Real Cost

What to watch: Large tool schemas with verbose descriptions consume significant context-window tokens before any call occurs. The cost report may show high per-tool costs that are actually description overhead, not usage cost. Guardrail: Separate tool description tokens from argument and output tokens in the attribution breakdown. Add a schema_overhead_ratio field per tool so engineers can target bloated descriptions for optimization.

04

Retry Loop Cost Amplification

What to watch: A single logical tool call that retries three times due to transient errors appears as three independent calls in the trace. The per-tool report inflates the tool's apparent cost and hides the retry multiplier. Guardrail: Group retries by tool_name and trace_id within a configurable time window. Report both raw call count and deduplicated logical call count, with a retry_cost_multiplier field.

05

Streaming and Partial Response Token Gaps

What to watch: Streaming tool outputs or incremental responses may not capture final token counts accurately in the trace, especially if the connection drops mid-stream. The attribution report uses incomplete data and under-reports cost. Guardrail: Cross-reference trace token counts with provider billing records where available. Flag any tool call where the trace token count differs from the billing record by more than 5%.

06

Cross-Tool Contamination from Shared Context Updates

What to watch: When one tool's output updates the shared context, subsequent tool calls benefit from that context without incurring the token cost. The attribution report credits the later tool for work done by the earlier tool's output. Guardrail: Track context-window state changes across the trace and attribute a portion of downstream tool output tokens back to the tool that provided the context. Include a context_contribution_credit field in the report.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of a per-tool cost attribution report before integrating it into a FinOps dashboard or automated optimization pipeline. Each criterion targets a specific failure mode common in cost breakdown prompts.

CriterionPass StandardFailure SignalTest Method

Token Attribution Completeness

Sum of all per-tool input, output, and description tokens equals the total trace tokens within a 1% margin.

Token sum mismatch > 1% or a tool call present in the trace is missing from the cost report.

Parse the report and trace metadata. Sum all token counts per tool and compare against the trace-level total token count.

Cost Calculation Accuracy

Per-tool cost matches the formula: (input_tokens * input_price) + (output_tokens * output_price) using the provided [MODEL_PRICING_TABLE].

Calculated cost deviates from the reported cost by more than $0.0001 for any tool.

Recompute cost for each tool row using the pricing table and compare to the value in the 'cost' field.

Tool Identification Integrity

Every tool name in the report exactly matches a tool name defined in the [TOOL_MANIFEST] or trace log.

A hallucinated or misspelled tool name appears in the report that does not exist in the source trace.

Extract all unique tool names from the report and validate membership against the set of tool names in the provided trace.

Argument Token Isolation

The 'argument_tokens' field for each tool call is a non-negative integer and is less than or equal to the tool's total 'input_tokens'.

Argument tokens are negative, null, or exceed the total input tokens for that tool call.

Schema-check each row: argument_tokens >= 0 and argument_tokens <= input_tokens. Flag any violations.

Output Schema Compliance

The report is valid JSON that strictly conforms to the [OUTPUT_SCHEMA] with all required fields present.

JSON parsing fails, a required field like 'total_cost' is missing, or a field has an incorrect type (e.g., string instead of number).

Validate the entire output against the JSON Schema. A single schema violation is a failure.

Cost Ranking Order

Tools in the report are sorted in descending order by 'total_cost'.

The report is not sorted by cost, making it difficult to quickly identify the most expensive tool.

Extract the 'total_cost' values in order and assert that each value is <= the previous one.

Unattributed Cost Handling

The 'unattributed_cost' field accounts for token overhead not assigned to any specific tool call (e.g., system prompt tokens).

The 'unattributed_cost' field is missing or is 0 when the sum of per-tool tokens is less than the total trace tokens.

Calculate unattributed_tokens = total_trace_tokens - sum(per_tool_tokens). Assert unattributed_cost > 0 if unattributed_tokens > 0.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add strict JSON output schema, per-field validation rules, and trace ID anchoring. Include a cost model configuration block so the prompt can apply your actual pricing tiers. Wire the output into a cost aggregation pipeline.

code
You are a FinOps cost attribution analyzer. Given a production trace, break down token and latency costs per tool call using the provided cost model.

Cost Model:
- input_token_cost_usd: [MODEL_INPUT_COST_PER_1K]
- output_token_cost_usd: [MODEL_OUTPUT_COST_PER_1K]
- tool_description_token_cost_usd: [SAME_AS_INPUT_OR_CUSTOM]

Trace: [TRACE_JSON]

Output JSON schema:
{
  "trace_id": "string",
  "total_cost_usd": "number",
  "tool_calls": [
    {
      "tool_name": "string",
      "call_index": "number",
      "description_tokens": "number",
      "argument_tokens": "number",
      "output_tokens": "number",
      "latency_ms": "number",
      "cost_usd": "number"
    }
  ]
}

Watch for

  • Silent format drift when the model omits optional fields like description_tokens
  • Missing human review for cost reports that drive budget decisions
  • Trace fields that are null or zero in your observability platform—validate before prompting
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.