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

闪电发卡1年前ChatGPT1969

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


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


相关文章

微软账户官网注册教程,使用自己的邮箱或手机号

微软账户官网注册教程,使用自己的邮箱或手机号

一、准备1、使用国内IP,正常网络就可以2、建议使用edge浏览器3、准备任意邮箱或任意手机号,也可以现注册微软outlook或hotmail邮箱二、开始注册1、打开微软账户官网,点击登录https:...

ChatGPT的工作原理:深入探究和分析ChatGPT背后的原理

ChatGPT的工作原理:深入探究和分析ChatGPT背后的原理

这篇文章主要探讨了ChatGPT的工作原理。ChatGPT是基于OpenAI开发的GPT-4架构的大型语言模型。首先,文章介绍了GPT的基本概念,即生成预测性网络模型。GPT模型利用大量的文本数据进行...

ChatGPT账号被封,如何申诉找回

昨天还传言ChatGPT暂停注册,今天ChatGPT就大面积封号,哀鸿遍野,不管你是不是亚洲地区,不管你是普号还是Plus号,都有被封号的案例。目前还没有一个绝对封号的参考标准大家不要随意切IP,据说...

ChatGPT会取代程序员吗?人类技术发展历史浅析

ChatGPT会取代程序员吗?人类技术发展历史浅析

近几日ChatGPT火爆全网,一时间ChatGPT遍布各行各业被不同身份不同背景的用户征询各种千奇百怪的问题,其回答的专业程度切题度让人叹为观止。所有信息类咨询类的岗位都在大呼狼来了,甚至有好事的媒体...

chatgpt新版gpt-3.5-turbo模型API教程

形式:输入一个问题,模型会生成一个结果,一问一答形式功能:创建一个聊天接口地址:POST https://api.openai.com/v1/chat/completions (B...

2023年4月最强AI开源项目合集

一、MiniGPT-4https://github.com/Vision-CAIR/MiniGPT-4来自阿布杜拉国王科技大学的几位博士做的,它能够提供类似于GPT4的图像理解,以及对话的能力,让你抢...

发表评论    

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