yangtb24 commited on
Commit
ba8e699
1 Parent(s): 72588b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -3
app.py CHANGED
@@ -3,7 +3,7 @@ import time
3
  import logging
4
  import requests
5
  from apscheduler.schedulers.background import BackgroundScheduler
6
- from flask import Flask, request, jsonify
7
 
8
  # 配置日志记录
9
  logging.basicConfig(level=logging.INFO,
@@ -11,9 +11,14 @@ logging.basicConfig(level=logging.INFO,
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
 
 
 
 
 
17
  def get_credit_summary(api_key):
18
  """
19
  使用 API 密钥获取额度信息。
@@ -27,7 +32,6 @@ def get_credit_summary(api_key):
27
  response.raise_for_status()
28
  data = response.json().get("data", {})
29
  total_balance = data.get("totalBalance", 0)
30
- # 将 total_balance 转换为浮点数
31
  return {"total_balance": float(total_balance)}
32
  except requests.exceptions.RequestException as e:
33
  logging.error(f"获取额度信息失败,API Key:{api_key},错误信息:{e}")
@@ -57,7 +61,6 @@ def test_model_availability(api_key, model_name):
57
  "stream": False
58
  },
59
  timeout=10)
60
- response.raise_for_status()
61
  # 检查是否是429错误
62
  if response.status_code == 429:
63
  return True
@@ -105,15 +108,104 @@ def load_keys():
105
  logging.info(f"免费 KEY:{free_keys}")
106
  logging.info(f"未实名 KEY:{unverified_keys}")
107
  logging.info(f"有效 KEY:{valid_keys}")
 
 
 
 
 
 
 
108
 
109
  else:
110
  logging.warning("环境变量 KEYS 未设置。")
111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  # 创建一个后台调度器
113
  scheduler = BackgroundScheduler()
114
 
115
  # 添加定时任务,每小时执行一次 load_keys 函数
116
  scheduler.add_job(load_keys, 'interval', hours=1)
 
 
117
 
118
  @app.route('/')
119
  def index():
@@ -147,10 +239,59 @@ def check_tokens():
147
 
148
  return jsonify(results)
149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  if __name__ == '__main__':
151
  # 打印所有环境变量,方便调试
152
  logging.info(f"环境变量:{os.environ}")
153
 
 
 
 
 
 
 
154
  # 启动调度器
155
  scheduler.start()
156
 
@@ -158,5 +299,9 @@ if __name__ == '__main__':
158
  load_keys()
159
  logging.info("首次加载 keys 已手动触发执行")
160
 
 
 
 
 
161
  # 启动 Flask 应用,监听所有 IP 的 7860 端口(Hugging Face Space 默认端口)
162
  app.run(debug=False, host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))
 
3
  import logging
4
  import requests
5
  from apscheduler.schedulers.background import BackgroundScheduler
6
+ from flask import Flask, request, jsonify, Response, stream_with_context
7
 
8
  # 配置日志记录
9
  logging.basicConfig(level=logging.INFO,
 
11
 
12
  API_ENDPOINT = "https://api.siliconflow.cn/v1/user/info"
13
  TEST_MODEL_ENDPOINT = "https://api.siliconflow.cn/v1/chat/completions"
14
+ MODELS_ENDPOINT = "https://api.siliconflow.cn/v1/models"
15
 
16
  app = Flask(__name__)
17
 
18
+ # 全局变量,用于存储模型列表和免费模型列表
19
+ all_models = []
20
+ free_models = []
21
+
22
  def get_credit_summary(api_key):
23
  """
24
  使用 API 密钥获取额度信息。
 
32
  response.raise_for_status()
33
  data = response.json().get("data", {})
34
  total_balance = data.get("totalBalance", 0)
 
35
  return {"total_balance": float(total_balance)}
36
  except requests.exceptions.RequestException as e:
37
  logging.error(f"获取额度信息失败,API Key:{api_key},错误信息:{e}")
 
61
  "stream": False
62
  },
63
  timeout=10)
 
64
  # 检查是否是429错误
65
  if response.status_code == 429:
66
  return True
 
108
  logging.info(f"免费 KEY:{free_keys}")
109
  logging.info(f"未实名 KEY:{unverified_keys}")
110
  logging.info(f"有效 KEY:{valid_keys}")
111
+
112
+ # 更新全局的 key 列表
113
+ global invalid_keys_global, free_keys_global, unverified_keys_global, valid_keys_global
114
+ invalid_keys_global = invalid_keys
115
+ free_keys_global = free_keys
116
+ unverified_keys_global = unverified_keys
117
+ valid_keys_global = valid_keys
118
 
119
  else:
120
  logging.warning("环境变量 KEYS 未设置。")
121
 
122
+ def get_all_models(api_key):
123
+ """
124
+ 获取所有模型列表。
125
+ """
126
+ headers = {
127
+ "Authorization": f"Bearer {api_key}",
128
+ "Content-Type": "application/json"
129
+ }
130
+ try:
131
+ response = requests.get(MODELS_ENDPOINT, headers=headers, params={"sub_type": "chat"})
132
+ response.raise_for_status()
133
+ data = response.json()
134
+ # 确保 data 是字典且包含 'data' 键,'data' 对应的值是一个列表
135
+ if isinstance(data, dict) and 'data' in data and isinstance(data['data'], list):
136
+ return [model.get("id") for model in data["data"] if isinstance(model, dict) and "id" in model]
137
+ else:
138
+ logging.error("获取模型列表失败:响应数据格式不正确")
139
+ return []
140
+ except requests.exceptions.RequestException as e:
141
+ logging.error(f"获取模型列表失败,API Key:{api_key},错误信息:{e}")
142
+ return []
143
+ except (KeyError, TypeError) as e:
144
+ logging.error(f"解析模型列表失败,API Key:{api_key},错误信息:{e}")
145
+ return []
146
+
147
+ def refresh_models():
148
+ """
149
+ 刷新模型列表和免费模型列表。
150
+ """
151
+ global all_models, free_models
152
+
153
+ # 使用 valid_keys_global 中的第一个 key 获取完整模型列表
154
+ if valid_keys_global:
155
+ all_models = get_all_models(valid_keys_global[0])
156
+ else:
157
+ logging.warning("没有有效的key,无法获取完整模型列表。")
158
+ all_models = []
159
+
160
+ # 使用 free_keys_global 中的第一个 key 获取免费模型列表
161
+ if free_keys_global:
162
+ free_models = get_all_models(free_keys_global[0])
163
+ else:
164
+ logging.warning("没有免费的key,无法获取免费模型列表。")
165
+ free_models = []
166
+
167
+ logging.info(f"所有模型列表:{all_models}")
168
+ logging.info(f"免费模型列表:{free_models}")
169
+
170
+ def determine_request_type(model_name):
171
+ """
172
+ 根据用户请求的模型判断请求类型。
173
+ """
174
+ if model_name in free_models:
175
+ return "free"
176
+ elif model_name in all_models:
177
+ return "paid"
178
+ else:
179
+ return "unknown"
180
+
181
+ def select_key(request_type):
182
+ """
183
+ 根据请求类型选择合适的 KEY。
184
+ """
185
+ if request_type == "free":
186
+ # 免费请求:使用 2、3、4 类 KEY
187
+ available_keys = free_keys_global + unverified_keys_global + valid_keys_global
188
+ elif request_type == "paid":
189
+ # 付费请求:使用 3、4 类 KEY
190
+ available_keys = unverified_keys_global + valid_keys_global
191
+ else:
192
+ # 未知请求:使用所有 KEY
193
+ available_keys = free_keys_global + unverified_keys_global + valid_keys_global
194
+
195
+ if not available_keys:
196
+ return None
197
+
198
+ # 简单的轮询策略选择 KEY
199
+ key = available_keys[int(time.time() * 1000) % len(available_keys)]
200
+ return key
201
+
202
  # 创建一个后台调度器
203
  scheduler = BackgroundScheduler()
204
 
205
  # 添加定时任务,每小时执行一次 load_keys 函数
206
  scheduler.add_job(load_keys, 'interval', hours=1)
207
+ # 添加定时任务,每10分钟执行一次 refresh_models 函数
208
+ scheduler.add_job(refresh_models, 'interval', minutes=10)
209
 
210
  @app.route('/')
211
  def index():
 
239
 
240
  return jsonify(results)
241
 
242
+ @app.route('/handsome/v1/chat/completions', methods=['POST'])
243
+ def handsome_chat_completions():
244
+ """
245
+ 处理 /handsome/v1/chat/completions 路由的请求。
246
+ """
247
+ data = request.get_json()
248
+ if not data or 'model' not in data:
249
+ return jsonify({"error": "Invalid request data"}), 400
250
+
251
+ model_name = data['model']
252
+ request_type = determine_request_type(model_name)
253
+ api_key = select_key(request_type)
254
+
255
+ if not api_key:
256
+ return jsonify({"error": "No available API key for this request type"}), 400
257
+
258
+ headers = {
259
+ "Authorization": f"Bearer {api_key}",
260
+ "Content-Type": "application/json"
261
+ }
262
+
263
+ # 转发请求到真正的 API
264
+ try:
265
+ response = requests.post(
266
+ TEST_MODEL_ENDPOINT,
267
+ headers=headers,
268
+ json=data,
269
+ stream=data.get("stream", False),
270
+ timeout=60
271
+ )
272
+
273
+ # 检查是否是429错误
274
+ if response.status_code == 429:
275
+ return jsonify(response.json()), 429
276
+
277
+ if data.get("stream", False):
278
+ return Response(stream_with_context(response.iter_content(chunk_size=1024)), content_type=response.headers['Content-Type'])
279
+ else:
280
+ response.raise_for_status()
281
+ return jsonify(response.json())
282
+ except requests.exceptions.RequestException as e:
283
+ return jsonify({"error": str(e)}), 500
284
+
285
  if __name__ == '__main__':
286
  # 打印所有环境变量,方便调试
287
  logging.info(f"环境变量:{os.environ}")
288
 
289
+ # 初始化全局的 key 列表
290
+ invalid_keys_global = []
291
+ free_keys_global = []
292
+ unverified_keys_global = []
293
+ valid_keys_global = []
294
+
295
  # 启动调度器
296
  scheduler.start()
297
 
 
299
  load_keys()
300
  logging.info("首次加载 keys 已手动触发执行")
301
 
302
+ # 手动触发一次 refresh_models 任务
303
+ refresh_models()
304
+ logging.info("首次刷新模型列表已手动触发执行")
305
+
306
  # 启动 Flask 应用,监听所有 IP 的 7860 端口(Hugging Face Space 默认端口)
307
  app.run(debug=False, host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))