2023-09-23更新:openai在几个月前改了方式,现在通过APIKey是无法调用查询余额接口了,现在要查询余额只能用sessionKey(即登录帐号后才能获取),所以这个文章算是废了。

经常使用OpenAI服务的人都知道,如果拥有多个APIKey,要时刻关注这些key是否可用、余额多少,一个个查看太麻烦。为了解决这个问题,我编写了一个Python脚本,可以一键查看所有key的可用状态、余额多少、近5天使用量等等。方便
自己时刻掌握各个key的状态

功能特点

  • 多线程查询:支持多线程查询,避免key太多时慢
  • 简单原理:使用requests库发请求到OpenAI查询,不用额外装一些花里胡哨的依赖

使用方法

  1. 安装python

  2. 创建一个文件夹(名字随意),文件夹内创建一个keyManager.py(文件名随意),将下面的脚本代码粘贴上去。

     脚本代码默认加了代理`http://127.0.0.1:7890`,如果要去掉代理可以去掉里面的proxies对象
    
mkdir keyManager
vim keyManager.py
import requests
import datetime
import multiprocessing as mp

def get_monthly_stats(apikey):
    proxies = {
        "http": "http://127.0.0.1:7890",
        "https": "http://127.0.0.1:7890"
    }
    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, proxies=proxies)
    if subscription_response.status_code == 200:
        data = subscription_response.json()
        total = data.get("hard_limit_usd")
    else:
        return "-","-","-","-"
    # start_date设置为今天日期前32天
    start_date = (datetime.datetime.now() - datetime.timedelta(days=32)).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, proxies=proxies)
    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 = ""
        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"[{cost / 100:.4f}] "

        month_cost = 0
        days = min(datetime.datetime.today().day, len(daily_costs))
        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")
            for item in line_items:
                month_cost += item.get("cost")
        month_cost = month_cost / 100
    else:
        return "-","-","-","-"

    return round(total, 4), round(total_usage, 4), round(month_cost, 4), recent

def load_api_keys():
    with open('.config', 'r') as f:
        lines = f.readlines()
    api_keys = [{'name': line.split()[0], 'key': line.split()[1]} for line in lines]
    return api_keys

def generate_table():
    out_str = ""
    api_keys = load_api_keys()
    with mp.Pool() as pool:
        results = pool.map(get_stats_and_format, api_keys)
    out_str = "\n".join(results)
    return out_str

def get_stats_and_format(api_key):
    total, used, month_cost, recent = get_monthly_stats(api_key["key"])
    return f"{api_key['name']}\t{api_key['key']}\t总额:{total}\t已用:{used}\t本月已用:{month_cost}\t近5天使用: {recent}"

# 打印
print(generate_table())
  1. 创建一个配置文件.config(文件名不能改,跟keyManager.py里的代码有关联),将你的API Key和key的别名逐行添加到文件中。格式如下
key1 sk-xxxxxxxxx
key2 sk-xxxxxxxxx
key3 sk-xxxxxxxxx
  1. 运行脚本
python keyManager.py
  1. 结果

结果有-代表该key已失效

ubuntu@VM-20-4-ubuntu:~/keyManager$ python3 keyManager.py 
key1 sk-xxxxxxxxxxxxxxxx 总额:20.0 已用:2.2164 本月已用:0.128  近5天使用: [0.0000] [0.0000] [0.0000] [0.0000] [0.0000] 
key2 sk-xxxxxxxxxxxxxxxx 总额:20.0 已用:0.3663 本月已用:0.0496 近5天使用: [0.0000] [0.0000] [0.0000] [0.0000] [0.0000] 
key3 sk-xxxxxxxxxxxxxxxx 总额:20.0 已用:1.0931 本月已用:0.8504  近5天使用: [0.0000] [0.0136] [0.1339] [0.3178] [4.9815] 
key4 sk-xxxxxxxxxxxxxxxx 总额:120.0  已用:1.1929 本月已用:0.9798 近5天使用: [0.2239] [0.1067] [0.3364] [0.0327] [0.0000] 
key5 sk-xxxxxxxxxxxxxxxx 总额:-  已用:-  本月已用:-  近5天使用: -
key6 sk-xxxxxxxxxxxxxxxx 总额:-  已用:-  本月已用:-  近5天使用: -