查询OpenAI账号APIKey可用余额、使用量和使用明细接口,用python实现

闪电发卡3年前ChatGPT4809

现在可以使用以下接口进行实现


Python


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")
        days = min(5, 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} \n"
    else:
        return billing_response.text
 
    return f"\n总额:\t{total:.4f}  \n" \
                f"已用:\t{total_usage:.4f}  \n" \
                f"剩余:\t{total-total_usage:.4f}  \n" \
                f"\n"+recent

输出结果如下:


总额: 18.0000


已用: 0.4737


剩余: 17.5263


最近5天使用情况


2023-04-28 0.0


2023-04-27 0.0


2023-04-26 0.0


2023-04-25 0.0


2023-04-24 0.0


可访问 https://aichat.xingtupai.com 查看示例

余额查询方法可参考:https://www.chatgptzh.com/post/325.html


相关文章

详解闪电发卡所售各种的ChatGPT相关产品的基本概念和产品区别

我们在购买ChatGPT账号时由于产品众多,不能分清每个产品的不同,本篇文章就用最简单的语言让您了解ChatGPT相关产品的联系和区别。在购买ChatGPT产品之前,我们要了解ChatGPT相关的基本...

ChatGPT Plus会员升级指南:如何享受GPT-5的强大功能

闪电发卡ChatGPT和Claude产品推荐: ChatGPT Pro共享账号 ChatGPT Pro独享账号 ChatGPT独享账号 Claude Pr...

Python使用OpenAI官方库调用ChatGPT转发API调用示例(新版+旧版)

新版:OpenAI库1.0.0以上调用参数解释:https://www.chatgptzh.com/post/12.htmlfrom openai import Open...

ChatGPT应用案例:ChatGPT处理电子表格的若干例子详解

第一问:如何实现一个在线电子表格要实现一个在线电子表格,您需要使用以下步骤:选择一种编程语言和一个Web框架来创建您的应用程序。常见的Web框架包括Ruby on Rails、Django、Flask...

探索ChatGPT的原理:从输入到输出的全过程

大家好!今天我想和大家聊聊一个最近很火的话题——ChatGPT。可能有些朋友还不太清楚这是什么,其实它是一种基于人工智能技术的聊天机器人,可以和我们进行类似于人类对话的交流。今天就让我们一起来探索一下...

购买ChatGPT Pro共享账号的最佳平台推荐

闪电发卡ChatGPT和Claude产品推荐: ChatGPT Pro共享账号 ChatGPT Pro独享账号 ChatGPT独享账号 Claude Pr...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。