import os import time import logging import requests from datetime import datetime, timedelta from apscheduler.schedulers.background import BackgroundScheduler from flask import Flask, request, jsonify, Response, stream_with_context logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') API_ENDPOINT = "https://api.siliconflow.cn/v1/user/info" TEST_MODEL_ENDPOINT = "https://api.siliconflow.cn/v1/chat/completions" MODELS_ENDPOINT = "https://api.siliconflow.cn/v1/models" app = Flask(__name__) all_models = [] free_models = [] invalid_keys_global = [] free_keys_global = [] unverified_keys_global = [] valid_keys_global = [] def get_credit_summary(api_key): """ 使用 API 密钥获取额度信息。 """ headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } try: response = requests.get(API_ENDPOINT, headers=headers) response.raise_for_status() data = response.json().get("data", {}) total_balance = data.get("totalBalance", 0) return {"total_balance": float(total_balance)} except requests.exceptions.RequestException as e: logging.error(f"获取额度信息失败,API Key:{api_key},错误信息:{e}") return None except (KeyError, TypeError) as e: logging.error(f"解析额度信息失败,API Key:{api_key},错误信息:{e}") return None except ValueError as e: logging.error(f"total_balance 无法转换为浮点数,API Key:{api_key},错误信息:{e}") return None FREE_MODEL_TEST_KEY = "sk-bmjbjzleaqfgtqfzmcnsbagxrlohriadnxqrzfocbizaxukw" # 硬编码免费模型测试 KEY def test_model_availability(api_key, model_name): """ 测试指定的模型是否可用。 """ headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } try: response = requests.post(TEST_MODEL_ENDPOINT, headers=headers, json={ "model": model_name, "messages": [{"role": "user", "content": "hi"}], "max_tokens": 10, "stream": False }, timeout=10) # 正常返回或返回 429 都被认为是免费模型 if response.status_code == 429 or response.status_code == 200 : return True else: return False except requests.exceptions.RequestException as e: logging.error(f"测试模型 {model_name} 可用性失败,API Key:{api_key},错误信息:{e}") return False def refresh_models(): """ 刷新模型列表和免费模型列表。 """ global all_models, free_models # 使用 FREE_MODEL_TEST_KEY 获取所有模型列表 all_models = get_all_models(FREE_MODEL_TEST_KEY) free_models = [] # 使用 ThreadPoolExecutor 并发执行测试 with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor: # 限制最大工作线程数为 10,可根据实际情况调整 # 创建一个模型到 future 的映射 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: is_free = future.result() if is_free: free_models.append(model) except Exception as exc: logging.error(f"模型 {model} 测试生成异常: {exc}") logging.info(f"所有模型列表:{all_models}") logging.info(f"免费模型列表:{free_models}") def load_keys(): """ 从环境变量中加载 keys,并根据额度和模型可用性进行分类,然后记录到日志中。 """ keys_str = os.environ.get("KEYS") test_model = os.environ.get("TEST_MODEL", "Pro/google/gemma-2-9b-it") invalid_keys = [] free_keys = [] unverified_keys = [] valid_keys = [] if keys_str: keys = [key.strip() for key in keys_str.split(',')] logging.info(f"加载的 keys:{keys}") for key in keys: credit_summary = get_credit_summary(key) if credit_summary is None: invalid_keys.append(key) else: total_balance = credit_summary.get("total_balance", 0) if total_balance <= 0: free_keys.append(key) else: if test_model_availability(key, test_model): valid_keys.append(key) else: unverified_keys.append(key) logging.info(f"无效 KEY:{invalid_keys}") logging.info(f"免费 KEY:{free_keys}") logging.info(f"未实名 KEY:{unverified_keys}") logging.info(f"有效 KEY:{valid_keys}") # 更新全局的 key 列表 global invalid_keys_global, free_keys_global, unverified_keys_global, valid_keys_global invalid_keys_global = invalid_keys free_keys_global = free_keys unverified_keys_global = unverified_keys valid_keys_global = valid_keys else: logging.warning("环境变量 KEYS 未设置。") def get_all_models(api_key): """ 获取所有模型列表。 """ headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } try: response = requests.get(MODELS_ENDPOINT, headers=headers, params={"sub_type": "chat"}) response.raise_for_status() data = response.json() # 确保 data 是字典且包含 'data' 键,'data' 对应的值是一个列表 if isinstance(data, dict) and 'data' in data and isinstance(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"获取模型列表失败,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): """ 根据用户请求的模型判断请求类型。 """ if model_name in free_models: return "free" elif model_name in all_models: return "paid" else: return "unknown" def select_key(request_type): """ 根据请求类型选择合适的 KEY。 """ if request_type == "free": # 免费请求:使用 2、3、4 类 KEY available_keys = free_keys_global + unverified_keys_global + valid_keys_global elif request_type == "paid": # 付费请求:使用 3、4 类 KEY available_keys = unverified_keys_global + valid_keys_global else: # 未知请求:使用所有 KEY available_keys = free_keys_global + unverified_keys_global + valid_keys_global if not available_keys: return None # 简单的轮询策略选择 KEY key = available_keys[int(time.time() * 1000) % len(available_keys)] return key def check_authorization(request): """ 检查请求头中的 Authorization 字段是否匹配环境变量 AUTHORIZATION_KEY。 """ authorization_key = os.environ.get("AUTHORIZATION_KEY") if not authorization_key: logging.warning("环境变量 AUTHORIZATION_KEY 未设置,请设置后重试。") return False auth_header = request.headers.get('Authorization') if not auth_header: logging.warning("请求头中缺少 Authorization 字段。") return False if auth_header != f"Bearer {authorization_key}": logging.warning(f"无效的 Authorization 密钥:{auth_header}") return False return True # 创建一个后台调度器 scheduler = BackgroundScheduler() # 添加定时任务,每小时执行一次 load_keys 函数 scheduler.add_job(load_keys, 'interval', hours=1) # 添加定时任务,每10分钟执行一次 refresh_models 函数 scheduler.add_job(refresh_models, 'interval', minutes=10) @app.route('/') def index(): """ 处理根路由的访问请求。 """ return "