We cut our browser-driving LLM agent from about 60 minutes and $7 per job to 9 minutes and $1.67 with four changes: a moving prompt-cache breakpoint with the OpenRouter provider pinned, batch history pruning with hysteresis, structured rehearsal feedback instead of probe runs, and a "sighted" explorer. Caching cut cost per turn; the explorer cut rehearsals.
The agent is a Claude Sonnet 5 tool loop. It explores a live web app in Playwright, writes a narrated demo scene, then rehearses that scene headlessly until it passes before recording. Every job writes its real token usage and computed USD to a usage_costs JSON column, so every number below comes from our own job ledger, not from estimates. We also include the job that went badly wrong after the fixes.
What did the per-job numbers look like before and after?
Before the fixes, a job took 28 to 69 agent-loop minutes and $3 to $8 in LLM spend, with up to 84 rehearsals. After all four changes, our good jobs ran in 9 to 14 minutes with one or two rehearsals and cost $1.65 to $4, depending almost entirely on turn count. One outlier didn't.
Agent-loop minutes are measured from the first to the last agent event in our job_events table. Rehearsal counts come from per-rehearsal events, which we only started logging partway through, so the earliest rows have none. LLM cost covers tokens only. Text-to-speech adds roughly $0.07 to $0.38 per job.
| Job | State of the loop | Turns | Rehearsals | Minutes | LLM cost |
|---|---|---|---|---|---|
| 05966e19 | Caching on, sliding-window pruning, provider not pinned | 130 | not logged | 27 | $14.11 (failed) |
| d13675ad | + pruning hysteresis + provider pin | 121 | not logged | 28 | $4.01 |
| f1efd525 | Degraded-settle retry loop | 111 | ~95 | 60 | $4.88 |
| cf3a59da | Failing reports swallowed as "pipeline error" | 71 | 58 | 48 | $3.08 |
| 75c5f5ea | After settle and report fixes | 40 | 27 | 21 | $1.81 |
| 4cb24700 | Complex form app, blind explorer | 92 | 84 | 65 | $7.40 |
| a97454d2 | Sighted explorer, first run | 39 | 2 | 9 | $1.67 |
| c906c00f | Sighted explorer | 51 | 2 | 10 | $1.65 |
| c25464c9 | Sighted explorer, agent lost in exploration | 357 | 2 | 38 | $20.75 |
| e6815a0c | Sighted explorer, a week later | 98 | 1 | 9 | $3.17 |
The table shows two separate levers. Token cost per turn was a caching problem. Wall-clock time was a rehearsal problem, because each rehearsal replays the whole flow from login and takes about 1 to 2 minutes. We fixed them separately, and the sections below follow that order.
Why did a 130-turn job cost $14.11 with prompt caching on?
Our cache was being rewritten, not read. Job 05966e19 wrote 3.25M cache tokens and read back only 2.23M; cache writes alone cost $12.18 of its $14.11. The history pruner edited the conversation prefix every turn (85 prune events in one job), so each request invalidated the cache the previous one had just paid to write.
On Anthropic models, a 5-minute cache write costs 1.25x the base input price and a cache read costs 0.1x, per Anthropic's prompt caching docs. On Sonnet 5 that is $3.75 per million to write and $0.30 to read. A cache you keep rewriting is worse than no cache, because every write carries a 25% surcharge.
The very next job, d13675ad, ran with the two fixes below. It took 121 turns, wrote 277K cache tokens, read 5.27M, and cost $4.01. That is a 93% read share of prompt tokens. At full input price, the same token volume would have cost about $18. Both fixes landed within the same hour, so our data can't fully separate their effects. The 85 prune events are the strongest evidence for which one mattered most.
How do you move a cache breakpoint inside the Anthropic SDK tool runner?
Each turn, strip every existing cache_control marker from the history, then put one on the last eligible block of the newest message. With client.beta.messages.tool_runner, do it in a callback passed to runner.set_messages_params(), which rewrites params before each request. Plus one static marker on the system block, two breakpoints cover the whole prefix.
_CACHE_CONTROL = {"type": "ephemeral"}
def _strip_cache_control(blocks):
for block in blocks:
# Runner-appended assistant messages hold SDK-typed blocks
# (BetaToolUseBlock, BetaThinkingBlock...), not dicts.
# Calling .pop() on one crashed turn 1 in production.
if isinstance(block, dict):
block.pop("cache_control", None)
def _move_last_message_cache_breakpoint(messages):
for m in messages:
if isinstance(m, dict) and isinstance(m.get("content"), list):
_strip_cache_control(m["content"])
for m in reversed(messages):
if not isinstance(m, dict):
continue
content = m.get("content")
if isinstance(content, str):
content = [{"type": "text", "text": content}]
m["content"] = content
if not (isinstance(content, list) and content):
continue
for i in range(len(content) - 1, -1, -1):
btype = content[i].get("type") if isinstance(content[i], dict) \
else getattr(content[i], "type", None)
if btype in ("thinking", "redacted_thinking"):
continue # API rejects cache_control on these
block = content[i]
if not isinstance(block, dict):
block = block.model_dump(exclude_none=True)
content[i] = {**block, "cache_control": dict(_CACHE_CONTROL)}
return
runner = client.beta.messages.tool_runner(
model="anthropic/claude-sonnet-5",
max_tokens=16000,
system=[{"type": "text", "text": SYSTEM_PROMPT,
"cache_control": {"type": "ephemeral"}}],
tools=tools,
messages=[{"role": "user", "content": user_prompt}],
max_iterations=MAX_TOOL_TURNS,
extra_body={"provider": {"order": ["anthropic"],
"allow_fallbacks": False}},
)
turn = 0
for message in runner:
if turn > 0:
def _mutate(params):
msgs = list(params["messages"])
_prune_old_tool_results(msgs) # next section
_move_last_message_cache_breakpoint(msgs)
return {**params, "messages": msgs}
runner.set_messages_params(_mutate)
turn += 1
# accumulate message.usage: input_tokens, output_tokens,
# cache_read_input_tokens, cache_creation_input_tokens
We ran into three problems here. First, SDK-typed blocks have to be converted with model_dump() before you can add a dict key to them. Second, thinking blocks can never carry the marker, which is why the loop walks backwards past them. Third, the runner appends the latest turn's messages only when you call next(). A mutation made in the loop body therefore takes effect one request later, so the first cache hit comes one turn late. After that it behaves correctly.
We kept the tool runner instead of writing our own while-loop. That cost us the one-turn lag. In return we kept the runner's tool dispatch and stop semantics without reimplementing them, which we judged the better deal. The tool definitions don't need their own breakpoint either. Tools come before system in the cache prefix, so the system breakpoint already covers a tool set that never changes.
Why does batch history pruning need hysteresis?
Without hysteresis, a "batch" pruner turns into a sliding window. Once history passes the threshold, one more tool result ages past the keep-recent window every turn. Each prune then rewrites the prefix and invalidates the cache. Our fix: prune only after at least 20 unpruned results have aged out, stub them all at once, and leave existing stubs byte-identical.
_PRUNE_TOOL_RESULT_THRESHOLD = 40 # start pruning past this many results
_PRUNE_KEEP_RECENT_TURNS = 20 # never touch the newest 20 turns
_PRUNE_BATCH_MIN = 20 # hysteresis: wait for a full batch
_PRUNE_STUB = "[pruned page snapshot -- was {n} chars; re-run the tool if needed]"
def _prune_old_tool_results(messages):
if _count_tool_result_blocks(messages) <= _PRUNE_TOOL_RESULT_THRESHOLD:
return 0
idx = [i for i, m in enumerate(messages)
if isinstance(m.get("content"), list)
and any(isinstance(b, dict) and b.get("type") == "tool_result"
for b in m["content"])]
if len(idx) <= _PRUNE_KEEP_RECENT_TURNS:
return 0
prunable = set(idx[:-_PRUNE_KEEP_RECENT_TURNS])
eligible = sum(
1 for i in prunable for b in messages[i]["content"]
if isinstance(b, dict) and b.get("type") == "tool_result"
and not str(b.get("content", "")).startswith("[pruned page snapshot")
and not _is_rehearsal_tool_result(b, messages, i))
if eligible < _PRUNE_BATCH_MIN:
return 0 # prefix stays stable this turn
pruned = 0
for i in prunable:
new = []
for b in messages[i]["content"]:
orig = b.get("content", "") if isinstance(b, dict) else None
if (not isinstance(b, dict) or b.get("type") != "tool_result"
or _is_rehearsal_tool_result(b, messages, i)
or (isinstance(orig, str)
and orig.startswith("[pruned page snapshot"))):
new.append(b) # untouched, byte-identical
continue
new.append({**b, "content": _PRUNE_STUB.format(n=len(str(orig)))})
pruned += 1
messages[i]["content"] = new
return pruned
Three rules matter. Rehearsal results are never pruned, because they are the feedback the agent is acting on. Assistant reasoning is never touched. An existing stub is never re-stubbed. Our first version re-stubbed old stubs with the stub's own length, which changed bytes on every turn and broke the cache again. A unit test caught that. The live job ledger caught the sliding-window behavior.
_is_rehearsal_tool_result has to find the tool name by matching tool_use_id back to the earlier tool_use block, because a tool_result doesn't carry its own name. It also has to handle both dict blocks and SDK-typed blocks. If it doesn't, rehearsal results silently lose their prune protection.
Why pin the OpenRouter provider when caching Claude?
OpenRouter can serve anthropic/* models from more than one upstream provider, and a cache written at one can't be read at another. Sticky routing is best-effort, and OpenRouter's caching guide says it's disabled once you set a provider order. Pin order: ["anthropic"] with allow_fallbacks: false so a cold-cache fallback fails loudly.
We checked this before trusting it. With the pin in place, the second request of an identical cached prompt read back 3,604 of the 3,604 tokens the first request had written. The tradeoff is availability. If Anthropic's endpoint is down, the request errors and our Celery task retries, instead of falling over to another provider. We accept that, because a long agent job on a cold cache costs more than a retry. The provider routing reference documents both parameters.
If you are calling the Anthropic SDK through OpenRouter at all, the base URL and tool_result shape also have quirks. We covered them in using the Anthropic Python SDK through OpenRouter's /api/v1/messages: the trailing-/v1 404 and 'invalid_union' tool_result 400s.
Why were rehearsals, not tokens, eating the wall clock?
Each rehearsal replays the full scene from login in a fresh browser, so a job with 60 to 95 rehearsals spends most of its hour in Playwright, not the model. Three fixable causes drove the count: failures that could never pass, failure reports that never reached the agent, and no way to see mid-scene DOM state except another rehearsal.
Unclearable settles (job f1efd525, ~95 rehearsals, ~50 minutes). Two actions on a continuously animating AI try-on modal came back degraded: true, reason: "timeout" on every run. The page never went quiet, so no fix could clear them. Our fix is a two-strike rule. On strike one, apply the report's proposed settle timeout and rehearse again. On strike two, accept the result. A degraded settle no longer blocks passed. We also added a circuit breaker that tracks consecutive failure signatures and adds a repeat_failure_note to the tool result after three repeats.
Failing reports swallowed as crashes (job cf3a59da, 29 of 58 attempts). The rehearsal subprocess exits 1 both when it crashes and when a scene legitimately fails after writing a full report. Our wrapper treated both as fatal, so the agent got a stderr tail instead of per-action errors. It then blind-bisected the scene. The fix is to accept exit 1, then return the report only if it is fresh:
pre_invoke_ts = time.time()
try:
_run_poc_module(job_id, "rehearsal")
crash_error = None
except PipelineError as exc:
crash_error = exc
reports = list(scenes_dir.glob("*/rehearsal_report.json"))
fresh = [r for r in reports if r.stat().st_mtime >= pre_invoke_ts]
if fresh:
return json.loads(fresh[0].read_text()) # pass OR fail, structured
if crash_error is not None:
raise crash_error
raise PipelineError("rehearsal.py ran but produced no rehearsal_report.json")
The mtime check matters. A crash can leave a stale report from an earlier attempt on disk, and returning that report as the current result would be wrong. Related bug: we were truncating error strings from the head. For subprocess errors, the first 300 characters were often just a Pillow DeprecationWarning banner. Truncate from the tail.
Probe rehearsals (job 75c5f5ea, ~24 of 27 runs). This was our first "fixed" job at 21 minutes and $1.81. Its event log showed the next problem. Most of its rehearsals existed only to run an evaluate that throws an error, so the page HTML would leak out through the error message. We added page_state snapshots to rehearsal reports: dialog presence, up to 12 visible interactive elements including open shadow roots, and visible validation messages, capped at about 1,200 characters. Snapshots are captured only on errors, pausable actions, and the final action, because rehearsal reports are prune-protected and every byte stays in context.
What is a "sighted" explorer and why did it cut rehearsals from 84 to 2?
A sighted explorer is a set of live-browser tools that let the agent verify an action's real effect before committing to a rehearsal: log in, read validation text and toasts, screenshot, run single actions through the real recording handlers, and build the scene incrementally server-side. Our first job with it took 39 turns and 2 rehearsals, versus 84 rehearsals blind.
On a form-heavy web app, the old explorer could not log in, could not see inline validation, and used plain Playwright instead of the recording harness. Harness-only bugs therefore surfaced only during rehearsals. One such bug cost about 170 rehearsals across three jobs. Our zoom camera left a permanent CSS transform on <body>. That turned position: fixed modals into click sinks, so focus stayed on BODY and typing went nowhere. The agent repeatedly reported this as a site bug.
The new toolset closes those gaps:
type_credential(selector, env_name)logs in from a sealed credentials file. The value never crosses the tool boundary.read_page()returns controls, validation text, react-select state, and toasts, including toasts that have already disappeared, from a MutationObserver.run_action(action_json)executes one scene action with the real recorder handlers. It is stricter than the harness: an unresolvable selector, a no-opselecton a custom dropdown, or typing that lands nowhere all fail.draft_*+rehearse_draft()build the scene on the server one action at a time. The agent patches a field instead of re-sending the whole scene JSON.
The best job's tool mix shows the change: 27 run_action, 27 draft_patch_action, 4 read_page, 2 rehearse_draft. Validation moved from two-minute rehearsals into calls that take a few seconds. The rehearsal became what it should be: one final proof that what ships is what was tested.
Does the $1.67 result hold across a 2026 production job ledger?
The time win held; the cost win did not hold uniformly. After the sighted explorer shipped, every delivered job used one or two rehearsals and most finished in 9 to 14 minutes. But LLM cost ranged from $1.65 to $20.75, because cost now tracks turn count, and an agent lost in exploration can run hundreds of cheap turns.
Job c25464c9 ran the same day as the $1.67 job. It took 357 turns and 2 rehearsals and cost $20.75. Its tool mix was 86 read_page and 77 inspect calls, meaning the agent was flailing on a complex event-creation form. Cache reads alone cost $10.51, on an average context of about 105K tokens per turn. Caching kept that job from costing about $114. It can't fix a loop whose context grows with every turn while the turns keep coming.
We have no turn budget on purpose. A small fixed cap forced honest but incomplete scenes on genuinely complex sites, so the only backstop is a 120-minute hard task limit. We chose correctness over a cost ceiling at this stage. The next lever is an exploration budget that resets on progress, not a hard turn cap. If you're seeing the related failure where an agent passes in staging and slowly gets worse in production, we covered it in why does our AI agent work in staging but degrade in production after a few days?
How should you track LLM agent cost per job?
Sum the four token counts the API returns every turn (input, output, cache-creation, cache-read), store them per job, and price them from one rate table that returns null for unknown models. Alert on the cache read-to-write ratio: every healthy job in our ledger read 8x to 56x more than it wrote. The broken job read 0.7x.
PRICING_USD_PER_MILLION = {
"anthropic/claude-sonnet-5": {"input": 3.00, "output": 15.00,
"cache_write": 3.75, "cache_read": 0.30},
}
def compute_llm_cost_usd(model, input_tokens, output_tokens,
cache_write_tokens, cache_read_tokens):
rates = PRICING_USD_PER_MILLION.get(model)
if rates is None:
return None # track tokens, never guess a price
return ((input_tokens / 1e6) * rates["input"]
+ (output_tokens / 1e6) * rates["output"]
+ (cache_write_tokens / 1e6) * rates["cache_write"]
+ (cache_read_tokens / 1e6) * rates["cache_read"])
Here is the $1.67 job broken down: cache writes $0.64, cache reads $0.43, uncached input $0.27, output $0.33. If cache writes make up most of your bill, your prefix is churning. Look for anything that rewrites history on every turn. We go deeper into breakpoint placement for request-response workloads in prompt caching: how we cut Claude API costs by 90% in production.
What actually moved the numbers?
Going from 60 minutes and $7 to 9 minutes and $1.67 took two separate fixes. Caching fixed cost per turn: a moving breakpoint, a pinned provider, and batch pruning that leaves the prefix alone. Rehearsal fixes cut wall-clock time: real failure reports, page-state snapshots, and a sighted explorer. Neither caps turn count; only a per-job cost ledger showed that.