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

闪电发卡3年前ChatGPT4509

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


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撬动百亿级应用搜索的AIGC市场

应用企业搜索的市场巨变——ChatGPT撬动百亿级应用搜索的AIGC市场

我们刚刚经历的不可思议的一周。本周,再次迎来了Open AI的另一个王炸。我们先来看一下简单的新闻稿:北美时间3月23日,Open AI在官网宣布推出ChatGPT插件功能,同时开源知识库检索插件源代...

ChatGPT在会计行业的未来前景:人工智能将如何改变财务分析

在当今的数字化时代,人工智能(AI)正以惊人的速度改变着各个行业,其中也包括会计行业。作为AI技术的前沿代表,ChatGPT不仅在日常交流中展现了其卓越的语言处理能力,更在专业领域展现出了巨大的潜力。...

深入剖析ChatGPT Pro:购买前需要了解的关键因素

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

最新ChatGPT 4.0购买信息:功能、价格与获取途径解析

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

ChatGPT-4.0有哪些优势,有哪些使用ChatGPT-4.0的方案

概述本文详细介绍了GPT-4和chatGPT的区别,GPT-4相对于ChatGPT有哪些进步和提升,GPT-4到底有哪些强大之处,GPT-4提供了哪些新功能和新变化,GPT-4具有什么特点和应用场景,...

人工智能与教育的结合:ChatGPT的优势和应用

随着科技的快速发展,人工智能(AI)逐渐渗透到我们生活的方方面面,其中教育领域的变革尤为显著。作为一名长期关注AI发展的博主,我想和大家聊聊一个在教育中备受关注的AI工具——ChatGPT。它究竟有哪...

发表评论    

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