ai newsDi., 1. Dez.
EilmeldungThe Model Proposes, Your Code Disposes: A Tool-Calling Agent Loop for Android with Gemini Nano

Our AI Agent Cost $0.90 Per Run: Runaway Loops, Context Snowballs & the Tiering Fix That Took It to $0.12 (Real Code)

AI in Production: War Stories, Scenario #2. One real production incident: the alert, the triage (dead ends included), the root cause, the fix with runnable code, the measured result — and how to tell it in a senior interview. Scenario #1 was the hallucination incident. This one is about money. Full

dev.toSonntag 13:39 · 29.11.5 Min. Lesezeit
Bild: dev.to

Posted on Nov 29 • Originally published at prepstack.co.in

AI in Production: War Stories, Scenario #2. One real production incident: the alert, the triage (dead ends included), the root cause, the fix with runnable code, the measured result — and how to tell it in a senior interview. Scenario #1 was the hallucination incident. This one is about money.

Full original (canonical) on PrepStack: https://prepstack.co.in/blog/ai-production-scenario-2-agent-cost-explosion

Our agentic analytics feature plans an investigation, calls governed analytics APIs through an MCP layer, cross-references segments, and writes a finding. In the pilot it was magic. Then finance forwarded the model-provider invoice with one cell highlighted.

The pilot cohort ran ~400 agent runs a day. Average cost per run: $0.90. That's $360/day — a ~$11,000/month run-rate for a feature we planned to roll out to 20x the pilot's users. Dead unit economics: it would cost more to serve than the plan tier it shipped in.

Nobody had done anything wrong. "Use the strong model, it's smarter." "Let the agent keep working until it's done." "Pass the full tool output back so it has context." Every decision was locally reasonable. Together they compounded into a money fire. This is the most common agent incident there is.

Root cause: agent cost is price x tokens x iterations, and we were managing none of the three. The strong model multiplied price, the snowballing context multiplied tokens, the unbounded loop multiplied iterations. Multiplication is why agent bills surprise teams used to linear per-request LLM costs.

# Multiplier 1: PRICE - model-per-role tiering (escalation, never default) MODEL_ROUTER = "claude-haiku-5-5" # classify complexity MODEL_WORKER = "claude-sonnet-5-5" # the default workhorse MODEL_ESCALATION = "claude-opus-5-5" # earned by 'complex' runs only # Multiplier 3: ITERATIONS - explicit budgets MAX_ITERATIONS = 10 MAX_COST_USD = 0.25 WRAP_UP_AT = 0.8 # at 80% of any budget, tell the agent to conclude Enter fullscreen mode Exit fullscreen mode # The meter: cost from ACTUAL usage fields - finance's number must be # computable from our own logs, not reverse-engineered from the invoice. class RunMeter: def add ( self, model, usage ): inp, out = PRICES [ model ] cached = getattr ( usage, "cache_read_input_tokens", 0 ) or 0 self. cost_usd += ( usage. input_tokens * inp + cached * inp * 0.1 + usage. output_tokens * out ) / 1_000_000 def over ( self ): return self. iterations >= MAX_ITERATIONS or self. cost_usd >= MAX_COST_USD def near ( self ): return self. cost_usd >= MAX_COST_USD * WRAP_UP_AT Enter fullscreen mode Exit fullscreen mode # Multiplier 2: TOKENS - compact tool results, keep a reference escape hatch def compact_tool_result ( raw, run_id, tool_use_id ): data = json. loads ( raw ); rows = data. get ( "rows", [ ] ) return json. dumps ( { "metric": data. get ( "metric" ), "segment": data. get ( "segment" ), "row_count": len ( rows ), "first_rows": rows [: 5 ], "last_rows": rows [ - 5: ], "full_result_ref": f "{run_id}/{tool_use_id}", # stored server-side; model can ask to expand } ) # [C5] killer: same tool + same args a third time is a retry loop, not progress def detect_loop ( meter, name, args ): sig = hashlib. md5 ( ( name + json. dumps ( args, sort_keys = True ) ). encode ( ) ). hexdigest ( ) meter. tool_signatures [ sig ] = meter. tool_signatures. get ( sig, 0 ) + 1 return meter. tool_signatures [ sig ] > 2 Enter fullscreen mode Exit fullscreen mode # The loop, with caching on a byte-stable prefix and graceful budget exits while True: meter. iterations += 1 response = client. messages. create ( model = model, max_tokens = 4096, system = [ { "type": "text", "text": SYSTEM, "cache_control": { "type": "ephemeral" } } ], tools = tools, messages = messages ) meter. add ( model, response. usage ) messages. append ( { "role": "assistant", "content": response. content } ) if response. stop_reason!= "tool_use": return text, meter if meter. over ( ): return ( "I hit the investigation budget. Partial findings above; " "a human analyst has been notified to complete this." ), meter #... execute tools through detect_loop() + compact_tool_result()... if meter. near ( ) and not wrap_up_sent: messages. append ( { "role": "system", "content": WRAP_UP } ) # "conclude with what you have" Enter fullscreen mode Exit fullscreen mode What matters more than the code:

Case 6 confession: our first caching attempt saved nothing. The system prompt had a freshly formatted timestamp — one changing byte at the top of the prefix, so every request was a cache miss. If cache_read_input_tokens is ~0, hunt for the volatile byte: almost always a timestamp, a UUID, or unsorted JSON.

Cost optimization that quietly degrades answers is just a slower incident. Everything ran through an eval gate (investigation accuracy + completeness, hard floor 0.90) before shipping. Tiering moved the score 0.93 → 0.92 (inside noise); compaction, no measurable change; budgets end 3% of runs with a budgeted partial answer, counted as successes-with-caveats that each file a gap ticket.

87% cost reduction, quality statistically unchanged — and the part I underline in every retro: the meter is permanent. The $0.12 isn't a trophy; it's a monitored SLO with an alert on it.

STAR, 60 seconds: "Our agentic feature cost $0.90/run in pilot — dead unit economics at rollout scale. Agent cost is price times tokens times iterations, so I attacked all three: model-per-role tiering with escalation instead of a default premium model; context control via deterministic compaction and prompt caching; explicit run budgets with a graceful wrap-up plus a deterministic repeated-call detector. Cost fell 87% to $0.12 with the eval score inside noise, p95 iterations 18→6, and cost-per-run became a monitored SLO with alerting."

Follow-ups you'll get: why not the cheapest model everywhere? (eval gate failed; complex causal runs dropped below 0.90 — tiering is an empirical boundary). How do you know cost exactly? ( usage fields priced through a config table, per run_id — not invoice / run count). Budget UX? (wrap-up at 80%, hard stop + escalation at 100%, 3% end budgeted, labeled honestly). What stops regression? (evals with cost assertions in CI + production p95 alert). Remaining waste? (cross-run re-investigation; cross-run memory is the next lever, with its own staleness risks).

Quelle: dev.to (dev.to). Original öffnen