-
Notifications
You must be signed in to change notification settings - Fork 116
/
main.py
2395 lines (2073 loc) · 105 KB
/
main.py
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
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 导入所需的库
from flask import Flask, request, jsonify, Response, send_from_directory
from flask_cors import CORS, cross_origin
import requests
import uuid
import json
import time
import os
from datetime import datetime
from PIL import Image
import io
import re
import threading
from queue import Queue, Empty
import logging
from logging.handlers import TimedRotatingFileHandler
import uuid
import hashlib
import requests
import json
import hashlib
from PIL import Image
from io import BytesIO
from urllib.parse import urlparse, urlunparse
import base64
from fake_useragent import UserAgent
import os
from urllib.parse import urlparse
# 读取配置文件
def load_config(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
return json.load(file)
CONFIG = load_config('./data/config.json')
LOG_LEVEL = CONFIG.get('log_level', 'INFO').upper()
NEED_LOG_TO_FILE = CONFIG.get('need_log_to_file', 'true').lower() == 'true'
# 使用 get 方法获取配置项,同时提供默认值
BASE_URL = CONFIG.get('upstream_base_url', '')
PROXY_API_PREFIX = CONFIG.get('upstream_api_prefix', '')
if PROXY_API_PREFIX != '':
PROXY_API_PREFIX = "/" + PROXY_API_PREFIX
UPLOAD_BASE_URL = CONFIG.get('backend_container_url', '')
KEY_FOR_GPTS_INFO = CONFIG.get('key_for_gpts_info', '')
API_PREFIX = CONFIG.get('backend_container_api_prefix', '')
GPT_4_S_New_Names = CONFIG.get('gpt_4_s_new_name', 'gpt-4-s').split(',')
GPT_4_MOBILE_NEW_NAMES = CONFIG.get('gpt_4_mobile_new_name', 'gpt-4-mobile').split(',')
GPT_3_5_NEW_NAMES = CONFIG.get('gpt_3_5_new_name', 'gpt-3.5-turbo').split(',')
BOT_MODE = CONFIG.get('bot_mode', {})
BOT_MODE_ENABLED = BOT_MODE.get('enabled', 'false').lower() == 'true'
BOT_MODE_ENABLED_MARKDOWN_IMAGE_OUTPUT = BOT_MODE.get('enabled_markdown_image_output', 'false').lower() == 'true'
BOT_MODE_ENABLED_BING_REFERENCE_OUTPUT = BOT_MODE.get('enabled_bing_reference_output', 'false').lower() == 'true'
BOT_MODE_ENABLED_CODE_BLOCK_OUTPUT = BOT_MODE.get('enabled_plugin_output', 'false').lower() == 'true'
BOT_MODE_ENABLED_PLAIN_IMAGE_URL_OUTPUT = BOT_MODE.get('enabled_plain_image_url_output', 'false').lower() == 'true'
NEED_DELETE_CONVERSATION_AFTER_RESPONSE = CONFIG.get('need_delete_conversation_after_response', 'true').lower() == 'true'
USE_OAIUSERCONTENT_URL = CONFIG.get('use_oaiusercontent_url', 'false').lower() == 'true'
# USE_PANDORA_FILE_SERVER = CONFIG.get('use_pandora_file_server', 'false').lower() == 'true'
CUSTOM_ARKOSE = CONFIG.get('custom_arkose_url', 'false').lower() == 'true'
ARKOSE_URLS = CONFIG.get('arkose_urls', "")
DALLE_PROMPT_PREFIX = CONFIG.get('dalle_prompt_prefix', '')
# redis配置读取
REDIS_CONFIG = CONFIG.get('redis', {})
REDIS_CONFIG_HOST = REDIS_CONFIG.get('host', 'redis')
REDIS_CONFIG_PORT = REDIS_CONFIG.get('port', 6379)
REDIS_CONFIG_PASSWORD = REDIS_CONFIG.get('password', '')
REDIS_CONFIG_DB = REDIS_CONFIG.get('db', 0)
REDIS_CONFIG_POOL_SIZE = REDIS_CONFIG.get('pool_size', 10)
REDIS_CONFIG_POOL_TIMEOUT = REDIS_CONFIG.get('pool_timeout', 30)
# 设置日志级别
log_level_dict = {
'DEBUG': logging.DEBUG,
'INFO': logging.INFO,
'WARNING': logging.WARNING,
'ERROR': logging.ERROR,
'CRITICAL': logging.CRITICAL
}
log_formatter = logging.Formatter('%(asctime)s [%(levelname)s] - %(message)s')
logger = logging.getLogger()
logger.setLevel(log_level_dict.get(LOG_LEVEL, logging.DEBUG))
import redis
# 假设您已经有一个Redis客户端的实例
redis_client = redis.StrictRedis(host=REDIS_CONFIG_HOST,
port=REDIS_CONFIG_PORT,
password=REDIS_CONFIG_PASSWORD,
db=REDIS_CONFIG_DB,
retry_on_timeout=True
)
# 如果环境变量指示需要输出到文件
if NEED_LOG_TO_FILE:
log_filename = './log/access.log'
file_handler = TimedRotatingFileHandler(log_filename, when="midnight", interval=1, backupCount=30)
file_handler.setFormatter(log_formatter)
logger.addHandler(file_handler)
# 添加标准输出流处理器(控制台输出)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(log_formatter)
logger.addHandler(stream_handler)
# 创建FakeUserAgent对象
ua = UserAgent()
def generate_unique_id(prefix):
# 生成一个随机的 UUID
random_uuid = uuid.uuid4()
# 将 UUID 转换为字符串,并移除其中的短横线
random_uuid_str = str(random_uuid).replace('-', '')
# 结合前缀和处理过的 UUID 生成最终的唯一 ID
unique_id = f"{prefix}-{random_uuid_str}"
return unique_id
def get_accessible_model_list():
return [config['name'] for config in gpts_configurations]
def find_model_config(model_name):
for config in gpts_configurations:
if config['name'] == model_name:
return config
return None
# 从 gpts.json 读取配置
def load_gpts_config(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
return json.load(file)
# 根据 ID 发送请求并获取配置信息
def fetch_gizmo_info(base_url, proxy_api_prefix, model_id):
url = f"{base_url}{proxy_api_prefix}/backend-api/gizmos/{model_id}"
headers = {
"Authorization": f"Bearer {KEY_FOR_GPTS_INFO}"
}
response = requests.get(url, headers=headers)
# logger.debug(f"fetch_gizmo_info_response: {response.text}")
if response.status_code == 200:
return response.json()
else:
return None
# gpts_configurations = []
# 将配置添加到全局列表
def add_config_to_global_list(base_url, proxy_api_prefix, gpts_data):
global gpts_configurations
# print(f"gpts_data: {gpts_data}")
for model_name, model_info in gpts_data.items():
# print(f"model_name: {model_name}")
# print(f"model_info: {model_info}")
model_id = model_info['id']
# 首先尝试从 Redis 获取缓存数据
cached_gizmo_info = redis_client.get(model_id)
if cached_gizmo_info:
gizmo_info = eval(cached_gizmo_info) # 将字符串转换回字典
logger.info(f"Using cached info for {model_name}, {model_id}")
else:
logger.info(f"Fetching gpts info for {model_name}, {model_id}")
gizmo_info = fetch_gizmo_info(base_url, proxy_api_prefix, model_id)
# 如果成功获取到数据,则将其存入 Redis
if gizmo_info:
redis_client.set(model_id, str(gizmo_info))
logger.info(f"Cached gizmo info for {model_name}, {model_id}")
if gizmo_info:
gpts_configurations.append({
'name': model_name,
'id': model_id,
'config': gizmo_info
})
def generate_gpts_payload(model, messages):
model_config = find_model_config(model)
if model_config:
gizmo_info = model_config['config']
gizmo_id = gizmo_info['gizmo']['id']
payload = {
"action": "next",
"messages": messages,
"parent_message_id": str(uuid.uuid4()),
"model": "gpt-4-gizmo",
"timezone_offset_min": -480,
"history_and_training_disabled": False,
"conversation_mode": {
"gizmo": gizmo_info,
"kind": "gizmo_interaction",
"gizmo_id": gizmo_id
},
"force_paragen": False,
"force_rate_limit": False
}
return payload
else:
return None
# 创建 Flask 应用
app = Flask(__name__)
CORS(app, resources={r"/images/*": {"origins": "*"}})
# PANDORA_UPLOAD_URL = 'files.pandoranext.com'
VERSION = '0.7.7'
# VERSION = 'test'
UPDATE_INFO = '增加Arkose请求头'
# UPDATE_INFO = '【仅供临时测试使用】 '
# 解析响应中的信息
def parse_oai_ip_info():
tmp_ua = ua.random
res = requests.get("https://auth0.openai.com/cdn-cgi/trace", headers={"User-Agent":tmp_ua}, proxies=proxies)
lines = res.text.strip().split("\n")
info_dict = {line.split('=')[0]: line.split('=')[1] for line in lines if '=' in line}
return {key: info_dict[key] for key in ["ip", "loc", "colo", "warp"] if key in info_dict}
with app.app_context():
global gpts_configurations # 移到作用域的最开始
global proxies
global proxy_type
global proxy_host
global proxy_port
# 获取环境变量
proxy_url = CONFIG.get('proxy', None)
logger.info(f"==========================================")
if proxy_url and proxy_url != '':
parsed_url = urlparse(proxy_url)
scheme = parsed_url.scheme
hostname = parsed_url.hostname
port = parsed_url.port
# 构建requests支持的代理格式
if scheme in ['http']:
proxy_address = f"{scheme}://{hostname}:{port}"
proxies = {
'http': proxy_address,
'https': proxy_address,
}
proxy_type = scheme
proxy_host = hostname
proxy_port = port
elif scheme in ['socks5']:
proxy_address = f"{scheme}://{hostname}:{port}"
proxies = {
'http': proxy_address,
'https': proxy_address,
}
proxy_type = scheme
proxy_host = hostname
proxy_port = port
else:
raise ValueError("Unsupport proxy scheme: " + scheme)
# 打印当前使用的代理设置
logger.info(f"Use Proxy: {scheme}://{proxy_host}:{proxy_port}")
else:
# 如果没有设置代理
proxies = {}
proxy_type = None
http_proxy_host = None
http_proxy_port = None
logger.info("No Proxy")
ip_info = parse_oai_ip_info()
logger.info(f"The ip you are using to access oai is: {ip_info['ip']}")
logger.info(f"The location of this ip is: {ip_info['loc']}")
logger.info(f"The colo is: {ip_info['colo']}")
logger.info(f"Is this ip a Warp ip: {ip_info['warp']}")
# 输出版本信息
logger.info(f"==========================================")
logger.info(f"Version: {VERSION}")
logger.info(f"Update Info: {UPDATE_INFO}")
logger.info(f"LOG_LEVEL: {LOG_LEVEL}")
logger.info(f"NEED_LOG_TO_FILE: {NEED_LOG_TO_FILE}")
logger.info(f"BOT_MODE_ENABLED: {BOT_MODE_ENABLED}")
if BOT_MODE_ENABLED:
logger.info(f"enabled_markdown_image_output: {BOT_MODE_ENABLED_MARKDOWN_IMAGE_OUTPUT}")
logger.info(f"enabled_plain_image_url_output: {BOT_MODE_ENABLED_PLAIN_IMAGE_URL_OUTPUT}")
logger.info(f"enabled_bing_reference_output: {BOT_MODE_ENABLED_BING_REFERENCE_OUTPUT}")
logger.info(f"enabled_plugin_output: {BOT_MODE_ENABLED_CODE_BLOCK_OUTPUT}")
if not BASE_URL:
raise Exception('upstream_base_url is not set')
else:
logger.info(f"upstream_base_url: {BASE_URL}")
if not PROXY_API_PREFIX:
logger.warning('upstream_api_prefix is not set')
else:
logger.info(f"upstream_api_prefix: {PROXY_API_PREFIX}")
if USE_OAIUSERCONTENT_URL == False:
# 检测./images和./files文件夹是否存在,不存在则创建
if not os.path.exists('./images'):
os.makedirs('./images')
if not os.path.exists('./files'):
os.makedirs('./files')
if not UPLOAD_BASE_URL:
if USE_OAIUSERCONTENT_URL:
logger.info("backend_container_url 未设置,将使用 oaiusercontent.com 作为图片域名")
else:
logger.warning("backend_container_url 未设置,图片生成功能将无法正常使用")
else:
logger.info(f"backend_container_url: {UPLOAD_BASE_URL}")
if not KEY_FOR_GPTS_INFO:
logger.warning("key_for_gpts_info 未设置,请将 gpts.json 中仅保留 “{}” 作为内容")
else:
logger.info(f"key_for_gpts_info: {KEY_FOR_GPTS_INFO}")
if not API_PREFIX:
logger.warning("backend_container_api_prefix 未设置,安全性会有所下降")
logger.info(f'Chat 接口 URI: /v1/chat/completions')
logger.info(f'绘图接口 URI: /v1/images/generations')
else:
logger.info(f"backend_container_api_prefix: {API_PREFIX}")
logger.info(f'Chat 接口 URI: /{API_PREFIX}/v1/chat/completions')
logger.info(f'绘图接口 URI: /{API_PREFIX}/v1/images/generations')
logger.info(f"need_delete_conversation_after_response: {NEED_DELETE_CONVERSATION_AFTER_RESPONSE}")
logger.info(f"use_oaiusercontent_url: {USE_OAIUSERCONTENT_URL}")
logger.info(f"use_pandora_file_server: False")
logger.info(f"custom_arkose_url: {CUSTOM_ARKOSE}")
if CUSTOM_ARKOSE:
logger.info(f"arkose_urls: {ARKOSE_URLS}")
logger.info(f"DALLE_prompt_prefix: {DALLE_PROMPT_PREFIX}")
logger.info(f"==========================================")
# 更新 gpts_configurations 列表,支持多个映射
gpts_configurations = []
for name in GPT_4_S_New_Names:
gpts_configurations.append({
"name": name.strip(),
"ori_name": "gpt-4-s"
})
for name in GPT_4_MOBILE_NEW_NAMES:
gpts_configurations.append({
"name": name.strip(),
"ori_name": "gpt-4-mobile"
})
for name in GPT_3_5_NEW_NAMES:
gpts_configurations.append({
"name": name.strip(),
"ori_name": "gpt-3.5-turbo"
})
logger.info(f"GPTS 配置信息")
# 加载配置并添加到全局列表
gpts_data = load_gpts_config("./data/gpts.json")
add_config_to_global_list(BASE_URL, PROXY_API_PREFIX, gpts_data)
# print("当前可用GPTS:" + get_accessible_model_list())
# 输出当前可用 GPTS name
# 获取当前可用的 GPTS 模型列表
accessible_model_list = get_accessible_model_list()
logger.info(f"当前可用 GPTS 列表: {accessible_model_list}")
# 检查列表中是否有重复的模型名称
if len(accessible_model_list) != len(set(accessible_model_list)):
raise Exception("检测到重复的模型名称,请检查环境变量或配置文件。")
logger.info(f"==========================================")
# print(f"GPTs Payload 生成测试")
# print(f"gpt-4-classic: {generate_gpts_payload('gpt-4-classic', [])}")
# 定义获取 token 的函数
def get_token():
# 从环境变量获取 URL 列表,并去除每个 URL 周围的空白字符
api_urls = [url.strip() for url in ARKOSE_URLS.split(",")]
for url in api_urls:
if not url:
continue
full_url = f"{url}/api/arkose/token"
payload = {'type': 'gpt-4'}
try:
response = requests.post(full_url, data=payload)
if response.status_code == 200:
token = response.json().get('token')
# 确保 token 字段存在且不是 None 或空字符串
if token:
logger.debug(f"成功从 {url} 获取 arkose token")
return token
else:
logger.error(f"获取的 token 响应无效: {token}")
else:
logger.error(f"获取 arkose token 失败: {response.status_code}, {response.text}")
except requests.RequestException as e:
logger.error(f"请求异常: {e}")
raise Exception("获取 arkose token 失败")
return None
import os
def get_image_dimensions(file_content):
with Image.open(BytesIO(file_content)) as img:
return img.width, img.height
def determine_file_use_case(mime_type):
multimodal_types = ["image/jpeg", "image/webp", "image/png", "image/gif"]
my_files_types = ["text/x-php", "application/msword", "text/x-c", "text/html",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/json", "text/javascript", "application/pdf",
"text/x-java", "text/x-tex", "text/x-typescript", "text/x-sh",
"text/x-csharp", "application/vnd.openxmlformats-officedocument.presentationml.presentation",
"text/x-c++", "application/x-latext", "text/markdown", "text/plain",
"text/x-ruby", "text/x-script.python"]
if mime_type in multimodal_types:
return "multimodal"
elif mime_type in my_files_types:
return "my_files"
else:
return "ace_upload"
def upload_file(file_content, mime_type, api_key):
logger.debug("文件上传开始")
width = None
height = None
if mime_type.startswith('image/'):
try:
width, height = get_image_dimensions(file_content)
except Exception as e:
logger.error(f"图片信息获取异常, 切换为text/plain: {e}")
mime_type = 'text/plain'
# logger.debug(f"文件内容: {file_content}")
file_size = len(file_content)
logger.debug(f"文件大小: {file_size}")
file_extension = get_file_extension(mime_type)
logger.debug(f"文件扩展名: {file_extension}")
sha256_hash = hashlib.sha256(file_content).hexdigest()
logger.debug(f"sha256_hash: {sha256_hash}")
file_name = f"{sha256_hash}{file_extension}"
logger.debug(f"文件名: {file_name}")
logger.debug(f"Use Case: {determine_file_use_case(mime_type)}")
if determine_file_use_case(mime_type) == "ace_upload":
mime_type = ''
logger.debug(f"非已知文件类型,MINE置空")
# 第1步:调用/backend-api/files接口获取上传URL
upload_api_url = f"{BASE_URL}{PROXY_API_PREFIX}/backend-api/files"
upload_request_payload = {
"file_name": file_name,
"file_size": file_size,
"use_case": determine_file_use_case(mime_type)
}
headers = {
"Authorization": f"Bearer {api_key}"
}
upload_response = requests.post(upload_api_url, json=upload_request_payload, headers=headers)
logger.debug(f"upload_response: {upload_response.text}")
if upload_response.status_code != 200:
raise Exception("Failed to get upload URL")
upload_data = upload_response.json()
upload_url = upload_data.get("upload_url")
logger.debug(f"upload_url: {upload_url}")
file_id = upload_data.get("file_id")
logger.debug(f"file_id: {file_id}")
# 第2步:上传文件
put_headers = {
'Content-Type': mime_type,
'x-ms-blob-type': 'BlockBlob' # 添加这个头部
}
put_response = requests.put(upload_url, data=file_content, headers=put_headers, proxies=proxies)
if put_response.status_code != 201:
logger.debug(f"put_response: {put_response.text}")
logger.debug(f"put_response status_code: {put_response.status_code}")
raise Exception("Failed to upload file")
# 第3步:检测上传是否成功并检查响应
check_url = f"{BASE_URL}{PROXY_API_PREFIX}/backend-api/files/{file_id}/uploaded"
check_response = requests.post(check_url, json={}, headers=headers)
logger.debug(f"check_response: {check_response.text}")
if check_response.status_code != 200:
raise Exception("Failed to check file upload completion")
check_data = check_response.json()
if check_data.get("status") != "success":
raise Exception("File upload completion check not successful")
return {
"file_id": file_id,
"file_name": file_name,
"size_bytes": file_size,
"mimeType": mime_type,
"width": width,
"height": height
}
def get_file_metadata(file_content, mime_type, api_key):
sha256_hash = hashlib.sha256(file_content).hexdigest()
logger.debug(f"sha256_hash: {sha256_hash}")
# 首先尝试从Redis中获取数据
cached_data = redis_client.get(sha256_hash)
if cached_data is not None:
# 如果在Redis中找到了数据,解码后直接返回
logger.info(f"从Redis中获取到文件缓存数据")
cache_file_data = json.loads(cached_data.decode())
tag = True
file_id = cache_file_data.get("file_id")
# 检测之前的文件是否仍然有效
check_url = f"{BASE_URL}{PROXY_API_PREFIX}/backend-api/files/{file_id}/uploaded"
headers = {
"Authorization": f"Bearer {api_key}"
}
check_response = requests.post(check_url, json={}, headers=headers)
logger.debug(f"check_response: {check_response.text}")
if check_response.status_code != 200:
tag = False
check_data = check_response.json()
if check_data.get("status") != "success":
tag = False
if tag:
logger.info(f"Redis中的文件缓存数据有效,将使用缓存数据")
return cache_file_data
else:
logger.info(f"Redis中的文件缓存数据已失效,重新上传文件")
else:
logger.info(f"Redis中没有找到文件缓存数据")
# 如果Redis中没有,上传文件并保存新数据
new_file_data = upload_file(file_content, mime_type, api_key)
mime_type = new_file_data.get('mimeType')
# 为图片类型文件添加宽度和高度信息
if mime_type.startswith('image/'):
width, height = get_image_dimensions(file_content)
new_file_data['width'] = width
new_file_data['height'] = height
# 将新的文件数据存入Redis
redis_client.set(sha256_hash, json.dumps(new_file_data))
return new_file_data
def get_file_extension(mime_type):
# 基于 MIME 类型返回文件扩展名的映射表
extension_mapping = {
"image/jpeg": ".jpg",
"image/png": ".png",
"image/gif": ".gif",
"image/webp": ".webp",
"text/x-php": ".php",
"application/msword": ".doc",
"text/x-c": ".c",
"text/html": ".html",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",
"application/json": ".json",
"text/javascript": ".js",
"application/pdf": ".pdf",
"text/x-java": ".java",
"text/x-tex": ".tex",
"text/x-typescript": ".ts",
"text/x-sh": ".sh",
"text/x-csharp": ".cs",
"application/vnd.openxmlformats-officedocument.presentationml.presentation": ".pptx",
"text/x-c++": ".cpp",
"application/x-latext": ".latex", # 这里可能需要根据实际情况调整
"text/markdown": ".md",
"text/plain": ".txt",
"text/x-ruby": ".rb",
"text/x-script.python": ".py",
# 其他 MIME 类型和扩展名...
}
return extension_mapping.get(mime_type, "")
my_files_types = [
"text/x-php", "application/msword", "text/x-c", "text/html",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/json", "text/javascript", "application/pdf",
"text/x-java", "text/x-tex", "text/x-typescript", "text/x-sh",
"text/x-csharp", "application/vnd.openxmlformats-officedocument.presentationml.presentation",
"text/x-c++", "application/x-latext", "text/markdown", "text/plain",
"text/x-ruby", "text/x-script.python"
]
# 定义发送请求的函数
def send_text_prompt_and_get_response(messages, api_key, stream, model):
url = f"{BASE_URL}{PROXY_API_PREFIX}/backend-api/conversation"
headers = {
"Authorization": f"Bearer {api_key}"
}
# 查找模型配置
model_config = find_model_config(model)
ori_model_name = ''
if model_config:
# 检查是否有 ori_name
ori_model_name = model_config.get('ori_name', model)
formatted_messages = []
# logger.debug(f"原始 messages: {messages}")
for message in messages:
message_id = str(uuid.uuid4())
content = message.get("content")
if isinstance(content, list) and ori_model_name != 'gpt-3.5-turbo':
logger.debug(f"gpt-vision 调用")
new_parts = []
attachments = []
contains_image = False # 标记是否包含图片
for part in content:
if isinstance(part, dict) and "type" in part:
if part["type"] == "text":
new_parts.append(part["text"])
elif part["type"] == "image_url":
# logger.debug(f"image_url: {part['image_url']}")
file_url = part["image_url"]["url"]
if file_url.startswith('data:'):
# 处理 base64 编码的文件数据
mime_type, base64_data = file_url.split(';')[0], file_url.split(',')[1]
mime_type = mime_type.split(':')[1]
try:
file_content = base64.b64decode(base64_data)
except Exception as e:
logger.error(f"类型为 {mime_type} 的 base64 编码数据解码失败: {e}")
continue
else:
# 处理普通的文件URL
try:
tmp_user_agent = ua.random
logger.debug(f"随机 User-Agent: {tmp_user_agent}")
tmp_headers = {
'User-Agent': tmp_user_agent
}
file_response = requests.get(url=file_url, headers=tmp_headers, proxies=proxies)
file_content = file_response.content
mime_type = file_response.headers.get('Content-Type', '').split(';')[0].strip()
except Exception as e:
logger.error(f"获取文件 {file_url} 失败: {e}")
continue
logger.debug(f"mime_type: {mime_type}")
file_metadata = get_file_metadata(file_content, mime_type, api_key)
mime_type = file_metadata["mimeType"]
logger.debug(f"处理后 mime_type: {mime_type}")
if mime_type.startswith('image/'):
contains_image = True
new_part = {
"asset_pointer": f"file-service://{file_metadata['file_id']}",
"size_bytes": file_metadata["size_bytes"],
"width": file_metadata["width"],
"height": file_metadata["height"]
}
new_parts.append(new_part)
attachment = {
"name": file_metadata["file_name"],
"id": file_metadata["file_id"],
"mimeType": file_metadata["mimeType"],
"size": file_metadata["size_bytes"] # 添加文件大小
}
if mime_type.startswith('image/'):
attachment.update({
"width": file_metadata["width"],
"height": file_metadata["height"]
})
elif mime_type in my_files_types:
attachment.update({"fileTokenSize": len(file_metadata["file_name"])})
attachments.append(attachment)
else:
# 确保 part 是字符串
text_part = str(part) if not isinstance(part, str) else part
new_parts.append(text_part)
content_type = "multimodal_text" if contains_image else "text"
formatted_message = {
"id": message_id,
"author": {"role": message.get("role")},
"content": {"content_type": content_type, "parts": new_parts},
"metadata": {"attachments": attachments}
}
formatted_messages.append(formatted_message)
logger.critical(f"formatted_message: {formatted_message}")
else:
# 处理单个文本消息的情况
formatted_message = {
"id": message_id,
"author": {"role": message.get("role")},
"content": {"content_type": "text", "parts": [content]},
"metadata": {}
}
formatted_messages.append(formatted_message)
# logger.debug(f"formatted_messages: {formatted_messages}")
# return
payload = {}
logger.info(f"model: {model}")
# 查找模型配置
model_config = find_model_config(model)
if model_config:
# 检查是否有 ori_name
ori_model_name = model_config.get('ori_name', model)
logger.info(f"原模型名: {ori_model_name}")
if ori_model_name == 'gpt-4-s':
payload = {
# 构建 payload
"action": "next",
"messages": formatted_messages,
"parent_message_id": str(uuid.uuid4()),
"model":"gpt-4",
"timezone_offset_min": -480,
"suggestions":[],
"history_and_training_disabled": False,
"conversation_mode":{"kind":"primary_assistant"},"force_paragen":False,"force_rate_limit":False
}
elif ori_model_name == 'gpt-4-mobile':
payload = {
# 构建 payload
"action": "next",
"messages": formatted_messages,
"parent_message_id": str(uuid.uuid4()),
"model":"gpt-4-mobile",
"timezone_offset_min": -480,
"suggestions":["Give me 3 ideas about how to plan good New Years resolutions. Give me some that are personal, family, and professionally-oriented.","Write a text asking a friend to be my plus-one at a wedding next month. I want to keep it super short and casual, and offer an out.","Design a database schema for an online merch store.","Compare Gen Z and Millennial marketing strategies for sunglasses."],
"history_and_training_disabled": False,
"conversation_mode":{"kind":"primary_assistant"},"force_paragen":False,"force_rate_limit":False
}
elif ori_model_name =='gpt-3.5-turbo':
payload = {
# 构建 payload
"action": "next",
"messages": formatted_messages,
"parent_message_id": str(uuid.uuid4()),
"model": "text-davinci-002-render-sha",
"timezone_offset_min": -480,
"suggestions": [
"What are 5 creative things I could do with my kids' art? I don't want to throw them away, but it's also so much clutter.",
"I want to cheer up my friend who's having a rough day. Can you suggest a couple short and sweet text messages to go with a kitten gif?",
"Come up with 5 concepts for a retro-style arcade game.",
"I have a photoshoot tomorrow. Can you recommend me some colors and outfit options that will look good on camera?"
],
"history_and_training_disabled":False,
"arkose_token":None,
"conversation_mode": {
"kind": "primary_assistant"
},
"force_paragen":False,
"force_rate_limit":False
}
else:
payload = generate_gpts_payload(model, formatted_messages)
if not payload:
raise Exception('model is not accessible')
# 根据NEED_DELETE_CONVERSATION_AFTER_RESPONSE修改history_and_training_disabled
if NEED_DELETE_CONVERSATION_AFTER_RESPONSE:
logger.debug(f"是否保留会话: {NEED_DELETE_CONVERSATION_AFTER_RESPONSE == False}")
payload['history_and_training_disabled'] = True
if ori_model_name != 'gpt-3.5-turbo':
if CUSTOM_ARKOSE:
token = get_token()
payload["arkose_token"] = token
# 在headers中添加新字段
headers["Openai-Sentinel-Arkose-Token"] = token
logger.debug(f"headers: {headers}")
logger.debug(f"payload: {payload}")
response = requests.post(url, headers=headers, json=payload, stream=True)
# print(response)
return response
def delete_conversation(conversation_id, api_key):
logger.info(f"准备删除的会话id: {conversation_id}")
if not NEED_DELETE_CONVERSATION_AFTER_RESPONSE:
logger.info(f"自动删除会话功能已禁用")
return
if conversation_id and NEED_DELETE_CONVERSATION_AFTER_RESPONSE:
patch_url = f"{BASE_URL}{PROXY_API_PREFIX}/backend-api/conversation/{conversation_id}"
patch_headers = {
"Authorization": f"Bearer {api_key}",
}
patch_data = {"is_visible": False}
response = requests.patch(patch_url, headers=patch_headers, json=patch_data)
if response.status_code == 200:
logger.info(f"删除会话 {conversation_id} 成功")
else:
logger.error(f"PATCH 请求失败: {response.text}")
from PIL import Image
import io
def save_image(image_data, path='images'):
try:
# print(f"image_data: {image_data}")
if not os.path.exists(path):
os.makedirs(path)
current_time = datetime.now().strftime('%Y%m%d%H%M%S')
filename = f'image_{current_time}.png'
full_path = os.path.join(path, filename)
logger.debug(f"完整的文件路径: {full_path}") # 打印完整路径
# print(f"filename: {filename}")
# 使用 PIL 打开图像数据
with Image.open(io.BytesIO(image_data)) as image:
# 保存为 PNG 格式
image.save(os.path.join(path, filename), 'PNG')
logger.debug(f"保存图片成功: {filename}")
return os.path.join(path, filename)
except Exception as e:
logger.error(f"保存图片时出现异常: {e}")
def unicode_to_chinese(unicode_string):
# 首先将字符串转换为标准的 JSON 格式字符串
json_formatted_str = json.dumps(unicode_string)
# 然后将 JSON 格式的字符串解析回正常的字符串
return json.loads(json_formatted_str)
import re
# 辅助函数:检查是否为合法的引用格式或正在构建中的引用格式
def is_valid_citation_format(text):
# 完整且合法的引用格式,允许紧跟另一个起始引用标记
if re.fullmatch(r'\u3010\d+\u2020(source|\u6765\u6e90)\u3011\u3010?', text):
return True
# 完整且合法的引用格式
if re.fullmatch(r'\u3010\d+\u2020(source|\u6765\u6e90)\u3011', text):
return True
# 合法的部分构建格式
if re.fullmatch(r'\u3010(\d+)?(\u2020(source|\u6765\u6e90)?)?', text):
return True
# 不合法的格式
return False
# 辅助函数:检查是否为完整的引用格式
# 检查是否为完整的引用格式
def is_complete_citation_format(text):
return bool(re.fullmatch(r'\u3010\d+\u2020(source|\u6765\u6e90)\u3011\u3010?', text))
# 替换完整的引用格式
def replace_complete_citation(text, citations):
def replace_match(match):
citation_number = match.group(1)
for citation in citations:
cited_message_idx = citation.get('metadata', {}).get('extra', {}).get('cited_message_idx')
logger.debug(f"cited_message_idx: {cited_message_idx}")
logger.debug(f"citation_number: {citation_number}")
logger.debug(f"is citation_number == cited_message_idx: {cited_message_idx == int(citation_number)}")
logger.debug(f"citation: {citation}")
if cited_message_idx == int(citation_number):
url = citation.get("metadata", {}).get("url", "")
if ((BOT_MODE_ENABLED == False) or (BOT_MODE_ENABLED == True and BOT_MODE_ENABLED_BING_REFERENCE_OUTPUT == True)):
return f"[[{citation_number}]({url})]"
else:
return ""
# return match.group(0) # 如果没有找到对应的引用,返回原文本
logger.critical(f"没有找到对应的引用,舍弃{match.group(0)}引用")
return ""
# 使用 finditer 找到第一个匹配项
match_iter = re.finditer(r'\u3010(\d+)\u2020(source|\u6765\u6e90)\u3011', text)
first_match = next(match_iter, None)
if first_match:
start, end = first_match.span()
replaced_text = text[:start] + replace_match(first_match) + text[end:]
remaining_text = text[end:]
else:
replaced_text = text
remaining_text = ""
is_potential_citation = is_valid_citation_format(remaining_text)
# 替换掉replaced_text末尾的remaining_text
logger.debug(f"replaced_text: {replaced_text}")
logger.debug(f"remaining_text: {remaining_text}")
logger.debug(f"is_potential_citation: {is_potential_citation}")
if is_potential_citation:
replaced_text = replaced_text[:-len(remaining_text)]
return replaced_text, remaining_text, is_potential_citation
def is_valid_sandbox_combined_corrected_final_v2(text):
# 更新正则表达式以包含所有合法格式
patterns = [
r'.*\(sandbox:\/[^)]*\)?', # sandbox 后跟路径,包括不完整路径
r'.*\(', # 只有 "(" 也视为合法格式
r'.*\(sandbox(:|$)', # 匹配 "(sandbox" 或 "(sandbox:",确保后面不跟其他字符或字符串结束
r'.*\(sandbox:.*\n*', # 匹配 "(sandbox:" 后跟任意数量的换行符
]
# 检查文本是否符合任一合法格式
return any(bool(re.fullmatch(pattern, text)) for pattern in patterns)
def is_complete_sandbox_format(text):
# 完整格式应该类似于 (sandbox:/xx/xx/xx 或 (sandbox:/xx/xx)
pattern = r'.*\(sandbox\:\/[^)]+\)\n*' # 匹配 "(sandbox:" 后跟任意数量的换行符
return bool(re.fullmatch(pattern, text))
import urllib.parse
from urllib.parse import unquote
def replace_sandbox(text, conversation_id, message_id, api_key):
def replace_match(match):
sandbox_path = match.group(1)
download_url = get_download_url(conversation_id, message_id, sandbox_path)
if download_url == None:
return "\n```\nError: 沙箱文件下载失败,这可能是因为您启用了隐私模式\n```"
file_name = extract_filename(download_url)
timestamped_file_name = timestamp_filename(file_name)
if USE_OAIUSERCONTENT_URL == False:
download_file(download_url, timestamped_file_name)
return f"({UPLOAD_BASE_URL}/files/{timestamped_file_name})"
else:
return f"({download_url})"
def get_download_url(conversation_id, message_id, sandbox_path):
# 模拟发起请求以获取下载 URL
sandbox_info_url = f"{BASE_URL}{PROXY_API_PREFIX}/backend-api/conversation/{conversation_id}/interpreter/download?message_id={message_id}&sandbox_path={sandbox_path}"
headers = {
"Authorization": f"Bearer {api_key}"
}
response = requests.get(sandbox_info_url, headers=headers)
if response.status_code == 200:
logger.debug(f"获取下载 URL 成功: {response.json()}")
return response.json().get("download_url")
else:
logger.error(f"获取下载 URL 失败: {response.text}")
return None