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

闪电发卡3年前ChatGPT4722

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


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 Prompt:全面教程

大家好!今天我们要来聊一聊如何打造一个完美的ChatGPT Prompt。Prompt就是我们输入给ChatGPT的那段文本,它会引导AI给出相应的回答。掌握如何撰写有效的Prompt,不仅能提高回答...

从人工智能到电商成功:ChatGPT的多种应用

大家好,欢迎来到我的博客。今天我们来聊聊一个非常热门的话题——ChatGPT。你可能已经听说过ChatGPT,但你知道它不仅仅是一款聊天机器人吗?事实上,ChatGPT在各个领域都有着广泛的应用,从人...

中国国内如何优雅的使用ChatGPT:论ChatGPT的安全使用问题

中国国内如何优雅的使用ChatGPT:论ChatGPT的安全使用问题

ChatGPT 是一个在线的语言模型,可以通过 Web 端访问。由于中国大陆地区的网络环境和政策原因,访问 Web 端可能会遇到一些困难。以下是一些可能可行的方法:使用 VPN:通过使用 VPN 可以...

如何购买ChatGPT Plus 4.0会员账号:国内用户的完整指南

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

前沿技术与未来展望:迁移学习、强化学习与伦理问题

大家好,欢迎来到我的博客。今天,我们要探讨的是一些非常前沿的技术,如迁移学习和强化学习,同时也会涉及到这些技术在发展过程中不可忽视的伦理问题。人工智能(AI)不断进步,这些技术已经在各个领域中展现出巨...

发表评论    

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