This prompt is designed for FinOps engineers, AI platform teams, and prompt engineers who need to compare token consumption across multiple deployed prompt versions in production. The core job-to-be-done is cost attribution: you have traces from several prompt versions running concurrently (or in an A/B test), and you need a structured breakdown showing which versions consume the most tokens, where those tokens are spent (system prompt, user messages, tool calls, output generation), and a ranked list of versions by token efficiency. The ideal user has access to production trace data that includes prompt_version, token_counts (broken down by category), and cost_per_token metadata. Without this granular trace data, the prompt cannot produce a meaningful comparison.
Prompt
Token Consumption by Prompt Version Analysis Prompt

When to Use This Prompt
Define the job, reader, and constraints for the Token Consumption by Prompt Version Analysis Prompt.
Do not use this prompt when you only have a single prompt version deployed—this is a comparative analysis tool, not a single-version audit. It is also not a substitute for real-time cost monitoring dashboards; this prompt is for periodic, structured analysis of version-to-version efficiency. The prompt assumes that trace data is already collected and normalized. If your traces lack per-category token breakdowns (system, user, tool, output), you must first enrich your observability pipeline before this prompt can deliver value. For regulated environments where cost data feeds into financial reporting, always require human review of the output before it enters a formal cost allocation or chargeback process.
After running this analysis, the next step is typically to investigate the highest-cost versions using a deeper trace review prompt (such as the Token Waste Identification Prompt or the Cost Efficiency Score per Prompt Version Prompt Template) to identify specific inefficiencies. Avoid treating the ranked list as a definitive 'best version' score without also considering task success rates and latency—a version that uses fewer tokens but fails more often is not truly efficient. Always pair token efficiency findings with quality metrics before making a rollback or promotion decision.
Use Case Fit
Where the Token Consumption by Prompt Version Analysis Prompt delivers reliable value and where it introduces operational risk.
Good Fit: Multi-Version Cost Audits
Use when: you have production traces spanning multiple prompt versions and need to attribute token consumption and cost to each version. Guardrail: ensure trace data includes a reliable prompt_version or template_id field before running the analysis.
Good Fit: FinOps Chargeback Preparation
Use when: infrastructure or platform teams need to allocate model costs to specific product teams or features based on the prompt versions they own. Guardrail: pair the output with a cost-per-request baseline so that version-level totals can be normalized by traffic volume.
Bad Fit: Single-Version Debugging
Avoid when: you are investigating a token spike in a single prompt version without a comparison baseline. Guardrail: use a token waste identification or system prompt bloat detection prompt instead; this prompt requires at least two versions to produce a meaningful comparison.
Bad Fit: Real-Time Cost Enforcement
Avoid when: you need to block or throttle expensive requests in the hot path. Guardrail: this is an offline analysis prompt. Real-time enforcement requires a circuit breaker or rate limiter in the application layer, not a trace review prompt.
Required Inputs
What you need: production trace spans with prompt_version, token counts per segment (system, user, tool, output), and a cost-per-token mapping for each model endpoint. Guardrail: validate that token counts are extracted from API response metadata, not estimated client-side, to avoid undercounting.
Operational Risk: Version Labeling Gaps
Risk: traces missing version labels or using inconsistent naming conventions produce misleading rankings. Guardrail: run a pre-check query to confirm version label coverage exceeds 95% of the trace window before trusting the efficiency leaderboard.
Copy-Ready Prompt Template
A reusable prompt template for comparing token consumption and cost efficiency across deployed prompt versions.
This template is designed to be dropped directly into your observability or analysis pipeline. It expects structured trace data as input and produces a ranked breakdown of token usage by prompt version, including cost attribution and efficiency flags. Adapt the placeholders to match your internal schema, cost model, and reporting needs before use.
textYou are a FinOps analyst specializing in LLM infrastructure costs. Your task is to analyze production trace data and produce a token consumption report grouped by prompt version. ## INPUT DATA [TRACE_DATA] ## ANALYSIS PARAMETERS - Cost per 1K input tokens: [INPUT_TOKEN_COST] - Cost per 1K output tokens: [OUTPUT_TOKEN_COST] - Analysis period: [TIME_RANGE] - Minimum request count per version for inclusion: [MIN_REQUESTS] ## OUTPUT SCHEMA Return a JSON object with the following structure: { "report_metadata": { "analysis_period": "string", "total_requests_analyzed": "integer", "total_cost": "float", "cost_model": { "input_per_1k": "float", "output_per_1k": "float" } }, "version_breakdown": [ { "prompt_version": "string", "request_count": "integer", "avg_input_tokens": "float", "avg_output_tokens": "float", "avg_total_tokens": "float", "total_cost": "float", "cost_per_request": "float", "token_efficiency_rank": "integer", "anomalies": ["string"] } ], "efficiency_leaderboard": ["string"], "cost_anomalies": [ { "prompt_version": "string", "anomaly_type": "enum[cost_spike, token_bloat, low_efficiency]", "description": "string", "recommended_action": "string" } ] } ## CONSTRAINTS - Only include versions present in the input trace data. - Calculate costs using the provided per-1K token rates. - Flag any version where avg_total_tokens exceeds [TOKEN_BLOAT_THRESHOLD] as a token bloat anomaly. - Flag any version where cost_per_request exceeds [COST_SPIKE_THRESHOLD] as a cost spike anomaly. - Rank versions by token efficiency (lowest avg_total_tokens per successful request gets rank 1). - If a version has fewer than [MIN_REQUESTS] requests, exclude it from ranking but note it in a separate "low_volume_versions" array. - Do not invent data. If a field cannot be calculated, set it to null and add a note to the anomalies array. ## EXAMPLE OUTPUT { "report_metadata": { "analysis_period": "2025-03-01 to 2025-03-07", "total_requests_analyzed": 15420, "total_cost": 342.18, "cost_model": { "input_per_1k": 0.003, "output_per_1k": 0.015 } }, "version_breakdown": [ { "prompt_version": "v2.1.0", "request_count": 8200, "avg_input_tokens": 1250.5, "avg_output_tokens": 340.2, "avg_total_tokens": 1590.7, "total_cost": 187.45, "cost_per_request": 0.0229, "token_efficiency_rank": 1, "anomalies": [] } ], "efficiency_leaderboard": ["v2.1.0", "v2.0.1", "v1.9.3"], "cost_anomalies": [] } ## INSTRUCTIONS 1. Parse the input trace data and group requests by prompt_version. 2. For each version, calculate the average input, output, and total tokens. 3. Apply the cost model to compute total and per-request costs. 4. Check each version against the anomaly thresholds. 5. Build the efficiency leaderboard sorted by avg_total_tokens ascending. 6. Return only the JSON object. No additional commentary.
To adapt this template, replace the cost parameters with your actual model pricing and adjust the anomaly thresholds to match your budget alerts. The output schema is designed for direct ingestion into a dashboard or cost allocation system. If your trace data uses different field names, add a mapping section or preprocess the data before passing it to this prompt. For high-stakes financial reporting, always route the output through a human review step before committing to chargeback or budget decisions.
Prompt Variables
Required inputs for the Token Consumption by Prompt Version Analysis Prompt. Each placeholder must be populated from production trace data or observability platform exports before execution.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TRACE_DATA] | Raw trace spans containing token counts, model endpoints, prompt version tags, and step-level metadata | JSON array of OpenTelemetry-compatible spans with llm.usage.prompt_tokens and llm.usage.completion_tokens attributes | Must be valid JSON array with at least 2 prompt versions represented. Reject if token fields are null or missing across all spans. |
[PROMPT_VERSION_FIELD] | The trace attribute key that identifies which prompt version produced each span | prompt.version or resource.prompt_version | Must resolve to a non-empty string for every span. Reject spans where this field is missing or null. Validate against known version registry if available. |
[COST_PER_TOKEN_MODEL_MAP] | Mapping of model endpoint identifiers to per-token pricing for input and output tokens | {"gpt-4o": {"input": 0.000005, "output": 0.000015}, "claude-3-opus": {"input": 0.000015, "output": 0.000075}} | Must include all model endpoints present in trace data. Prices must be positive floats. Reject if any trace model lacks a pricing entry. |
[TOKEN_TYPE_BREAKDOWN] | Trace attribute names for system, user, tool, and output token sub-counts if available | ["llm.usage.system_tokens", "llm.usage.user_tokens", "llm.usage.tool_tokens", "llm.usage.completion_tokens"] | Optional. If provided, must be an array of valid attribute keys. Null allowed if trace data does not include sub-counts; prompt will use total token fields only. |
[ANALYSIS_WINDOW_START] | ISO 8601 timestamp for the start of the trace analysis window | 2025-01-15T00:00:00Z | Must be a valid ISO 8601 datetime string. Must be earlier than [ANALYSIS_WINDOW_END]. Reject if traces contain no spans within this window. |
[ANALYSIS_WINDOW_END] | ISO 8601 timestamp for the end of the trace analysis window | 2025-01-22T23:59:59Z | Must be a valid ISO 8601 datetime string. Must be later than [ANALYSIS_WINDOW_START]. Reject if window exceeds 90 days without explicit approval. |
[OUTPUT_SCHEMA] | Expected structure for the per-version breakdown and ranked efficiency list | JSON schema with required fields: version_id, total_tokens, system_tokens, user_tokens, tool_tokens, output_tokens, estimated_cost, requests_count, avg_tokens_per_request, efficiency_rank | Must be a valid JSON Schema object. Reject if required fields are missing from schema definition. Validate output against this schema before returning to caller. |
[COST_CURRENCY] | Currency code for cost attribution output | USD | Must be a valid ISO 4217 currency code. Default to USD if null. Reject if currency code is not recognized. |
Implementation Harness Notes
How to wire the Token Consumption by Prompt Version Analysis Prompt into an observability pipeline for automated cost governance.
This prompt is designed to be integrated into a batch trace analysis job, not a real-time user-facing endpoint. It expects a structured trace payload containing per-step token counts, model identifiers, and prompt version tags. The ideal execution environment is a scheduled workflow (e.g., a nightly FinOps aggregation job) that queries your observability backend (such as LangSmith, Arize, or a custom trace store), extracts the relevant spans, and feeds them into the prompt for comparative analysis.
Input Assembly: Before calling the model, you must flatten raw trace data into the [TRACE_BATCH] placeholder. This JSON array should contain one object per trace, with fields: trace_id, prompt_version, model, system_tokens, user_tokens, tool_tokens, output_tokens, and cost. To avoid token limit errors, implement a pre-filtering step that limits the batch to a specific time window or a maximum of 200 traces. If the dataset is larger, shard it and run the analysis in parallel, then use a secondary prompt to merge the results. Validation: Before passing the payload, validate that all required numeric fields are present and non-negative. A malformed trace object will cause the model to hallucinate cost figures or skip the version entirely.
Model Choice and Tool Use: Use a model with strong JSON reasoning and long-context capabilities (e.g., gpt-4o or claude-3.5-sonnet). Do not provide external tools for this analysis; the model should perform the ranking and breakdown internally. However, you should post-process the output with a deterministic script. Parse the model's JSON output, recalculate the total_tokens and total_cost from the raw input data, and cross-validate these against the model's summary. If a discrepancy is found, log a warning and fall back to the deterministic calculation for the final report, using the model's output only for the qualitative efficiency notes and ranking rationale.
Logging and Human Review: Log the full prompt, the raw model response, and the post-processed output to your prompt management system. This is critical for debugging version-tagging errors. If the analysis identifies a version with a cost spike exceeding a defined threshold (e.g., 20% increase over the baseline), route the report to a human FinOps reviewer via a ticketing system before automatically flagging the version for deprecation. This human-in-the-loop step prevents automated systems from blocking a production prompt version due to a transient traffic spike or a data logging error.
Expected Output Contract
Defines the shape, types, and validation rules for the output generated by the Token Consumption by Prompt Version Analysis Prompt. Use this contract to parse, validate, and integrate the model's response into downstream FinOps dashboards or alerting systems.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
analysis_summary.total_versions_analyzed | integer | Must be >= 1. Parse check: ensure value is a non-negative integer. | |
analysis_summary.observation_window | object | Must contain 'start_date' and 'end_date' in ISO 8601 format. Schema check: validate date string parseability. | |
version_breakdown[].version_id | string | Must match a prompt version identifier from the input trace data. Null not allowed. | |
version_breakdown[].token_usage.system_prompt_tokens | integer | Must be >= 0. Parse check: ensure numeric type. If system prompt is absent, value must be 0. | |
version_breakdown[].token_usage.user_input_tokens | integer | Must be >= 0. Parse check: ensure numeric type. | |
version_breakdown[].token_usage.tool_call_tokens | integer | Must be >= 0. Includes tokens for tool definitions and arguments. Null not allowed. | |
version_breakdown[].token_usage.output_tokens | integer | Must be >= 0. Parse check: ensure numeric type. | |
version_breakdown[].cost_attribution.total_cost_usd | number | Must be a positive float. Validation: total_cost_usd must equal the sum of per-category costs within a 0.01 tolerance. | |
efficiency_ranking[].rank | integer | Must be a unique sequential integer starting from 1. No gaps or duplicates allowed. | |
efficiency_ranking[].version_id | string | Must correspond to an entry in version_breakdown. Cross-reference check required. | |
efficiency_ranking[].composite_efficiency_score | number | Must be a float between 0.0 and 1.0. Confidence threshold: flag for human review if score is null or outside bounds. |
Common Failure Modes
Token consumption analysis across prompt versions fails in predictable ways. These cards cover the most common failure modes when comparing token usage, attributing costs, and ranking versions by efficiency.
Version-to-Version Token Inflation Goes Undetected
What to watch: Prompt versions accumulate instructions, examples, and tool definitions over time without anyone noticing the per-request token creep. A version that adds 200 tokens of system prompt may look identical in output quality but costs 15% more at scale. Guardrail: Set a token budget per prompt version and flag any version exceeding the baseline by more than 10% in automated trace comparison. Run the analysis weekly, not just at release time.
Tool Definition Tokens Are Misattributed to the Wrong Step
What to watch: Many tracing systems lump tool schema tokens into the model request total without separating them from system prompt or user input tokens. This makes it impossible to know whether tool definitions or conversation context is driving cost increases. Guardrail: Require trace spans to break out tool_definitions_tokens as a separate field. If your observability tool doesn't support this, add a pre-processing step that calculates tool schema token counts before the request is logged.
Output Token Variance Masks Real Efficiency Differences
What to watch: Two prompt versions may show different total token counts purely because one version produces longer outputs, not because it's less efficient. Ranking versions by total tokens without normalizing for output length produces misleading efficiency scores. Guardrail: Normalize token efficiency as input_tokens / successful_completion or compare input-side tokens separately from output tokens. Always report output token length alongside efficiency rankings so reviewers can distinguish verbose outputs from wasteful prompts.
Cost Attribution Breaks Across Multi-Model Pipelines
What to watch: When a single prompt version routes to different models (e.g., GPT-4 for complex tasks, GPT-3.5 for simple ones), per-version cost averages hide the real distribution. A version may appear expensive because it handled more complex requests, not because the prompt itself is inefficient. Guardrail: Segment cost analysis by model endpoint within each prompt version. Report per-model token counts and costs separately before computing version-level aggregates. Flag versions where the model routing distribution differs significantly from the baseline.
Retry and Self-Correction Tokens Inflate Version Costs
What to watch: A prompt version that triggers more retries or self-correction loops will show higher token consumption in aggregate, but the root cause may be output validation failures rather than prompt inefficiency. Blaming the prompt for retry overhead leads to wrong optimization targets. Guardrail: Separate first-attempt token consumption from retry and correction tokens in trace analysis. Report retry rate alongside token efficiency so teams can distinguish prompt bloat from reliability problems. A version with low first-attempt tokens but high retry overhead needs validation fixes, not prompt trimming.
Context Window Expansion Masks Per-Request Efficiency Gains
What to watch: When retrieval chunk counts or conversation history limits increase, per-request token counts rise even if the prompt itself became more efficient. Comparing versions without controlling for context window size produces false regressions. Guardrail: Normalize token comparisons by context window utilization percentage rather than raw token counts. Report both prompt_template_tokens (fixed overhead) and context_window_tokens (variable input) separately. Flag versions where the fixed overhead changed independently of context size.
Evaluation Rubric
Criteria for testing the Token Consumption by Prompt Version Analysis Prompt before deploying it as an automated trace review step. Each row defines a pass standard, a failure signal, and a concrete test method.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Schema compliance | Output is valid JSON matching the [OUTPUT_SCHEMA] exactly | JSON parse error, missing required fields, or extra fields not in schema | Validate output against the JSON Schema definition; reject on any schema violation |
Version completeness | Every [PROMPT_VERSION_ID] in the input trace batch appears in the output breakdown | A version present in the input is missing from the per-version breakdown array | Extract unique version IDs from input traces and assert set equality with output version IDs |
Token sum accuracy | Sum of per-version token counts equals the total token count reported in the summary | Mismatch between summed per-version tokens and the total_tokens field by more than 1% | Compute sum of all per-version token fields and compare against output total_tokens; flag if delta > 1% |
Cost attribution correctness | Per-version cost = token count × correct model rate from [MODEL_PRICING_TABLE] | Cost for a version does not match the expected calculation using the provided pricing table | Recompute cost for each version using token counts and the pricing table; assert exact match to 4 decimal places |
Ranking order validity | Versions are ranked by token_efficiency_score in descending order with no ties broken arbitrarily | Ranking is not monotonic by score, or two versions with different scores share the same rank | Verify efficiency_score values decrease monotonically with rank position; assert unique ranks for unique scores |
Token category breakdown | Each version includes system_tokens, user_tokens, tool_tokens, and output_tokens as non-negative integers | Any token category field is missing, negative, or null | Assert all four category fields exist per version, are integers, and are >= 0 |
Cost spike flagging | Versions exceeding [COST_THRESHOLD] per request are flagged with cost_anomaly: true and a reason string | A version above threshold is not flagged, or a version below threshold is incorrectly flagged | For each version, compare per_request_cost against [COST_THRESHOLD]; assert flag correctness and reason presence |
Empty input handling | When [INPUT_TRACES] is an empty array, output returns an empty per_version_breakdown and zero totals | Empty input causes a parse error, hallucinated versions, or non-zero totals | Submit an empty trace array; assert per_version_breakdown is [] and all total fields are 0 |
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 strict JSON schema validation, retry logic, and structured logging. Include cost attribution with configurable per-model pricing. Add an eval harness that checks field presence, numeric ranges, and version ordering.
codeAnalyze [TRACE_DATA] and produce a JSON report matching [OUTPUT_SCHEMA]. Use [MODEL_PRICING] for cost calculations. Flag any version missing from the trace metadata. If validation fails, retry once with the error message included.
Watch for
- Silent format drift when model outputs valid JSON with wrong field names
- Missing human review gate before cost data feeds into billing systems
- Pricing table staleness causing incorrect cost attribution over time

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