[Python] How to efficiently query the remaining quota and past usage history of ChatGPT (detailed code)


foreword

The current popularity of chatgpt is self-evident

But many development friends, or friends who use it for learning do not know how much credit is left in their key

1. Problems encountered

Officially disabled the previous acquisition method, the link is as follows:

https://api.openai.com/dashboard/billing/credit_grants

will get the following response

Your request to GET /dashboard/billing/credit_grants must be made with a session key (that is, it can only be made from the browser). You made it with the following key type: secret.

In fact, it is caused by replacing the general key with a session key

Not much to say, the following is the encapsulated currently available method of querying the remaining keys of chatGPT:

2. Practical code

1. Import library

The code is as follows (example):

import datetime
import requests
# macll.cn 免费用gpt!!

def get_key(apikey):
    subscription_url = "https://api.openai.com/v1/dashboard/billing/subscription"
    headers = {
    
    "Authorization": "Bearer " + apikey,
               "Content-Type": "application/json"}
    subscription_response = requests.get(subscription_url, headers=headers)
    if subscription_response.status_code == 200:
        data = subscription_response.json()
        total = data.get("hard_limit_usd")
    else:
        return subscription_response.text
    # start_date设置为今天日期前99
    start_date = (datetime.datetime.now() - datetime.timedelta(days=99)).strftime("%Y-%m-%d")
    # end_date设置为今天日期+1
    end_date = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
    billing_url = f"https://api.openai.com/v1/dashboard/billing/usage?start_date={start_date}&end_date={end_date}"
    billing_response = requests.get(billing_url, headers=headers)
    if billing_response.status_code == 200:
        data = billing_response.json()
        total_usage = data.get("total_usage") / 100
        daily_costs = data.get("daily_costs")
        # 这个10就是指10天,可以自己调整~
        days = min(10, len(daily_costs))
        recent = f"##### 最近{days}天使用情况  \n"
        for i in range(days):
            cur = daily_costs[-i - 1]
            date = datetime.datetime.fromtimestamp(cur.get("timestamp")).strftime("%Y-%m-%d")
            line_items = cur.get("line_items")
            cost = 0
            for item in line_items:
                cost += item.get("cost")
            recent += f"\t{date}\t{(cost / 100):.2f} \n"
    else:
        return billing_response.text

    return f"\n#### 监控key为:{apikey[:-25] + '*' * 25}\n" \
           f"#### 总额:\t{total:.2f}  \n" \
           f"#### 已用:\t{total_usage:.2f}  \n" \
           f"#### 剩余:\t{total - total_usage:.2f}  \n" \
           f"\n" + recent


print(get_key(apikey="这里放入你的key"))

insert image description here
You can also access your own mailbox and monitor it at any time, which is convenient and reliable~

insert image description here

The code is tested and works!

Summarize

If you find it useful, please click three times

Guess you like

Origin blog.csdn.net/liaozp88/article/details/130642797