返回提交历史
Modified
g4f/Provider/Yupp.py
+88
-52
XFEstudio/gpt4free
Only delete chats when "conversation" is not present on kwargs
7f78c93f
代码差异
1 个文件
+88
-52
@@ -23,8 +23,17 @@ from ..debug import log
23
23
from ..errors import RateLimitError, ProviderException, MissingAuthError, MissingRequirementsError
24
24
from ..image import is_accepted_format, to_bytes
25
25
from ..providers.base_provider import AsyncGeneratorProvider, ProviderModelMixin
26
from ..providers.response import Reasoning, PlainTextResponse, PreviewResponse, JsonConversation, ImageResponse, \
27
ProviderInfo, FinishReason, JsonResponse, VariantResponse
26
from ..providers.response import (
27
Reasoning,
28
PlainTextResponse,
29
PreviewResponse,
30
JsonConversation,
31
ImageResponse,
32
ProviderInfo,
33
FinishReason,
34
JsonResponse,
35
VariantResponse,
36
)
28
37
from ..tools.auth import AuthManager
29
38
from ..tools.media import merge_media
30
39
from ..typing import AsyncResult, Messages
@@ -91,10 +100,10 @@ async def get_best_yupp_account() -> Optional[Dict[str, Any]]:
91
100
acc
92
101
for acc in YUPP_ACCOUNTS
93
102
if acc["is_valid"]
94
and (
95
acc["error_count"] < max_error_count
96
or now - acc["last_used"] > error_cooldown
97
)
103
and (
104
acc["error_count"] < max_error_count
105
or now - acc["last_used"] > error_cooldown
106
)
98
107
]
99
108
100
109
if not valid_accounts:
@@ -102,8 +111,8 @@ async def get_best_yupp_account() -> Optional[Dict[str, Any]]:
102
111
103
112
for acc in valid_accounts:
104
113
if (
105
acc["error_count"] >= max_error_count
106
and now - acc["last_used"] > error_cooldown
114
acc["error_count"] >= max_error_count
115
and now - acc["last_used"] > error_cooldown
107
116
):
108
117
acc["error_count"] = 0
109
118
@@ -135,7 +144,13 @@ async def claim_yupp_reward(scraper: CloudScraper, account: Dict[str, Any], eval
135
144
return await loop.run_in_executor(_executor, sync_claim_yupp_reward, scraper, account, eval_id)
136
145
137
146
138
def sync_record_model_feedback(scraper: CloudScraper, account: Dict[str, Any], turn_id: str, left_message_id: str, right_message_id: str) -> Optional[str]:
147
def sync_record_model_feedback(
148
scraper: CloudScraper,
149
account: Dict[str, Any],
150
turn_id: str,
151
left_message_id: str,
152
right_message_id: str
153
) -> Optional[str]:
139
154
try:
140
155
log_debug(f"Recording model feedback for turn {turn_id}...")
141
156
url = "https://yupp.ai/api/trpc/evals.recordModelFeedback?batch=1"
@@ -165,13 +180,13 @@ def sync_record_model_feedback(scraper: CloudScraper, account: Dict[str, Any], t
165
180
response = scraper.post(url, json=payload)
166
181
response.raise_for_status()
167
182
data = response.json()
168
183
169
184
for result in data:
170
185
json_data = result.get("result", {}).get("data", {}).get("json", {})
171
186
eval_id = json_data.get("evalId")
172
187
final_reward = json_data.get("finalRewardAmount")
173
188
log_debug(f"Feedback recorded - evalId: {eval_id}, reward: {final_reward}")
174
189
175
190
if final_reward:
176
191
return eval_id
177
192
return None
@@ -180,9 +195,17 @@ def sync_record_model_feedback(scraper: CloudScraper, account: Dict[str, Any], t
180
195
return None
181
196
182
197
183
async def record_model_feedback(scraper: CloudScraper, account: Dict[str, Any], turn_id: str, left_message_id: str, right_message_id: str) -> Optional[str]:
198
async def record_model_feedback(
199
scraper: CloudScraper,
200
account: Dict[str, Any],
201
turn_id: str,
202
left_message_id: str,
203
right_message_id: str
204
) -> Optional[str]:
184
205
loop = asyncio.get_event_loop()
185
return await loop.run_in_executor(_executor, sync_record_model_feedback, scraper, account, turn_id, left_message_id, right_message_id)
206
return await loop.run_in_executor(
207
_executor, sync_record_model_feedback, scraper, account, turn_id, left_message_id, right_message_id
208
)
186
209
187
210
188
211
def sync_delete_chat(scraper: CloudScraper, account: Dict[str, Any], chat_id: str) -> bool:
@@ -195,8 +218,8 @@ def sync_delete_chat(scraper: CloudScraper, account: Dict[str, Any], chat_id: st
195
218
response.raise_for_status()
196
219
data = response.json()
197
220
if (
198
isinstance(data, list) and len(data) > 0
199
and data[0].get("result", {}).get("data", {}).get("json") is None
221
isinstance(data, list) and len(data) > 0
222
and data[0].get("result", {}).get("data", {}).get("json") is None
200
223
):
201
224
log_debug(f"Chat {chat_id} deleted successfully")
202
225
return True
@@ -229,8 +252,8 @@ def sync_make_chat_private(scraper: CloudScraper, account: Dict[str, Any], chat_
229
252
response.raise_for_status()
230
253
data = response.json()
231
254
if (
232
isinstance(data, list) and len(data) > 0
233
and "json" in data[0].get("result", {}).get("data", {})
255
isinstance(data, list) and len(data) > 0
256
and "json" in data[0].get("result", {}).get("data", {})
234
257
):
235
258
log_debug(f"Chat {chat_id} is now PRIVATE")
236
259
return True
@@ -317,8 +340,10 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
317
340
cls.models_tags = {model.get("name"): manager.processor.generate_tags(model) for model in models}
318
341
cls.models = [model.get("name") for model in models]
319
342
cls.image_models = [model.get("name") for model in models if model.get("isImageGeneration")]
320
cls.vision_models = [model.get("name") for model in models if
321
"image/*" in model.get("supportedAttachmentMimeTypes", [])]
343
cls.vision_models = [
344
model.get("name") for model in models
345
if "image/*" in model.get("supportedAttachmentMimeTypes", [])
346
]
322
347
return cls.models
323
348
324
349
@classmethod
@@ -360,8 +385,15 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
360
385
361
386
attachment_resp = scraper.post(
362
387
"https://yupp.ai/api/trpc/chat.createAttachmentForUploadedFile?batch=1",
363
json={"0": {"json": {"fileName": name, "contentType": is_accepted_format(data),
364
"fileId": upload_info["fileId"]}}},
388
json={
389
"0": {
390
"json": {
391
"fileName": name,
392
"contentType": is_accepted_format(data),
393
"fileId": upload_info["fileId"]
394
}
395
}
396
},
365
397
cookies={"__Secure-yupp.session-token": account["token"]}
366
398
)
367
399
attachment_resp.raise_for_status()
@@ -419,7 +451,9 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
419
451
**kwargs,
420
452
) -> AsyncResult:
421
453
if not has_cloudscraper:
422
raise MissingRequirementsError("cloudscraper library is required for Yupp provider | install it via 'pip install cloudscraper'")
454
raise MissingRequirementsError(
455
"cloudscraper library is required for Yupp provider | install it via 'pip install cloudscraper'"
456
)
423
457
if not api_key:
424
458
api_key = AuthManager.load_api_key(cls)
425
459
if not api_key:
@@ -442,7 +476,8 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
442
476
prompt = get_last_user_message(messages, prompt)
443
477
444
478
log_debug(
445
f"Use url_uuid: {url_uuid}, Formatted prompt length: {len(prompt)}, Is new conversation: {is_new_conversation}")
479
f"Use url_uuid: {url_uuid}, Formatted prompt length: {len(prompt)}, Is new conversation: {is_new_conversation}"
480
)
446
481
447
482
max_attempts = len(YUPP_ACCOUNTS)
448
483
for attempt in range(max_attempts):
@@ -533,8 +568,8 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
533
568
yield chunk
534
569
finally:
535
570
response.close()
536
asyncio.create_task(delete_chat(scraper, account, url_uuid))
537
571
if not kwargs.get("conversation"):
572
asyncio.create_task(delete_chat(scraper, account, url_uuid))
538
573
return
539
574
540
575
except RateLimitError:
@@ -567,12 +602,12 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
567
602
568
603
@classmethod
569
604
async def _process_stream_response(
570
cls,
571
response,
572
account: Dict[str, Any],
573
scraper: CloudScraper,
574
prompt: str,
575
model_id: str
605
cls,
606
response,
607
account: Dict[str, Any],
608
scraper: CloudScraper,
609
prompt: str,
610
model_id: str
576
611
) -> AsyncResult:
577
612
line_pattern = re.compile(b"^([0-9a-fA-F]+):(.*)")
578
613
target_stream_id = None
@@ -738,7 +773,8 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
738
773
right_stream = data.get("rightStream", {})
739
774
if data.get("quickResponse", {}) != "$undefined":
740
775
quick_response_id = extract_ref_id(
741
data.get("quickResponse", {}).get("stream", {}).get("next"))
776
data.get("quickResponse", {}).get("stream", {}).get("next")
777
)
742
778
743
779
if data.get("turnId", {}) != "$undefined":
744
780
turn_id = extract_ref_id(data.get("turnId", {}).get("next"))
@@ -789,20 +825,20 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
789
825
if ref_name in image_blocks:
790
826
img_block_text = image_blocks[ref_name]
791
827
async for chunk in process_content_chunk(
792
img_block_text,
793
ref_name,
794
line_count,
795
for_target=True
828
img_block_text,
829
ref_name,
830
line_count,
831
for_target=True
796
832
):
797
833
stream["target"].append(chunk)
798
834
is_started = True
799
835
yield chunk
800
836
else:
801
837
async for chunk in process_content_chunk(
802
content,
803
chunk_id,
804
line_count,
805
for_target=True
838
content,
839
chunk_id,
840
line_count,
841
for_target=True
806
842
):
807
843
stream["target"].append(chunk)
808
844
is_started = True
@@ -815,10 +851,10 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
815
851
content = data.get("curr", "")
816
852
if content:
817
853
async for chunk in process_content_chunk(
818
content,
819
chunk_id,
820
line_count,
821
for_target=False
854
content,
855
chunk_id,
856
line_count,
857
for_target=False
822
858
):
823
859
stream["variant"].append(chunk)
824
860
if isinstance(chunk, ImageResponse):
@@ -834,10 +870,10 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
834
870
content = data.get("curr", "")
835
871
if content:
836
872
async for chunk in process_content_chunk(
837
content,
838
chunk_id,
839
line_count,
840
for_target=False
873
content,
874
chunk_id,
875
line_count,
876
for_target=False
841
877
):
842
878
stream["quick"].append(chunk)
843
879
quick_content += content
@@ -859,10 +895,10 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
859
895
content = data.get("curr", "")
860
896
if content:
861
897
async for chunk in process_content_chunk(
862
content,
863
chunk_id,
864
line_count,
865
for_target=False
898
content,
899
chunk_id,
900
line_count,
901
for_target=False
866
902
):
867
903
stream["extra"].append(chunk)
868
904
if isinstance(chunk, str) and "<streaming stopped unexpectedly" in chunk: