<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Hammad Malik</title>
    <description>The latest articles on DEV Community by Hammad Malik (@hammad_malik_d39574d24320).</description>
    <link>https://dev.to/hammad_malik_d39574d24320</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4191886%2Ffea4ba76-21de-4e1a-93d0-04a256ad411e.jpg</url>
      <title>DEV Community: Hammad Malik</title>
      <link>https://dev.to/hammad_malik_d39574d24320</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/hammad_malik_d39574d24320"/>
    <language>en</language>
    <item>
      <title>GPT-5.6 Sol Price After November 21: The Promo Didn't End — It Moved to November 30</title>
      <dc:creator>Hammad Malik</dc:creator>
      <pubDate>Sun, 29 Nov 2026 10:33:28 +0000</pubDate>
      <link>https://dev.to/hammad_malik_d39574d24320/gpt-56-sol-price-after-november-21-the-promo-didnt-end-it-moved-to-november-30-3d6f</link>
      <guid>https://dev.to/hammad_malik_d39574d24320/gpt-56-sol-price-after-november-21-the-promo-didnt-end-it-moved-to-november-30-3d6f</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://www.apicostlab.com/2026/11/gpt-56-sol-price-after-november-21.html" rel="noopener noreferrer"&gt;API Cost Lab&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  GPT-5.6 Sol Price After November 21: The Promo Didn't End — It Moved to November 30
&lt;/h1&gt;

&lt;p&gt;&lt;em&gt;Last updated: November 2026&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;November 21 came and went, and the price of GPT-5.6 Sol did not move. It is still $4 per million input tokens and $20 per million output tokens — the same promotional rate OpenAI set on August 21. What changed is the date on OpenAI's own page: where it used to say the promo was available "at least through November 21, 2026", it now says it is "available until November 30, 2026". The deadline moved nine days. The price after that date is still unpublished.&lt;/p&gt;

&lt;p&gt;That is the whole outcome, and it matters more than it looks. In October we warned that November 21 could bring a 41% overnight price rise, and we told you to budget for it. The rise did not arrive — but neither did an answer. OpenAI bought itself nine more days without saying what happens on the tenth. And the new wording is firmer than the old one: "until" is an expiry date, where "at least through" was only a floor. The risk did not vanish. It got a new date and a harder edge.&lt;/p&gt;

&lt;h2&gt;
  
  
  The deadline that wasn't
&lt;/h2&gt;

&lt;p&gt;Rewind to August 21, 2026. OpenAI cut GPT-5.6 Sol from $5.00 input and $30.00 output per million tokens to $4.00 and $20.00 — a 20% cut on input, a 33% cut on output — and guaranteed the new rates "at least through November 21, 2026". That phrasing was doing quiet work: it promised the price would not rise before November 21, and said nothing at all about November 22.&lt;/p&gt;

&lt;p&gt;Our &lt;a href="https://www.apicostlab.com/2026/10/gpt-56-api-pricing-november-21-deadline.html" rel="noopener noreferrer"&gt;October post on the November 21 deadline&lt;/a&gt; read the wording exactly that way. The promo could extend. It could also end on the date. OpenAI had published no price for what came after, so the only concrete "after" number was the old $5/$30 — a scenario to budget against, not a prediction.&lt;/p&gt;

&lt;p&gt;What actually happened was the third option nobody had a number for: an extension. The price stayed at $4/$20, and the date on the page moved to November 30. The change shows up on OpenAI's own model page, in the same sentence that used to carry the November 21 date. There is still no published price for December 1 and beyond.&lt;/p&gt;

&lt;p&gt;So the lesson of November 21 is not that the deadline was fake. It is that the date was never the event. The event is whatever OpenAI decides next, and it can decide it by editing one sentence on a pricing page — no announcement required.&lt;/p&gt;

&lt;h2&gt;
  
  
  What the page says today
&lt;/h2&gt;

&lt;p&gt;Checked November 24, 2026, on OpenAI's &lt;a href="https://developers.openai.com/api/docs/models/gpt-5.6-sol" rel="noopener noreferrer"&gt;GPT-5.6 Sol model page&lt;/a&gt;: input $4.00, cached input $0.40, output $20.00 per million tokens, and "GPT-5.6 Sol's promotional pricing is available until November 30, 2026." The page's own comparison still shows the older GPT-5.5 at $5.00 input and GPT-5.4 at $2.50 — so the promo price still undercuts the previous flagship's headline rate.&lt;/p&gt;

&lt;p&gt;The fine print is unchanged, and it still bites. A single request with more than 272,000 input tokens is billed at twice the input rate and one and a half times the output rate for the whole request — $8.00 and $30.00 on the promo rates, not just on the tokens above the line. Cache writes still cost 1.25 times the input rate, as our &lt;a href="https://www.apicostlab.com/2026/11/cache-write-pricing-surcharge-you-pay.html" rel="noopener noreferrer"&gt;cache-write investigation&lt;/a&gt; showed. And the $20 output rate is where reasoning tokens bill, even though you never see them — our &lt;a href="https://www.apicostlab.com/2026/11/reasoning-tokens-invisible-output.html" rel="noopener noreferrer"&gt;reasoning-tokens investigation&lt;/a&gt; explains why that line on the bill is bigger than the visible answer suggests.&lt;/p&gt;

&lt;p&gt;Nothing on the page says what Sol costs after November 30. If the promo ends and the price reverts to the pre-promo $5/$30, that is a 41% rise on identical usage. It is still a scenario, not a promise. But it is still the only scenario with a real number attached — and now it has a date nine days closer than it did last week.&lt;/p&gt;

&lt;h2&gt;
  
  
  What nine extra days are worth
&lt;/h2&gt;

&lt;p&gt;Take a different workload from the one we modelled in October — a support-chat product answering 200 conversations a day. Each conversation uses about 3,000 fresh input tokens, 12,000 cached input tokens and 1,500 output tokens. The cached share is high because the system prompt and help-centre text are the same every time.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;Promo ($4 / $0.40 / $20)&lt;/th&gt;
&lt;th&gt;If it reverts ($5 / $0.50 / $30)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Fresh input, per conversation&lt;/td&gt;
&lt;td&gt;$0.0120&lt;/td&gt;
&lt;td&gt;$0.0150&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Cached input, per conversation&lt;/td&gt;
&lt;td&gt;$0.0048&lt;/td&gt;
&lt;td&gt;$0.0060&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Output, per conversation&lt;/td&gt;
&lt;td&gt;$0.0300&lt;/td&gt;
&lt;td&gt;$0.0450&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Per conversation&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;$0.0468&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;$0.0660&lt;/strong&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Per day (200 conversations)&lt;/td&gt;
&lt;td&gt;$9.36&lt;/td&gt;
&lt;td&gt;$13.20&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Per month (30 days)&lt;/td&gt;
&lt;td&gt;$280.80&lt;/td&gt;
&lt;td&gt;$396.00&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The gap is the same 41% we calculated in October, because the rates are the same — the date moved, the maths didn't. On this workload the nine-day extension is worth 9 × $3.84 = $34.56. That is not much money. The real value of the nine days is not the saving; it is nine more days to test a cheaper fallback while the $4/$20 rate still holds. Run your own token mix through our &lt;a href="https://www.apicostlab.com/2026/10/ai-api-cost-calculator-estimate-your.html" rel="noopener noreferrer"&gt;AI API Cost Calculator&lt;/a&gt; — your cached share decides how much of that 41% actually lands on you.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why a quiet extension is still a warning
&lt;/h2&gt;

&lt;p&gt;It is tempting to read the extension as good news: OpenAI chose not to raise the price, so maybe it won't. That reading is not supported by anything OpenAI has said. What the evidence actually shows is narrower: OpenAI extended a promotion without publishing what follows it, and changed "at least through" to "until" while doing so.&lt;/p&gt;

&lt;p&gt;That wording change is the meaningful signal. "At least through November 21" was a floor — a promise the price would not rise before that date, with no commitment about the day after. "Available until November 30" is an expiry. November 30 now reads as a real end date, not a milestone. The safe assumption is that the promo ends then, and that the price after it is unknown — exactly the position we were in before November 21, except the runway is nine days instead of five weeks.&lt;/p&gt;

&lt;p&gt;There is a second lesson in how the extension arrived. It came as a one-sentence edit on a pricing page, not an announcement. If you were waiting for an email or a blog post to tell you the price changed, you would still be waiting. The pricing page is the source of truth, and it changes without telling you. Check it; do not wait to be told.&lt;/p&gt;

&lt;h2&gt;
  
  
  Three things to do before November 30
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Measure your real token mix.&lt;/strong&gt; The 41% figure is only real if your usage looks like the table above. Pull your actual fresh, cached and output tokens from the OpenAI dashboard. If you are not logging per-call costs yet, our &lt;a href="https://www.apicostlab.com/2026/10/openai-cost-tracking-middleware-build.html" rel="noopener noreferrer"&gt;OpenAI cost-tracking middleware&lt;/a&gt; is a small wrapper that records every call's price — ten minutes to add, and it turns the December question from a guess into arithmetic.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Test the fallback now, not on December 1.&lt;/strong&gt; In October we modelled two cheaper options on the same workload: GPT-6.1 Sol at $2 input and $10 output per million tokens, and Claude Opus 5.5 at $4/$20 with much cheaper cache reads. The numbers are in our &lt;a href="https://www.apicostlab.com/2026/10/gpt-61-sol-api-pricing-per-token-costs.html" rel="noopener noreferrer"&gt;GPT-6.1 Sol pricing post&lt;/a&gt; and our &lt;a href="https://www.apicostlab.com/2026/10/claude-vs-gpt-vs-gemini-for-coding-cost-per-task.html" rel="noopener noreferrer"&gt;Claude vs GPT vs Gemini comparison&lt;/a&gt;. Run both against a sample of your real tasks while the promo is still your safety net. You want to know before November 30 whether the cheaper model clears your quality bar — not discover it on the December invoice.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Budget December at $5/$30.&lt;/strong&gt; Set next month's budget on the reverted rates. If the promo extends again, the difference is a saving. If it doesn't, there is no shock. And put November 30 on your calendar: check OpenAI's model page that morning. That is the day the sentence changes again — or doesn't.&lt;/p&gt;

&lt;h2&gt;
  
  
  One more date after this one
&lt;/h2&gt;

&lt;p&gt;November 30 is not the last repricing date on the calendar. Argon's price change takes effect after December 1, and we will report what it actually becomes once the date passes — not predict it beforehand. The same rule applies here: report what happened, with the page as the source.&lt;/p&gt;

&lt;p&gt;November 21 came and went without a price rise, and that is nine days of good news. It is not a reprieve. It is a shorter deadline with harder wording — use it the way the first one was meant to be used: measure your usage, test the fallback, and budget for the price you can see, not the one you hope for.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Rates verified 24 November 2026 on OpenAI's GPT-5.6 Sol model page (developers.openai.com/api/docs/models/gpt-5.6-sol): $4.00 input, $0.40 cached input, $20.00 output per million tokens; promotional pricing available until November 30, 2026. No price after that date has been published.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>ai</category>
      <category>llm</category>
      <category>openai</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>API Retry Costs: Build a Cost-Aware Retry Wrapper for the Gemini API in Python</title>
      <dc:creator>Hammad Malik</dc:creator>
      <pubDate>Fri, 27 Nov 2026 10:31:43 +0000</pubDate>
      <link>https://dev.to/hammad_malik_d39574d24320/api-retry-costs-build-a-cost-aware-retry-wrapper-for-the-gemini-api-in-python-35e5</link>
      <guid>https://dev.to/hammad_malik_d39574d24320/api-retry-costs-build-a-cost-aware-retry-wrapper-for-the-gemini-api-in-python-35e5</guid>
      <description>

&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://www.apicostlab.com/2026/11/api-retry-costs-build-cost-aware-retry.html" rel="noopener noreferrer"&gt;API Cost Lab&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  API Retry Costs: Build a Cost-Aware Retry Wrapper for the Gemini API in Python
&lt;/h1&gt;

&lt;p&gt;&lt;em&gt;Last updated: November 2026&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Every retry of a failed API call re-sends the whole prompt and bills it again, so a retry loop that retries every error can turn one failed call into four bills for zero answers. The fix is a small wrapper that retries only the errors that can clear on their own — 429s and 500-series errors — waits longer after each failure, and stops retrying once the call's own spend passes a cap you set. The code below does that for the Gemini API in about sixty lines.&lt;/p&gt;

&lt;p&gt;A library default of three retries sounds harmless until you multiply it by a whole day of traffic.&lt;/p&gt;

&lt;h2&gt;
  
  
  A failed call still has a bill
&lt;/h2&gt;

&lt;p&gt;Take one call to Gemini 2.5 Flash with a 20,000-token prompt — a system prompt plus a help-centre document, as in our &lt;a href="https://www.apicostlab.com/2026/11/your-ai-agent-pays-for-same-prompt-five.html" rel="noopener noreferrer"&gt;tool-loop investigation&lt;/a&gt; — and a 1,000-token answer. Rates are the published standard rates, verified 20 November 2026 on Google's pricing page: input $0.30, output $2.50 per million tokens. One attempt costs 20,000 × $0.30 ÷ 1,000,000 = $0.006 of input plus 1,000 × $2.50 ÷ 1,000,000 = $0.0025 of output: $0.0085 in total.&lt;/p&gt;

&lt;p&gt;Now the call fails, and your code retries three times — the usual default. Every attempt re-sends the whole 20,000-token prompt, so the $0.006 input charge repeats in full, and output is billed for whatever the model produced before the error. Worst case, each attempt costs the full $0.0085. Four attempts on one question: $0.034, for an answer you never got.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Attempts&lt;/th&gt;
&lt;th&gt;What happened&lt;/th&gt;
&lt;th&gt;Cost&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;Success on the first try&lt;/td&gt;
&lt;td&gt;$0.0085&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;One 500 error, then success&lt;/td&gt;
&lt;td&gt;$0.0170&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;Three blind retries on a 400 error&lt;/td&gt;
&lt;td&gt;$0.0340&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;At volume the gap stops looking small. Say your app makes 10,000 calls a day and 5 percent hit a transient 500 error. That is 500 calls a day, each retried three times: 1,500 extra attempts × $0.0085 = $12.75 a day, about $382 a month — annoying, but at least the money buys a completed call. The pure waste is the other kind of failure. If 1 percent of calls are bad requests and each is retried three times, that is 100 calls × 3 wasted attempts × $0.0085 = $2.55 a day, $76.50 a month, paying four times for an error that will fail identically every time. Run your own daily call count through our &lt;a href="https://www.apicostlab.com/2026/10/ai-api-cost-calculator-estimate-your.html" rel="noopener noreferrer"&gt;AI API Cost Calculator&lt;/a&gt; with the per-call figure from your logs, and the monthly retry waste is the number to stare at.&lt;/p&gt;

&lt;h2&gt;
  
  
  Which errors deserve a second try
&lt;/h2&gt;

&lt;p&gt;The whole wrapper is one decision, repeated: is this error the kind that can clear on its own? A rate-limit 429 clears when the quota window rolls over. A 500, 502, 503 or 504 is the provider's problem, and a minute later it is often gone. Everything else is your problem, and retrying it is paying to be told the same thing again. A 400 means the request itself is wrong — a bad parameter, a prompt the model refuses — and it will be wrong on the fifth try too. A 401 or 403 means the key or access is wrong. A 404 means the model name does not exist.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Error&lt;/th&gt;
&lt;th&gt;Retry?&lt;/th&gt;
&lt;th&gt;Why&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;429 rate limit&lt;/td&gt;
&lt;td&gt;Yes, with backoff&lt;/td&gt;
&lt;td&gt;Clears when the quota window rolls over&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;500 / 502 / 503 / 504&lt;/td&gt;
&lt;td&gt;Yes, with backoff&lt;/td&gt;
&lt;td&gt;The provider's problem, often gone in a minute&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;400 bad request&lt;/td&gt;
&lt;td&gt;Never&lt;/td&gt;
&lt;td&gt;Your request is wrong and stays wrong&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;401 / 403&lt;/td&gt;
&lt;td&gt;Never&lt;/td&gt;
&lt;td&gt;Your key or access is wrong, not the timing&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;404&lt;/td&gt;
&lt;td&gt;Never&lt;/td&gt;
&lt;td&gt;The model name does not exist&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;One more case: a client-side timeout. Retry it only if no response arrived at all — a timeout after the model already answered can double-bill a call that succeeded. If your HTTP layer cannot tell you whether a response arrived, treat a timeout as non-retryable and log it.&lt;/p&gt;

&lt;h2&gt;
  
  
  The wrapper
&lt;/h2&gt;

&lt;p&gt;Install the SDK with &lt;code&gt;pip install google-genai&lt;/code&gt; and set &lt;code&gt;GEMINI_API_KEY&lt;/code&gt; in your environment. Save the code below as &lt;code&gt;gemini_retry.py&lt;/code&gt; and call &lt;code&gt;call_with_retry()&lt;/code&gt; instead of calling &lt;code&gt;client.models.generate_content&lt;/code&gt; directly. It returns the original response untouched and logs every attempt.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;logging&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;random&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;

&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;google&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;genai&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;google&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;genai&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;errors&lt;/span&gt;

&lt;span class="c1"&gt;# Rates per 1M tokens, verified 20 November 2026 on Google's&lt;/span&gt;
&lt;span class="c1"&gt;# Gemini API pricing page. From 1 December 2026, gemini-2.5-flash&lt;/span&gt;
&lt;span class="c1"&gt;# routes to gemini-3.5-flash-lite, billed at that model's rates.&lt;/span&gt;
&lt;span class="no"&gt;INPUT_PER_MILLION&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;0.30&lt;/span&gt;    &lt;span class="c1"&gt;# fresh text input&lt;/span&gt;
&lt;span class="no"&gt;OUTPUT_PER_MILLION&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;2.50&lt;/span&gt;   &lt;span class="c1"&gt;# visible output + thinking tokens&lt;/span&gt;

&lt;span class="c1"&gt;# Retry only errors that can clear on their own: not 400s (bad&lt;/span&gt;
&lt;span class="c1"&gt;# request), 401/403s (bad key), or 404s (bad model name).&lt;/span&gt;
&lt;span class="no"&gt;RETRYABLE_STATUS&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;429&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;500&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;502&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;503&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;504&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="n"&gt;client&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;genai&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Client&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# reads GEMINI_API_KEY from the environment&lt;/span&gt;
&lt;span class="n"&gt;log&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;logging&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getLogger&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"gemini_retry"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_estimate_tokens&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""Rough token estimate for English text: ~4 chars per token."""&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;max&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;//&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_attempt_estimate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;contents&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;expected_output_tokens&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""Rough cost of one attempt, used only to enforce the cap."""&lt;/span&gt;
    &lt;span class="n"&gt;prompt_tokens&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;_estimate_tokens&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;contents&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; \
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nb"&gt;isinstance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;contents&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;list&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="nf"&gt;_estimate_tokens&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;contents&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;prompt_tokens&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="no"&gt;INPUT_PER_MILLION&lt;/span&gt;
            &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;expected_output_tokens&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="no"&gt;OUTPUT_PER_MILLION&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;1_000_000&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_measured_cost&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""Exact cost of a finished call, from the usage object."""&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;usage&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mf"&gt;0.0&lt;/span&gt;
    &lt;span class="n"&gt;prompt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;getattr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"prompt_token_count"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="n"&gt;output&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;getattr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"candidates_token_count"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="n"&gt;thoughts&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;getattr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"thoughts_token_count"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="c1"&gt;# Thinking tokens bill at the output rate, though you never see them.&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;prompt&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="no"&gt;INPUT_PER_MILLION&lt;/span&gt;
            &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;output&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;thoughts&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="no"&gt;OUTPUT_PER_MILLION&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;1_000_000&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;call_with_retry&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;contents&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;feature&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"unknown"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="n"&gt;max_attempts&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;max_cost_per_call&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;0.03&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="n"&gt;base_delay&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;1.0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="n"&gt;kwargs&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""Call generate_content with cost-aware retries: only 429/5xx,
    longer waits after each failure, and no retry once the estimated
    spend for this call passes max_cost_per_call."""&lt;/span&gt;
    &lt;span class="n"&gt;estimate&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;_attempt_estimate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;contents&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;spent_estimate&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;0.0&lt;/span&gt;
    &lt;span class="n"&gt;last_error&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;attempt&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;max_attempts&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;spent_estimate&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;estimate&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;max_cost_per_call&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;warning&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"cost cap $%.4f hit on %s after %d attempts"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                        &lt;span class="n"&gt;max_cost_per_call&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;feature&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;attempt&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;break&lt;/span&gt;
        &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;generate_content&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;contents&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;contents&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="n"&gt;kwargs&lt;/span&gt;
            &lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="n"&gt;errors&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;APIError&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;status&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;getattr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"code"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;last_error&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;
            &lt;span class="n"&gt;spent_estimate&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="n"&gt;estimate&lt;/span&gt;
            &lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;warning&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"attempt %d/%d failed: HTTP %s (%s)"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                        &lt;span class="n"&gt;attempt&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;max_attempts&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;feature&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="no"&gt;RETRYABLE_STATUS&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="n"&gt;attempt&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;max_attempts&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;raise&lt;/span&gt;
            &lt;span class="n"&gt;delay&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;min&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;base_delay&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;attempt&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; \
                &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;random&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;uniform&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sleep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;delay&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;continue&lt;/span&gt;
        &lt;span class="n"&gt;cost&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;_measured_cost&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;getattr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"usage_metadata"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;info&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"feature=%s attempts=%d cost_usd=%.6f"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                 &lt;span class="n"&gt;feature&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;attempt&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cost&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;
    &lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="n"&gt;last_error&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using it is one line different from a normal call. Replace &lt;code&gt;client.models.generate_content(model="gemini-2.5-flash", contents=prompt)&lt;/code&gt; with &lt;code&gt;call_with_retry("gemini-2.5-flash", prompt, feature="support_reply")&lt;/code&gt;. The &lt;code&gt;feature&lt;/code&gt; label is the one to get right: it is what you will group by later, so name it after your product ("support_reply", "summariser", "nightly_report"), not your code. With the defaults above, a 20,000-token prompt is estimated at $0.0085 an attempt, so three attempts fit under the $0.03 cap.&lt;/p&gt;

&lt;h2&gt;
  
  
  Two settings that matter more than the code
&lt;/h2&gt;

&lt;p&gt;The first is the backoff. The delay doubles after each failure — one second, then two, then four — plus a random fraction of a second. Without it, a hundred clients retrying a 500 at once all hit the recovering server at the same instant. The random jitter spreads them out, and the 30-second ceiling stops a long chain from waiting minutes for a call nobody is watching.&lt;/p&gt;

&lt;p&gt;The second is the cap, and it needs to be set from your own numbers, not copied from this article. Take the cost of one attempt for your biggest prompt and set &lt;code&gt;max_cost_per_call&lt;/code&gt; to a small multiple of it — three attempts' worth is a sane default. Set it from your cheapest prompt and your biggest prompt gets capped after one failed attempt — as it should: a prompt costing $0.05 a try should never be retried three times on autopilot. The cap is also what protects you from the failure mode no error list can catch: an error your code classifies as retryable that never clears.&lt;/p&gt;

&lt;h2&gt;
  
  
  Seeing retries in your own logs
&lt;/h2&gt;

&lt;p&gt;The wrapper earns its keep when you read the log lines it writes. Two numbers tell the story: attempts per call, and cost per call. A feature that averages 1.0 attempts is healthy. A feature that averages 1.4 attempts is paying a 40 percent retry tax, and the HTTP status in the warning lines says whether the tax is rate limits — fix it by slowing down or raising quota — or 500s, which are the provider's and mostly out of your hands. If the warnings are all 400s, the wrapper already saved the retries; fix the request, because the original call still cost $0.0085 each time.&lt;/p&gt;

&lt;p&gt;Pair the retry log with the per-call cost log from our &lt;a href="https://www.apicostlab.com/2026/11/gemini-cost-tracking-build-usage-logger.html" rel="noopener noreferrer"&gt;Gemini usage logger&lt;/a&gt;: the logger records what a finished call cost, the wrapper records what the failed attempts cost, and together they are the whole bill. If one user is behind most of the retries, the &lt;a href="https://www.apicostlab.com/2026/11/stop-one-user-from-eating-your-ai.html" rel="noopener noreferrer"&gt;per-user spending guard&lt;/a&gt; caps their share before it eats the budget the other users need. And retries are only one multiplier on an agent's bill: our &lt;a href="https://www.apicostlab.com/2026/11/your-ai-agent-pays-for-same-prompt-five.html" rel="noopener noreferrer"&gt;tool-loop investigation&lt;/a&gt; showed a five-round agent task costs six times a single call, because every round re-sends the whole conversation — a retry inside that loop multiplies a bill that is already multiplied.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;em&gt;Rates verified 20 November 2026 on Google's Gemini API pricing page (ai.google.dev/gemini-api/docs/pricing): Gemini 2.5 Flash standard tier, input $0.30, output $2.50 (including thinking tokens) per million tokens. All worked figures are arithmetic on those published rates, using the stated example token counts — not measured runs. Gemini 2.5 Flash is deprecated and routes to Gemini 3.5 Flash-Lite from 1 December 2026, billed at that model's rates.&lt;/em&gt;
&lt;/h2&gt;

</description>
      <category>ai</category>
      <category>llm</category>
      <category>gemini</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Your AI Agent Pays for the Same Prompt Five Times: The Tool-Loop Tax on Your Bill</title>
      <dc:creator>Hammad Malik</dc:creator>
      <pubDate>Wed, 25 Nov 2026 10:31:29 +0000</pubDate>
      <link>https://dev.to/hammad_malik_d39574d24320/your-ai-agent-pays-for-the-same-prompt-five-times-the-tool-loop-tax-on-your-bill-128m</link>
      <guid>https://dev.to/hammad_malik_d39574d24320/your-ai-agent-pays-for-the-same-prompt-five-times-the-tool-loop-tax-on-your-bill-128m</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://www.apicostlab.com/2026/11/your-ai-agent-pays-for-same-prompt-five.html" rel="noopener noreferrer"&gt;API Cost Lab&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Your AI Agent Pays for the Same Prompt Five Times: The Tool-Loop Tax on Your Bill
&lt;/h1&gt;

&lt;p&gt;&lt;em&gt;Last updated: November 2026&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;An AI agent task is not one API call. It is a loop: the model answers, calls a tool, reads the result, answers again, calls another tool, and so on — and every round re-sends the entire conversation so far. The system prompt, the user question, the earlier answers, and every tool result come back as fresh input tokens, billed again at the full input rate. A support agent that needs five tool rounds costs six times a single call, not because the answers are expensive, but because the same 20,000-token context is paid for five times. That is the tool-loop tax, and it is the main reason agent bills surprise people who priced their app as if each task were one call.&lt;/p&gt;

&lt;h2&gt;
  
  
  One task, five bills
&lt;/h2&gt;

&lt;p&gt;Here is how the loop actually bills. You send a system prompt and a user question. The model replies with a tool call instead of an answer. Your code runs the tool and sends the result back — but the API has no memory between calls, so that second request carries everything again: the system prompt, the user question, the model's first reply, and the new tool result. The third request carries all of that plus the second reply and the second tool result. Nothing is ever sent only once. Our &lt;a href="https://www.apicostlab.com/2026/11/gemini-cost-tracking-build-usage-logger.html" rel="noopener noreferrer"&gt;Gemini usage logger&lt;/a&gt; shows this directly: its &lt;code&gt;tool_use_prompt_token_count&lt;/code&gt; field climbs every turn, because tool results are fed back in as input tokens and billed at the input rate.&lt;/p&gt;

&lt;p&gt;Two other charges ride along with the loop. Thinking tokens bill at the output rate on every round, so a reasoning model thinks — and charges — five times for one task. And the output of each round becomes input for the next, so a wordy intermediate answer is an expensive input on every round after it. Our &lt;a href="https://www.apicostlab.com/2026/10/why-is-my-ai-agent-so-expensive-to-run.html" rel="noopener noreferrer"&gt;agent cost explainer&lt;/a&gt; named the loop as the suspect; this article puts numbers on it.&lt;/p&gt;

&lt;h2&gt;
  
  
  The worked example: a five-round support agent
&lt;/h2&gt;

&lt;p&gt;Take a support agent on Gemini 2.5 Flash, with a 20,000-token system prompt and help-centre document, and a 500-token user question. Each round the model writes 500 output tokens and each tool returns a 2,000-token result. Rates are the published standard rates, verified 16 November 2026 on Google's pricing page: input $0.30, output $2.50 per million tokens. The token counts are a worked example, not a measured run — the arithmetic is the point.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Round&lt;/th&gt;
&lt;th&gt;Input tokens sent&lt;/th&gt;
&lt;th&gt;Input cost&lt;/th&gt;
&lt;th&gt;Output cost&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;20,500&lt;/td&gt;
&lt;td&gt;$0.00615&lt;/td&gt;
&lt;td&gt;$0.00125&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;23,000&lt;/td&gt;
&lt;td&gt;$0.00690&lt;/td&gt;
&lt;td&gt;$0.00125&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;25,500&lt;/td&gt;
&lt;td&gt;$0.00765&lt;/td&gt;
&lt;td&gt;$0.00125&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;28,000&lt;/td&gt;
&lt;td&gt;$0.00840&lt;/td&gt;
&lt;td&gt;$0.00125&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;td&gt;30,500&lt;/td&gt;
&lt;td&gt;$0.00915&lt;/td&gt;
&lt;td&gt;$0.00125&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Each round adds the previous output (500 tokens) and the previous tool result (2,000 tokens) to the input, so the input grows by 2,500 tokens a round. Total input is 127,500 tokens at $0.30 per million: $0.03825. Total output is 2,500 tokens at $2.50 per million: $0.00625. The task costs $0.0445, against $0.0074 for the same question in a single call — almost exactly six times as much. And look at where the money went: the fixed 20,000-token context was sent five times, 100,000 tokens for $0.03 — 78 percent of the whole input bill. The tool results, the thing the loop is actually for, cost far less than re-reading the instructions.&lt;/p&gt;

&lt;p&gt;At volume the gap stops looking small. Ten thousand of these tasks a day cost $445 a day, $13,350 a month, against $74 a day and $2,220 a month if each task were a single call. Same model, same question — the difference is entirely the loop. Run your own daily task count through our &lt;a href="https://www.apicostlab.com/2026/10/ai-api-cost-calculator-estimate-your.html" rel="noopener noreferrer"&gt;AI API Cost Calculator&lt;/a&gt; with the per-task figure from your logs, and the monthly gap is the number to stare at.&lt;/p&gt;

&lt;h2&gt;
  
  
  The runaway version: big tool results, ten rounds
&lt;/h2&gt;

&lt;p&gt;The five-round example is the polite version. Now let each tool return a 10,000-token result — a full search dump, a whole database row set, a long document chunk — and let the loop run ten rounds, because the model keeps fetching more context to be sure. Round one sends 20,500 input tokens. Round two sends 31,000: the fixed context, the question, the first answer, and a 10,000-token result. Every round adds 10,500 tokens — 500 of model output plus 10,000 of tool result. After ten rounds the input total is 677,500 tokens, costing $0.20325, plus 5,000 output tokens at $0.0125. One task: $0.2158, or 29 times the $0.0074 single call.&lt;/p&gt;

&lt;p&gt;The shape of that growth is what makes runaway loops dangerous. Input does not grow by one tool result per round; it grows by the sum of all previous results, because each one stays in the conversation. A loop with no round cap and no result-size cap has no cost ceiling at all, which is how a single user session can quietly burn a day's budget. Our &lt;a href="https://www.apicostlab.com/2026/11/stop-one-user-from-eating-your-ai.html" rel="noopener noreferrer"&gt;per-user spending guard&lt;/a&gt; exists for exactly this failure: it stops one runaway session from eating the budget the other users need.&lt;/p&gt;

&lt;h2&gt;
  
  
  Three fixes, with the numbers
&lt;/h2&gt;

&lt;p&gt;The first fix is to cache the fixed context. On the paid tier, cached input on Gemini 2.5 Flash costs $0.03 per million tokens instead of $0.30 — a tenth of the fresh rate. Apply that to the five-round example and the 100,000 tokens of re-read context cost $0.003 instead of $0.03. The fresh tokens — user question, prior answers, tool results — still bill at the full rate and come to $0.00825. Total input falls from $0.03825 to $0.01125, and the whole task from $0.0445 to $0.0175: a 61 percent saving, without changing a word the model sees. The catch is the same one our &lt;a href="https://www.apicostlab.com/2026/11/cache-write-pricing-surcharge-you-pay.html" rel="noopener noreferrer"&gt;cache-write investigation&lt;/a&gt; found: caching has its own price — on Gemini it is storage rent of $1.00 per million tokens per hour for an explicit cache — and it is a paid-tier feature. Also note that Gemini 2.5 Flash is deprecated: from 1 December 2026 its requests route to Gemini 3.5 Flash-Lite and bill at that model's rates, so re-check the pricing page before budgeting on the numbers above.&lt;/p&gt;

&lt;p&gt;The second fix is to cap the rounds. A hard maximum of three tool rounds turns the five-round example into inputs of 20,500, 23,000 and 25,500 tokens — $0.0207 of input plus $0.00375 of output, $0.02445 in total, 45 percent cheaper than letting it run to five. The cap is not just a saving, it is a ceiling: the worst a task can cost is now a number you chose in advance, and a stuck loop fails loudly at round three instead of silently at round ten.&lt;/p&gt;

&lt;p&gt;The third fix is to trim tool results before they enter the conversation. In the five-round example this helps less than you would expect: capping each tool result at 500 tokens instead of 2,000 brings the task to $0.04, only a 10 percent saving, because the fixed 20,000-token context still dominates. In the runaway example it is the fix that matters most: the same ten rounds with 500-token results cost $0.0875 instead of $0.2158, a 59 percent saving, because there the tool results were the bill. So trim where the tokens actually are — summarise or filter the tool output when results are large, and spend the caching effort on the fixed context when the context is large.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to see it in your own logs
&lt;/h2&gt;

&lt;p&gt;Do not guess which of these is your problem — the logs already say. Our &lt;a href="https://www.apicostlab.com/2026/11/gemini-cost-tracking-build-usage-logger.html" rel="noopener noreferrer"&gt;Gemini logger&lt;/a&gt;, and the matching &lt;a href="https://www.apicostlab.com/2026/10/openai-cost-tracking-middleware-build.html" rel="noopener noreferrer"&gt;OpenAI middleware&lt;/a&gt; and &lt;a href="https://www.apicostlab.com/2026/11/anthropic-cost-tracking-build-claude.html" rel="noopener noreferrer"&gt;Claude logger&lt;/a&gt;, record one line per call with the input, output, thinking and tool-use token counts. Group a day's lines by feature and look at two numbers: input tokens per task, and how fast &lt;code&gt;tool_use_prompt_token_count&lt;/code&gt; climbs across the rounds of one task. If input per task is five to ten times the size of your system prompt, the loop is re-reading context — cache it. If the tool-use column grows by thousands every round, the results are too big — trim them.&lt;/p&gt;

&lt;p&gt;The same invisible-output pattern sits behind our &lt;a href="https://www.apicostlab.com/2026/11/reasoning-tokens-invisible-output.html" rel="noopener noreferrer"&gt;reasoning-token investigation&lt;/a&gt;: the tokens you pay for are not the tokens you can see. With agents, the hidden charge is repetition. Count the rounds, cache the context, cap the loop, and the agent that looked six times too expensive turns out to be one task priced as six calls.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Rates verified 16 November 2026 on Google's Gemini API pricing page (ai.google.dev/gemini-api/docs/pricing): Gemini 2.5 Flash standard tier, input $0.30, output $2.50 (including thinking tokens), cached input $0.03 per million tokens; explicit-cache storage $1.00 per million tokens per hour. All worked figures are arithmetic on those published rates, using the stated example token counts — they illustrate the mechanism, they are not measured runs. Gemini 2.5 Flash is deprecated and routes to Gemini 3.5 Flash-Lite from 1 December 2026, billed at that model's rates.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>ai</category>
      <category>llm</category>
      <category>agents</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Gemini Cost Tracking: Build a Usage Logger for the Gemini API in Python</title>
      <dc:creator>Hammad Malik</dc:creator>
      <pubDate>Mon, 23 Nov 2026 10:31:32 +0000</pubDate>
      <link>https://dev.to/hammad_malik_d39574d24320/gemini-cost-tracking-build-a-usage-logger-for-the-gemini-api-in-python-5bl5</link>
      <guid>https://dev.to/hammad_malik_d39574d24320/gemini-cost-tracking-build-a-usage-logger-for-the-gemini-api-in-python-5bl5</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://www.apicostlab.com/2026/11/gemini-cost-tracking-build-usage-logger.html" rel="noopener noreferrer"&gt;API Cost Lab&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Gemini Cost Tracking: Build a Usage Logger for the Gemini API in Python
&lt;/h1&gt;

&lt;p&gt;&lt;em&gt;Last updated: November 2026&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Gemini cost tracking is a small wrapper around your Gemini API calls that reads the &lt;code&gt;usage_metadata&lt;/code&gt; on every response, splits it into fresh input, cached input, visible output, thinking tokens, and tool-use tokens, prices each bucket at the rate Google publishes for your model, and writes one JSON line per call to a file. Put it between your code and the &lt;code&gt;google-genai&lt;/code&gt; client, and the next time your Gemini bill looks wrong you can point at the exact feature and the exact token bucket that produced it. If you already built the &lt;a href="https://www.apicostlab.com/2026/10/openai-cost-tracking-middleware-build.html" rel="noopener noreferrer"&gt;OpenAI version of this wrapper&lt;/a&gt; or the &lt;a href="https://www.apicostlab.com/2026/11/anthropic-cost-tracking-build-claude.html" rel="noopener noreferrer"&gt;Claude version&lt;/a&gt;, this is the Gemini twin — the same sixty-line shape, but Gemini's usage object hides its two most expensive surprises inside totals that look innocent.&lt;/p&gt;

&lt;p&gt;The first surprise is thinking tokens. The second is cached tokens folded into the prompt total. A logger that reads the two fields that look like totals — prompt tokens and output tokens — gets both wrong at once, in opposite directions, and the errors cancel just enough that the monthly total looks plausible while every per-feature number is fiction.&lt;/p&gt;

&lt;h2&gt;
  
  
  Gemini's usage object has five numbers, and two of them will fool you
&lt;/h2&gt;

&lt;p&gt;Every &lt;code&gt;generate_content&lt;/code&gt; response carries a &lt;code&gt;usage_metadata&lt;/code&gt; object with six fields that matter for pricing: &lt;code&gt;prompt_token_count&lt;/code&gt; for everything sent in, &lt;code&gt;cached_content_token_count&lt;/code&gt; for the part of the prompt served from cache, &lt;code&gt;candidates_token_count&lt;/code&gt; for the visible answer, &lt;code&gt;thoughts_token_count&lt;/code&gt; for the model's hidden reasoning, &lt;code&gt;tool_use_prompt_token_count&lt;/code&gt; for tool results fed back in as input, and &lt;code&gt;total_token_count&lt;/code&gt;, which is the sum of the first four groups. Two facts about that list do all the damage. First, &lt;code&gt;prompt_token_count&lt;/code&gt; already includes the cached tokens, so it is not the fresh-input count. Second, &lt;code&gt;candidates_token_count&lt;/code&gt; does not include thinking — thoughts are a separate field, billed at the output rate, and they never appear in &lt;code&gt;response.text&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;On Gemini 2.5 Flash, verified 13 November 2026 on Google's pricing page, fresh text input costs $0.30 per million tokens, cached input costs $0.03, and output — visible answer plus thinking — costs $2.50. Audio input is a different price entirely at $1.00 per million, more than triple the text rate, with cached audio at $0.10. Take one call with 10,000 fresh text tokens, a 50,000-token document served from cache, 1,000 tokens of visible answer, and 2,000 thinking tokens. The arithmetic on the published rates is: fresh input 10,000 × $0.30 ÷ 1,000,000 = $0.003; cached input 50,000 × $0.03 ÷ 1,000,000 = $0.0015; output (1,000 + 2,000) × $2.50 ÷ 1,000,000 = $0.0075. Total: $0.012 — and thinking is nearly two-thirds of the output bill on a call whose answer is only 1,000 tokens long.&lt;/p&gt;

&lt;p&gt;Now watch what two naive loggers report for that same call. One prices the whole &lt;code&gt;prompt_token_count&lt;/code&gt; of 60,000 at the fresh rate and reports $0.018 of input — four times the real $0.0045. The other counts only &lt;code&gt;candidates_token_count&lt;/code&gt; as output and reports $0.0025 instead of $0.0075 — missing two-thirds of the output cost. The first logger over-reports, the second under-reports, and both are reading fields whose names sound like exactly what they want. That is the same invisible-output pattern our &lt;a href="https://www.apicostlab.com/2026/11/reasoning-tokens-invisible-output.html" rel="noopener noreferrer"&gt;reasoning-tokens investigation&lt;/a&gt; found on OpenAI: the tokens you pay for are not the tokens you can see.&lt;/p&gt;

&lt;h2&gt;
  
  
  The code: a wrapper you can drop in
&lt;/h2&gt;

&lt;p&gt;Install the SDK with &lt;code&gt;pip install google-genai&lt;/code&gt; and set &lt;code&gt;GEMINI_API_KEY&lt;/code&gt; in your environment. Save the code below as &lt;code&gt;gemini_tracker.py&lt;/code&gt; next to your app, and call &lt;code&gt;track_content()&lt;/code&gt; instead of calling &lt;code&gt;client.models.generate_content&lt;/code&gt; directly. It appends one JSON line per call to &lt;code&gt;gemini_costs.jsonl&lt;/code&gt;, stores no prompt or answer text, and returns the original response untouched, so the rest of your code does not change.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;datetime&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;datetime&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;timezone&lt;/span&gt;

&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;google&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;genai&lt;/span&gt;

&lt;span class="c1"&gt;# Rates per 1M tokens, verified 13 November 2026 on Google's&lt;/span&gt;
&lt;span class="c1"&gt;# Gemini API pricing page (ai.google.dev/gemini-api/docs/pricing).&lt;/span&gt;
&lt;span class="c1"&gt;# Re-check them before you budget. From 1 December 2026,&lt;/span&gt;
&lt;span class="c1"&gt;# gemini-2.5-flash routes to gemini-3.5-flash-lite and gemini-2.5-pro&lt;/span&gt;
&lt;span class="c1"&gt;# routes to gemini-3.8-flash, billed at the new models' rates.&lt;/span&gt;
&lt;span class="no"&gt;FLASH_RATES&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="s2"&gt;"input_per_million"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;0.30&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;         &lt;span class="c1"&gt;# fresh text/image/video input&lt;/span&gt;
    &lt;span class="s2"&gt;"input_audio_per_million"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;1.00&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;   &lt;span class="c1"&gt;# fresh audio input&lt;/span&gt;
    &lt;span class="s2"&gt;"cached_per_million"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;0.03&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;        &lt;span class="c1"&gt;# cached text/image/video input&lt;/span&gt;
    &lt;span class="s2"&gt;"cached_audio_per_million"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;0.10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;  &lt;span class="c1"&gt;# cached audio input&lt;/span&gt;
    &lt;span class="s2"&gt;"output_per_million"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;2.50&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;        &lt;span class="c1"&gt;# visible output + thinking tokens&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="no"&gt;FLASH_LITE_RATES&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="s2"&gt;"input_per_million"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;0.10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;"input_audio_per_million"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;0.30&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;"cached_per_million"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;0.01&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;"cached_audio_per_million"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;0.03&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;"output_per_million"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;0.40&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="c1"&gt;# Pro charges one rate up to 200,000 prompt tokens and a higher rate&lt;/span&gt;
&lt;span class="c1"&gt;# above it -- and the higher rate applies to the whole prompt, not&lt;/span&gt;
&lt;span class="c1"&gt;# just the tokens past the line.&lt;/span&gt;
&lt;span class="no"&gt;PRO_RATES&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="s2"&gt;"input_per_million"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;1.25&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;"input_per_million_over_200k"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;2.50&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;"cached_per_million"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;0.125&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;"cached_per_million_over_200k"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;0.25&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;"output_per_million"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;10.00&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;"output_per_million_over_200k"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;15.00&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="n"&gt;client&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;genai&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Client&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# reads GEMINI_API_KEY from the environment&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_rates_for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;prompt_tokens&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;audio_input&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;False&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""Pick the rate row for this model, prompt size, and modality."""&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="s2"&gt;"2.5-pro"&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;over&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;prompt_tokens&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;200_000&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="s2"&gt;"input"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="no"&gt;PRO_RATES&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"input_per_million_over_200k"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;over&lt;/span&gt;
                   &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="no"&gt;PRO_RATES&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"input_per_million"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"cached"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="no"&gt;PRO_RATES&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"cached_per_million_over_200k"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;over&lt;/span&gt;
                    &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="no"&gt;PRO_RATES&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"cached_per_million"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"output"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="no"&gt;PRO_RATES&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"output_per_million_over_200k"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;over&lt;/span&gt;
                    &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="no"&gt;PRO_RATES&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"output_per_million"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="n"&gt;base&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;FLASH_LITE_RATES&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="s2"&gt;"flash-lite"&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;model&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="no"&gt;FLASH_RATES&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;audio_input&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="s2"&gt;"input"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;base&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"input_audio_per_million"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"cached"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;base&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"cached_audio_per_million"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"output"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;base&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"output_per_million"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="s2"&gt;"input"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;base&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"input_per_million"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"cached"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;base&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"cached_per_million"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"output"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;base&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"output_per_million"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_cost_usd&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;rates&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;prompt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;prompt_token_count&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="n"&gt;cached&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;getattr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"cached_content_token_count"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="n"&gt;fresh&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;max&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;prompt&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;cached&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;candidates&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;getattr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"candidates_token_count"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="n"&gt;thoughts&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;getattr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"thoughts_token_count"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="n"&gt;tool_use&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;getattr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"tool_use_prompt_token_count"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="c1"&gt;# Thinking tokens bill at the output rate. Tool-use tokens are&lt;/span&gt;
    &lt;span class="c1"&gt;# prompt tokens fed back in, so they bill at the input rate.&lt;/span&gt;
    &lt;span class="n"&gt;cost&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;fresh&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;rates&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"input"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;cached&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;rates&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"cached"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;candidates&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;thoughts&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;rates&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"output"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;tool_use&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;rates&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"input"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;1_000_000&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;fresh&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cached&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;candidates&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;thoughts&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;tool_use&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cost&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;track_content&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;contents&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;feature&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"unknown"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                  &lt;span class="n"&gt;audio_input&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;False&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="n"&gt;kwargs&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""Drop-in replacement for client.models.generate_content."""&lt;/span&gt;
    &lt;span class="n"&gt;started&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;monotonic&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;generate_content&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;contents&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;contents&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="n"&gt;kwargs&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;latency_ms&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;monotonic&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;started&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="n"&gt;record&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="s2"&gt;"timestamp"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;datetime&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;timezone&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;utc&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;isoformat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"feature"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;feature&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"model"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"latency_ms"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;latency_ms&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="n"&gt;usage&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;getattr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"usage_metadata"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;usage&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;rates&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;_rates_for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;prompt_token_count&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;audio_input&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;fresh&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cached&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;candidates&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;thoughts&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;tool_use&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cost&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;_cost_usd&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;rates&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;record&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="s2"&gt;"input_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;fresh&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"cached_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;cached&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"output_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;candidates&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"thinking_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;thoughts&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"tool_use_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;tool_use&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"cost_usd"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cost&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;record&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"note"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"no usage_metadata returned"&lt;/span&gt;

    &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"gemini_costs.jsonl"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"a"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;write&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dumps&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;record&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s2"&gt;"\n"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using it is one line different from a normal call. Replace &lt;code&gt;client.models.generate_content(model="gemini-2.5-flash", contents=prompt)&lt;/code&gt; with &lt;code&gt;track_content("gemini-2.5-flash", prompt, feature="support_reply")&lt;/code&gt;. The &lt;code&gt;feature&lt;/code&gt; label is the most important parameter in the file: it is what you will group by later, so name it after your product ("support_reply", "summariser", "nightly_report"), not your code. Pass &lt;code&gt;audio_input=True&lt;/code&gt; when the prompt is audio — the wrapper cannot tell from the usage object which modality the prompt tokens were, so you declare it, exactly as the Claude wrapper asks you to declare the cache lifetime. If you send a voice note through the API and leave the default, the input column is priced at $0.30 instead of $1.00 and your log under-reports by two-thirds on that bucket.&lt;/p&gt;

&lt;h2&gt;
  
  
  Reading one log line
&lt;/h2&gt;

&lt;p&gt;After a few calls, &lt;code&gt;gemini_costs.jsonl&lt;/code&gt; holds lines shaped like the worked example above, with the numbers shown only to illustrate the shape of a record:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nl"&gt;"timestamp"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"2026-11-13T05:00:00+00:00"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nl"&gt;"feature"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"support_reply"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
 &lt;span class="nl"&gt;"model"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"gemini-2.5-flash"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nl"&gt;"latency_ms"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1840&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nl"&gt;"input_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;10000&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
 &lt;span class="nl"&gt;"cached_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;50000&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nl"&gt;"output_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
 &lt;span class="nl"&gt;"thinking_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2000&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nl"&gt;"tool_use_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nl"&gt;"cost_usd"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;0.012&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Read it from right to left. The cost is the headline, but the five token numbers are the diagnosis. Here thinking is double the visible output, which is normal on a reasoning model with a default thinking budget — but if &lt;code&gt;thinking_tokens&lt;/code&gt; ever runs ten times the visible answer on a one-line classification, the budget is doing work nobody asked for. If &lt;code&gt;cached_tokens&lt;/code&gt; sits near &lt;code&gt;input_tokens&lt;/code&gt; plus the cache, the cache is working; if it stays at zero while you keep sending the same long document, the cache never engaged — on the free tier it cannot, because context caching is a paid-tier feature, which is the first trap below. And if &lt;code&gt;tool_use_tokens&lt;/code&gt; climbs every turn, an agent loop is feeding tool results back into the prompt, and the cost of that loop belongs to the feature that owns it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Three Gemini traps that make logs lie
&lt;/h2&gt;

&lt;p&gt;The first trap is the thinking budget. Gemini 2.5 Flash reasons by default, and every thinking token bills at the $2.50 output rate while staying invisible in the answer. When a short reply suddenly costs what a long one used to, check the budget before blaming the model: pass &lt;code&gt;config=types.GenerateContentConfig(thinking_config=types.ThinkingConfig(thinking_budget=0))&lt;/code&gt; to switch thinking off, or a small number to cap it. The wrapper records the total honestly, because it reads the field the API returns — but it cannot tell you the budget was the problem unless you also log the config you sent, so keep the budget in the same place you keep the model ID.&lt;/p&gt;

&lt;p&gt;The second trap is the free tier, and the calendar. The same code costs exactly $0 on the free tier, which makes it tempting to treat the log's dollar column as decoration — until the day you upgrade to paid and identical traffic starts billing, with no code change and no warning in the log. Note the date you flip tiers next to the log file. The same kind of silent change arrives on 1 December 2026, when Google routes &lt;code&gt;gemini-2.5-flash&lt;/code&gt; requests to &lt;code&gt;gemini-3.5-flash-lite&lt;/code&gt; and &lt;code&gt;gemini-2.5-pro&lt;/code&gt; requests to &lt;code&gt;gemini-3.8-flash&lt;/code&gt;, billed at the new models' rates. The wrapper logs the model ID you asked for, not the one that answered, so after that date re-check the rates dict against Google's pricing page or your log will keep pricing a model you are no longer running. The same date logic applies to Pro's 200,000-token cliff: one token over the line reprices the whole prompt from $1.25 to $2.50 input and $10.00 to $15.00 output, which is why &lt;code&gt;_rates_for&lt;/code&gt; picks the band from the prompt size instead of trusting a single rate.&lt;/p&gt;

&lt;p&gt;The third trap is streaming. A streamed Gemini response does not hand you a complete &lt;code&gt;usage_metadata&lt;/code&gt; in the normal way: with &lt;code&gt;client.models.generate_content_stream&lt;/code&gt;, the usage object arrives on the final chunk only. Wrap a streaming call with the code above and log every chunk, and you count one call many times over — or log nothing at all, if you only read the first chunk. Collect the chunks, read usage from the last one, and log once.&lt;/p&gt;

&lt;h2&gt;
  
  
  Turn the log into a daily summary, not a spreadsheet
&lt;/h2&gt;

&lt;p&gt;A log file nobody reads is decoration. The wrapper earns its keep when a tiny script reads it once a day and tells you only what changed. Start with three summaries, and nothing more: total cost per feature for the last 24 hours, the ten most expensive single calls, and any feature whose daily cost doubled compared with its seven-day average. The first tells you where the money goes, the second tells you what to fix next, and the third is the early warning that catches a runaway job before the month ends.&lt;/p&gt;

&lt;p&gt;When a summary surprises you, the log already holds the feature, model, token split, and timestamp you need to act — and if the surprise is one user rather than one feature, the same per-call records feed directly into the &lt;a href="https://www.apicostlab.com/2026/11/stop-one-user-from-eating-your-ai.html" rel="noopener noreferrer"&gt;per-user spending guard&lt;/a&gt; we built for that exact problem. To sanity-check the totals against your own token mix, our &lt;a href="https://www.apicostlab.com/2026/10/ai-api-cost-calculator-estimate-your.html" rel="noopener noreferrer"&gt;AI API Cost Calculator&lt;/a&gt; lets you plug in your own numbers and compare them with what the log reports. Rates in this tutorial were verified 13 November 2026 on Google's Gemini API pricing page; re-check them before you budget, because Google changes them — the 1 December reroute is the live example.&lt;/p&gt;

&lt;p&gt;That measurement habit is the real point of this tutorial, and it completes the set: the OpenAI wrapper, the Claude wrapper, and now the Gemini one, all logging the same shape — one line per call, priced per bucket. Pricing pages tell you what a token costs; only your own log tells you what your app actually spends tokens on — and on Gemini, "what it spends" is five different numbers hiding inside two innocent-looking totals.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>llm</category>
      <category>tutorial</category>
      <category>gemini</category>
    </item>
    <item>
      <title>Anthropic Cost Tracking: Build a Claude Usage Logger in Python</title>
      <dc:creator>Hammad Malik</dc:creator>
      <pubDate>Sat, 21 Nov 2026 10:31:47 +0000</pubDate>
      <link>https://dev.to/hammad_malik_d39574d24320/anthropic-cost-tracking-build-a-claude-usage-logger-in-python-1e4h</link>
      <guid>https://dev.to/hammad_malik_d39574d24320/anthropic-cost-tracking-build-a-claude-usage-logger-in-python-1e4h</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://www.apicostlab.com/2026/11/anthropic-cost-tracking-build-claude.html" rel="noopener noreferrer"&gt;API Cost Lab&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Anthropic Cost Tracking: Build a Claude Usage Logger in Python
&lt;/h1&gt;

&lt;p&gt;&lt;em&gt;Last updated: November 2026&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Anthropic cost tracking is a small wrapper around your Claude API calls that records, for every single request, how many fresh input tokens you sent, how many tokens you paid to write into the prompt cache, how many you read back from it, how many output tokens the model produced, and what that request cost under the rates you configure. Put it between your code and the Anthropic client, log one line per call to a file, and the next time a number on the Claude Console looks wrong, you can point at the exact feature, user, or prompt that produced it. If you already built the &lt;a href="https://www.apicostlab.com/2026/10/openai-cost-tracking-middleware-build.html" rel="noopener noreferrer"&gt;OpenAI version of this wrapper&lt;/a&gt;, this is its Claude twin — the same sixty-line shape, but the usage object it reads is different in exactly the way that makes Claude bills confusing.&lt;/p&gt;

&lt;p&gt;That difference is the whole reason this tutorial exists. OpenAI reports one prompt-token count and tells you how many of those tokens were cached. Claude reports three separate input numbers, and each one is priced differently. Miss one of the three and your log quietly under-reports your bill — usually by the most expensive line on it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Claude splits your input three ways, and each way has its own price
&lt;/h2&gt;

&lt;p&gt;Every Claude Messages API response carries a &lt;code&gt;usage&lt;/code&gt; object with four token counts that matter for pricing: &lt;code&gt;input_tokens&lt;/code&gt; for fresh input, &lt;code&gt;cache_creation_input_tokens&lt;/code&gt; for tokens written into the prompt cache, &lt;code&gt;cache_read_input_tokens&lt;/code&gt; for tokens read back from it, and &lt;code&gt;output_tokens&lt;/code&gt; for everything the model generated. The first three are all "input", but Anthropic prices them as three different things. On Claude Sonnet 5.5, verified 10 November 2026 on Anthropic's pricing page, fresh input costs $2.00 per million tokens, a 5-minute cache write costs $2.50, a 1-hour write costs $4.00, and a cache read costs $0.10. Output is $10.00 per million.&lt;/p&gt;

&lt;p&gt;Take one call on Sonnet 5.5 with 10,000 fresh input tokens, a 50,000-token system prompt written to a 5-minute cache, 40,000 tokens read back from that cache, and 1,000 output tokens. The arithmetic on the published rates is: fresh input 10,000 × $2.00 ÷ 1,000,000 = $0.02; cache write 50,000 × $2.50 ÷ 1,000,000 = $0.125; cache read 40,000 × $0.10 ÷ 1,000,000 = $0.004; output 1,000 × $10.00 ÷ 1,000,000 = $0.01. Total: $0.159. The write alone is nearly eighty percent of the call, and it is the line most homemade loggers never record, because the field that carries it does not exist in OpenAI's usage object.&lt;/p&gt;

&lt;p&gt;Notice what the same call costs the first time it runs, before any cache exists: 60,000 fresh input tokens at $2.00 per million is $0.12, plus $0.01 of output, for $0.13. The cached call at $0.159 is dearer than the uncached one, because the write fee is paid before the read discount starts. That is the surcharge our &lt;a href="https://www.apicostlab.com/2026/11/cache-write-pricing-surcharge-you-pay.html" rel="noopener noreferrer"&gt;cache-write pricing investigation&lt;/a&gt; worked through in detail — the wrapper below is how you catch it happening on your own traffic instead of reading about it in an article.&lt;/p&gt;

&lt;h2&gt;
  
  
  The code: a wrapper you can drop in
&lt;/h2&gt;

&lt;p&gt;Install the SDK with &lt;code&gt;pip install anthropic&lt;/code&gt; and set &lt;code&gt;ANTHROPIC_API_KEY&lt;/code&gt; in your environment. Save the code below as &lt;code&gt;claude_tracker.py&lt;/code&gt; next to your app, and call &lt;code&gt;track_message()&lt;/code&gt; instead of calling the client directly. It appends one JSON line per call to &lt;code&gt;claude_costs.jsonl&lt;/code&gt;, stores no prompt or answer text, and returns the original response untouched, so the rest of your code does not change.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;datetime&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;datetime&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;timezone&lt;/span&gt;

&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;anthropic&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;Anthropic&lt;/span&gt;

&lt;span class="c1"&gt;# Rates per 1M tokens for Claude Sonnet 5.5, verified 10 November 2026&lt;/span&gt;
&lt;span class="c1"&gt;# on Anthropic's pricing page (docs.claude.com/en/docs/about-claude/pricing).&lt;/span&gt;
&lt;span class="c1"&gt;# If you use a different model, replace these with its row from that page.&lt;/span&gt;
&lt;span class="no"&gt;SONNET_55_RATES&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="s2"&gt;"input_per_million"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;2.00&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;           &lt;span class="c1"&gt;# fresh input tokens&lt;/span&gt;
    &lt;span class="s2"&gt;"cache_write_5m_per_million"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;2.50&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;  &lt;span class="c1"&gt;# 5-minute cache write&lt;/span&gt;
    &lt;span class="s2"&gt;"cache_write_1h_per_million"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;4.00&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;  &lt;span class="c1"&gt;# 1-hour cache write&lt;/span&gt;
    &lt;span class="s2"&gt;"cache_read_per_million"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;0.10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;      &lt;span class="c1"&gt;# cached input tokens read back&lt;/span&gt;
    &lt;span class="s2"&gt;"output_per_million"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;10.00&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;         &lt;span class="c1"&gt;# output tokens&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="n"&gt;client&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Anthropic&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# reads ANTHROPIC_API_KEY from the environment&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_cache_write_tokens&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""Cache write tokens, handling both the flat field and the
    breakdown object newer API versions return."""&lt;/span&gt;
    &lt;span class="n"&gt;direct&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;getattr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"cache_creation_input_tokens"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;direct&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;direct&lt;/span&gt;
    &lt;span class="n"&gt;breakdown&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;getattr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"cache_creation"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;breakdown&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="nb"&gt;getattr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;breakdown&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"ephemeral_5m_input_tokens"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nb"&gt;getattr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;breakdown&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"ephemeral_1h_input_tokens"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_cost_usd&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;rates&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cache_ttl&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"5m"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;fresh&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;input_tokens&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="n"&gt;write&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;_cache_write_tokens&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;read&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;getattr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"cache_read_input_tokens"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="n"&gt;output&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;output_tokens&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="n"&gt;write_rate&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;rates&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"cache_write_1h_per_million"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;cache_ttl&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;"1h"&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="n"&gt;rates&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"cache_write_5m_per_million"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;cost&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;fresh&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;rates&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"input_per_million"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;write&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;write_rate&lt;/span&gt;
        &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;read&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;rates&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"cache_read_per_million"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;output&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;rates&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"output_per_million"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;1_000_000&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;fresh&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;write&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;read&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;output&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cost&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;track_message&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;messages&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;feature&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"unknown"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                  &lt;span class="n"&gt;rates&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="no"&gt;SONNET_55_RATES&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cache_ttl&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"5m"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="n"&gt;kwargs&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""Drop-in replacement for client.messages.create."""&lt;/span&gt;
    &lt;span class="n"&gt;started&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;monotonic&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;messages&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;messages&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;messages&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="n"&gt;kwargs&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;latency_ms&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;monotonic&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;started&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="n"&gt;record&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="s2"&gt;"timestamp"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;datetime&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;timezone&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;utc&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;isoformat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"feature"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;feature&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"model"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"latency_ms"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;latency_ms&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="n"&gt;usage&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;getattr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"usage"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;usage&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;fresh&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;write&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;read&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;output&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cost&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;_cost_usd&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;rates&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cache_ttl&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;record&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="s2"&gt;"input_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;fresh&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"cache_write_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;write&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"cache_read_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;read&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"output_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;output&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"cost_usd"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cost&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;record&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"note"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"no usage object returned"&lt;/span&gt;

    &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"claude_costs.jsonl"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"a"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;write&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dumps&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;record&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s2"&gt;"\n"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using it is one line different from a normal call. Replace &lt;code&gt;client.messages.create(model=..., messages=...)&lt;/code&gt; with &lt;code&gt;track_message("your-model-id", messages, feature="support_reply", max_tokens=1024)&lt;/code&gt; — the Messages API requires &lt;code&gt;max_tokens&lt;/code&gt;, so pass it through as before. The &lt;code&gt;feature&lt;/code&gt; label is the most important parameter in the file: it is what you will group by later, so name it after your product ("support_reply", "summariser", "nightly_report"), not your code.&lt;/p&gt;

&lt;p&gt;One parameter deserves a second look: &lt;code&gt;cache_ttl&lt;/code&gt;. The usage object tells you how many tokens were written to the cache, but not which lifetime you asked for, and a 1-hour write costs 60 percent more than a 5-minute one on Sonnet 5.5. The wrapper cannot detect the lifetime, so you declare it: pass &lt;code&gt;cache_ttl="1h"&lt;/code&gt; when your request set a one-hour cache breakpoint, and leave the default when it did not. If you get this wrong, the token counts stay right and only the dollar column is off — which is still better than not logging the write at all, the mistake this wrapper exists to prevent.&lt;/p&gt;

&lt;h2&gt;
  
  
  Reading one log line
&lt;/h2&gt;

&lt;p&gt;After a few calls, &lt;code&gt;claude_costs.jsonl&lt;/code&gt; holds lines shaped like the worked example above, with the numbers shown only to illustrate the shape of a record:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nl"&gt;"timestamp"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"2026-11-10T05:00:00+00:00"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nl"&gt;"feature"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"support_reply"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
 &lt;span class="nl"&gt;"model"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"your-model-id"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nl"&gt;"latency_ms"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2130&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nl"&gt;"input_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;10000&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
 &lt;span class="nl"&gt;"cache_write_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;50000&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nl"&gt;"cache_read_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;40000&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
 &lt;span class="nl"&gt;"output_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nl"&gt;"cost_usd"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;0.159&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Read it from right to left. The cost is the headline, but the three input numbers are the diagnosis. Here the write dwarfs everything else, which is expected on a first call that fills the cache — the next call on the same prompt should show the write near zero and the read near 50,000, dropping the same request to roughly $0.034. If instead the write stays high day after day, the cache is never being hit: something is changing the prompt prefix on every call, perhaps a timestamp or a user ID injected at the top, and every call is paying the write fee for a discount it never collects. That pattern is invisible on the Console, where the three input buckets are folded into one total, and it is the single most valuable thing this log will ever show you.&lt;/p&gt;

&lt;h2&gt;
  
  
  Two Claude-specific traps that make logs lie
&lt;/h2&gt;

&lt;p&gt;The first trap is extended thinking. If you enable thinking on a Claude call, the tokens the model spends thinking are billed as output tokens — they arrive inside &lt;code&gt;output_tokens&lt;/code&gt;, not as a separate field. A short-looking answer can therefore carry a long hidden output count, exactly like the &lt;a href="https://www.apicostlab.com/2026/11/reasoning-tokens-invisible-output.html" rel="noopener noreferrer"&gt;reasoning tokens we investigated on OpenAI&lt;/a&gt;. The wrapper records the total honestly, because it reads the field the API returns, but if you ever wonder why a feature's output column doubled overnight, check whether someone turned thinking on before blaming the model or the prompt.&lt;/p&gt;

&lt;p&gt;The second trap is streaming. A streamed Claude response does not hand you a complete usage object in the normal way. With the Python SDK, wrap the call in the streaming helper and read the usage from the final message: &lt;code&gt;with client.messages.stream(model=..., messages=..., max_tokens=...) as stream: message = stream.get_final_message()&lt;/code&gt;, then pass &lt;code&gt;message.usage&lt;/code&gt; through the same &lt;code&gt;_cost_usd&lt;/code&gt; function. If you wrap a streaming call with the code above and never see usage, that is why — the stream simply never sent the numbers to the place you looked. Never log per chunk: you would count one call many times over, and your totals would be fiction.&lt;/p&gt;

&lt;h2&gt;
  
  
  Turn the log into a daily summary, not a spreadsheet
&lt;/h2&gt;

&lt;p&gt;A log file nobody reads is decoration. The wrapper earns its keep when a tiny script reads it once a day and tells you only what changed. Start with three summaries, and nothing more: total cost per feature for the last 24 hours, the ten most expensive single calls, and any feature whose daily cost doubled compared with its seven-day average. The first tells you where the money goes, the second tells you what to fix next, and the third is the early warning that catches a runaway job before the month ends.&lt;/p&gt;

&lt;p&gt;When a summary surprises you, the log already holds the feature, model, token split, and timestamp you need to act — and if the surprise is one user rather than one feature, the same per-call records feed directly into the &lt;a href="https://www.apicostlab.com/2026/11/stop-one-user-from-eating-your-ai.html" rel="noopener noreferrer"&gt;per-user spending guard&lt;/a&gt; we built for that exact problem. To sanity-check the totals against your own token mix, our &lt;a href="https://www.apicostlab.com/2026/10/ai-api-cost-calculator-estimate-your.html" rel="noopener noreferrer"&gt;AI API Cost Calculator&lt;/a&gt; lets you plug in your own numbers and compare them with what the log reports.&lt;/p&gt;

&lt;p&gt;That measurement habit is the real point of this tutorial. Pricing pages tell you what a token costs; only your own log tells you what your app actually spends tokens on — and on Claude, "what it spends" is three different input prices hiding inside one total. Build the wrapper this week, let it run for seven days without changing anything else, and read the per-feature summary before you change a single prompt or model. The numbers will almost certainly surprise you, and unlike a dashboard total, they will tell you exactly what to do next.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Rates in this tutorial were verified 10 November 2026 on Anthropic's pricing documentation (docs.claude.com/en/docs/about-claude/pricing). Usage fields follow Anthropic's Messages API: &lt;code&gt;input_tokens&lt;/code&gt;, &lt;code&gt;cache_creation_input_tokens&lt;/code&gt;, &lt;code&gt;cache_read_input_tokens&lt;/code&gt;, and &lt;code&gt;output_tokens&lt;/code&gt; on the response usage object. Rates change — re-check the pricing page whenever you change models, and never trust a dollar figure copied from a tutorial over the provider's own page.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>ai</category>
      <category>llm</category>
      <category>tutorial</category>
      <category>anthropic</category>
    </item>
    <item>
      <title>Cache Write Pricing: The Surcharge You Pay Before Prompt Caching Saves You Anything</title>
      <dc:creator>Hammad Malik</dc:creator>
      <pubDate>Thu, 19 Nov 2026 10:31:46 +0000</pubDate>
      <link>https://dev.to/hammad_malik_d39574d24320/cache-write-pricing-the-surcharge-you-pay-before-prompt-caching-saves-you-anything-1ed8</link>
      <guid>https://dev.to/hammad_malik_d39574d24320/cache-write-pricing-the-surcharge-you-pay-before-prompt-caching-saves-you-anything-1ed8</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://www.apicostlab.com/2026/11/cache-write-pricing-surcharge-you-pay.html" rel="noopener noreferrer"&gt;API Cost Lab&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Cache Write Pricing: The Surcharge You Pay Before Prompt Caching Saves You Anything
&lt;/h1&gt;

&lt;p&gt;&lt;em&gt;Last updated: November 2026&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Prompt caching is sold as a 90% discount, and the discount is real — but it is the second price on the bill, not the first. Before a single cached token is read back at the cheap rate, the provider charges you to write the cache, at 1.25 times the normal input price for a short-lived cache and two to two-and-a-half times for a long-lived one. If the cached prompt is never read again, or only after the cache has expired, you paid more than if you had never turned caching on at all. The discount is real. So is the entry fee.&lt;/p&gt;

&lt;h2&gt;
  
  
  Caching has two prices, not one
&lt;/h2&gt;

&lt;p&gt;Every caching story quotes the read price: cached tokens at a tenth, or a twentieth, of the standard input rate. Almost nobody quotes the write price — it sits in a different column of the pricing page. The first time you send a prompt, the provider processes it at the normal input rate and stores the result — and that storage step is billed separately, as cache write tokens. Every later call that reuses the same prompt pays the cheap cache read rate instead. One price to put the prompt in the fridge, a much lower price to take it out again.&lt;/p&gt;

&lt;p&gt;Both providers publish the write price openly. Anthropic states it as multipliers: a 5-minute write costs 1.25 times base input, a 1-hour write twice, and a cache read a tenth — a twentieth on Opus 5.5 and Sonnet 5.5. OpenAI lists it per model: a 30-minute write is 1.25 times input, a 12-hour write 2.5 times, and a cached read 5 percent of input. Same idea, different numbers.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Per 1M tokens&lt;/th&gt;
&lt;th&gt;Base input&lt;/th&gt;
&lt;th&gt;Short write&lt;/th&gt;
&lt;th&gt;Long write&lt;/th&gt;
&lt;th&gt;Cached read&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;GPT-6.1 Sol (OpenAI)&lt;/td&gt;
&lt;td&gt;$2.00&lt;/td&gt;
&lt;td&gt;$2.50 (30 min)&lt;/td&gt;
&lt;td&gt;$5.00 (12 hr)&lt;/td&gt;
&lt;td&gt;$0.10&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Claude Sonnet 5.5 (Anthropic)&lt;/td&gt;
&lt;td&gt;$2.00&lt;/td&gt;
&lt;td&gt;$2.50 (5 min)&lt;/td&gt;
&lt;td&gt;$4.00 (1 hr)&lt;/td&gt;
&lt;td&gt;$0.10&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The pattern holds across each provider's whole model line: short writes are always 1.25 times base input; the long write is 2.5 times on OpenAI, twice on Anthropic. The workhorse models above are the ones most developers run, so the rest of this article prices everything on them. Our &lt;a href="https://www.apicostlab.com/2026/10/prompt-caching-90-discount-youre-missing.html" rel="noopener noreferrer"&gt;prompt caching guide&lt;/a&gt; shows how to win the read discount; this article is about the price you pay before it does.&lt;/p&gt;

&lt;h2&gt;
  
  
  The break-even math on a 100,000-token prompt
&lt;/h2&gt;

&lt;p&gt;Take a coding assistant with a 100,000-token system prompt and repository context, sent unchanged on every call. Uncached, that prompt costs 100,000 × $2.00 ÷ 1,000,000 = $0.20 per call on either workhorse model.&lt;/p&gt;

&lt;p&gt;On a short-lived cache, the first call writes the prompt at $2.50 per million tokens: 100,000 × $2.50 ÷ 1,000,000 = $0.25. Each later read costs $0.01. So the write plus one read is $0.26, against two plain calls at $0.40. You are ahead after a single read — exactly as Anthropic's pricing page promises.&lt;/p&gt;

&lt;p&gt;On Anthropic's 1-hour cache, the first call writes at $4.00 per million: $0.40 for the same tokens. Reads are still $0.01, so the write plus two reads is $0.42 against three plain calls at $0.60 — ahead after two reads, as Anthropic publishes. On OpenAI's 12-hour cache the write is $5.00 per million, so the first call costs $0.50; the write plus two reads is $0.52 against three plain calls at $0.60 — it also breaks even after two reads, but the first call costs two and a half times a plain call.&lt;/p&gt;

&lt;p&gt;Notice the sting in every one of those sums. The write alone is always dearer than the plain call it replaces: $0.25 instead of $0.20 on a short cache, $0.40 or $0.50 instead of $0.20 on a long one. Caching is a bet that the same prompt will be reused inside the cache lifetime, placed again each time the entry expires. Win the bet and the read discount swamps the write fee within one or two calls; lose it and you paid a premium for nothing.&lt;/p&gt;

&lt;h2&gt;
  
  
  Three ways the write fee makes your bill worse
&lt;/h2&gt;

&lt;p&gt;The first way is the one-shot document. Send a 200,000-token contract through Claude Sonnet 5.5 once, with caching left on, and the 1-hour write costs 200,000 × $4.00 ÷ 1,000,000 = $0.80. The same tokens as plain input cost $0.40 — you doubled the input bill on a prompt never read again. Even the 5-minute write costs $0.50 against $0.40, a 25 percent surcharge for a feature that saved nothing. If a prompt is used once, the write fee is pure loss, and the loss grows with the size of the prompt.&lt;/p&gt;

&lt;p&gt;The second way is sparse traffic and an expiring cache. Picture a support chatbot where sessions arrive minutes apart and the cache lifetime is five minutes. The cache expires between requests, so every call writes the prompt again at 1.25 times input and no call ever gets a read. At 1,000 calls a day on the 100,000-token prompt, that is 1,000 × $0.25 = $250 a day against $200 uncached — $50 a day, $1,500 a month, extra. The same traffic on OpenAI's 12-hour write is worse: 1,000 × $0.50 = $500 a day against $200 uncached, two and a half times the plain bill, for a feature marketed as a discount. A cache lifetime has to match your traffic rhythm: a five-minute cache on traffic that arrives every ten minutes is not a discount, it is a 25 percent surcharge on every call.&lt;/p&gt;

&lt;p&gt;The third way is the churning prefix. Caches match on the exact prefix of the prompt, so change anything near the top and the match breaks — the whole block is written again at the write price. A prompt that starts with a timestamp, a rotating date, or a per-user greeting never matches anything: every call pays the write fee and none ever gets a read. Appending to the end is fine — only the new tokens are written — but anything that rewrites the beginning re-buys the entire cached block at 1.25 to 2.5 times the input rate, on every call. If your template puts something unique first, caching is silently charging you extra on every request.&lt;/p&gt;

&lt;h2&gt;
  
  
  Gemini charges rent instead of a write fee
&lt;/h2&gt;

&lt;p&gt;Google does the same job with a different mechanism, and it changes where the trap sits. On Gemini 4 Argon, caching is implicit only: Google decides what gets cached, and cached reads cost $0.10 per million tokens against a $2.00 input price through November 30, 2026 ($0.20 against $4.00 from December 1). There is no write surcharge to watch for — but no control over what is cached or for how long, either.&lt;/p&gt;

&lt;p&gt;On Gemini 3.8 Flash, the charge is storage rent: $0.50 per million tokens per hour to keep a cache alive through December 31, 2026, doubling to $1.00 from January 1, 2027. A 200,000-token cache held for a day costs 0.2 × $0.50 × 24 = $2.40 in storage alone, before a single read — $4.80 a day from January. The reads are cheap, at $0.075 per million tokens, but the meter runs while the cache sits idle. Three providers, three mechanisms, one lesson: the cheap read always has a price attached before it, whether that price is a write fee or rent.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to tell whether caching is helping you
&lt;/h2&gt;

&lt;p&gt;Start by logging write tokens and read tokens as separate columns, not one total. Anthropic's usage object reports them as &lt;code&gt;cache_creation_input_tokens&lt;/code&gt; and &lt;code&gt;cache_read_input_tokens&lt;/code&gt;; OpenAI reports cached tokens in &lt;code&gt;prompt_tokens_details.cached_tokens&lt;/code&gt;. Our &lt;a href="https://www.apicostlab.com/2026/10/openai-cost-tracking-middleware-build.html" rel="noopener noreferrer"&gt;cost-tracking middleware tutorial&lt;/a&gt; shows how to log one line per call with the full usage breakdown — extend it to record cache writes and reads separately, and the question answers itself.&lt;/p&gt;

&lt;p&gt;Then run this test over a week of traffic for each feature: add up what the writes cost and what the reads saved against plain input pricing. If the writes cost more than the reads saved, caching is losing money on that feature — turn it off there and keep it where it wins. The ratio that matters is reads per write, and the thresholds are now yours to check: one read repays a short write, two repay a long one. Anything below that is a surcharge with a discount label on it.&lt;/p&gt;

&lt;p&gt;Finally, match the lifetime to the traffic: a busy endpoint with the same prompt repeated inside minutes wants the short cache; a quiet endpoint where calls arrive hours apart wants no cache at all, unless the reads are guaranteed. And before assuming the 90 percent headline applies to your workload, run your own prompt size and daily call count through our &lt;a href="https://www.apicostlab.com/2026/10/ai-api-cost-calculator-estimate-your.html" rel="noopener noreferrer"&gt;AI API Cost Calculator&lt;/a&gt; — the same habit behind our &lt;a href="https://www.apicostlab.com/2026/11/stop-one-user-from-eating-your-ai.html" rel="noopener noreferrer"&gt;per-user spending guard&lt;/a&gt; and the &lt;a href="https://www.apicostlab.com/2026/11/reasoning-tokens-invisible-output.html" rel="noopener noreferrer"&gt;reasoning-token investigation&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The 90 percent discount is real, and for the right workload it is the biggest saving on the bill. But it is a discount on reads, and reads are the second half of the transaction. The first half is a write at a premium: 25 percent more for a short cache, double or two and a half times for a long one. Count the writes, match the lifetime to your traffic, and caching pays for itself in a single read. Skip that, and the discount feature quietly becomes the most expensive line on the invoice.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Rates verified 6 November 2026 on OpenAI's API pricing page, Anthropic's Claude Platform pricing documentation, and Google's Gemini API pricing page. All worked figures are arithmetic on those published rates. Our &lt;a href="https://www.apicostlab.com/2026/10/is-claude-cheaper-than-gpt-the-honest-math.html" rel="noopener noreferrer"&gt;Claude vs GPT comparison&lt;/a&gt; covers the same two models tier by tier.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>ai</category>
      <category>llm</category>
      <category>openai</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Reasoning Tokens: The Invisible Output Tokens Eating Your OpenAI Bill</title>
      <dc:creator>Hammad Malik</dc:creator>
      <pubDate>Tue, 17 Nov 2026 10:31:11 +0000</pubDate>
      <link>https://dev.to/hammad_malik_d39574d24320/reasoning-tokens-the-invisible-output-tokens-eating-your-openai-bill-31m1</link>
      <guid>https://dev.to/hammad_malik_d39574d24320/reasoning-tokens-the-invisible-output-tokens-eating-your-openai-bill-31m1</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://www.apicostlab.com/2026/11/reasoning-tokens-invisible-output.html" rel="noopener noreferrer"&gt;API Cost Lab&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Reasoning Tokens: The Invisible Output Tokens Eating Your OpenAI Bill
&lt;/h1&gt;

&lt;p&gt;&lt;em&gt;Last updated: November 2026&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Here is the direct answer: when you call one of OpenAI's reasoning models, the model thinks before it answers, and that thinking is billed as output tokens — even though you never see a single one of those tokens. OpenAI's own reasoning guide says it plainly: reasoning tokens are not visible via the API, they still occupy space in the model's context window, and they are billed as output tokens. If your bill for a reasoning model looks far too high for the short answers you received, this is almost certainly why. You were not charged for the answer. You were charged for the thinking that produced it, at the most expensive rate on the price list.&lt;/p&gt;

&lt;h2&gt;
  
  
  The bill that does not add up
&lt;/h2&gt;

&lt;p&gt;OpenAI's reasoning guide contains a small usage example that explains more about real bills than most pricing pages do. A request sends 75 input tokens and gets back 1,186 output tokens. That already looks odd for a short answer, and the breakdown explains why: of those 1,186 output tokens, 1,024 are reasoning tokens. Only 162 tokens are the visible answer. The model did roughly six times more thinking than writing, and every one of those 1,024 thinking tokens is billed at the output rate.&lt;/p&gt;

&lt;p&gt;This is not a rounding error or an edge case. It is the normal behaviour of reasoning models. Before producing a response, the model generates internal reasoning tokens to plan, consider alternatives, and work through a problem step by step. The API does not return that reasoning text. What it returns is the final answer, plus a usage object that quietly records how much thinking happened. Developers who only look at the answer — the text their app displays — see a 162-token reply and expect a 162-token charge. The invoice says 1,186.&lt;/p&gt;

&lt;p&gt;The gap gets worse with harder tasks. OpenAI's guide says a request may generate anywhere from a few hundred to tens of thousands of reasoning tokens, depending on the problem's complexity. A simple classification question might think for a few hundred tokens. A multi-step coding or research task can think for tens of thousands before writing anything. The harder the task you hand a reasoning model, the larger the share of your bill becomes invisible.&lt;/p&gt;

&lt;h2&gt;
  
  
  Worked math: what the invisible part actually costs
&lt;/h2&gt;

&lt;p&gt;Take the guide's own example and price it on gpt-6.1-sol, whose standard rates on OpenAI's pricing page are $2.00 per million input tokens and $10.00 per million output tokens. The arithmetic is straightforward, and every number below comes from those two published rates and the guide's own token counts.&lt;/p&gt;

&lt;p&gt;The output charge is 1,186 tokens × $10.00 ÷ 1,000,000 = $0.01186. The reasoning share of that is 1,024 × $10.00 ÷ 1,000,000 = $0.01024. The visible answer, priced alone, is 162 × $10.00 ÷ 1,000,000 = $0.00162. So 86 percent of the output bill — $0.01024 of $0.01186 — pays for thinking you never saw, and the answer you actually received costs about one-seventh of what you paid for the call's output.&lt;/p&gt;

&lt;p&gt;Now scale the thinking up to the size OpenAI itself tells developers to plan for. The guide recommends reserving at least 25,000 tokens for reasoning and outputs when you start experimenting with these models. A call that uses the full 25,000-token reserve as reasoning costs 25,000 × $10.00 ÷ 1,000,000 = $0.25 in reasoning alone, before a single visible word. That is one call. Ten thousand such calls — an ordinary month for a small production feature — would be $2,500 of reasoning tokens. These are not measured bills from a real app; they are the guide's own reserve figure multiplied by the published output rate, shown so you can see how fast invisible tokens compound. The point is the multiplier: output tokens cost five times input tokens on this model, and reasoning tokens are billed at the output rate, not the input rate. Invisible thinking is charged at the most expensive price the model has.&lt;/p&gt;

&lt;h2&gt;
  
  
  Three traps the usage object hides
&lt;/h2&gt;

&lt;p&gt;The first trap is the one above: invisibility. Nothing in the answer itself hints at how much thinking happened. Two answers of identical length can cost wildly different amounts, because one took 300 reasoning tokens and the other took 30,000. If your code logs only the visible text, or only total tokens, you cannot tell them apart. The fix is to read the field OpenAI actually provides: &lt;code&gt;output_tokens_details.reasoning_tokens&lt;/code&gt; in the usage object. Our &lt;a href="https://www.apicostlab.com/2026/10/openai-cost-tracking-middleware-build.html" rel="noopener noreferrer"&gt;cost-tracking middleware tutorial&lt;/a&gt; shows how to log one line per call with the full usage breakdown — extend it to record reasoning tokens separately, and the invisible line on your bill becomes a column you can sort.&lt;/p&gt;

&lt;p&gt;The second trap is the output cap. The &lt;code&gt;max_output_tokens&lt;/code&gt; parameter limits everything the model generates: reasoning tokens, visible answer tokens, and non-visible formatting tokens together. OpenAI's guide warns that if generation hits the cap, you get a response marked incomplete — and that this can happen before any visible output tokens are produced. Read that carefully: you can pay for the input and for thousands of reasoning tokens and receive nothing usable at all. A low output cap on a reasoning model does not save money the way it does on a chat model; it creates paid calls that return no answer. Set the cap with the reasoning reserve in mind, not the answer length you expect.&lt;/p&gt;

&lt;p&gt;The third trap is the default effort. Reasoning models expose a &lt;code&gt;reasoning.effort&lt;/code&gt; setting — none, minimal, low, medium, high, xhigh, and max depending on the model — and the default is not "as little as possible." GPT-5.5, for example, defaults to medium effort. GPT-5.6 and GPT-6 models add a separate &lt;code&gt;pro&lt;/code&gt; reasoning mode that performs more model work than standard mode, billed at the model's standard token rates. If you never touch these settings, you are running at a middle-to-high thinking budget on every call, including the easy ones. And on GPT-5.6 models, the default reasoning context setting renders reasoning from earlier turns into the next sample, so a long conversation carries its earlier thinking forward as context. None of this is wrong — it is how reasoning models earn their quality — but every default here points toward more thinking, and more thinking is billed at the output rate.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to keep reasoning tokens from eating your bill
&lt;/h2&gt;

&lt;p&gt;Start by measuring the ratio, not the total. For each feature, log reasoning tokens and visible output tokens separately for a week, and compute the reasoning share the way the worked example above does. A feature with a reasoning share above 80 percent is a feature where the model is doing far more thinking than writing; that is where effort tuning pays. A feature with a low, stable share is fine at its current setting. This is the same measure-first discipline behind our &lt;a href="https://www.apicostlab.com/2026/11/stop-one-user-from-eating-your-ai.html" rel="noopener noreferrer"&gt;per-user spending guard&lt;/a&gt;: you cannot control a cost line you cannot see, and reasoning tokens are the least visible line on an OpenAI invoice.&lt;/p&gt;

&lt;p&gt;Then match effort to the task, deliberately. Use minimal or low effort for classification, extraction, and simple lookups — tasks where the answer is short and the thinking should be too. Reserve medium and high effort for the genuinely hard work: debugging, planning, and multi-step agentic tasks. OpenAI's own guidance says lower effort favours speed and lower token usage, while higher effort is for cases where quality justifies the extra latency and cost. Test the lower setting first and only raise it when your own evaluation shows a clear quality gain, not because the default felt safe.&lt;/p&gt;

&lt;p&gt;Finally, treat reasoning tokens as part of the price of the model, not as an overhead to ignore. When you compare a reasoning model against a non-reasoning one, do not compare output rates alone — compare the full output line, reasoning included, for the same task. That comparison is the honest version of the argument in our &lt;a href="https://www.apicostlab.com/2026/11/ai-api-pricing-is-broken-per-token.html" rel="noopener noreferrer"&gt;piece on why per-token pricing misleads&lt;/a&gt;: you pay for effort, not results, and reasoning tokens are the purest form of that. The models are worth their price when the thinking improves the answer. The gotcha is only that the thinking is billed invisibly, at the output rate, whether or not you ever look at the usage object. Once you do look, the bill stops being a mystery — and the effort dial becomes the cheapest optimisation you have. Our &lt;a href="https://www.apicostlab.com/2026/10/openai-api-pricing-explained-every.html" rel="noopener noreferrer"&gt;OpenAI pricing guide&lt;/a&gt; lists the current rates to run this math against for the model you actually use.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>llm</category>
      <category>openai</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>AI API Pricing Is Broken: Per-Token Billing Charges You for the Wrong Thing</title>
      <dc:creator>Hammad Malik</dc:creator>
      <pubDate>Sun, 15 Nov 2026 10:31:21 +0000</pubDate>
      <link>https://dev.to/hammad_malik_d39574d24320/ai-api-pricing-is-broken-per-token-billing-charges-you-for-the-wrong-thing-546h</link>
      <guid>https://dev.to/hammad_malik_d39574d24320/ai-api-pricing-is-broken-per-token-billing-charges-you-for-the-wrong-thing-546h</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://www.apicostlab.com/2026/11/ai-api-pricing-is-broken-per-token.html" rel="noopener noreferrer"&gt;API Cost Lab&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  AI API Pricing Is Broken: Per-Token Billing Charges You for the Wrong Thing
&lt;/h1&gt;

&lt;p&gt;&lt;em&gt;Last updated: November 2026&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Per-token pricing is the wrong unit for AI APIs. It charges you for effort, not for results — for every token a model burns on the way to an answer, including the tokens you never see, the retries that failed, and the words a rambling answer didn't need. The fix is not a cheaper token. It is a different unit: price per finished task, not per token spent getting there.&lt;/p&gt;

&lt;p&gt;That sounds like a small accounting complaint. It isn't. The unit you pay by decides what you optimise for, what you fear, and what your provider is rewarded for. Right now, all three point the wrong way.&lt;/p&gt;

&lt;h2&gt;
  
  
  You pay for the journey, not the arrival
&lt;/h2&gt;

&lt;p&gt;Think of a taxi ride. You pay for arriving, with the meter as a rough proxy for distance. Now imagine a taxi that charged per turn of the wheels — extra when the driver took a wrong turn, circled the block, or sat thinking at a junction with the engine running. That is how an AI API bill works today.&lt;/p&gt;

&lt;p&gt;Every call is metered in tokens, and a token is not a unit of value. It is a chunk of text, roughly part of a word. You are billed for the prompt you send, for the answer you receive, and for everything the model generates in between — including work that produces nothing you can use. A call that fails halfway still costs you the tokens it consumed. An agent loop that retries a step five times bills you five times for one job. A model that answers in 400 words costs roughly twice as much as one that answers the same question correctly in 200. The meter runs on effort, and effort is the one thing you cannot see or control in advance.&lt;/p&gt;

&lt;p&gt;This was tolerable when an API call was one prompt and one answer. It is not tolerable now that a single user request can set off a chain of dozens of calls, each feeding the next, with the total unknown until the chain stops. Our &lt;a href="https://www.apicostlab.com/2026/10/why-is-my-openai-api-bill-so-high.html" rel="noopener noreferrer"&gt;bill-diagnosis checklist&lt;/a&gt; walks through the usual ways a bill runs away, and nearly all of them are the same story: a loop nobody capped, a prompt nobody trimmed, a retry nobody counted. Per-token pricing turns every one of those slips into money, silently, at machine speed.&lt;/p&gt;

&lt;h2&gt;
  
  
  Exhibit one: the tokens you never see
&lt;/h2&gt;

&lt;p&gt;The clearest proof that the token is the wrong unit is the reasoning token. When a reasoning model works through a hard problem, it generates an internal draft — its working-out — before producing the answer you actually read. OpenAI's own documentation says those reasoning tokens are not visible through the API, but they still occupy context space and are billed as output tokens, at the output price.&lt;/p&gt;

&lt;p&gt;Read that again: the most expensive tokens on the bill are the ones you are not allowed to read. The same documentation notes that a model may generate anywhere from a few hundred to tens of thousands of reasoning tokens for one problem. You asked for a short answer and paid for a hidden essay you will never see.&lt;/p&gt;

&lt;p&gt;Reasoning effort settings make the absurdity explicit. Turn the effort dial up and the same question, with the same correct answer, costs more — because the model was allowed to think longer. The answer didn't change. The value didn't change. Only the amount of invisible work changed, and the meter charges for invisible work at the highest rate on the price sheet. A unit that bills you more for the same answer, depending on a dial you set blind, is not measuring value. It is measuring its own process.&lt;/p&gt;

&lt;h2&gt;
  
  
  Exhibit two: the same answer at five different prices
&lt;/h2&gt;

&lt;p&gt;If the token were a real unit of value, the same answer would cost the same. It doesn't — not even close. The price of an identical response swings wildly depending on plumbing choices that have nothing to do with what you received.&lt;/p&gt;

&lt;p&gt;Send a prompt whose beginning matches a cached prefix and, on Anthropic's published terms, those tokens are read back at a tenth of the standard input price. Write a new cache entry and the same tokens cost a quarter more than standard on a five-minute lifetime, or double on a one-hour lifetime. Send the work through a batch queue instead of in real time and every token is discounted by half, because you waited. Same model, same prompt, same answer — and the bill can differ several-fold based on timing, cache state, and queue choice.&lt;/p&gt;

&lt;p&gt;None of these discounts is a bad thing. Caching and batching are genuinely useful, and providers deserve credit for pricing them. But notice what they reveal: the price already depends on everything except the value of the answer — on whether you waited, whether your prefix matched, whether your cache was warm. The token is not a unit of output. It is a unit of compute with a loyalty scheme bolted on, and every discount is an admission that the headline meter doesn't reflect what the work is worth.&lt;/p&gt;

&lt;h2&gt;
  
  
  Exhibit three: verbosity pays, and that should worry you
&lt;/h2&gt;

&lt;p&gt;The deepest problem is the incentive the meter creates. Under per-token pricing, a provider earns more when its model says more. A model that answers in a tight paragraph bills less than a model that pads the same answer into five paragraphs. A model that reasons at length bills more than one that reasons efficiently. The meter rewards wordiness and wandering, and punishes exactly the qualities you want: brevity, precision, and getting it right the first time.&lt;/p&gt;

&lt;p&gt;You would never accept this deal anywhere else. You don't pay a plumber per turn of the wrench, or a lawyer per word of the contract, precisely because you know what happens next: more turns, more words. Yet AI — the tool where output length is most directly under the supplier's control — is priced by the word, and we act surprised when bills grow with verbosity.&lt;/p&gt;

&lt;p&gt;Defenders of the token will say it is the only fair meter, because it tracks real compute. That is true and beside the point. Compute is the provider's cost, not the customer's value. A restaurant's costs are ingredients and labour, but it charges per meal, not per gram of flour and minute of stove time — because the customer buys a meal. The token meter confuses the provider's cost ledger with the customer's purchase, and then makes the customer audit the ledger line by line to understand a bill.&lt;/p&gt;

&lt;h2&gt;
  
  
  What the right unit looks like
&lt;/h2&gt;

&lt;p&gt;The honest replacement is price per finished task. A summarised document. A resolved support ticket. A passing test suite. A completed research brief, with the model allowed to choose how much thinking, retrying, and tool use that takes — because the thinking is the provider's problem, not yours.&lt;/p&gt;

&lt;p&gt;Providers are already inching toward it. A batch discount is, in effect, a price for patience rather than a price for tokens. A cached-read discount is a price for repetition. And Anthropic's own cost guidance now frames optimisation in terms of cost per completed task rather than cost per token, because the token stops being informative once work becomes multi-step.&lt;/p&gt;

&lt;p&gt;Task pricing would also fix the incentives overnight. A provider selling finished tasks would want its models concise, efficient, and right the first time — because every wasted token would eat its own margin instead of inflating your bill. Verbosity would become a cost to the seller, not a revenue stream. That single flip is worth more than any discount a token price sheet will ever offer.&lt;/p&gt;

&lt;h2&gt;
  
  
  What to do until the unit changes
&lt;/h2&gt;

&lt;p&gt;The token meter is not going away this quarter, so the practical move is to stop budgeting in tokens and start budgeting in tasks. Measure what a completed job costs you, per feature, and let that number — not the token count — drive your decisions.&lt;/p&gt;

&lt;p&gt;That starts with logging the usage object on every call, including the reasoning and cache fields providers already report, so you can see where the meter actually runs. Our &lt;a href="https://www.apicostlab.com/2026/10/openai-cost-tracking-middleware-build.html" rel="noopener noreferrer"&gt;cost-tracking middleware tutorial&lt;/a&gt; shows how to build that logging in an afternoon. Then put a guard in front of spending so one user or one loop cannot turn a meter into a flood: our &lt;a href="https://www.apicostlab.com/2026/11/stop-one-user-from-eating-your-ai.html" rel="noopener noreferrer"&gt;per-user spending guard&lt;/a&gt; refuses a call before it is made when a budget is already spent. And when you compare options, run your own numbers through our &lt;a href="https://www.apicostlab.com/2026/10/ai-api-cost-calculator-estimate-your.html" rel="noopener noreferrer"&gt;AI API cost calculator&lt;/a&gt; — but read the result as cost per task you actually ship, not as a token total to admire.&lt;/p&gt;

&lt;h2&gt;
  
  
  The token had a good run
&lt;/h2&gt;

&lt;p&gt;The token was a fine unit for the era it was built in, when an API call was a single prompt and a single answer and the meter roughly tracked the work. That era is over. Agents reason invisibly, retry silently, and chain calls you never see — and the meter charges you for a process you cannot inspect, at a rate that changes with plumbing choices you did not make.&lt;/p&gt;

&lt;p&gt;Some provider will eventually sell you the finished task instead of the tokens, and take the efficiency risk onto its own books. When that happens, every developer who has ever stared at a surprise invoice will know exactly why they switched. The only question is which provider moves first — and how many more meter-shock bills the rest of us pay while we wait.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>llm</category>
      <category>tutorial</category>
      <category>productivity</category>
    </item>
    <item>
      <title>Stop One User From Eating Your AI Budget: Build a Per-User Spending Guard in Python</title>
      <dc:creator>Hammad Malik</dc:creator>
      <pubDate>Fri, 13 Nov 2026 10:31:27 +0000</pubDate>
      <link>https://dev.to/hammad_malik_d39574d24320/stop-one-user-from-eating-your-ai-budget-build-a-per-user-spending-guard-in-python-1dcj</link>
      <guid>https://dev.to/hammad_malik_d39574d24320/stop-one-user-from-eating-your-ai-budget-build-a-per-user-spending-guard-in-python-1dcj</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://www.apicostlab.com/2026/11/stop-one-user-from-eating-your-ai.html" rel="noopener noreferrer"&gt;API Cost Lab&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Stop One User From Eating Your AI Budget: Build a Per-User Spending Guard in Python
&lt;/h1&gt;

&lt;p&gt;&lt;em&gt;Last updated: November 2026&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Logging tells you what happened. It does not stop anything. Our last tutorial built a &lt;a href="https://www.apicostlab.com/2026/10/openai-cost-tracking-middleware-build.html" rel="noopener noreferrer"&gt;logging wrapper that records every call's price&lt;/a&gt; — and that wrapper is the right first step, because you cannot control spending you cannot see. But sooner or later every developer with a public-facing AI feature hits the next problem: one user, one script, or one runaway loop spends in a weekend what the rest of your users spend in a month, and you only find out from the invoice.&lt;/p&gt;

&lt;p&gt;This tutorial builds the second half: a spending guard that sits in front of your API calls and refuses a call before it is made, when the user behind it is already over budget. It is about two hundred lines of Python, it uses only the standard library, and it stores its data in a small SQLite file you can inspect with any database tool. There is no new service to run, no dashboard to learn, and no pricing data to trust: you supply the rates from your provider's pricing page, and the guard does arithmetic on your own token counts.&lt;/p&gt;

&lt;p&gt;One honesty note before the code. Every dollar figure in the demo below comes from made-up toy rates, labelled as such, chosen so the arithmetic is easy to follow. They are not any provider's prices and not measurements from a real app. In production you replace them with the rates on your provider's pricing page on the day you deploy — our &lt;a href="https://www.apicostlab.com/2026/10/openai-api-pricing-explained-every.html" rel="noopener noreferrer"&gt;OpenAI pricing guide&lt;/a&gt; and &lt;a href="https://www.apicostlab.com/2026/10/deepseek-api-pricing-explained-what.html" rel="noopener noreferrer"&gt;DeepSeek pricing guide&lt;/a&gt; show where those numbers live, but the guard itself never guesses a rate.&lt;/p&gt;

&lt;h2&gt;
  
  
  The problem with after-the-fact controls
&lt;/h2&gt;

&lt;p&gt;Most AI cost controls work after the money is spent. A dashboard total, a daily email summary, or a log file all answer the same question: what did we spend? None of them can answer the question that matters when a bill is running away: should this next call be allowed? By the time a human reads an alert, the calls that caused it have already been billed. Our &lt;a href="https://www.apicostlab.com/2026/10/why-is-my-openai-api-bill-so-high.html" rel="noopener noreferrer"&gt;bill-diagnosis checklist&lt;/a&gt; walks through the usual causes of a surprise invoice — a retry loop, a growing system prompt, an agent loop with no step cap — and nearly all of them share one property: they are patterns that repeat a cheap call many times. A guard aimed at the individual user is the cheapest way to bound that repetition, because it turns an unbounded loop into a bounded one: at most one budget's worth of calls, and then a refusal your code can handle gracefully.&lt;/p&gt;

&lt;p&gt;There are three design decisions that make this guard practical instead of annoying. First, it checks before the call, using an estimate, and records the real token counts after the call. Estimates are always wrong in detail, so the guard never treats an estimate as a bill — it treats it as a gate, and the recorded actuals are what the next check trusts. Second, budgets are monthly windows that reset on the first of the month, which matches how most API billing works and means you never have to write a reset job. Third, a user with no budget set is never blocked. That last rule matters more than it looks: it means you can roll the guard out for one heavy user, one expensive feature, or one trial tier, without changing behaviour for everyone else on day one.&lt;/p&gt;

&lt;h2&gt;
  
  
  What the guard does, in plain terms
&lt;/h2&gt;

&lt;p&gt;A budget is a pair: a user id and a scope. The scope is any label you already use for a feature — "chat", "summariser", "agent", or anything else. You set a monthly dollar limit for a user on a scope, and the guard tracks what that user has spent on that scope this month. There is one special scope, "*", which means a user-wide budget: it is checked on every call for that user, whatever the feature is. So a user can have a tight budget on an expensive agent feature and a looser budget overall, and the guard enforces whichever one runs out first.&lt;/p&gt;

&lt;p&gt;Every call goes through three steps. Before the call, &lt;code&gt;check()&lt;/code&gt; adds the estimated cost to what the user has already spent this month and refuses the call if the total would pass the budget, raising a &lt;code&gt;BudgetExceeded&lt;/code&gt; exception your code catches and turns into a friendly message, a degraded answer, or a queue-and-retry-later — your choice, not the guard's. If spending has passed eighty percent of a budget, &lt;code&gt;check()&lt;/code&gt; returns a warning string instead of blocking, so you can warn the user or alert yourself while the call still goes ahead. After the call, &lt;code&gt;record()&lt;/code&gt; stores the real input and output token counts and the real cost, computed from your rates. The helper &lt;code&gt;run_guarded()&lt;/code&gt; ties the three steps together: give it a function that makes the call and returns the real token counts, and it checks, runs, and records in one place.&lt;/p&gt;

&lt;p&gt;Two things the guard deliberately does not do. It does not decide what a call should cost — that is your rates table, and if a rate is wrong, only the dollar column is wrong while the token counts stay right. And it does not store prompt or answer text, user content, or anything but user ids, scope labels, token counts, costs, and timestamps. A budget database should be boring enough to keep forever and safe enough to show a teammate.&lt;/p&gt;

&lt;h2&gt;
  
  
  The code: a guard you can drop in
&lt;/h2&gt;

&lt;p&gt;Save this as &lt;code&gt;budget_guard.py&lt;/code&gt; next to your app. It needs Python 3.8 or newer and nothing to install — &lt;code&gt;sqlite3&lt;/code&gt; and &lt;code&gt;datetime&lt;/code&gt; are in the standard library. By default it stores budgets and usage in a file called &lt;code&gt;budgets.db&lt;/code&gt; in the working directory; pass &lt;code&gt;":memory:"&lt;/code&gt; instead if you want a throwaway database for tests, as the demo does.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="s2"&gt;"""budget_guard.py -- Per-user / per-feature AI spending guard.

Standard library only (sqlite3). No API calls are made by this module:
it only tracks budgets and costs. You supply the rates from your
provider's pricing page, and you pass in the token counts your API
client reports after each call.

Core idea, in three steps for every call:
  1. guard.check(...)  -- before the call, refuse it if the user is
     already over budget (or the estimate alone would push them over).
  2. Make the API call.
  3. guard.record(...) -- after the call, store the real token counts
     and cost, so the next check uses actuals, not guesses.
"""&lt;/span&gt;

&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;sqlite3&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;datetime&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;datetime&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;timezone&lt;/span&gt;


&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;BudgetExceeded&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Exception&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""Raised when a call would push a user past their budget."""&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_month_start_utc&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""Timestamp (seconds) of the first day of the current month, UTC."""&lt;/span&gt;
    &lt;span class="n"&gt;now&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;datetime&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;timezone&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;utc&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;datetime&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;year&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;month&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;tzinfo&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;timezone&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;utc&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;timestamp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;BudgetGuard&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""Monthly spending budgets, per user and per feature scope.

    A budget is identified by (user_id, scope). Scope is any label you
    already use, e.g. "chat", "summariser", "agent". Two scopes are
    special:
      "*"  -- a user-wide budget, checked on every call for that user,
              whatever the feature scope is.
    A user with no budget set is never blocked: check() simply passes.
    """&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;db_path&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"budgets.db"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;db&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;sqlite3&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;connect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;db_path&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="s2"&gt;"CREATE TABLE IF NOT EXISTS budgets ("&lt;/span&gt;
            &lt;span class="s2"&gt;"  user_id TEXT, scope TEXT, limit_usd REAL,"&lt;/span&gt;
            &lt;span class="s2"&gt;"  PRIMARY KEY (user_id, scope))"&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="s2"&gt;"CREATE TABLE IF NOT EXISTS usage ("&lt;/span&gt;
            &lt;span class="s2"&gt;"  id INTEGER PRIMARY KEY AUTOINCREMENT,"&lt;/span&gt;
            &lt;span class="s2"&gt;"  user_id TEXT, scope TEXT,"&lt;/span&gt;
            &lt;span class="s2"&gt;"  input_tokens INTEGER, output_tokens INTEGER,"&lt;/span&gt;
            &lt;span class="s2"&gt;"  cost_usd REAL, ts REAL)"&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;commit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="c1"&gt;# -- budgets ------------------------------------------------------&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;set_budget&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;limit_usd&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="s2"&gt;"""Set (or replace) a monthly budget in US dollars."""&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="s2"&gt;"INSERT OR REPLACE INTO budgets VALUES (?, ?, ?)"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;float&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;limit_usd&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;commit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_budget&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="s2"&gt;"SELECT limit_usd FROM budgets WHERE user_id=? AND scope=?"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;fetchone&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;

    &lt;span class="c1"&gt;# -- spending -----------------------------------------------------&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;spent&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="s2"&gt;"""Dollars spent this month. scope=None means all scopes."""&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                &lt;span class="s2"&gt;"SELECT COALESCE(SUM(cost_usd), 0) FROM usage"&lt;/span&gt;
                &lt;span class="s2"&gt;" WHERE user_id=? AND ts&amp;gt;=?"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;_month_start_utc&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;fetchone&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                &lt;span class="s2"&gt;"SELECT COALESCE(SUM(cost_usd), 0) FROM usage"&lt;/span&gt;
                &lt;span class="s2"&gt;" WHERE user_id=? AND scope=? AND ts&amp;gt;=?"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;_month_start_utc&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;fetchone&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;remaining&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="s2"&gt;"""Dollars left on a budget, or None if no budget is set."""&lt;/span&gt;
        &lt;span class="n"&gt;limit&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get_budget&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;limit&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
        &lt;span class="n"&gt;base&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;spent&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;"*"&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;spent&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;limit&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;base&lt;/span&gt;

    &lt;span class="c1"&gt;# -- pricing ------------------------------------------------------&lt;/span&gt;
    &lt;span class="nd"&gt;@staticmethod&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;estimate_cost&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;input_tokens&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;output_tokens&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                      &lt;span class="n"&gt;price_in_per_million&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;price_out_per_million&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="s2"&gt;"""Cost of a call from token counts and per-million rates."""&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="n"&gt;input_tokens&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;price_in_per_million&lt;/span&gt;
            &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;output_tokens&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;price_out_per_million&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;1_000_000&lt;/span&gt;

    &lt;span class="c1"&gt;# -- the guard ----------------------------------------------------&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;check&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;estimated_cost&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;warn_at&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;0.8&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="s2"&gt;"""Pre-call check. Returns a warning string, or None.

        Raises BudgetExceeded if the estimated cost would push the user
        past any budget that applies: the feature scope budget and/or
        the user-wide ("*") budget. Users with no budget are never
        blocked. warn_at=0.8 means: warn once spending passes 80% of
        a budget (the call still goes ahead).
        """&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;budget_scope&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"*"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;limit&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get_budget&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;budget_scope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;limit&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;continue&lt;/span&gt;
            &lt;span class="n"&gt;base&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;spent&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;budget_scope&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;"*"&lt;/span&gt;
                    &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;spent&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;base&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;estimated_cost&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;limit&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="nc"&gt;BudgetExceeded&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                    &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"user {user_id!r} scope {budget_scope!r}: "&lt;/span&gt;
                    &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"spent ${base:.4f} + estimated ${estimated_cost:.4f} "&lt;/span&gt;
                    &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"exceeds monthly budget ${limit:.4f}"&lt;/span&gt;
                &lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;base&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="n"&gt;warn_at&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;limit&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
                    &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"warning: user {user_id!r} has used "&lt;/span&gt;
                    &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"${base:.4f} of ${limit:.4f} "&lt;/span&gt;
                    &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"({100 * base / limit:.0f}%) on {budget_scope!r} "&lt;/span&gt;
                    &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"this month"&lt;/span&gt;
                &lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;record&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;input_tokens&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;output_tokens&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
               &lt;span class="n"&gt;price_in_per_million&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;price_out_per_million&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="s2"&gt;"""Post-call true-up. Stores real token counts and cost.

        Returns the cost of this call in dollars.
        """&lt;/span&gt;
        &lt;span class="n"&gt;cost&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;estimate_cost&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;input_tokens&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;output_tokens&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                                  &lt;span class="n"&gt;price_in_per_million&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                                  &lt;span class="n"&gt;price_out_per_million&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;execute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="s2"&gt;"INSERT INTO usage (user_id, scope, input_tokens,"&lt;/span&gt;
            &lt;span class="s2"&gt;" output_tokens, cost_usd, ts) VALUES (?, ?, ?, ?, ?, ?)"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;input_tokens&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;output_tokens&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
             &lt;span class="n"&gt;cost&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;datetime&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;timezone&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;utc&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;timestamp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;commit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;cost&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;run_guarded&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;call_fn&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="n"&gt;est_input_tokens&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;est_output_tokens&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="n"&gt;price_in_per_million&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;price_out_per_million&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                    &lt;span class="n"&gt;warn_at&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;0.8&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="s2"&gt;"""Run call_fn() under the guard; returns (result, cost, warn).

        call_fn must return (result, actual_input_tokens,
        actual_output_tokens). The estimate only gates the call; the
        recorded cost always comes from the actual token counts.
        """&lt;/span&gt;
        &lt;span class="n"&gt;est&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;estimate_cost&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;est_input_tokens&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;est_output_tokens&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                                 &lt;span class="n"&gt;price_in_per_million&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                                 &lt;span class="n"&gt;price_out_per_million&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;warn&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;check&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;est&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;warn_at&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;warn_at&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;actual_in&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;actual_out&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;call_fn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;cost&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;record&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;actual_in&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;actual_out&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                           &lt;span class="n"&gt;price_in_per_million&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;price_out_per_million&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cost&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;warn&lt;/span&gt;


&lt;span class="c1"&gt;# -- demo (fake client, no network, no API key) ------------------------&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;FakeClient&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""Stands in for a real API client in the demo."""&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;input_tokens&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;2000&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;output_tokens&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;500&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;input_tokens&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;input_tokens&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;output_tokens&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;output_tokens&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;chat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;_prompt&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"&amp;lt;fake answer&amp;gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;input_tokens&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;output_tokens&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;demo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="c1"&gt;# Toy rates for the demo ONLY -- replace these with the rates on&lt;/span&gt;
    &lt;span class="c1"&gt;# your provider's pricing page before using this for real traffic.&lt;/span&gt;
    &lt;span class="no"&gt;PRICE_IN&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;PRICE_OUT&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;1.00&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;3.00&lt;/span&gt;  &lt;span class="c1"&gt;# dollars per million tokens&lt;/span&gt;
    &lt;span class="n"&gt;guard&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;BudgetGuard&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;":memory:"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# in-memory DB, nothing is saved&lt;/span&gt;
    &lt;span class="n"&gt;client&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;FakeClient&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"== alice, feature budget $0.012 =="&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;guard&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;set_budget&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"alice"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"chat"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;0.012&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;_res&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cost&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;warn&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;guard&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;run_guarded&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                &lt;span class="s2"&gt;"alice"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"chat"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;lambda&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;chat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"hello"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="mi"&gt;2000&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;500&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;PRICE_IN&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;PRICE_OUT&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"call {i}: ok, cost ${cost:.4f}, "&lt;/span&gt;
                  &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"spent ${guard.spent('alice', 'chat'):.4f}"&lt;/span&gt;
                  &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;" -- {warn}"&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;warn&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="s2"&gt;""&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="nc"&gt;BudgetExceeded&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;exc&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"call {i}: BLOCKED -- {exc}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"== bob, feature budget $0.004 (warning demo) =="&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;guard&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;set_budget&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"bob"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"chat"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;0.004&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;_res&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cost&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;_warn&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;guard&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;run_guarded&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="s2"&gt;"bob"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"chat"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;lambda&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;chat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"hello"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="mi"&gt;2000&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;500&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;PRICE_IN&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;PRICE_OUT&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"call 1: ok, cost ${cost:.4f}, "&lt;/span&gt;
          &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"spent ${guard.spent('bob', 'chat'):.4f}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="c1"&gt;# A check with a zero estimate passes the budget but still reports&lt;/span&gt;
    &lt;span class="c1"&gt;# the warning, because bob is already past 80% of his budget.&lt;/span&gt;
    &lt;span class="n"&gt;warn&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;guard&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;check&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"bob"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"chat"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;0.0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"pre-call check for call 2: {warn}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;


&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;__name__&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;"__main__"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="nf"&gt;demo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How to run it
&lt;/h2&gt;

&lt;p&gt;There is nothing to install and no API key to configure. Save the file, then run it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python3 budget_guard.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because the demo uses a fake client and an in-memory database, it runs anywhere and touches nothing: no network calls, no files written, no money spent. Its output is the guard doing exactly the two things it exists for — letting calls through while there is budget left, and refusing the call that would cross the line:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;== alice, feature budget $0.012 ==
call 1: ok, cost $0.0035, spent $0.0035
call 2: ok, cost $0.0035, spent $0.0070
call 3: ok, cost $0.0035, spent $0.0105
call 4: BLOCKED -- user 'alice' scope 'chat': spent $0.0105 + estimated $0.0035 exceeds monthly budget $0.0120
== bob, feature budget $0.004 (warning demo) ==
call 1: ok, cost $0.0035, spent $0.0035
pre-call check for call 2: warning: user 'bob' has used $0.0035 of $0.0040 (88%) on 'chat' this month
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Read the alice sequence carefully, because it shows the estimate rule working as designed. The fourth call is refused before it runs, not after it bills: at that point alice has spent $0.0105, and the next call's estimate of $0.0035 would take her to $0.0140, past her $0.0120 budget. The guard does not need to know what the call would actually have cost — the estimate alone is enough to refuse it, and refusing early is the whole point. The bob sequence shows the warning side: at 88% of his budget, a check still allows the call but hands you a warning string you can show the user or send to your own alert channel.&lt;/p&gt;

&lt;p&gt;One detail worth noticing: the guard's monthly window is computed from the current date in UTC, so spending resets automatically on the first of the month and old rows simply fall out of the window. Nothing deletes them, which is deliberate — last month's rows are still there if you ever want to query them, but they no longer count against this month's budgets.&lt;/p&gt;

&lt;h2&gt;
  
  
  Wiring it to a real client
&lt;/h2&gt;

&lt;p&gt;The demo's fake client stands in for whatever SDK you actually use. The only thing the guard needs from a real call is the token counts the provider already reports. With OpenAI's Python SDK, a chat completion response carries a &lt;code&gt;usage&lt;/code&gt; object with &lt;code&gt;prompt_tokens&lt;/code&gt; and &lt;code&gt;completion_tokens&lt;/code&gt;, exactly the two numbers &lt;code&gt;run_guarded&lt;/code&gt; wants back from your function. So the production version of the demo's one-liner looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;make_call&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;chat&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;completions&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"your-model-id"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;messages&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;messages&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;prompt_tokens&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;completion_tokens&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cost&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;warn&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;guard&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;run_guarded&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"chat"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;make_call&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;est_input_tokens&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;est_output_tokens&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="no"&gt;PRICE_IN&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;PRICE_OUT&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="nc"&gt;BudgetExceeded&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s2"&gt;"You have used this month's AI budget. It resets on the 1st."&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Two practical notes on that wiring. First, the estimate before the call: for a chat feature you can estimate input tokens from the prompt you are about to send — most providers publish a tokenizer, or you can start with a rough character-based guess and let the post-call true-up correct it, since the recorded cost always comes from the real counts. What you must not do is skip the pre-call check for calls you cannot estimate: estimate generously instead, because an overestimate only refuses a call slightly early, while no estimate at all refuses nothing. Second, streaming: if you stream a response, the usage object arrives with the final chunk, so record after the stream finishes rather than per chunk — the same rule our logging wrapper follows, for the same reason. A guard that records per chunk would count one call many times over and block users who did nothing wrong.&lt;/p&gt;

&lt;p&gt;When a call is blocked, catch &lt;code&gt;BudgetExceeded&lt;/code&gt; at the edge of your feature and answer the user plainly. "You have used this month's AI budget" beats a bare error, and it beats silently degrading to a worse answer without explanation. If you sell tiers, the block is also the natural place to offer the upgrade: the user who just hit a limit is the user most likely to understand what a higher limit is worth.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to adapt it
&lt;/h2&gt;

&lt;p&gt;The file is intentionally small so that adapting it is a matter of changing one function, not redesigning it. Four adaptations cover nearly every real deployment. First, the database: SQLite is one file and one writer at a time, which is fine for a single-process app but not for several web workers. To move to Postgres or MySQL, replace the five SQL statements with your driver's equivalents — the table shapes stay the same, and nothing else in the file knows or cares which database it is. Second, the period: if your billing or your product works on daily budgets instead of monthly ones, change only &lt;code&gt;_month_start_utc()&lt;/code&gt; to return the start of the current day; every query reads through that one function. Third, the warning: &lt;code&gt;check()&lt;/code&gt; returns a string, and what you do with it is up to you — log it, email it, or send it to a webhook. A one-line change at the call site turns a returned warning into a Slack message the first time a user crosses eighty percent. Fourth, cached input: this version prices two token kinds, input and output. If your provider bills cached input at a different rate, add a third rate and a third token count to &lt;code&gt;record()&lt;/code&gt; and &lt;code&gt;estimate_cost()&lt;/code&gt; — the same split our logging wrapper records, for the same reason. Do not add a rate you cannot verify on a pricing page: a guard with a guessed rate enforces a fictional budget, which is worse than no guard at all.&lt;/p&gt;

&lt;p&gt;One more adaptation deserves a warning of its own. It is tempting to give the guard a back door — an admin override, a "just this once" flag, a second code path that skips the check for internal users. Every back door becomes the path all traffic eventually takes, usually via a forgotten debug flag. If some callers genuinely need no limit, give them no budget instead: the guard already treats "no budget set" as "never blocked", so an unlimited internal job is just a caller with no budget row, visible in the same table as everything else, instead of a secret exception in code.&lt;/p&gt;

&lt;h2&gt;
  
  
  FAQ
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Do I need exact token counts before the call?
&lt;/h3&gt;

&lt;p&gt;No. The pre-call check runs on an estimate, and the estimate only needs to be in the right neighbourhood. If it is too high, a call gets refused slightly early; if it is too low, the post-call true-up still records the real cost, so the next check is computed from real spending. The failure mode to avoid is skipping the check entirely for calls you cannot estimate — estimate generously and let the true-up correct you.&lt;/p&gt;

&lt;h3&gt;
  
  
  What happens when the month changes?
&lt;/h3&gt;

&lt;p&gt;Nothing you need to do. The spending window starts on the first of the current month in UTC, so on the first, last month's rows fall outside the window and every user starts at zero again. Old rows are kept, not deleted, so you can still query last month's totals — they just no longer count against any budget.&lt;/p&gt;

&lt;h3&gt;
  
  
  Can I use this for something that is not a user?
&lt;/h3&gt;

&lt;p&gt;Yes. The guard does not know what a user id is — it is just a label. Use a job name for a nightly pipeline, a team name for a shared key, or a customer id for a paying account. A background job with a monthly budget behaves exactly like a user with one: it runs until the budget is gone, and then it stops instead of running up a bill while nobody watches.&lt;/p&gt;

&lt;p&gt;Logging showed you where the money goes; this guard decides where it stops. Build it this week, set a budget for your heaviest user or your most expensive feature first, and let the rest of your traffic run unbudgeted until the numbers tell you where the next budget belongs. The goal is not to spend less in general — it is to make sure no single user, job, or loop can ever spend without a limit again.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>llm</category>
      <category>python</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>OpenAI Cost Tracking Middleware: Build a Logging Wrapper That Shows Every Call's Price</title>
      <dc:creator>Hammad Malik</dc:creator>
      <pubDate>Wed, 11 Nov 2026 10:34:02 +0000</pubDate>
      <link>https://dev.to/hammad_malik_d39574d24320/openai-cost-tracking-middleware-build-a-logging-wrapper-that-shows-every-calls-price-n8m</link>
      <guid>https://dev.to/hammad_malik_d39574d24320/openai-cost-tracking-middleware-build-a-logging-wrapper-that-shows-every-calls-price-n8m</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://www.apicostlab.com/2026/10/openai-cost-tracking-middleware-build.html" rel="noopener noreferrer"&gt;API Cost Lab&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  OpenAI Cost Tracking Middleware: Build a Logging Wrapper That Shows Every Call's Price
&lt;/h1&gt;

&lt;p&gt;&lt;em&gt;Last updated: October 2026&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;OpenAI cost tracking middleware is a small wrapper around your API calls that records, for every single request, how many tokens went in, how many came out, how many of those input tokens were cached, and what that request cost under the rates you configure. Put it between your code and the OpenAI client, log one line per call to a file, and you stop guessing about your bill: the next time a number on the dashboard looks wrong, you can point at the exact feature, user, or prompt that produced it.&lt;/p&gt;

&lt;p&gt;This tutorial gives you that wrapper in Python. It is about sixty lines of code, stores no prompt or answer text, and uses the usage object OpenAI already returns on every non-streaming response. You supply your own rates, because the only rate that matters is the one on your provider's pricing page on the day you run the code. It is the piece our earlier guide to &lt;a href="https://www.apicostlab.com/2026/10/why-is-my-openai-api-bill-so-high.html" rel="noopener noreferrer"&gt;why an OpenAI bill gets so high&lt;/a&gt; kept pointing back to: measure first, optimise second.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why your dashboard arrives too late
&lt;/h2&gt;

&lt;p&gt;The OpenAI usage dashboard is useful, but it answers the wrong question at the wrong time. It tells you, days later, that you spent a certain amount in total. It does not tell you whether the spike on Tuesday came from the new summariser, the retry loop you added on Monday, or one user pasting a fifty-page document into a chat box. By the time you see the total, the calls that caused it are gone, and the only evidence left is a vague memory of what you shipped that week.&lt;/p&gt;

&lt;p&gt;Per-call logging flips that around. When every request writes its own line — timestamp, feature name, model, token counts, cost — a spike becomes a query instead of a mystery. You sort the log by cost, and the top ten lines usually tell the whole story. Often the story is embarrassing in a useful way: a background job retrying a failed call five times, a system prompt that grew to thousands of tokens without anyone noticing, or a "quick" agent loop that makes forty calls where you assumed it made four. Our post on &lt;a href="https://www.apicostlab.com/2026/10/why-is-my-ai-agent-so-expensive-to-run.html" rel="noopener noreferrer"&gt;why AI agents get so expensive to run&lt;/a&gt; describes exactly that pattern: the per-call price looks small, and the step count is what does the damage. A wrapper is how you catch the step count.&lt;/p&gt;

&lt;h2&gt;
  
  
  What the wrapper records, and what it deliberately leaves out
&lt;/h2&gt;

&lt;p&gt;Every OpenAI chat completion response carries a &lt;code&gt;usage&lt;/code&gt; object. According to OpenAI's own API reference, that object reports &lt;code&gt;prompt_tokens&lt;/code&gt;, &lt;code&gt;completion_tokens&lt;/code&gt;, and &lt;code&gt;total_tokens&lt;/code&gt;, with a breakdown under &lt;code&gt;prompt_tokens_details&lt;/code&gt; that includes &lt;code&gt;cached_tokens&lt;/code&gt; and a breakdown under &lt;code&gt;completion_tokens_details&lt;/code&gt; that includes &lt;code&gt;reasoning_tokens&lt;/code&gt;. Those five numbers are the whole story of a call's price, and the wrapper's job is simply to capture them before your code moves on and forgets them.&lt;/p&gt;

&lt;p&gt;The split matters. Prompt tokens and cached tokens are not the same line on your bill: cached input is normally priced far below fresh input, so a call with a large prompt can be cheap if most of it hit the cache and expensive if none of it did. Recording only the total hides that difference, which is why this wrapper stores fresh and cached input separately. Reasoning tokens matter for the same reason: on a reasoning model, the thinking that happens before the answer is billed as output, so a short-looking answer can carry a long hidden output count. If your log only stored the visible answer length, you would never explain that bill. Our &lt;a href="https://www.apicostlab.com/2026/10/prompt-caching-90-discount-youre-missing.html" rel="noopener noreferrer"&gt;prompt caching guide&lt;/a&gt; explains how the cache side works in more detail; the wrapper is how you prove whether it is working for your prompts.&lt;/p&gt;

&lt;p&gt;What the wrapper does not record is just as deliberate: no prompt text, no answer text, no user content of any kind. A cost log should be safe to keep, safe to share with a teammate, and safe to grep in a hurry. The moment it contains user data it becomes a privacy liability and a file nobody wants to open. If you later need to debug a specific expensive prompt, add a separate debug flag that logs a hash of the prompt, not the prompt itself, and keep it off by default.&lt;/p&gt;

&lt;h2&gt;
  
  
  The code: a wrapper you can drop in
&lt;/h2&gt;

&lt;p&gt;Here is the complete wrapper. Save it as &lt;code&gt;cost_tracker.py&lt;/code&gt; next to your app, fill in the rates from your provider's pricing page, and call &lt;code&gt;track_chat()&lt;/code&gt; instead of calling the client directly. It appends one JSON line per call to &lt;code&gt;llm_costs.jsonl&lt;/code&gt;, a format any log tool can read, and it returns the original response untouched, so the rest of your code does not change.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;datetime&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;datetime&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;timezone&lt;/span&gt;

&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;openai&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;OpenAI&lt;/span&gt;

&lt;span class="c1"&gt;# Fill these in from your provider's pricing page, per 1M tokens.&lt;/span&gt;
&lt;span class="c1"&gt;# The wrapper never guesses a rate: if a rate is wrong here, the&lt;/span&gt;
&lt;span class="c1"&gt;# token counts are still right and only the dollar column is off.&lt;/span&gt;
&lt;span class="no"&gt;RATES&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="s2"&gt;"input_per_million"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;0.0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;    &lt;span class="c1"&gt;# fresh (uncached) input tokens&lt;/span&gt;
    &lt;span class="s2"&gt;"cached_per_million"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;0.0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;   &lt;span class="c1"&gt;# cached input tokens&lt;/span&gt;
    &lt;span class="s2"&gt;"output_per_million"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;0.0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;   &lt;span class="c1"&gt;# output tokens, including reasoning&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="n"&gt;client&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;OpenAI&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# reads OPENAI_API_KEY from the environment&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_cost_usd&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;rates&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;prompt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;prompt_tokens&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="n"&gt;cached&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;prompt_tokens_details&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;cached&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;prompt_tokens_details&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;cached_tokens&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="n"&gt;fresh&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;max&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;prompt&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;cached&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;output&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;completion_tokens&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="n"&gt;cost&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;fresh&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;rates&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"input_per_million"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;cached&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;rates&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"cached_per_million"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;output&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;rates&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"output_per_million"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;1_000_000&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;fresh&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cached&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;output&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cost&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;track_chat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;messages&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;feature&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"unknown"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="n"&gt;kwargs&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""Drop-in replacement for client.chat.completions.create."""&lt;/span&gt;
    &lt;span class="n"&gt;started&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;monotonic&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;chat&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;completions&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;messages&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;messages&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="n"&gt;kwargs&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;latency_ms&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;monotonic&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;started&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="n"&gt;record&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="s2"&gt;"timestamp"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;datetime&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;timezone&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;utc&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;isoformat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"feature"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;feature&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"model"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"latency_ms"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;latency_ms&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="n"&gt;usage&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;getattr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"usage"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;usage&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;fresh&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cached&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;output&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;cost&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;_cost_usd&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;RATES&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;record&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="s2"&gt;"prompt_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;prompt_tokens&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"fresh_input_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;fresh&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"cached_input_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;cached&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"output_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;output&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"reasoning_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
                &lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;completion_tokens_details&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;reasoning_tokens&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;usage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;completion_tokens_details&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
                &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
            &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"cost_usd"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;round&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cost&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;record&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"note"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"no usage object returned"&lt;/span&gt;

    &lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"llm_costs.jsonl"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"a"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;encoding&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;write&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dumps&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;record&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="s2"&gt;"\n"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using it is one line different from a normal call: replace &lt;code&gt;client.chat.completions.create(...)&lt;/code&gt; with &lt;code&gt;track_chat(..., feature="support_reply")&lt;/code&gt;. The &lt;code&gt;feature&lt;/code&gt; label is the most important parameter in the file — it is what you will group by later, so name it after your product ("support_reply", "summariser", "nightly_report"), not your code.&lt;/p&gt;

&lt;p&gt;Two details in the code deserve a second look. First, the cost calculation subtracts cached tokens from prompt tokens to get fresh input, because &lt;code&gt;prompt_tokens&lt;/code&gt; already includes the cached ones. Counting both would double-charge the cache. Second, the wrapper reads the reasoning count defensively, with a check for a missing details object, because not every model and endpoint populates every breakdown field. A wrapper that crashes on an unusual response is worse than no wrapper: it would take your feature down over a logging detail. Logging must never be allowed to break the call it is measuring.&lt;/p&gt;

&lt;h2&gt;
  
  
  Reading one log line
&lt;/h2&gt;

&lt;p&gt;After a few calls, &lt;code&gt;llm_costs.jsonl&lt;/code&gt; holds lines like this example, with the numbers shown only to illustrate the shape of a record:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nl"&gt;"timestamp"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"2026-10-30T05:00:00+00:00"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nl"&gt;"feature"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"support_reply"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
 &lt;span class="nl"&gt;"model"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"your-model-id"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nl"&gt;"latency_ms"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1840&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nl"&gt;"prompt_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2400&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
 &lt;span class="nl"&gt;"fresh_input_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;400&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nl"&gt;"cached_input_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2000&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
 &lt;span class="nl"&gt;"output_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;320&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nl"&gt;"reasoning_tokens"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nl"&gt;"cost_usd"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;0.0042&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Read it from right to left. The cost is the headline, but the token split is the diagnosis. Here, most of the prompt was cached, so the call stayed cheap despite a long prompt — exactly the behaviour you want from a repeated system prompt. If the same feature's lines showed &lt;code&gt;cached_input_tokens&lt;/code&gt; near zero day after day, that would be your first fix: something is changing the prompt prefix on every call, perhaps a timestamp or a user ID injected at the top, and the cache never gets a chance to hit. That single field, watched over a week, is worth more than any pricing article, because it is measured on your traffic rather than assumed.&lt;/p&gt;

&lt;h2&gt;
  
  
  Two traps that make logs lie
&lt;/h2&gt;

&lt;p&gt;The first trap is streaming. A streamed response does not hand you a complete usage object in the normal way: the usage arrives in a final chunk, and only if you ask for it, by setting &lt;code&gt;stream_options={"include_usage": True}&lt;/code&gt; on the request. If you wrap a streaming call with the code above and never see usage, that is why — the wrapper did not fail, the stream simply never sent the numbers. For streamed calls, collect the chunks, keep the last chunk's usage, and log once when the stream finishes. Never log per chunk: you would count one call many times over, and your totals would be fiction.&lt;/p&gt;

&lt;p&gt;The second trap is retries. If your app retries a failed call three times, your log should show three lines and your bill will too — the provider charges for the attempts that ran, not just the one that succeeded. That is correct behaviour for a log, but it surprises people who expect one line per user action. When a feature's cost looks too high, count its lines per user action before blaming the model. A retry loop with no backoff, or an agent loop with no step cap, will outspend any rate difference between models, and the log is the only place that pattern is visible.&lt;/p&gt;

&lt;h2&gt;
  
  
  Turn the log into an alert, not a spreadsheet
&lt;/h2&gt;

&lt;p&gt;A log file nobody reads is decoration. The wrapper earns its keep when a tiny script reads it once a day and tells you only what changed. Start with three summaries, and nothing more: total cost per feature for the last 24 hours, the ten most expensive single calls, and any feature whose daily cost doubled compared with its seven-day average. The first tells you where the money goes, the second tells you what to fix next, and the third is the early warning that catches a runaway job before the month ends.&lt;/p&gt;

&lt;p&gt;Keep the alert threshold simple at first, and when one fires, the log already holds the feature, model, token split, and timestamp you need to act. If you want to sanity-check the totals against your own token mix, our &lt;a href="https://www.apicostlab.com/2026/10/ai-api-cost-calculator-estimate-your.html" rel="noopener noreferrer"&gt;AI API Cost Calculator&lt;/a&gt; lets you plug in your own numbers and compare them with what the log reports.&lt;/p&gt;

&lt;p&gt;That measurement habit is the real point of this tutorial. Pricing pages tell you what a token costs; only your own log tells you what your app actually spends tokens on. Build the wrapper this week, let it run for seven days without changing anything else, and read the per-feature summary before you change a single prompt or model. The numbers will almost certainly surprise you — and unlike a dashboard total, they will tell you exactly what to do next.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Usage fields in this tutorial follow OpenAI's published API reference for chat completions and its usage documentation: &lt;a href="https://developers.openai.com/api/reference/resources/completions" rel="noopener noreferrer"&gt;Completions reference&lt;/a&gt; and &lt;a href="https://help.openai.com/en/articles/10478918-reviewing-api-usage-and-costs" rel="noopener noreferrer"&gt;Reviewing API usage and costs&lt;/a&gt;. Rates are not listed here on purpose — fill in the RATES table from your provider's current pricing page, and re-check it whenever you change models.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>ai</category>
      <category>llm</category>
      <category>openai</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>AI Subscriptions vs API Pricing: Where's the Crossover?</title>
      <dc:creator>Hammad Malik</dc:creator>
      <pubDate>Sun, 01 Nov 2026 10:45:49 +0000</pubDate>
      <link>https://dev.to/hammad_malik_d39574d24320/ai-subscriptions-vs-api-pricing-wheres-the-crossover-2gn7</link>
      <guid>https://dev.to/hammad_malik_d39574d24320/ai-subscriptions-vs-api-pricing-wheres-the-crossover-2gn7</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://www.apicostlab.com/2026/10/ai-subscriptions-vs-api-pricing-wheres.html" rel="noopener noreferrer"&gt;API Cost Lab&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Last updated: October 2026&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;If you're building with AI, you eventually face a deceptively simple question: should I just pay for the subscription, or pay per token through the API? The answer isn't a preference — it's math. And the math has a crossover point most developers never calculate.&lt;/p&gt;

&lt;h2&gt;
  
  
  The $200/Month Rule of Thumb
&lt;/h2&gt;

&lt;p&gt;Here's the heuristic, stated up front as what it is — a rule of thumb, not a law:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Under ~$200/month of usage:&lt;/strong&gt; a flat subscription (ChatGPT Plus/Pro, Claude Pro/Max tier equivalents) usually wins.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Above ~$200/month:&lt;/strong&gt; metered API pricing — with caching and routing — is typically cheaper and scales linearly.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Why does this threshold exist? Because subscriptions and APIs price fundamentally different things. A subscription sells you &lt;em&gt;access&lt;/em&gt; at a flat fee: one price, generous-but-capped usage, no meter running. An API sells you &lt;em&gt;tokens&lt;/em&gt; at unit prices: every token metered, no cap, cost scaling exactly with consumption.&lt;/p&gt;

&lt;p&gt;At low volumes, the flat fee is subsidized — you're getting more value than you pay for, because the provider averages you against lighter users. At high volumes, you become the heavy user everyone else is averaged against, and the meter starts looking generous by comparison.&lt;/p&gt;

&lt;p&gt;The exact crossover moves with prices and your usage shape, but ~$200/month is where the two curves typically cross for individual developers in 2026. Below it, don't overthink: subscribe. Above it, read on.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Subscriptions Win at Low Volume
&lt;/h2&gt;

&lt;p&gt;Three reasons, all structural:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. The flat fee subsidizes exploration.&lt;/strong&gt; When you're prototyping, experimenting, or using AI as a personal productivity tool, your usage is bursty and unpredictable. A subscription absorbs that variance — a heavy week costs the same as a light one. On the API, every experiment has a meter running, which subtly discourages the tinkering that produces good results.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. No engineering overhead.&lt;/strong&gt; API usage needs keys, billing alerts, rate-limit handling, cost tracking. A subscription needs a login. For a solo developer or a small team just getting started, that simplicity is worth real money — your time spent on billing plumbing is time not spent building.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. The caps are generous for humans.&lt;/strong&gt; Subscription usage limits are designed around human-paced interaction. If your usage is "a developer chatting with a model through the day," you will rarely hit them. The meter only matters when usage stops being human-paced.&lt;/p&gt;

&lt;p&gt;The honest version: if AI is a &lt;em&gt;tool you use&lt;/em&gt;, subscribe. The subscription product is built for you, priced for you, and optimized for you.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why APIs Win at Scale
&lt;/h2&gt;

&lt;p&gt;The moment usage stops being human-paced — background jobs, user-facing features, agents, anything programmatic — the subscription model breaks down:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Subscriptions don't scale to machines.&lt;/strong&gt; Usage caps assume a human clicking. An agent loop making hundreds of calls per hour blows through "generous" caps before lunch. And most subscription terms restrict or prohibit automated/API-style usage anyway — that's what the API product is for.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Per-token pricing rewards optimization.&lt;/strong&gt; On the API, every efficiency gain drops your bill directly: prompt caching (~90% off repeated input on GPT-5.6 Sol: $0.40 vs $4.00 per 1M), batch processing (~50% off), routing simple tasks to cheaper models (GPT-6.1 Sol at $2/$10 vs $4/$20 — the reference workload drops from $205.92 to $97.68/month). Subscriptions give you none of these levers; the price is the price regardless of how clever your architecture is.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Costs scale linearly and predictably.&lt;/strong&gt; API cost = tokens × rate. Double your users, double your tokens, double your bill — no cliffs, no "contact sales," no renegotiating tiers. For a business, that linearity is a feature: your unit economics are a formula, not a negotiation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Teams multiply the gap.&lt;/strong&gt; One subscription per human gets expensive fast at team scale — and still doesn't cover programmatic usage. API keys with per-key budgets and usage tracking are how teams actually manage AI spend.&lt;/p&gt;

&lt;p&gt;The honest version: if AI is &lt;em&gt;infrastructure you run&lt;/em&gt;, use the API. The metered product is built for machines, priced for machines, and gets cheaper the better you engineer.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to Decide With Your Own Numbers
&lt;/h2&gt;

&lt;p&gt;Forget the rule of thumb for a minute and do the actual comparison. It takes twenty minutes:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Measure a month.&lt;/strong&gt; Pull your real usage — or estimate it honestly. Count: how many tasks/requests per day, average input tokens (fresh vs. repeatable), average output tokens. If you're already on the API, the dashboard has this. If you're on a subscription, estimate from a heavy week and multiply.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Price the API scenario.&lt;/strong&gt; Use the workload formula: monthly cost = tasks × [(fresh_in × P_in) + (cached_in × P_cache) + (out × P_out)]. Use real rate-card prices — for example, GPT-5.6 Sol's promo at $4.00/$0.40/$20.00 per 1M, or GPT-6.1 Sol at $2.00/$0.10/$10.00. Apply the discounts you'd actually use: caching if your context repeats, batch if the work can wait.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Compare against the subscription stack.&lt;/strong&gt; Add up what you'd actually pay in subscriptions to cover the same usage: per-seat fees × team members, plus any overage or higher-tier costs when caps bind. Be honest about caps — "unlimited*" usually isn't.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4: Check which side of the line you're on.&lt;/strong&gt; If the API scenario comes in under the subscription stack, switch — and keep optimizing, because the API number only goes down as you tune. If subscriptions win, stay — and revisit when usage grows, because the crossover only moves in one direction as you scale.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 5: Consider the hybrid.&lt;/strong&gt; This is what most serious teams end up with: subscriptions for humans (developers chatting, experimenting, doing support) and API for machines (features, agents, pipelines). They're different products for different consumers. Using both isn't indecision — it's the correct architecture.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Trap: Subscription Thinking at API Scale
&lt;/h2&gt;

&lt;p&gt;The most expensive mistake isn't picking the wrong option — it's keeping the right-for-last-quarter option too long. The pattern repeats constantly:&lt;/p&gt;

&lt;p&gt;A solo developer subscribes, builds a side project, and wires the subscription's web UI into their workflow with copy-paste. It works. The project grows. They add a cron job that hits the API with their personal key "just for now." Then a second job. Then a teammate. Six months later they're paying for four subscriptions &lt;em&gt;and&lt;/em&gt; an API bill, with no cost tracking, no caching, and no idea which dollar went where.&lt;/p&gt;

&lt;p&gt;The subscription mindset — flat fee, don't think about usage — actively harms you at API scale, because the API rewards exactly the thinking the subscription trained you out of: measuring tokens, structuring prompts for cache hits, batching what can wait. Teams that migrate late discover their architecture was designed for a pricing model they no longer use: unbatched, uncached, flagship-everything.&lt;/p&gt;

&lt;p&gt;The way out is a deliberate transition, not a flag day. Keep subscriptions for the humans. Move one machine workload to the API with proper tracking. Optimize it — caching, batch, model routing — until the per-task cost is dialed in. Then move the next. Each migration funds the engineering time for the one after, because the savings are immediate and measurable.&lt;/p&gt;

&lt;p&gt;Watch for the signal that you're overdue: when your subscription tier's usage caps start binding, or when you're paying per-seat fees primarily to cover automated usage rather than humans. That's the market telling you the subscription product isn't yours anymore. Listen the first time — every month of delay is the most expensive month of AI spend you'll have.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Bottom Line
&lt;/h2&gt;

&lt;p&gt;Subscriptions vs. API isn't a loyalty question — it's a volume question with a crossover around ~$200/month. Below it, the flat fee subsidizes you; above it, the meter rewards your engineering. Measure your usage, run the formula, and let the numbers pick. And whatever you choose, recheck as you grow: the right answer at prototype scale is rarely the right answer at production scale.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>llm</category>
      <category>tutorial</category>
      <category>productivity</category>
    </item>
    <item>
      <title>Batch API vs Real-Time: When 50% Off Is Worth the Wait</title>
      <dc:creator>Hammad Malik</dc:creator>
      <pubDate>Fri, 30 Oct 2026 10:35:42 +0000</pubDate>
      <link>https://dev.to/hammad_malik_d39574d24320/batch-api-vs-real-time-when-50-off-is-worth-the-wait-32ij</link>
      <guid>https://dev.to/hammad_malik_d39574d24320/batch-api-vs-real-time-when-50-off-is-worth-the-wait-32ij</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published at &lt;a href="https://www.apicostlab.com/2026/10/batch-api-vs-real-time-when-50-off-is.html" rel="noopener noreferrer"&gt;API Cost Lab&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Last updated: October 2026&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Every major LLM provider sells the same model at two prices: full price for answers in seconds, roughly half price for answers in hours. The Batch API is the most underused discount in the industry — same model, same quality, ~50% off, in exchange for patience. Here's when it's worth it and when it isn't.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Batch Mode Actually Is
&lt;/h2&gt;

&lt;p&gt;A batch request is exactly what it sounds like: instead of sending one request and waiting for the response, you submit a &lt;em&gt;batch&lt;/em&gt; of requests as a file, the provider processes them when it has spare capacity, and you collect the results later — typically within 24 hours.&lt;/p&gt;

&lt;p&gt;Nothing about the model changes. It's the same weights, the same capabilities, the same output quality. The discount exists because you're letting the provider schedule your work during off-peak capacity instead of demanding instant compute. You're selling flexibility; they're buying it back at 50% off.&lt;/p&gt;

&lt;p&gt;On GPT-5.6 Sol, the numbers are concrete: batch processing cuts the promo rates in half — &lt;strong&gt;$2.00 input / $10.00 output per 1M tokens&lt;/strong&gt; instead of $4.00/$20.00. (Cached reads in batch presumably follow the same halving, though the headline discount is what providers publish.)&lt;/p&gt;

&lt;p&gt;The mechanics are simple across providers: you upload a JSONL file of requests, poll for completion, download the results. Most providers return results well before the 24-hour SLA — but the SLA is what you're signing up for, so plan around the worst case.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Worked Example: What 50% Off Looks Like
&lt;/h2&gt;

&lt;p&gt;Take a concrete workload: a nightly eval run — 500 test cases, each with 8K input tokens and 2K output tokens, on GPT-5.6 Sol's promo pricing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real-time:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Input: 500 × 8,000 = 4M tokens × $4.00/1M = $16.00&lt;/li&gt;
&lt;li&gt;Output: 500 × 2,000 = 1M tokens × $20.00/1M = $20.00&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Total: $36.00 per nightly run → ~$1,080/month&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Batch (50% off):&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Input: 4M × $2.00/1M = $8.00&lt;/li&gt;
&lt;li&gt;Output: 1M × $10.00/1M = $10.00&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Total: $18.00 per run → ~$540/month&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Same model, same evals, &lt;strong&gt;$540/month saved&lt;/strong&gt; — for changing when the work runs, not what the work is. And this is a modest example. Teams running large eval suites, backfills, or bulk classification at 10x this volume save thousands monthly for a scheduling change.&lt;/p&gt;

&lt;p&gt;Note this stacks with other optimizations. Batch requests with well-structured cached prefixes get both discounts. Batch on the cheaper model tier (say, GPT-6.1 Sol at $2/$10 → $1/$5 batched) compounds further. The teams with the lowest bills layer every applicable discount; batch is usually the easiest layer to add.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Latency Tradeoff, Honestly
&lt;/h2&gt;

&lt;p&gt;The catch is real: you don't control when results come back. The SLA is typically 24 hours. In practice, providers often return batch results in minutes to a few hours during off-peak times — but "often" isn't a guarantee, and you should architect for the SLA, not the typical.&lt;/p&gt;

&lt;p&gt;This kills batch for anything user-facing or interactive. But it also rules out more than people think:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Fits batch:&lt;/strong&gt; nightly eval suites, dataset labeling and backfills, bulk document processing, embedding generation, offline classification, regression test runs, periodic report generation, training-data preparation. Anything where the consumer of the output is a pipeline, a dashboard, or tomorrow's standup.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Doesn't fit:&lt;/strong&gt; chat, interactive agents, anything with a human waiting, real-time moderation, request-response APIs, multi-step agent loops (each step would take hours — a 10-step agent becomes a 10-day agent).&lt;/p&gt;

&lt;p&gt;The gray area is bigger than it looks. Many "real-time" workloads aren't: that Slack bot summarizing threads? Nobody needs it in seconds. The weekly analytics digest? The support-ticket triage that runs overnight anyway? Audit your async jobs — teams routinely find 30–50% of their API spend is on work that could wait hours with zero user impact.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Migration Is Smaller Than You Think
&lt;/h2&gt;

&lt;p&gt;The reason teams don't use batch isn't the tradeoff — it's inertia. The migration is genuinely small:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Collect requests instead of sending them.&lt;/strong&gt; Where your code currently calls the API in a loop, write the requests to a JSONL file instead.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Submit and poll.&lt;/strong&gt; One submit call, one status poll on a schedule (or a webhook where supported).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Process results the same way.&lt;/strong&gt; The response format matches the real-time API — your result-handling code barely changes.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Most teams do this in a day for a single pipeline. The pattern generalizes: once one pipeline runs on batch, adding the next is mostly copy-paste.&lt;/p&gt;

&lt;p&gt;Two operational notes. First, &lt;strong&gt;error handling differs&lt;/strong&gt;: a malformed request in a batch of 10,000 doesn't fail fast — you find out hours later. Validate requests before submitting. Second, &lt;strong&gt;don't batch what you haven't measured&lt;/strong&gt;: run the workload real-time first, confirm quality, &lt;em&gt;then&lt;/em&gt; move it to batch. Debugging quality issues through a 24-hour feedback loop is miserable.&lt;/p&gt;

&lt;h2&gt;
  
  
  Stacking Discounts: Batch Plus Everything Else
&lt;/h2&gt;

&lt;p&gt;The batch discount composes with every other optimization, and the combination is where the real money is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Batch + caching:&lt;/strong&gt; batch requests with well-structured cached prefixes get both the ~50% batch discount and the ~90% cached-input discount. On GPT-5.6 Sol's promo, a cached input token in a batch request costs a fraction of a cent per million — the input side of the bill effectively disappears.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Batch + smaller models:&lt;/strong&gt; batching GPT-6.1 Sol ($2/$10 → $1/$5 batched) for bulk work gets you frontier-adjacent quality at budget-tier prices, halved again. For classification, extraction, and eval workloads, this combination is routinely 70–80% cheaper than the naive real-time flagship setup.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Batch + off-peak scheduling:&lt;/strong&gt; submit batches in the evening, collect results by morning standup. The latency is invisible because nobody was waiting.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Work the full stack on the earlier eval example: 500 cases/night on GPT-6.1 Sol batched with decent caching, and the $36/run real-time flagship cost collapses to single digits. That's not a marginal optimization — it's an order-of-magnitude change in what the workload costs to run.&lt;/p&gt;

&lt;h2&gt;
  
  
  Finding Your Batch Candidates
&lt;/h2&gt;

&lt;p&gt;If you're not sure what qualifies, run this audit over your API usage for a week:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;List every automated caller&lt;/strong&gt; — cron jobs, pipelines, background workers, scripts. Not user-facing features; machines.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;For each, ask: who reads the output, and when?&lt;/strong&gt; If the answer is "a dashboard tomorrow," "a data warehouse," or "an engineer next week," it's a batch candidate. If the answer is "a user staring at a spinner," it isn't.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Estimate the spend per candidate.&lt;/strong&gt; Even rough numbers work: requests/day × average tokens × rate. Rank by spend, migrate the top two first.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Most teams find their top batch candidates in places they weren't thinking about: the nightly data-quality checks, the weekly report generation, the eval suite someone runs manually every Friday, the backfill script that runs "just this once" every month. The pattern is always the same — work scheduled by habit on the real-time API that never needed to be real-time.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Bottom Line
&lt;/h2&gt;

&lt;p&gt;The Batch API is a 50% discount for the cost of patience, and most teams are leaving it on the table because their async work is accidentally running on the real-time API. Audit your jobs, find everything that doesn't need an answer in seconds, and move it. It's the easiest large discount in LLM pricing — same model, half the price, one day of engineering.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>llm</category>
      <category>openai</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
