2023.04.02似乎官方禁用了之前的获取方式,通过https://api.openai.com/dashboard/billing/credit_grants
将会得到如下回复
Your request to GET /dashboard/billing/credit_grants must be made with a session key (that is, it can only be made from the browser). You made it with the following key type: secret.
可将实现方式改为如下文章来源:https://www.toymoban.com/news/detail-533109.html
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
返回示例如下:from https://github.com/LiangYang666/ChatGPT-Web
文章来源地址https://www.toymoban.com/news/detail-533109.html
到了这里,关于【python】使用apikey查询OpenAi可用余额的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!