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

闪电发卡3年前ChatGPT4874

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


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与人力资源:如何实现智能化员工入职

在科技飞速发展的今天,人工智能(AI)正以前所未有的速度渗透到各行各业,其中,ChatGPT作为一款强大的语言模型,在人力资源领域中也逐渐展现出了其独特的优势。特别是在员工入职这一环节,ChatGPT...

闪电发卡ChatGPT账号购买批发商品优惠

为感谢广大用户对闪电发卡的支持,即日起用户在闪电发卡淘宝店铺下单并好评可以享受商品低价打折优惠。商品优惠价格详情如下:ChatGPT独享账号(微软邮箱,0余额):0.5元/个ChatGPT Plus共...

用ChatGPT生成热门视频脚本:自媒体创作新利器

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

ChatGPT的技术架构:探索背后的AI算法与训练数据

在今天的科技世界中,AI已经变得无处不在。而在这片广袤的人工智能领域中,ChatGPT无疑是其中的明星。你或许会好奇,是什么样的技术架构支撑起了ChatGPT?它背后的AI算法和训练数据又是怎样的呢?...

keyimage.jpg

利用ChatGPT背后的AI加速药物发现 - 每天可筛选1亿种化合物

通过将语言模型应用于蛋白质与药物的相互作用,研究人员可以快速筛选大量的潜在药物化合物库。巨大的药物化合物库可能拥有治疗各种疾病的潜力,如癌症或心脏病。理想情况下,科学家们希望通过实验对这些化合物中的每...

ChatGPT与会计自动化:人工智能如何减少财务错误

大家好!今天我们来聊一聊一个既前沿又实用的话题——ChatGPT与会计自动化:人工智能如何减少财务错误。 随着科技的迅猛发展,人工智能(AI)已经逐渐渗透到各行各业,其中会计领域也不例外。过去,财务工...

发表评论    

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