yangtb24 commited on
Commit
e5dce64
1 Parent(s): 76f9b1e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -41
app.py CHANGED
@@ -9,7 +9,8 @@ from flask import Flask, request, jsonify
9
  logging.basicConfig(level=logging.INFO,
10
  format='%(asctime)s - %(levelname)s - %(message)s')
11
 
12
- API_ENDPOINT = "https://api.siliconflow.cn/v1/user/info" # 修改为获取用户信息的接口
 
13
 
14
  app = Flask(__name__)
15
 
@@ -25,7 +26,7 @@ def get_credit_summary(api_key):
25
  response = requests.get(API_ENDPOINT, headers=headers)
26
  response.raise_for_status()
27
  data = response.json().get("data", {})
28
- total_balance = data.get("totalBalance", 0) # 获取总余额
29
  return {"total_balance": total_balance}
30
  except requests.exceptions.RequestException as e:
31
  logging.error(f"获取额度信息失败,API Key:{api_key},错误信息:{e}")
@@ -34,19 +35,73 @@ def get_credit_summary(api_key):
34
  logging.error(f"解析额度信息失败,API Key:{api_key},错误信息:{e}")
35
  return None
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  def load_keys():
38
  """
39
- 从环境变量中加载 keys,并记录到日志中,同时获取并记录每个 key 的额度信息。
40
  """
41
  keys_str = os.environ.get("KEYS")
 
 
 
 
 
 
 
42
  if keys_str:
43
  keys = [key.strip() for key in keys_str.split(',')]
44
  logging.info(f"加载的 keys:{keys}")
45
 
46
  for key in keys:
47
  credit_summary = get_credit_summary(key)
48
- if credit_summary:
49
- logging.info(f"API Key:{key},额度信息:{credit_summary}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  else:
51
  logging.warning("环境变量 KEYS 未设置。")
52
 
@@ -69,45 +124,22 @@ def check_tokens():
69
  处理前端发送的 Token 检测请求。
70
  """
71
  tokens = request.json.get('tokens', [])
 
 
72
  results = []
73
  for token in tokens:
74
- is_valid = False
75
- balance = 0
76
- error_message = ""
77
-
78
- # 先尝试进行一个简单的请求来验证 Token 的有效性
79
- try:
80
- headers = {
81
- "Authorization": f"Bearer {token}",
82
- "Content-Type": "application/json"
83
- }
84
- test_response = requests.post("https://api.siliconflow.cn/v1/chat/completions",
85
- headers=headers,
86
- json={
87
- "model": "Qwen/Qwen2.5-72B-Instruct",
88
- "messages": [{"role": "user", "content": "hi"}],
89
- "max_tokens": 100,
90
- "stream": False
91
- },
92
- timeout=5)
93
-
94
- if test_response.status_code == 200:
95
- is_valid = True
96
- credit_summary = get_credit_summary(token)
97
- if credit_summary:
98
- balance = credit_summary.get("total_balance", 0)
99
  else:
100
- error_message = test_response.json().get("message", "未知错误")
101
-
102
- except requests.exceptions.RequestException as e:
103
- error_message = str(e)
104
-
105
- results.append({
106
- "token": token,
107
- "isValid": is_valid,
108
- "balance": balance,
109
- "message": error_message
110
- })
111
 
112
  return jsonify(results)
113
 
 
9
  logging.basicConfig(level=logging.INFO,
10
  format='%(asctime)s - %(levelname)s - %(message)s')
11
 
12
+ API_ENDPOINT = "https://api.siliconflow.cn/v1/user/info"
13
+ TEST_MODEL_ENDPOINT = "https://api.siliconflow.cn/v1/chat/completions"
14
 
15
  app = Flask(__name__)
16
 
 
26
  response = requests.get(API_ENDPOINT, headers=headers)
27
  response.raise_for_status()
28
  data = response.json().get("data", {})
29
+ total_balance = data.get("totalBalance", 0)
30
  return {"total_balance": total_balance}
31
  except requests.exceptions.RequestException as e:
32
  logging.error(f"获取额度信息失败,API Key:{api_key},错误信息:{e}")
 
35
  logging.error(f"解析额度信息失败,API Key:{api_key},错误信息:{e}")
36
  return None
37
 
38
+ def test_model_availability(api_key, model_name):
39
+ """
40
+ 测试指定的模型是否可用。
41
+ """
42
+ headers = {
43
+ "Authorization": f"Bearer {api_key}",
44
+ "Content-Type": "application/json"
45
+ }
46
+ try:
47
+ response = requests.post(TEST_MODEL_ENDPOINT,
48
+ headers=headers,
49
+ json={
50
+ "model": model_name,
51
+ "messages": [{"role": "user", "content": "hi"}],
52
+ "max_tokens": 10,
53
+ "stream": False
54
+ },
55
+ timeout=10)
56
+ response.raise_for_status()
57
+ # 检查是否是429错误
58
+ if response.status_code == 429:
59
+ return True
60
+
61
+ response.json() # 尝试解析 JSON 响应
62
+ return True
63
+ except requests.exceptions.RequestException as e:
64
+ logging.error(f"测试模型 {model_name} 可用性失败,API Key:{api_key},错误信息:{e}")
65
+ return False
66
+ except ValueError:
67
+ logging.error(f"测试模型 {model_name} 可用性失败,API Key:{api_key},响应不是有效的 JSON 格式")
68
+ return False
69
+
70
  def load_keys():
71
  """
72
+ 从环境变量中加载 keys,并根据额度和模型可用性进行分类,然后记录到日志中。
73
  """
74
  keys_str = os.environ.get("KEYS")
75
+ test_model = os.environ.get("TEST_MODEL", "Pro/google/gemma-2-9b-it")
76
+
77
+ invalid_keys = []
78
+ free_keys = []
79
+ unverified_keys = []
80
+ valid_keys = []
81
+
82
  if keys_str:
83
  keys = [key.strip() for key in keys_str.split(',')]
84
  logging.info(f"加载的 keys:{keys}")
85
 
86
  for key in keys:
87
  credit_summary = get_credit_summary(key)
88
+ if credit_summary is None:
89
+ invalid_keys.append(key)
90
+ else:
91
+ total_balance = credit_summary.get("total_balance", 0)
92
+ if total_balance <= 0:
93
+ free_keys.append(key)
94
+ else:
95
+ if test_model_availability(key, test_model):
96
+ valid_keys.append(key)
97
+ else:
98
+ unverified_keys.append(key)
99
+
100
+ logging.info(f"无效 KEY:{invalid_keys}")
101
+ logging.info(f"免费 KEY:{free_keys}")
102
+ logging.info(f"未实名 KEY:{unverified_keys}")
103
+ logging.info(f"有效 KEY:{valid_keys}")
104
+
105
  else:
106
  logging.warning("环境变量 KEYS 未设置。")
107
 
 
124
  处理前端发送的 Token 检测请求。
125
  """
126
  tokens = request.json.get('tokens', [])
127
+ test_model = os.environ.get("TEST_MODEL", "Pro/google/gemma-2-9b-it")
128
+
129
  results = []
130
  for token in tokens:
131
+ credit_summary = get_credit_summary(token)
132
+ if credit_summary is None:
133
+ results.append({"token": token, "type": "无效 KEY", "balance": 0, "message": "无法获取额度信息"})
134
+ else:
135
+ total_balance = credit_summary.get("total_balance", 0)
136
+ if total_balance <= 0:
137
+ results.append({"token": token, "type": "免费 KEY", "balance": total_balance, "message": "额度不足"})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  else:
139
+ if test_model_availability(token, test_model):
140
+ results.append({"token": token, "type": "有效 KEY", "balance": total_balance, "message": "可以使用指定模型"})
141
+ else:
142
+ results.append({"token": token, "type": "未实名 KEY", "balance": total_balance, "message": "无法使用指定模型"})
 
 
 
 
 
 
 
143
 
144
  return jsonify(results)
145