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

闪电发卡3年前ChatGPT4706

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


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...

GPT-4o语音功能完全教程:如何用AI实现无缝语音交互体验

闪电发卡ChatGPT产品推荐: ChatGPT独享账号 ChatGPT Plus 4.0独享共享账号购买代充 ChatGPT APIKey 3.5和4.0购买充值(直连+...

AI人工智能在书籍编写中的应用:ChatGPT创作技巧

近年来,人工智能(AI)技术在各个领域得到了广泛的应用,书籍编写也不例外。AI不仅能帮助作者提升写作效率,还能为读者带来全新的阅读体验。今天,我们就来聊聊AI人工智能在书籍编写中的应用,特别是以Cha...

AI医疗行业的未来:ChatGPT和人工智能的融合

大家好,欢迎来到我的博客,今天我们要聊的是一个非常前沿的话题——AI医疗行业的未来:ChatGPT和人工智能的融合。这个话题听起来很酷,对吧?其实,它不仅酷,而且还关系到你我的生活。 我们都知道,医疗...

ChatGPT原理探秘:理解其在人工智能领域的重要性

随着人工智能技术的飞速发展,越来越多的应用程序和工具走进我们的生活。而在这些应用中,ChatGPT无疑是近年来最为瞩目的明星之一。作为一种强大的自然语言处理工具,ChatGPT得到了广泛的关注和研究。...

购买ChatGPT Plus成品号的五大理由

闪电发卡ChatGPT产品推荐:ChatGPT独享账号:https://www.chatgptzh.com/post/86.htmlChatGPT Plus独享共享账号购买代充:https://www...

发表评论    

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