Update app.py
Browse files53 unmodified lines545556575859606162634 unmodified lines68697071727374757677787980818283848586878889909192939495969798991001011021031043 unmodified lines10810911011111211311411511611717 unmodified lines13513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517613 unmodified lines19019119219319419519628 unmodified lines2252262272282292302312322332342352362372382392402412422432449 unmodified lines2542552562572582592602612622632642652662678 unmodified lines27627727827928028128228328428528628728828913 unmodified lines30330430530630730830913 unmodified lines3233243253263273283292 unmodified lines3323333343353363373383393403411 unmodified line3433443453463473483493503513523533543553563573583593603613627 unmodified lines37037137237337437537637737837938038125 unmodified lines4074084094104114124137 unmodified lines4214224234244254264274284294304314324334344354364374384393 unmodified lines4434444454464474484494504514524534544554564574584594604612 unmodified lines4644654664674684694704714724736 unmodified lines48048148248348448548648748848949049149249349449542 unmodified lines53853954054154254354454554654754854955055122 unmodified lines57457557657757857958035 unmodified lines6166176186196206216226236246256266276 unmodified lines6346356366376386396408 unmodified lines64965065165265365465565665765865966018 unmodified lines67968068168268368468568668768868969053 unmodified lineslogging.error(f"解析额度信息失败,API Key:{api_key},错误信息:{e}")return Noneexcept ValueError as e:logging.error(f"total_balance 无法转换为浮点数,API Key:{api_key},错误信息:{e}")return NoneFREE_MODEL_TEST_KEY = "sk-bmjbjzleaqfgtqfzmcnsbagxrlohriadnxqrzfocbizaxukw"def test_model_availability(api_key, model_name):"""4 unmodified lines"Content-Type": "application/json"}try:response = requests.post(TEST_MODEL_ENDPOINT,headers=headers,json={"model": model_name,"messages": [{"role": "user", "content": "hi"}],"max_tokens": 5,"stream": False},timeout=10)if response.status_code == 429 or response.status_code == 200:return Trueelse:return Falseexcept requests.exceptions.RequestException as e:logging.error(f"测试模型 {model_name} 可用性失败,API Key:{api_key},错误信息:{e}")return Falsedef refresh_models():"""刷新模型列表和免费模型列表。"""global all_models, free_models, embedding_models, free_embedding_modelsall_models = get_all_models(FREE_MODEL_TEST_KEY, "chat")embedding_models = get_all_models(FREE_MODEL_TEST_KEY, "embedding")free_models = []free_embedding_models = []with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:future_to_model = {executor.submit(test_model_availability, FREE_MODEL_TEST_KEY, model): model for model inall_models}for future in concurrent.futures.as_completed(future_to_model):model = future_to_model[future]try:3 unmodified linesexcept Exception as exc:logging.error(f"模型 {model} 测试生成异常: {exc}")with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:future_to_model = {executor.submit(test_embedding_model_availability, FREE_MODEL_TEST_KEY, model): model for model inembedding_models}for future in concurrent.futures.as_completed(future_to_model):model = future_to_model[future]try:17 unmodified lines"Content-Type": "application/json"}try:response = requests.post(EMBEDDINGS_ENDPOINT,headers=headers,json={"model": model_name,"input": ["hi"],},timeout=10)if response.status_code == 429 or response.status_code == 200:return Trueelse:return Falseexcept requests.exceptions.RequestException as e:logging.error(f"测试向量模型 {model_name} 可用性失败,API Key:{api_key},错误信息:{e}")return Falsedef load_keys():"""从环境变量中加载 keys,并根据额度和模型可用性进行分类,然后记录到日志中。使用线程池并发处理每个 key。"""keys_str = os.environ.get("KEYS")test_model = os.environ.get("TEST_MODEL", "Pro/google/gemma-2-9b-it")if keys_str:keys = [key.strip() for key in keys_str.split(',')]logging.info(f"加载的 keys:{keys}")with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:future_to_key = {executor.submit(process_key, key, test_model): key for key in keys}invalid_keys = []free_keys = []unverified_keys = []valid_keys = []for future in concurrent.futures.as_completed(future_to_key):key = future_to_key[future]try:key_type = future.result()13 unmodified lineslogging.info(f"未实名 KEY:{unverified_keys}")logging.info(f"有效 KEY:{valid_keys}")global invalid_keys_global, free_keys_global, unverified_keys_global, valid_keys_globalinvalid_keys_global = invalid_keysfree_keys_global = free_keysunverified_keys_global = unverified_keys28 unmodified lines"Content-Type": "application/json"}try:response = requests.get(MODELS_ENDPOINT, headers=headers, params={"sub_type": sub_type})response.raise_for_status()data = response.json()if isinstance(data, dict) and 'data' in data and isinstance(data['data'], list):return [model.get("id") for model in data["data"] ifisinstance(model, dict) and "id" in model]else:logging.error("获取模型列表失败:响应数据格式不正确")return []except requests.exceptions.RequestException as e:logging.error(f"获取模型列表失败,API Key:{api_key},错误信息:{e}")return []except (KeyError, TypeError) as e:logging.error(f"解析模型列表失败,API Key:{api_key},错误信息:{e}")return []def determine_request_type(model_name, model_list, free_model_list):9 unmodified linesdef select_key(request_type, model_name):"""根据请求类型和模型名称选择合适的 KEY,并实现轮询和重试机制。"""if request_type == "free":available_keys = free_keys_global + unverified_keys_global + valid_keys_globalelif request_type == "paid":available_keys = unverified_keys_global + valid_keys_globalelse:available_keys = free_keys_global + unverified_keys_global + valid_keys_globalif not available_keys:return None8 unmodified linesmodel_key_indices[model_name] = current_indexreturn keyelse:logging.warning(f"KEY {key} 无效或达到限制,尝试下一个 KEY")model_key_indices[model_name] = 0return Nonedef key_is_valid(key, request_type):"""检查 KEY 是否有效,根据不同的请求类型进行不同的检查。"""if request_type == "invalid":return False13 unmodified linesdef check_authorization(request):"""检查请求头中的 Authorization 字段是否匹配环境变量 AUTHORIZATION_KEY。"""authorization_key = os.environ.get("AUTHORIZATION_KEY")if not authorization_key:13 unmodified linesscheduler = BackgroundScheduler()scheduler.add_job(load_keys, 'interval', hours=1)scheduler.add_job(refresh_models, 'interval', minutes=10)@app.route('/')def index():2 unmodified lines@app.route('/check_tokens', methods=['POST'])def check_tokens():tokens = request.json.get('tokens', [])test_model = os.environ.get("TEST_MODEL", "Pro/google/gemma-2-9b-it")with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:future_to_token = {executor.submit(process_key, token, test_model): token for token in tokens}results = []for future in concurrent.futures.as_completed(future_to_token):1 unmodified linetry:key_type = future.result()credit_summary = get_credit_summary(token)balance = credit_summary.get("total_balance", 0) if credit_summary else 0if key_type == "invalid":results.append({"token": token, "type": "无效 KEY", "balance": balance, "message": "无法获取额度信息"})elif key_type == "free":results.append({"token": token, "type": "免费 KEY", "balance": balance, "message": "额度不足"})elif key_type == "unverified":results.append({"token": token, "type": "未实名 KEY", "balance": balance, "message": "无法使用指定模型"})elif key_type == "valid":results.append({"token": token, "type": "有效 KEY", "balance": balance, "message": "可以使用指定模型"})except Exception as exc:logging.error(f"处理 Token {token} 生成异常: {exc}")return jsonify(results)7 unmodified linesreturn jsonify({"error": "Invalid request data"}), 400model_name = data['model']request_type = determine_request_type(model_name, all_models, free_models)api_key = select_key(request_type, model_name)if not api_key:return jsonify({"error": "No available API key for this request type or all keys have reached their limits"}), 429headers = {"Authorization": f"Bearer {api_key}",25 unmodified linesyield chunkend_time = time.time()first_token_time = first_chunk_time - start_time if first_chunk_time else 0total_time = end_time - start_timeprompt_tokens = 07 unmodified linestry:response_json = json.loads(line)if "usage" in response_json and "completion_tokens" in response_json["usage"]:completion_tokens = response_json["usage"]["completion_tokens"]if "choices" in response_json and len(response_json["choices"]) > 0 and "delta" in \response_json["choices"][0] and "content" in response_json["choices"][0]["delta"]:response_content += response_json["choices"][0]["delta"]["content"]if "usage" in response_json and "prompt_tokens" in response_json["usage"]:prompt_tokens = response_json["usage"]["prompt_tokens"]except (KeyError, ValueError, IndexError) as e:logging.error(f"解析流式响应单行 JSON 失败: {e}, 行内容: {line}")user_content = ""messages = data.get("messages", [])3 unmodified linesuser_content += message["content"] + " "elif isinstance(message["content"], list):for item in message["content"]:if isinstance(item, dict) and item.get("type") == "text":user_content += item.get("text", "") + " "user_content = user_content.strip()user_content_replaced = user_content.replace('\n', '\\n').replace('\r', '\\n')response_content_replaced = response_content.replace('\n', '\\n').replace('\r', '\\n')logging.info(f"使用的key: {api_key}, 提示token: {prompt_tokens}, 输出token: {completion_tokens}, 首字用时: {first_token_time:.4f}秒, 总共用时: {total_time:.4f}秒, 使用的模型: {model_name}, 用户的内容: {user_content_replaced}, 输出的内容: {response_content_replaced}")return Response(stream_with_context(generate()), content_type=response.headers['Content-Type'])else:response.raise_for_status()end_time = time.time()2 unmodified linestry:prompt_tokens = response_json["usage"]["prompt_tokens"]completion_tokens = response_json["usage"]["completion_tokens"]response_content = response_json["choices"][0]["message"]["content"]except (KeyError, ValueError, IndexError) as e:logging.error(f"解析非流式响应 JSON 失败: {e}, 完整内容: {response_json}")prompt_tokens = 0completion_tokens = 0response_content = ""6 unmodified linesuser_content += message["content"] + " "elif isinstance(message["content"], list):for item in message["content"]:if isinstance(item, dict) and item.get("type") == "text":user_content += item.get("text", "") + " "user_content = user_content.strip()user_content_replaced = user_content.replace('\n', '\\n').replace('\r', '\\n')response_content_replaced = response_content.replace('\n', '\\n').replace('\r', '\\n')logging.info(f"使用的key: {api_key}, 提示token: {prompt_tokens}, 输出token: {completion_tokens}, 首字用时: 0, 总共用时: {total_time:.4f}秒, 使用的模型: {model_name}, 用户的内容: {user_content_replaced}, 输出的内容: {response_content_replaced}")return jsonify(response_json)42 unmodified lineskeys = valid_keys_global + unverified_keys_globaltotal_balance = 0with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:futures = [executor.submit(get_credit_summary, key) for key in keys]for future in concurrent.futures.as_completed(futures):try:credit_summary = future.result()if credit_summary:total_balance += credit_summary.get("total_balance", 0)except Exception as exc:logging.error(f"获取额度信息生成异常: {exc}")22 unmodified lines"total_usage": 0})@app.route('/handsome/v1/dashboard/billing/subscription', methods=['GET'])def billing_subscription():if not check_authorization(request):return jsonify({"error": "Unauthorized"}), 40135 unmodified linesreturn jsonify({"error": "Invalid request data"}), 400model_name = data['model']request_type = determine_request_type(model_name, embedding_models, free_embedding_models)api_key = select_key(request_type, model_name)if not api_key:return jsonify({"error": "No available API key for this request type or all keys have reached their limits"}), 429headers = {"Authorization": f"Bearer {api_key}",6 unmodified linesEMBEDDINGS_ENDPOINT,headers=headers,json=data,timeout=60)if response.status_code == 429:8 unmodified linesprompt_tokens = response_json["usage"]["prompt_tokens"]embedding_data = response_json["data"]except (KeyError, ValueError, IndexError) as e:logging.error(f"解析响应 JSON 失败: {e}, 完整内容: {response_json}")prompt_tokens = 0embedding_data = []logging.info(f"使用的key: {api_key}, 提示token: {prompt_tokens}, 总共用时: {total_time:.4f}秒, 使用的模型: {model_name}")return jsonify({18 unmodified linesunverified_keys_global = []valid_keys_global = []scheduler.start()load_keys()logging.info("首次加载 keys 已手动触发执行")refresh_models()logging.info("首次刷新模型列表已手动触发执行")app.run(debug=False, host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))53 unmodified lines5455565758596061626364656667684 unmodified lines7374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211223 unmodified lines12612712812913013113213313413513613713813914017 unmodified lines15815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022113 unmodified lines23523623723823924024124228 unmodified lines2712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053069 unmodified lines3163173183193203213223233243253263273283293303313323333343353363373388 unmodified lines34734834935035135235335435535635735835936036136236313 unmodified lines37737837938038138238338413 unmodified lines3983994004014024034044052 unmodified lines4084094104114124134144154164174184194204214224234244254261 unmodified line4284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764777 unmodified lines48548648748848949049149249349449549649749849950050150250350450550650725 unmodified lines5335345355365375385395405415427 unmodified lines5505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915923 unmodified lines5965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336342 unmodified lines6376386396406416426436446456466476486496506516526536 unmodified lines66066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069142 unmodified lines73473573673773873974074174274374474574674774874975075175275375422 unmodified lines77777877978078178278378478578635 unmodified lines8228238248258268278288298308318328338348358368378388398408418428438446 unmodified lines8518528538548558568578 unmodified lines86686786886987087187287387487587687787887988088188288318 unmodified lines90290390490590690790890991091191291391491591691791891992092153 unmodified lineslogging.error(f"解析额度信息失败,API Key:{api_key},错误信息:{e}")return Noneexcept ValueError as e:logging.error(f"total_balance 无法转换为浮点数,"f"API Key:{api_key},错误信息:{e}")return NoneFREE_MODEL_TEST_KEY = ("sk-bmjbjzleaqfgtqfzmcnsbagxrlohriadnxqrzfocbizaxukw")def test_model_availability(api_key, model_name):"""4 unmodified lines"Content-Type": "application/json"}try:response = requests.post(TEST_MODEL_ENDPOINT,headers=headers,json={"model": model_name,"messages": [{"role": "user", "content": "hi"}],"max_tokens": 5,"stream": False},timeout=10)if response.status_code == 429 or response.status_code == 200:return Trueelse:return Falseexcept requests.exceptions.RequestException as e:logging.error(f"测试模型 {model_name} 可用性失败,"f"API Key:{api_key},错误信息:{e}")return Falsedef refresh_models():"""刷新模型列表和免费模型列表。"""global all_models, free_modelsglobal embedding_models, free_embedding_modelsall_models = get_all_models(FREE_MODEL_TEST_KEY, "chat")embedding_models = get_all_models(FREE_MODEL_TEST_KEY, "embedding")free_models = []free_embedding_models = []with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:future_to_model = {executor.submit(test_model_availability,FREE_MODEL_TEST_KEY,model): model for model in all_models}for future in concurrent.futures.as_completed(future_to_model):model = future_to_model[future]try:3 unmodified linesexcept Exception as exc:logging.error(f"模型 {model} 测试生成异常: {exc}")with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:future_to_model = {executor.submit(test_embedding_model_availability,FREE_MODEL_TEST_KEY, model): model for model in embedding_models}for future in concurrent.futures.as_completed(future_to_model):model = future_to_model[future]try:17 unmodified lines"Content-Type": "application/json"}try:response = requests.post(EMBEDDINGS_ENDPOINT,headers=headers,json={"model": model_name,"input": ["hi"],},timeout=10)if response.status_code == 429 or response.status_code == 200:return Trueelse:return Falseexcept requests.exceptions.RequestException as e:logging.error(f"测试向量模型 {model_name} 可用性失败,"f"API Key:{api_key},错误信息:{e}")return Falsedef load_keys():"""从环境变量中加载 keys,进行去重,并根据额度和模型可用性进行分类,然后记录到日志中。使用线程池并发处理每个 key。"""keys_str = os.environ.get("KEYS")test_model = os.environ.get("TEST_MODEL","Pro/google/gemma-2-9b-it")if keys_str:keys = [key.strip() for key in keys_str.split(',')]unique_keys = list(set(keys))keys_str = ','.join(unique_keys)os.environ["KEYS"] = keys_strlogging.info(f"加载的 keys:{unique_keys}")with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:future_to_key = {executor.submit(process_key, key, test_model): key for key in unique_keys}invalid_keys = []free_keys = []unverified_keys = []valid_keys = []for future in concurrent.futures.as_completed(future_to_key):key = future_to_key[future]try:key_type = future.result()13 unmodified lineslogging.info(f"未实名 KEY:{unverified_keys}")logging.info(f"有效 KEY:{valid_keys}")global invalid_keys_global, free_keys_globalglobal unverified_keys_global, valid_keys_globalinvalid_keys_global = invalid_keysfree_keys_global = free_keysunverified_keys_global = unverified_keys28 unmodified lines"Content-Type": "application/json"}try:response = requests.get(MODELS_ENDPOINT,headers=headers,params={"sub_type": sub_type})response.raise_for_status()data = response.json()if (isinstance(data, dict) and'data' in data andisinstance(data['data'], list)):return [model.get("id") for model in data["data"]if isinstance(model, dict) and "id" in model]else:logging.error("获取模型列表失败:响应数据格式不正确")return []except requests.exceptions.RequestException as e:logging.error(f"获取模型列表失败,"f"API Key:{api_key},错误信息:{e}")return []except (KeyError, TypeError) as e:logging.error(f"解析模型列表失败,"f"API Key:{api_key},错误信息:{e}")return []def determine_request_type(model_name, model_list, free_model_list):9 unmodified linesdef select_key(request_type, model_name):"""根据请求类型和模型名称选择合适的 KEY,并实现轮询和重试机制。"""if request_type == "free":available_keys = (free_keys_global +unverified_keys_global +valid_keys_global)elif request_type == "paid":available_keys = unverified_keys_global + valid_keys_globalelse:available_keys = (free_keys_global +unverified_keys_global +valid_keys_global)if not available_keys:return None8 unmodified linesmodel_key_indices[model_name] = current_indexreturn keyelse:logging.warning(f"KEY {key} 无效或达到限制,尝试下一个 KEY")model_key_indices[model_name] = 0return Nonedef key_is_valid(key, request_type):"""检查 KEY 是否有效,根据不同的请求类型进行不同的检查。"""if request_type == "invalid":return False13 unmodified linesdef check_authorization(request):"""检查请求头中的 Authorization 字段是否匹配环境变量 AUTHORIZATION_KEY。"""authorization_key = os.environ.get("AUTHORIZATION_KEY")if not authorization_key:13 unmodified linesscheduler = BackgroundScheduler()scheduler.add_job(load_keys, 'interval', hours=1)scheduler.remove_all_jobs()scheduler.add_job(refresh_models, 'interval', hours=1)@app.route('/')def index():2 unmodified lines@app.route('/check_tokens', methods=['POST'])def check_tokens():tokens = request.json.get('tokens', [])test_model = os.environ.get("TEST_MODEL","Pro/google/gemma-2-9b-it")with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:future_to_token = {executor.submit(process_key, token, test_model): token for token in tokens}results = []for future in concurrent.futures.as_completed(future_to_token):1 unmodified linetry:key_type = future.result()credit_summary = get_credit_summary(token)balance = (credit_summary.get("total_balance", 0)if credit_summary else 0)if key_type == "invalid":results.append({"token": token,"type": "无效 KEY","balance": balance,"message": "无法获取额度信息"})elif key_type == "free":results.append({"token": token,"type": "免费 KEY","balance": balance,"message": "额度不足"})elif key_type == "unverified":results.append({"token": token,"type": "未实名 KEY","balance": balance,"message": "无法使用指定模型"})elif key_type == "valid":results.append({"token": token,"type": "有效 KEY","balance": balance,"message": "可以使用指定模型"})except Exception as exc:logging.error(f"处理 Token {token} 生成异常: {exc}")return jsonify(results)7 unmodified linesreturn jsonify({"error": "Invalid request data"}), 400model_name = data['model']request_type = determine_request_type(model_name,all_models,free_models)api_key = select_key(request_type, model_name)if not api_key:return jsonify({"error": ("No available API key for this ""request type or all keys have ""reached their limits")}), 429headers = {"Authorization": f"Bearer {api_key}",25 unmodified linesyield chunkend_time = time.time()first_token_time = (first_chunk_time - start_timeif first_chunk_time else 0)total_time = end_time - start_timeprompt_tokens = 07 unmodified linestry:response_json = json.loads(line)if ("usage" in response_json and"completion_tokens" in response_json["usage"]):completion_tokens = response_json["usage"]["completion_tokens"]if ("choices" in response_json andlen(response_json["choices"]) > 0 and"delta" in response_json["choices"][0] and"content" in response_json["choices"][0]["delta"]):response_content += response_json["choices"][0]["delta"]["content"]if ("usage" in response_json and"prompt_tokens" in response_json["usage"]):prompt_tokens = response_json["usage"]["prompt_tokens"]except (KeyError,ValueError,IndexError) as e:logging.error(f"解析流式响应单行 JSON 失败: {e}, "f"行内容: {line}")user_content = ""messages = data.get("messages", [])3 unmodified linesuser_content += message["content"] + " "elif isinstance(message["content"], list):for item in message["content"]:if (isinstance(item, dict) anditem.get("type") == "text"):user_content += (item.get("text", "") +" ")user_content = user_content.strip()user_content_replaced = user_content.replace('\n', '\\n').replace('\r', '\\n')response_content_replaced = response_content.replace('\n', '\\n').replace('\r', '\\n')logging.info(f"使用的key: {api_key}, "f"提示token: {prompt_tokens}, "f"输出token: {completion_tokens}, "f"首字用时: {first_token_time:.4f}秒, "f"总共用时: {total_time:.4f}秒, "f"使用的模型: {model_name}, "f"用户的内容: {user_content_replaced}, "f"输出的内容: {response_content_replaced}")return Response(stream_with_context(generate()),content_type=response.headers['Content-Type'])else:response.raise_for_status()end_time = time.time()2 unmodified linestry:prompt_tokens = response_json["usage"]["prompt_tokens"]completion_tokens = response_json["usage"]["completion_tokens"]response_content = response_json["choices"][0]["message"]["content"]except (KeyError, ValueError, IndexError) as e:logging.error(f"解析非流式响应 JSON 失败: {e}, "f"完整内容: {response_json}")prompt_tokens = 0completion_tokens = 0response_content = ""6 unmodified linesuser_content += message["content"] + " "elif isinstance(message["content"], list):for item in message["content"]:if (isinstance(item, dict) anditem.get("type") == "text"):user_content += (item.get("text", "") + " ")user_content = user_content.strip()user_content_replaced = user_content.replace('\n', '\\n').replace('\r', '\\n')response_content_replaced = response_content.replace('\n', '\\n').replace('\r', '\\n')logging.info(f"使用的key: {api_key}, "f"提示token: {prompt_tokens}, "f"输出token: {completion_tokens}, "f"首字用时: 0, "f"总共用时: {total_time:.4f}秒, "f"使用的模型: {model_name}, "f"用户的内容: {user_content_replaced}, "f"输出的内容: {response_content_replaced}")return jsonify(response_json)42 unmodified lineskeys = valid_keys_global + unverified_keys_globaltotal_balance = 0with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:futures = [executor.submit(get_credit_summary, key) for key in keys]for future in concurrent.futures.as_completed(futures):try:credit_summary = future.result()if credit_summary:total_balance += credit_summary.get("total_balance",0)except Exception as exc:logging.error(f"获取额度信息生成异常: {exc}")22 unmodified lines"total_usage": 0})@app.route('/handsome/v1/dashboard/billing/subscription',methods=['GET'])def billing_subscription():if not check_authorization(request):return jsonify({"error": "Unauthorized"}), 40135 unmodified linesreturn jsonify({"error": "Invalid request data"}), 400model_name = data['model']request_type = determine_request_type(model_name,embedding_models,free_embedding_models)api_key = select_key(request_type, model_name)if not api_key:return jsonify({"error": ("No available API key for this ""request type or all keys have ""reached their limits")}), 429headers = {"Authorization": f"Bearer {api_key}",6 unmodified linesEMBEDDINGS_ENDPOINT,headers=headers,json=data,timeout=120)if response.status_code == 429:8 unmodified linesprompt_tokens = response_json["usage"]["prompt_tokens"]embedding_data = response_json["data"]except (KeyError, ValueError, IndexError) as e:logging.error(f"解析响应 JSON 失败: {e}, "f"完整内容: {response_json}")prompt_tokens = 0embedding_data = []logging.info(f"使用的key: {api_key}, "f"提示token: {prompt_tokens}, "f"总共用时: {total_time:.4f}秒, "f"使用的模型: {model_name}")return jsonify({18 unmodified linesunverified_keys_global = []valid_keys_global = []# 启动时先调用一次 load_keys()load_keys()logging.info("程序启动时首次加载 keys 已执行")scheduler.start()# load_keys()logging.info("首次加载 keys 已手动触发执行")refresh_models()logging.info("首次刷新模型列表已手动触发执行")app.run(debug=False,host='0.0.0.0',port=int(os.environ.get('PORT', 7860)))
app.py+330-99