Wasted tokens are model inputs or outputs that add avoidable cost without improving the result. An agent trace shows where to investigate: our expense-review demo produced a failed $0.12 run with 32 LLM calls. It wrote 2,476 tokens to cache on each of eight main-loop calls without a cache read and asked Claude Opus 5 the same three classification questions eight times each.
These are candidates for investigation, not proof that every token was avoidable. We'll inspect the spans, query recurring patterns, and compare cost per successful run. For pricing and attribution, see AI token cost.
Drawn from measured demo run 5a479103: eight main-loop calls and three classifier input groups repeated eight times each; $0.12, no submitted review.
A demo with deliberately planted waste
The measurements come from an expense-review agent we ran against a local Laminar instance. A Claude Sonnet 5 loop reviews reports against a 2,476-token policy, with four tools: get_receipts, convert_currency, flag_line_item, and submit_review. Its step budget is eight. Laminar's Anthropic integration records the model calls.
- v1 changes a timestamp at the start of the system prompt, reclassifies every receipt on every step, and uses Claude Opus 5.
- v2 keeps the system prefix byte-stable with cache breakpoints, moves the timestamp into the user message, and classifies each receipt once with Claude Haiku 4.5.
Both versions encounter injected tool faults: a currency-service 503 on the first conversion attempt, and a permanent lock on report R-104 that prevents submission. We ran each version 12 times over the same four reports. This small, planted-waste demo establishes a workflow, not a general savings rate.
Start with an expensive run
The dashboard's Expensive traces preset ranks runs by cost; Expensive spans ranks individual calls. Open a row to inspect its trace. The Trace p90 cost preset tracks the expensive tail over time (dashboards).
Our three costliest traces were v1 runs of R-104 at $0.1131 to $0.1200, with roughly 33,000 to 34,000 input tokens and no cache reads. The cheapest v1 run cost $0.0443. Rank by cost, since input, output, and cached tokens have different rates. For a custom ranking, order traces by total_cost and include your cohort metadata.
Switch to Tree view. LLM spans show duration, input and output tokens, and cost; parent spans show child totals. The Cost heatmap tints spans relative to the most expensive span in that trace. Its colors do not compare absolute cost across traces.

The measured v1 run ended with RuntimeError: step budget exhausted after 8 steps without a submitted review.
The main-loop steps cost $0.0069 to $0.0179 as input grows from 2,559 to 5,442 tokens. Three classifier calls recur before every step, with input counts of 77, 76, and 69. The currency conversion fails and is requested again. Opening a Sonnet input reveals Current time: 2026-11-24T11:31:25.603909+00:00 at the beginning.
Find wasted tokens in an agent trace
Each shape below needs a second check before you change the agent.
| Pattern | Trace shape | Confirm before fixing |
|---|---|---|
| Growing history | Inputs increase each step | Context remains useful; caching applies |
| Repeated calls | Matching inputs within a run | One answer could replace repeated work |
| Tool retries | Error followed by another attempt | Error is recoverable or terminal |
| Cache misses | Writes without reads | Cold cache, expiry, eligibility, and prefix changes |
| Costly model | Small step on an expensive model | Cheaper model passes an evaluation |
| Failed run | Spend without task completion | Identify when further work became futile |
Run the queries in the SQL editor or through the SQL API. Keep a start_time filter: the tables are ordered by time. These queries use a one-day window; narrow the cohort when your project contains unrelated agents.
Input grows on each step
An agent loop sends accumulated replies and tool results again. Laminar's input_tokens includes cached input, so growth alone does not establish waste. Filter by the main-loop span path to keep helper calls out of the sequence:
SELECT
row_number() OVER (ORDER BY start_time) AS step,
input_tokens,
input_tokens - lagInFrame(input_tokens) OVER (ORDER BY start_time) AS added,
cache_read_input_tokens AS cache_read,
cache_creation_input_tokens AS cache_write,
round(total_cost, 4) AS cost
FROM spans
WHERE trace_id = '5a479103-1f21-66c3-3d1a-7a494e75f670'
AND span_type = 'LLM'
AND path = 'expense-review.anthropic.chat'
AND start_time > now() - INTERVAL 1 DAY
ORDER BY start_time
For the failed v1 run, every step had zero cache reads:
| step | input | cache write | cost |
|---|---|---|---|
| 1 | 2,559 | 2,476 | $0.0069 |
| 2 | 3,092 | 2,476 | $0.0089 |
| 4 | 3,463 | 2,476 | $0.0179 |
| 6 | 4,844 | 2,476 | $0.0131 |
| 8 | 5,442 | 2,476 | $0.0143 |
Compare the input before and after a large added value. Look for bulky tool results retained after their useful step, unnecessary loop iterations, or a repeated prefix that could be cached. The cache columns distinguish total context growth from how that context was billed.
Calls repeat with matching inputs
Group LLM spans by trace, model, and input hash to find repeated requests:
SELECT
trace_id,
model,
count() AS calls,
round(sum(total_cost) - min(total_cost), 4) AS repeat_cost,
substring(any(input), 1, 80) AS input_preview
FROM spans
WHERE span_type = 'LLM'
AND start_time > now() - INTERVAL 1 DAY
GROUP BY trace_id, model, cityHash64(input)
HAVING calls > 1
ORDER BY repeat_cost DESC
repeat_cost estimates spend beyond retaining the group's cheapest call; it is not a measured saving. Every matching group in our demo was a v1 Opus classifier call, repeated three to eight times. The estimate totaled $0.1687 of $1.3089 in LLM spend across both versions, or 12.9%. v2 returned no groups.
Read two matching inputs before removing a call. Repeated requests may deliberately sample answers for a vote. If the result is reusable, compute it outside the loop or cache it in application code.
Changing timestamps can conceal repeats. In our main-loop inputs, normalizing timestamps reduced distinct inputs from 132 to 116. This normalization used cityHash64(replaceRegexpAll(input, '\\d{4}-\\d{2}-\\d{2}T[0-9:.+]+', '<ts>')). Confirm that the removed fields cannot change the answer before treating normalized matches as reusable work.
The normalized total spans both versions and several runs. Each report's first-step inputs matched across runs after removing timestamps, but that does not establish that later state was equivalent. Keep within-run and cross-run reuse separate.
Tool errors lead to retries
Count errors by tool and message, then inspect whether the next attempt recovered:
SELECT
name AS tool,
simpleJSONExtractString(e.attributes, 'exception.message') AS error,
count() AS errors,
uniq(trace_id) AS traces
FROM spans
ARRAY JOIN events AS e
WHERE span_type = 'TOOL'
AND status = 'error'
AND e.name = 'exception'
AND start_time > now() - INTERVAL 1 DAY
GROUP BY tool, error
ORDER BY errors DESC
convert_currency produced 18 HTTP 503 errors in 18 traces. submit_review produced 16 lock errors across six traces: repeated attempts could not change the demo's permanent lock. flag_line_item also logged five missing-argument errors. A recoverable error and a terminal error need different retry policies.
End the run in code when another attempt cannot succeed, and make terminal errors explicit in tool output. This query requires tools recorded as TOOL spans.
Cache writes never become reads
Anthropic requires cache_control and matches the prefix in tools, system, messages order, with identical prompt segments. On most models, a five-minute cache write costs 1.25 times the base input rate; a read costs 0.1 times. OpenAI caches automatically on supported models and also requires the rendered prefix to match.
Count writes without reads for one version:
SELECT
model,
count() AS calls,
countIf(cache_read_input_tokens = 0 AND cache_creation_input_tokens > 0) AS writes_without_reads,
round(sum(cache_read_input_tokens) / sum(input_tokens) * 100, 1) AS pct_from_cache,
round(sum(total_cost), 4) AS cost
FROM spans
WHERE span_type = 'LLM'
AND start_time > now() - INTERVAL 1 DAY
AND trace_id IN (
SELECT id FROM traces
WHERE start_time > now() - INTERVAL 1 DAY
AND simpleJSONExtractString(metadata, 'variant') = 'v1'
)
GROUP BY model
ORDER BY cost DESC
All 67 v1 Sonnet calls wrote without reading; none of their input came from cache. In v2, one of 65 calls wrote without reading, and 87.8% of Sonnet input came from cache. Writing the 2,476-token prefix cost $0.0062 on v1's first step; reading it would have cost $0.0005.
Here, cache share measures tokens, not calls. A run can read cached input and still incur substantial output cost. Use this share to explain spending rather than treating a high percentage as the goal.
A write alone is not a defect. An eligible request with caching enabled needs a cold-cache write, and Anthropic's default cache expires after five minutes without use. Each use refreshes that lifetime. Below the minimum cacheable length, prompts run without caching or an error: 1,024 tokens for Claude Sonnet 5 and 4,096 for Claude Haiku 4.5.
In v1, consecutive calls seconds apart changed the timestamp before the policy. Diff two inputs to establish what changed. Keep reusable content before the cache breakpoint and variable fields afterward; also check tool-definition order. A zero read count by itself does not identify the cause.
A costly model handles a small step
Group LLM spans by model and path with average input and output tokens to surface these steps. In our demo, expense-review.classify_receipt made 234 Opus calls averaging 80 input and 18 output tokens, costing $0.2003. In v2, 42 Haiku calls cost $0.0034. Both the model and call count changed.
Small inputs and outputs nominate a step for testing; they do not establish that it is easy. Run an evaluation before switching models. We did not evaluate classification quality, so this demo does not establish that Haiku performs as well. Give distinct steps their own spans, such as @observe(name="classify_receipt"), to distinguish their paths.
A run spends money without completing
Trace status cannot define task success. Laminar marks a trace error if any span errored. Ten of twelve v1 traces had that status, but only three runs failed; seven recovered from tool errors.
Record the business outcome as trace metadata in a finally block:
from lmnr import Laminar, observe
Laminar.initialize()
@observe(name="expense-review")
def review(report_id: str, variant: str):
outcome = "failed"
try:
outcome = run_agent(report_id)
return outcome
finally:
Laminar.set_trace_metadata({"variant": variant, "outcome": outcome})
We tested both return and exception paths. Returning records the decision; raising records failed. Failed runs consumed $0.351 of v1's $1.0012, although they were only a quarter of runs.
Split that spend at the first submit_review lock error. Our window query using minIf(start_time, ...) OVER (PARTITION BY trace_id) put $0.1857 before the error and $0.1653 after it. Ending the run at that terminal error would avoid the later LLM spend, not the work already done.
Confirm the fix with cost per successful run
Cost per call alone can hide a regression: cheaper calls may require more attempts or produce fewer completed tasks. Define a comparable cohort and explicit success outcomes. Divide all cohort spend, failed runs included, by successful runs:
SELECT
simpleJSONExtractString(metadata, 'variant') AS variant,
count() AS runs,
countIf(simpleJSONExtractString(metadata, 'outcome') IN ('approved', 'returned')) AS succeeded,
countIf(simpleJSONExtractString(metadata, 'outcome') = 'failed') AS failed,
countIf(simpleJSONExtractString(metadata, 'outcome') NOT IN ('approved', 'returned', 'failed')) AS unknown,
round(sum(total_cost), 4) AS spend,
round(spend / nullIf(succeeded, 0), 4) AS cost_per_successful_run
FROM traces
WHERE start_time > now() - INTERVAL 1 DAY
AND top_span_name = 'expense-review'
AND simpleJSONExtractString(metadata, 'variant') IN ('v1', 'v2')
GROUP BY variant
ORDER BY variant
approved and returned count as success here. Missing or unexpected outcomes count as unknown; inspect them rather than quietly excluding them. nullIf returns null if no run succeeded.

Our demo, 12 runs per version: recorded completion stayed at 9/12 while cost per successful run fell. Review quality was not evaluated.
Cost per successful run fell from $0.1112 to $0.0342 in this cohort. Main-loop Sonnet spend fell from $0.801 to $0.3042; classifier spend fell from $0.2003 to $0.0034. v2 changed caching, classifier repetition, and classifier model together. These totals show their combined effect, not savings attributable to each change.
The remaining failures still matter: v2 spent $0.1007 on failed runs, split into $0.0514 before the first lock error and $0.0493 afterward. A recorded completion also says nothing about whether the review was correct.
For a production change, define the quality check before rerunning the workload: a completed expense review must also make the expected decision and submit the required fields. Preserve failed cases in the test set, including locked reports and temporary tool outages. If you need to attribute savings, deploy one change at a time and rerun the same cases. Then inspect representative traces to confirm the intended mechanism changed, such as fewer classifier spans or cache reads replacing writes.
Compare the same task mix over comparable windows, and check quality separately. Record the version on every trace, using metadata or the release column populated when the SDK reports a release (agent versions).
Separate budget enforcement from diagnosis
A gateway fits budget enforcement. LiteLLM's proxy attributes spend to keys, users, teams, customers, and models, and rejects requests before the provider when a budget is exceeded. Portkey supports cost or token budgets on provider integrations and expires the key at the limit.
Aggregate spending answers who spent money, but does not show the execution sequence that caused it. Some gateways also log individual requests. This workflow needs calls, tool spans, and errors connected into a run, plus queries across runs. Check whether your records let you reconstruct that sequence, not just total the requests.
Laminar is not in the request path and cannot block spending. Enforce limits in a gateway or your agent code, then use traces to explain the work before the limit. For the broader landscape, see AI agent cost tracking tools.
Watch for regressions after deployment
Save useful queries as dashboard charts. Advanced mode supports WITH, joins, and window functions. Replace the fixed interval with the dashboard's {start_time:DateTime64} and {end_time:DateTime64} parameters.
Track cache-read share and cost per successful run together. A cost drop is incomplete evidence when the unknown-outcome count rises or task mix changes. Keep the outcome breakdown beside spend so a deployment cannot look cheaper merely because it stopped finishing reviews.
FAQ
Why do Laminar's input token counts differ from the Anthropic API response?
A difference can come from normalization, not different usage. Laminar's input_tokens includes cached input. Anthropic reports ordinary input separately from cache_read_input_tokens and cache_creation_input_tokens. Add all three Anthropic fields before comparing with Laminar's total. For cost, keep token classes separate because they use different rates. This avoids double-counting cached tokens when you reconcile your own logs with a trace. See cost tracking.
Can I investigate patterns that are difficult to express in SQL?
Signals accept a plain-language instruction and JSON schema, read relevant trace steps, and emit a structured event with evidence links when they find a match. No match produces no event. You can configure triggers and trace filters for new traces, or backfill historical traces. For a suspected semantic repeat, inspect the linked steps before deciding the work was avoidable. See Signals.
Can I get notified when a pattern returns?
Signals alerts can fire for a new event or a new cluster. Notifications appear in Laminar's in-app notification center; Slack and email delivery are optional. Choose conditions that distinguish a recurring failure from an isolated recoverable tool error, and use the notification to inspect its trace. An alert informs an operator; it does not cancel calls or enforce a budget. Configure delivery through Signals alerts.