How can i check OpenAI usage with Python?

Hi, i want to check my usage with API in Python and i’ll publish on my website.

How can i do this?

2 Likes

Hi @Gelistirici,

you can use the API-response to figure out the amount of tokens used. You can use this data to figure out the total token usage and work with.

I’m not sure if this helps but there are no other ways mentioned from OpenAI’s end…

Source:

How do I check my token usage? | OpenAI Help Center

1 Like

To specify: Extract the token - usage from the JSON, convert to integer and then add this to a variable where you store your token usage.

1 Like

It would be great if you could check historical usage data with an API request or download the usage data from the billing dashboard in a spreadsheet format.

r = openai.api_requestor.APIRequestor();
resp = r.request("GET", '/usage?date=2023-04-05'); // or start_date and end_date
resp_object = resp[0]
resp_object.data // this object has all the info
2 Likes

Is there any doc that I can refer to on request structure ?
I need to get usage till now from a specific date. I am using python but start_date and end_date isn’t working for it. It says it requires ‘date’ parameter.

A year ago someone posted this: How to track individual usage? - #6 by DutytoDevelop

I don’t know if it still works, didn’t try it. I did try the one posted here for a single date, and it works. I would be nice to find some documentation on it.

1 Like

You find an answer to this? It would be nice to be able to get a date range.

I was using two models, one for embedding and other for text completion. I couldn’t find much documentation on how to fetch usage directly. However I coded like below and it serves my purpose though it could be buggy as I am hardcoding some values.

import requests
import datetime

# API key
api_key = ""

# API headers
headers = {'Authorization': f'Bearer {api_key}'}

# API endpoint
url = 'https://api.openai.com/v1/usage'

# Date for which to get usage data
date = datetime.date(2023, 4, 24)

# Parameters for API request
params = {'date': date.strftime('%Y-%m-%d')}

# Send API request and get response
response = requests.get(url, headers=headers, params=params)
usage_data = response.json()['data']

# Calculate total number of tokens used for each model
total_tokens_used_davinci = 0
total_tokens_used_ada = 0

for data in usage_data:
    model_name = data['model']
    n_generated_tokens_total = data['n_generated_tokens_total']
    n_context_tokens_total = data['n_context_tokens_total']
    total_tokens = n_generated_tokens_total + n_context_tokens_total
    if model_name == 'text-davinci-003':
        total_tokens_used_davinci += total_tokens
    elif model_name == 'text-embedding-ada-002':
        total_tokens_used_ada += total_tokens

# Estimate cost for each model based on token usage
davinci_cost_per_token = 0.002 / 1000
ada_cost_per_token = 0.0004 / 1000

total_cost_davinci = total_tokens_used_davinci * davinci_cost_per_token
total_cost_ada = total_tokens_used_ada * ada_cost_per_token

# Print estimated costs
print(f"Total number of tokens used by text-davinci-003 on {date}: {total_tokens_used_davinci}")
print(f"Estimated cost for text-davinci-003 on {date}: ${total_cost_davinci:.2f}")

print(f"\nTotal number of tokens used by text-embedding-ada-002 on {date}: {total_tokens_used_ada}")
print(f"Estimated cost for text-embedding-ada-002 on {date}: ${total_cost_ada:.2f}")

3 Likes

@thomasjv for getting usage with respect to end date and start date you can use the /dashboard/billing/usage? endpoint,

r = openai.api_requestor.APIRequestor()
resp = r.request("GET", '/dashboard/billing/usage?end_date=2023-05-11&start_date=2023-05-01') #or start_date and end_date
resp_object = resp[0]
resp_object.data # this object has all the info
2 Likes

Thanks a lot this works ! May I know how you got the documentation for the request links ?

Followed up on the Network calls being made at the page:- OpenAI API

1 Like

Weirdly, this endpoint stopped working for me today and requesting a session key. Any way to get that?

2 Likes

I made an open-source tool based on @thomasjv 's snippet. apiusage.info

1 Like

@nbbaier I am also facing the same issue. I had integrated this call to create a dashboard for my app but suddenly it stopped working and asked for a session key when I made an API call from Postman.

Did you manage to get a workaround for this?

I haven’t other than storing the data that I get whenever I fetch it from the usage API. It’s frustrating.

I attempted a workaround, but it proved to be ineffective. I tried retrieving the session key from the browser by fetching the network calls and utilized it with the API call. This method only functions as long as the session remains valid.