OpenAI Cost Tracking Middleware: Build a Logging Wrapper That Shows Every Call's Price
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. 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 why an OpenAI bill gets so high kept pointing back to: measure first, optimise second. Why your dashboard arrives too late ...