How to track API usage and cost by API key?

Is there a way to get this API key-level usage more programmatically through a usage endpoint? Not much point in having separate API keys for different teams if the only way to view usage is through an unconfigurable dashboard…

In the api.openai.com/v1/usage endpoint I see new inner fields for api_key_id and api_key_name but they seem to always be null. Would be really helpful if they were filled in or if there was a way to query usage by API key ID/name

Based on pointers in this thread, I’ve created a small Python script that can fetch and compute API usage and cost by API key and model, as well as input and output tokens.

One catch is that you need to get and enter in your session key from the request that your browser makes (ie. the network requests tab in your Chrome console). Thankfully, I’ve noticed that the session key is quite stable for me (doesn’t change across days).

Please leave any comments / I’m open to any feedback on the gist directly. Thanks!

I can’t put links in my post so go to

gist.github.com/shivaalroy/df3af8f3c9d6ba4f75b5361ea151c336
1 Like

perhaps you’ve noticed already, but on the API key page, you need to individually enable tracking per API key for older API keys - this is why you’re taken to this page from the “turn on tracking” link. New API keys are tracked by default.