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

闪电发卡4年前ChatGPT5430

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


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


相关文章

交通运输行业的未来趋势:AI引领的新方向

近年来,随着科技的飞速发展,交通运输行业也在悄然发生着巨大的变革。尤其是人工智能(AI)的引入,为交通运输带来了前所未有的机遇和挑战。今天,我们就来聊聊交通运输行业的未来趋势,看看AI是如何引领这一新...

角色扮演 - Prompt教程

嘿,大家好!今天我们聊一个非常有趣的话题——角色扮演(RPG)在Prompt中的应用。相信很多人都听过或玩过RPG游戏,对吧?但你有没有想过,RPG的概念也可以用于日常生活和工作中呢?特别是在Prom...

怎样使用Sora?Sora产品介绍和使用教程攻略

怎样使用Sora?Sora产品介绍和使用教程攻略

Sora 是什么? 2024年2月16日,OpenAI 在其官网上面正式宣布推出文本生成视频的大模型 Sora: openai.com/sora (PS:目前 openai 官方还未开放 so...

ChatGPT 4.0购买攻略:获取最佳使用体验的方法

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

人工智能和ChatGPT在现代营销中的角色

在当今数字化迅速发展的时代,人工智能(AI)已经成为各行各业不可或缺的一部分。而在这个大背景下,ChatGPT作为一种先进的自然语言处理模型,正在重塑现代营销的面貌。本文将深入探讨人工智能和ChatG...

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

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