eveyuyi/ChatGPT_Prompts
0
1import requests2import logging3from modules.presets import timeout_all, BALANCE_API_URL,standard_error_msg,connection_timeout_prompt,error_retrieve_prompt,read_timeout_prompt4from modules import shared5import os6 7 8def get_usage_response(openai_api_key):9 headers = {10 "Content-Type": "application/json",11 "Authorization": f"Bearer {openai_api_key}",12 }13 14 timeout = timeout_all15 16 # 获取环境变量中的代理设置17 http_proxy = os.environ.get("HTTP_PROXY") or os.environ.get("http_proxy")18 https_proxy = os.environ.get(19 "HTTPS_PROXY") or os.environ.get("https_proxy")20 21 # 如果存在代理设置,使用它们22 proxies = {}23 if http_proxy:24 logging.info(f"使用 HTTP 代理: {http_proxy}")25 proxies["http"] = http_proxy26 if https_proxy:27 logging.info(f"使用 HTTPS 代理: {https_proxy}")28 proxies["https"] = https_proxy29 30 # 如果有代理,使用代理发送请求,否则使用默认设置发送请求31 """32 暂不支持修改33 if shared.state.balance_api_url != BALANCE_API_URL:34 logging.info(f"使用自定义BALANCE API URL: {shared.state.balance_api_url}")35 """36 if proxies:37 response = requests.get(38 BALANCE_API_URL,39 headers=headers,40 timeout=timeout,41 proxies=proxies,42 )43 else:44 response = requests.get(45 BALANCE_API_URL,46 headers=headers,47 timeout=timeout,48 )49 return response50 51def get_usage(openai_api_key):52 try:53 response=get_usage_response(openai_api_key=openai_api_key)54 logging.debug(response.json())55 try:56 balance = response.json().get("total_available") if response.json().get(57 "total_available") else 058 total_used = response.json().get("total_used") if response.json().get(59 "total_used") else 060 except Exception as e:61 logging.error(f"API使用情况解析失败:"+str(e))62 balance = 063 total_used=064 return f"**API使用情况**(已用/余额)\u3000{total_used}$ / {balance}$"65 except requests.exceptions.ConnectTimeout:66 status_text = standard_error_msg + connection_timeout_prompt + error_retrieve_prompt67 return status_text68 except requests.exceptions.ReadTimeout:69 status_text = standard_error_msg + read_timeout_prompt + error_retrieve_prompt70 return status_text71 