File size: 35,473 Bytes
ddaefda
 
 
bae67bf
79bb4ee
3ae260c
8e3da9c
ae8d22c
bae67bf
ba8e699
4d3fe36
186320d
 
 
ddaefda
4078885
4d3fe36
c506221
 
c59d1e6
bae67bf
16b7f0b
 
989684f
ba8e699
1211b2c
 
 
5c4a8ce
91ee28f
 
8e3da9c
 
 
 
84eaeb7
bae67bf
84eaeb7
 
bae67bf
 
 
db69584
0de216a
 
 
 
90cb193
0de216a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c4a8ce
0de216a
5c4a8ce
 
0de216a
5c4a8ce
 
0de216a
5d0028a
bae67bf
84eaeb7
 
0de216a
5c4a8ce
 
0de216a
 
 
 
 
 
 
 
 
 
bae67bf
d9fee7e
d8305ac
77ef9af
d9fee7e
84eaeb7
8c17ac0
d89c20b
 
 
 
 
 
 
 
5c4a8ce
d89c20b
 
 
3cc247b
d89c20b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d91d51
3cc247b
91ee28f
 
 
 
 
 
c2bbdf7
91ee28f
c2bbdf7
91ee28f
7a44e1e
5a17a4c
ba8e699
91ee28f
 
 
 
 
5e02bab
 
91ee28f
 
 
 
09735d0
 
 
 
 
 
 
 
 
 
 
a5c5672
 
 
09735d0
 
 
bae67bf
84eaeb7
22197b0
bae67bf
16b7f0b
 
8e3da9c
 
 
 
 
 
 
 
 
 
 
 
90cb193
6740b78
 
 
 
90cb193
0de216a
 
 
6740b78
 
 
0de216a
6740b78
0de216a
07dcf56
 
 
d8305ac
07dcf56
 
 
44a7d85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0de216a
 
6740b78
 
 
 
 
 
 
ea45e87
6740b78
 
 
095a61c
6740b78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf63fc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01f588e
 
fccd514
09735d0
 
ba8e699
 
 
 
 
44a7d85
 
 
 
 
 
90cb193
44a7d85
ba8e699
 
c31239d
22197b0
 
 
 
 
 
 
 
90cb193
ba8e699
 
 
 
90cb193
6740b78
 
 
01f588e
6740b78
 
01f588e
0727ff4
6740b78
7191bab
6740b78
 
3ae260c
01f588e
 
3296e59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0727ff4
54ab1ea
 
03b936c
 
 
0727ff4
03b936c
54ab1ea
 
 
0727ff4
03b936c
0727ff4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54ab1ea
03b936c
0727ff4
e9eae75
 
0727ff4
e9eae75
54ab1ea
01f588e
 
90cb193
 
 
 
54ab1ea
01f588e
 
 
 
90cb193
 
 
 
 
 
 
 
 
 
2a0d3ff
90cb193
2a0d3ff
90cb193
9157eb3
90cb193
 
 
52d6899
90cb193
9157eb3
90cb193
 
03b936c
90cb193
 
6740b78
01f588e
 
 
df482ac
6740b78
3a2edd7
868e37f
 
 
 
 
 
 
 
 
 
 
 
 
 
90cb193
868e37f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df482ac
 
 
 
 
 
 
 
 
 
 
 
 
01f588e
 
df482ac
 
 
 
 
 
 
90cb193
 
868e37f
 
 
6740b78
df482ac
 
 
01f588e
df482ac
 
868e37f
 
6740b78
01f588e
6740b78
3a2edd7
90cb193
 
 
01f588e
7008444
 
90cb193
7008444
01f588e
 
 
 
 
 
 
 
90cb193
 
 
89c7765
90cb193
 
 
bad7adc
 
 
cae704c
90cb193
 
 
36bcac8
44a7d85
 
 
 
4e2509e
44a7d85
 
 
 
 
01f588e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90cb193
 
01f588e
df482ac
01f588e
df482ac
01f588e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90cb193
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01f588e
4cf5efc
 
 
90cb193
01f588e
 
 
 
99a5694
bae67bf
4078885
db69584
ba8e699
 
 
22197b0
4078885
22197b0
16b7f0b
 
4078885
db69584
ba8e699
4078885
ba8e699
22197b0
 
 
 
bad7adc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
import os
import time
import logging
import requests
import json
import concurrent.futures
import threading
from datetime import datetime, timedelta
from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask, request, jsonify, Response, stream_with_context

os.environ['TZ'] = 'Asia/Shanghai'
time.tzset()

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s')

API_ENDPOINT = "https://api.deepseek.com/user/balance"
TEST_MODEL_ENDPOINT = "https://api.deepseek.com/v1/chat/completions"
MODELS_ENDPOINT = "https://api.deepseek.com/models"

app = Flask(__name__)

text_models = []

invalid_keys_global = []
valid_keys_global = []

executor = concurrent.futures.ThreadPoolExecutor(max_workers=10000)
model_key_indices = {}

request_timestamps = []
token_counts = []
data_lock = threading.Lock()

def get_credit_summary(api_key):
    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()
        if not data.get("is_available", False):
            logging.warning(f"API Key: {api_key} is not available.")
            return None
      
        balance_infos = data.get("balance_infos", [])
        total_balance_cny = 0.0
        usd_balance = 0.0
        for balance_info in balance_infos:
            currency = balance_info.get("currency")
            total_balance = float(balance_info.get("total_balance", 0))

            if currency == "CNY":
                total_balance_cny += total_balance
            elif currency == "USD":
                usd_balance = total_balance

        try:
            exchange_rate = get_usd_to_cny_rate()
            if exchange_rate is not None:
                total_balance_cny += usd_balance * exchange_rate
                logging.info(f"获取美元兑人民币汇率成功,API Key:{api_key},当前总额度(CNY): {total_balance_cny}")
            else:
                logging.warning(f"获取美元兑人民币汇率失败,无法转换美元余额,API Key:{api_key}")
                total_balance_cny += usd_balance * 7.2
        except Exception as e:
            logging.error(f"获取美元兑人民币汇率失败,API Key:{api_key},错误信息:{e}")
            total_balance_cny += usd_balance * 7.2 

        return {"total_balance": float(total_balance_cny)}
    except requests.exceptions.RequestException as e:
        logging.error(f"获取额度信息失败,API Key:{api_key},错误信息:{e}")
        return None
    except Exception as e:
        logging.error(f"处理额度信息失败,API Key:{api_key},错误信息:{e}")
        return None

def get_usd_to_cny_rate():
    try:
        response = requests.get("https://api.exchangerate-api.com/v4/latest/USD")
        response.raise_for_status()
        data = response.json()
        return data.get("rates", {}).get("CNY")
    except requests.exceptions.RequestException as e:
        logging.error(f"获取美元兑人民币汇率失败,错误信息:{e}")
        return None

def refresh_models():
    text_models = ["deepseek-chat", "deepseek-reasoner"]
    logging.info(f"所有文本模型列表:{text_models}")

def load_keys():
    keys_str = os.environ.get("KEYS")
    keys = [key.strip() for key in keys_str.split(',')]
    unique_keys = list(set(keys))
    keys_str = ','.join(unique_keys) 
    os.environ["KEYS"] = keys_str

    logging.info(f"加载的 keys:{unique_keys}")

    with concurrent.futures.ThreadPoolExecutor(
        max_workers=10000
    ) as executor:
        future_to_key = {
            executor.submit(
                process_key, key
            ): key for key in unique_keys
        }

        invalid_keys = []
        valid_keys = []

        for future in concurrent.futures.as_completed(
            future_to_key
        ):
            key = future_to_key[future]
            try:
                key_type = future.result()
                if key_type == "invalid":
                    invalid_keys.append(key)
                elif key_type == "valid":
                    valid_keys.append(key)
            except Exception as exc:
                logging.error(f"处理 KEY {key} 生成异常: {exc}")

    logging.info(f"无效 KEY:{invalid_keys}")
    logging.info(f"有效 KEY:{valid_keys}")

    global invalid_keys_global, valid_keys_global
    invalid_keys_global = invalid_keys
    valid_keys_global = valid_keys

def process_key(key):
    credit_summary = get_credit_summary(key)
    if credit_summary is None:
        return "invalid"
    else:
        total_balance = credit_summary.get("total_balance", 0)
        if total_balance <= 0:
            return "invalid"
        else:
            return "valid"

def select_key(model_name):
    available_keys = valid_keys_global

    current_index = model_key_indices.get(model_name, 0)

    for _ in range(len(available_keys)):
        key = available_keys[current_index % len(available_keys)]
        current_index += 1
        model_key_indices[model_name] = current_index
        return key

    model_key_indices[model_name] = 0
    return None

def check_authorization(request):
    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()
scheduler.add_job(load_keys, 'interval', hours=1)
scheduler.remove_all_jobs()

@app.route('/')
def index():
    current_time = time.time()
    one_minute_ago = current_time - 60

    with data_lock:
        while request_timestamps and request_timestamps[0] < one_minute_ago:
            request_timestamps.pop(0)
            token_counts.pop(0)

        rpm = len(request_timestamps)
        tpm = sum(token_counts)

    return jsonify({"rpm": rpm, "tpm": tpm})
          
@app.route('/handsome/v1/models', methods=['GET'])
def list_models():
    if not check_authorization(request):
        return jsonify({"error": "Unauthorized"}), 401
  
    detailed_models = [
        {
            "id": "deepseek-chat",
            "object": "model",
            "created": 1678888888,
            "owned_by": "openai",
            "root": "deepseek-chat",
            "parent": None
        },
        {
            "id": "deepseek-reasoner",
            "object": "model",
            "created": 1678888889,
            "owned_by": "openai",
            "root": "deepseek-reasoner",
            "parent": None
        },
        {
            "id": "deepseek-reasoner-thinking",
            "object": "model",
            "created": 1678888889,
            "owned_by": "openai",
            "root": "deepseek-reasoner",
            "parent": None
        },
        {
            "id": "deepseek-reasoner-openwebui",
            "object": "model",
            "created": 1678888889,
            "owned_by": "openai",
            "root": "deepseek-reasoner",
            "parent": None
        }
    ]

    return jsonify({
        "success": True,
        "data": detailed_models
    })

def get_billing_info():
    keys = valid_keys_global
    total_balance = 0

    with concurrent.futures.ThreadPoolExecutor(
        max_workers=10000
    ) 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}")

    return total_balance

@app.route('/handsome/v1/dashboard/billing/usage', methods=['GET'])
def billing_usage():
    if not check_authorization(request):
        return jsonify({"error": "Unauthorized"}), 401

    end_date = datetime.now()
    start_date = end_date - timedelta(days=30)

    daily_usage = []
    current_date = start_date
    while current_date <= end_date:
        daily_usage.append({
            "timestamp": int(current_date.timestamp()),
            "daily_usage": 0
        })
        current_date += timedelta(days=1)

    return jsonify({
        "object": "list",
        "data": daily_usage,
        "total_usage": 0
    })

@app.route('/handsome/v1/dashboard/billing/subscription', methods=['GET'])
def billing_subscription():
    if not check_authorization(request):
        return jsonify({"error": "Unauthorized"}), 401

    total_balance = get_billing_info()

    return jsonify({
        "object": "billing_subscription",
        "has_payment_method": False,
        "canceled": False,
        "canceled_at": None,
        "delinquent": None,
        "access_until": int(datetime(9999, 12, 31).timestamp()),
        "soft_limit": 0,
        "hard_limit": total_balance,
        "system_hard_limit": total_balance,
        "soft_limit_usd": 0,
        "hard_limit_usd": total_balance,
        "system_hard_limit_usd": total_balance,
        "plan": {
            "name": "SiliconFlow API",
            "id": "siliconflow-api"
        },
        "account_name": "SiliconFlow User",
        "po_number": None,
        "billing_email": None,
        "tax_ids": [],
        "billing_address": None,
        "business_address": None
    })

@app.route('/handsome/v1/chat/completions', methods=['POST'])
def handsome_chat_completions():
    if not check_authorization(request):
        return jsonify({"error": "Unauthorized"}), 401

    data = request.get_json()
    if not data or 'model' not in data:
        return jsonify({"error": "Invalid request data"}), 400

    model_name = data['model']
    if model_name == "deepseek-reasoner-thinking" or model_name == "deepseek-reasoner-openwebui":
        model_realname = "deepseek-reasoner"
    else:
        model_realname = model_name

    data['model'] = model_realname

    api_key = select_key(model_realname)

    if not api_key:
        return jsonify(
            {
                "error": (
                    "No available API key for this "
                    "request type or all keys have "
                    "reached their limits"
                )
            }
        ), 429

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }

    try:
        start_time = time.time()
        response = requests.post(
            TEST_MODEL_ENDPOINT,
            headers=headers,
            json=data,
            stream=data.get("stream", False),
            timeout=120
        )

        if response.status_code == 429:
            return jsonify(response.json()), 429

        if data.get("stream", False):
            def generate():
                if model_name == "deepseek-reasoner": 
                    first_chunk_time = None
                    full_response_content = ""
                    for chunk in response.iter_content(chunk_size=2048):
                        if chunk:
                            if first_chunk_time is None:
                                first_chunk_time = time.time()
                            full_response_content += chunk.decode("utf-8")
                            yield chunk

                    end_time = time.time()
                    first_token_time = (
                        first_chunk_time - start_time
                        if first_chunk_time else 0
                    )
                    total_time = end_time - start_time

                    prompt_tokens = 0
                    completion_tokens = 0
                    response_content = ""
                    for line in full_response_content.splitlines():
                        if line.startswith("data:"):
                            line = line[5:].strip()
                            if line == "[DONE]":
                                continue
                            try:
                                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}, "
                                    f"行内容: {line}"
                                )

                    user_content = extract_user_content(data.get("messages", []))

                    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}"
                    )

                    with data_lock:
                        request_timestamps.append(time.time())
                        token_counts.append(prompt_tokens+completion_tokens)
                        request_timestamps_day.append(time.time())
                        token_counts_day.append(prompt_tokens+completion_tokens)

                    return Response(
                        stream_with_context(generate()),
                        content_type=response.headers['Content-Type']
                    )

                if model_name == "deepseek-reasoner-openwebui": 
                    first_chunk_time = None
                    full_response_content = ""
                    reasoning_content_accumulated = ""
                    content_accumulated = ""
                    first_reasoning_chunk = True
                    
                    for chunk in response.iter_lines():
                        if chunk:
                            if first_chunk_time is None:
                                first_chunk_time = time.time()
                            full_response_content += chunk.decode("utf-8")
                            
                            for line in chunk.decode("utf-8").splitlines():
                                if line.startswith("data:"):
                                    try:
                                        chunk_json = json.loads(line.lstrip("data: ").strip())
                                        if "choices" in chunk_json and len(chunk_json["choices"]) > 0:
                                            delta = chunk_json["choices"][0].get("delta", {})
                                            
                                            if delta.get("reasoning_content") is not None:
                                                reasoning_chunk = delta["reasoning_content"]
                                                if first_reasoning_chunk:
                                                    think_chunk = f"<"
                                                    yield f"data: {json.dumps({'choices': [{'delta': {'content': think_chunk}, 'index': 0}]})}\n\n"
                                                    think_chunk = f"think"
                                                    yield f"data: {json.dumps({'choices': [{'delta': {'content': think_chunk}, 'index': 0}]})}\n\n"
                                                    think_chunk = f">\n"
                                                    yield f"data: {json.dumps({'choices': [{'delta': {'content': think_chunk}, 'index': 0}]})}\n\n"
                                                    first_reasoning_chunk = False
                                                yield f"data: {json.dumps({'choices': [{'delta': {'content': reasoning_chunk}, 'index': 0}]})}\n\n"
                                                
                                            if delta.get("content") is not None:
                                                if not first_reasoning_chunk:
                                                    reasoning_chunk = f"\n</think>\n"
                                                    yield f"data: {json.dumps({'choices': [{'delta': {'content': reasoning_chunk}, 'index': 0}]})}\n\n"
                                                    first_reasoning_chunk = True
                                                yield f"data: {json.dumps({'choices': [{'delta': {'content': delta["content"]}, 'index': 0}]})}\n\n"

                                    except (KeyError, ValueError, json.JSONDecodeError) as e:
                                        continue

                    end_time = time.time()
                    first_token_time = (
                        first_chunk_time - start_time
                        if first_chunk_time else 0
                    )
                    total_time = end_time - start_time

                    prompt_tokens = 0
                    completion_tokens = 0
                    for line in full_response_content.splitlines():
                        if line.startswith("data:"):
                            line = line[5:].strip()
                            if line == "[DONE]":
                                continue
                            try:
                                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 (
                                    "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", [])
                    for message in messages:
                        if message["role"] == "user":
                            if isinstance(message["content"], str):
                                user_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 = (f"```Thinking\n{reasoning_content_accumulated}\n```\n" if reasoning_content_accumulated else "") + content_accumulated
                    response_content_replaced = response_content_replaced.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}"
                    )

                    with data_lock:
                        request_timestamps.append(time.time())
                        token_counts.append(prompt_tokens + completion_tokens)

                    yield "data: [DONE]\n\n"

                    return Response(
                        stream_with_context(generate()),
                        content_type="text/event-stream"
                    )

                first_chunk_time = None
                full_response_content = ""
                reasoning_content_accumulated = ""
                content_accumulated = ""
                first_reasoning_chunk = True
                
                for chunk in response.iter_lines():
                    if chunk:
                        if first_chunk_time is None:
                            first_chunk_time = time.time()
                        full_response_content += chunk.decode("utf-8")
                        
                        for line in chunk.decode("utf-8").splitlines():
                            if line.startswith("data:"):
                                try:
                                    chunk_json = json.loads(line.lstrip("data: ").strip())
                                    if "choices" in chunk_json and len(chunk_json["choices"]) > 0:
                                        delta = chunk_json["choices"][0].get("delta", {})
                                        
                                        if delta.get("reasoning_content") is not None:
                                            reasoning_chunk = delta["reasoning_content"]
                                            reasoning_chunk = reasoning_chunk.replace('\n', '\n> ')
                                            if first_reasoning_chunk:
                                                reasoning_chunk = "> " + reasoning_chunk
                                                first_reasoning_chunk = False
                                            yield f"data: {json.dumps({'choices': [{'delta': {'content': reasoning_chunk}, 'index': 0}]})}\n\n"
                                            
                                        if delta.get("content") is not None:
                                            if not first_reasoning_chunk:
                                                yield f"data: {json.dumps({'choices': [{'delta': {'content': '\n\n'}, 'index': 0}]})}\n\n"
                                                first_reasoning_chunk = True
                                            yield f"data: {json.dumps({'choices': [{'delta': {'content': delta["content"]}, 'index': 0}]})}\n\n"

                                except (KeyError, ValueError, json.JSONDecodeError) as e:
                                    # logging.error(f"解析流式响应单行 JSON 失败: {e}, 行内容: {line}")
                                    continue

                end_time = time.time()
                first_token_time = (
                    first_chunk_time - start_time
                    if first_chunk_time else 0
                )
                total_time = end_time - start_time

                prompt_tokens = 0
                completion_tokens = 0
                for line in full_response_content.splitlines():
                    if line.startswith("data:"):
                        line = line[5:].strip()
                        if line == "[DONE]":
                            continue
                        try:
                            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 (
                                "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", [])
                for message in messages:
                    if message["role"] == "user":
                        if isinstance(message["content"], str):
                            user_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 = (f"```Thinking\n{reasoning_content_accumulated}\n```\n" if reasoning_content_accumulated else "") + content_accumulated
                response_content_replaced = response_content_replaced.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}"
                )

                with data_lock:
                    request_timestamps.append(time.time())
                    token_counts.append(prompt_tokens + completion_tokens)

                yield "data: [DONE]\n\n"

            return Response(
                stream_with_context(generate()),
                content_type="text/event-stream"
            )
        else:
            response.raise_for_status()
            end_time = time.time()
            response_json = response.json()
            total_time = end_time - start_time

            try:
                prompt_tokens = response_json["usage"]["prompt_tokens"]
                completion_tokens = response_json["usage"]["completion_tokens"]
                response_content = ""

                if model_name == "deepseek-reasoner-thinking" and "choices" in response_json and len(response_json["choices"]) > 0:
                    choice = response_json["choices"][0]
                    if "message" in choice:
                        if "reasoning_content" in choice["message"]:
                            reasoning_content = choice["message"]["reasoning_content"]
                            reasoning_content = reasoning_content.replace('\n', '\n> ')
                            reasoning_content = '> ' + reasoning_content
                            formatted_reasoning = f"{reasoning_content}\n"
                            response_content += formatted_reasoning + "\n"
                        if "content" in choice["message"]:
                            response_content += choice["message"]["content"]
                elif model_name == "deepseek-reasoner-openwebui" and "choices" in response_json and len(response_json["choices"]) > 0:
                    choice = response_json["choices"][0]
                    if "message" in choice:
                        if "reasoning_content" in choice["message"]:
                            reasoning_content = choice["message"]["reasoning_content"]
                            response_content += f"<think>\n{reasoning_content}\n</think>\n"
                        if "content" in choice["message"]:
                            response_content += choice["message"]["content"]
                elif "choices" in response_json and len(response_json["choices"]) > 0:
                    response_content = response_json["choices"][0]["message"]["content"]

            except (KeyError, ValueError, IndexError) as e:
                logging.error(
                    f"解析非流式响应 JSON 失败: {e}, "
                    f"完整内容: {response_json}"
                )
                prompt_tokens = 0
                completion_tokens = 0
                response_content = ""

            user_content = ""
            messages = data.get("messages", [])
            for message in messages:
                if message["role"] == "user":
                    if isinstance(message["content"], str):
                        user_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}, "
                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}"
            )
            with data_lock:
                request_timestamps.append(time.time())
                token_counts.append(prompt_tokens + completion_tokens)

            formatted_response = {
                "id": response_json.get("id", ""),
                "object": "chat.completion",
                "created": response_json.get("created", int(time.time())),
                "model": model_name,
                "choices": [
                    {
                        "index": 0,
                        "message": {
                            "role": "assistant",
                            "content": response_content
                        },
                        "finish_reason": "stop"
                    }
                ],
                "usage": {
                    "prompt_tokens": prompt_tokens,
                    "completion_tokens": completion_tokens,
                    "total_tokens": prompt_tokens + completion_tokens
                }
            }

            if model_name == "deepseek-reasoner":
                formatted_response = response_json

            return jsonify(formatted_response)

    except requests.exceptions.RequestException as e:
        logging.error(f"请求转发异常: {e}")
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    logging.info(f"环境变量:{os.environ}")

    invalid_keys_global = []
    valid_keys_global = []

    load_keys()
    logging.info("程序启动时首次加载 keys 已执行")

    scheduler.start()

    logging.info("首次加载 keys 已手动触发执行")

    refresh_models()
    logging.info("首次刷新模型列表已手动触发执行")

    app.run(
        debug=False,
        host='0.0.0.0',
        port=int(os.environ.get('PORT', 7860))
    )