返回提交历史
Modified
g4f/Provider/Yupp.py
+29
-32
XFEstudio/gpt4free
Refactor Yupp provider: streamline API request handling, improve logging, and enhance model selection processing
73a3d3a4
代码差异
1 个文件
+29
-32
@@ -8,7 +8,7 @@ import threading
8
8
import requests
9
9
10
10
from ..providers.base_provider import AbstractProvider, ProviderModelMixin
11
from ..providers.response import Reasoning, PlainTextResponse, PreviewResponse, JsonConversation, ImageResponse, VariantResponse
11
from ..providers.response import Reasoning, PlainTextResponse, PreviewResponse, JsonConversation, ImageResponse, ProviderInfo
12
12
from ..errors import RateLimitError, ProviderException
13
13
from ..cookies import get_cookies
14
14
from ..tools.auth import AuthManager
@@ -135,9 +135,7 @@ def claim_yupp_reward(account: Dict[str, Any], reward_id: str):
135
135
url = "https://yupp.ai/api/trpc/reward.claim?batch=1"
136
136
payload = {"0": {"json": {"rewardId": reward_id}}}
137
137
headers = {
138
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0",
139
138
"Content-Type": "application/json",
140
"sec-fetch-site": "same-origin",
141
139
"Cookie": f"__Secure-yupp.session-token={account['token']}",
142
140
}
143
141
session = create_requests_session()
@@ -192,24 +190,23 @@ class Yupp(AbstractProvider, ProviderModelMixin):
192
190
conversation: JsonConversation = None,
193
191
**kwargs,
194
192
) -> Generator[str, Any, None]:
195
if not api_key:
196
api_key = get_cookies("yupp.ai", False).get("__Secure-yupp.session-token")
197
193
"""
194
Create completion using Yupp.ai API with account rotation
195
"""
198
196
# Initialize Yupp accounts and models
197
if not api_key and len(YUPP_ACCOUNTS) <= 1:
198
api_key = get_cookies("yupp.ai", False).get("__Secure-yupp.session-token")
199
199
if api_key:
200
200
load_yupp_accounts(api_key)
201
log_debug(f"Yupp provider initialized with {len(YUPP_ACCOUNTS)} accounts")
202
elif YUPP_ACCOUNTS:
203
log_debug(f"Yupp provider using existing accounts: {len(YUPP_ACCOUNTS)}")
204
else:
205
raise ProviderException("No Yupp accounts configured. Set YUPP_API_KEY environment variable.")
201
206
202
log_debug(f"Yupp provider initialized with {len(YUPP_ACCOUNTS)} accounts")
203
204
"""
205
Create completion using Yupp.ai API with account rotation
206
"""
207
207
if messages is None:
208
208
messages = []
209
209
210
if not YUPP_ACCOUNTS:
211
raise ProviderException("No Yupp accounts configured. Set YUPP_API_KEY environment variable.")
212
213
210
# Format messages
214
211
if conversation is None or True:
215
212
if prompt is None:
@@ -220,7 +217,7 @@ class Yupp(AbstractProvider, ProviderModelMixin):
220
217
if prompt is None:
221
218
prompt = get_last_message(messages)
222
219
url_uuid = conversation.url_uuid
223
log_debug(f"Use url uuid: {url_uuid}, Formatted prompt length: {len(prompt)}")
220
log_debug(f"Use url_uuid: {url_uuid}, Formatted prompt length: {len(prompt)}")
224
221
225
222
# Try all accounts with rotation
226
223
max_attempts = len(YUPP_ACCOUNTS)
@@ -275,18 +272,8 @@ class Yupp(AbstractProvider, ProviderModelMixin):
275
272
276
273
headers = {
277
274
"accept": "text/x-component",
278
"accept-language": "en-US",
279
"cache-control": "no-cache",
280
275
"content-type": "text/plain;charset=UTF-8",
281
276
"next-action": next_action,
282
"pragma": "no-cache",
283
"priority": "u=1, i",
284
"sec-ch-ua": "\"Chromium\";v=\"140\", \"Not=A?Brand\";v=\"24\", \"Google Chrome\";v=\"140\"",
285
"sec-ch-ua-mobile": "?0",
286
"sec-ch-ua-platform": "\"Linux\"",
287
"sec-fetch-dest": "empty",
288
"sec-fetch-mode": "cors",
289
"sec-fetch-site": "same-origin",
290
277
"cookie": f"__Secure-yupp.session-token={account['token']}",
291
278
}
292
279
@@ -318,7 +305,7 @@ class Yupp(AbstractProvider, ProviderModelMixin):
318
305
response.raise_for_status()
319
306
320
307
yield from cls._process_stream_response(
321
response.iter_lines(), account, session, question
308
response.iter_lines(), account, session, question, model_id
322
309
)
323
310
324
311
@classmethod
@@ -327,7 +314,8 @@ class Yupp(AbstractProvider, ProviderModelMixin):
327
314
response_lines: Iterable[bytes],
328
315
account: Dict[str, Any],
329
316
session: requests.Session,
330
prompt: Optional[str] = None,
317
prompt: str,
318
model_id: str
331
319
) -> Generator[str, Any, None]:
332
320
"""Process Yupp stream response and convert to OpenAI format"""
333
321
@@ -379,7 +367,7 @@ class Yupp(AbstractProvider, ProviderModelMixin):
379
367
line_count = 0
380
368
quick_response_id = None
381
369
variant_stream_id = None
382
found_image: Optional[ImageResponse] = None
370
is_started: bool = False
383
371
variant_image: Optional[ImageResponse] = None
384
372
variant_text = ""
385
373
@@ -419,13 +407,20 @@ class Yupp(AbstractProvider, ProviderModelMixin):
419
407
elif chunk_id == "e":
420
408
yield PlainTextResponse(line.decode(errors="ignore"))
421
409
if isinstance(data, dict):
410
provider_info = cls.get_dict()
411
provider_info['model'] = model_id
422
412
for i, selection in enumerate(data.get("modelSelections", [])):
423
413
if selection.get("selectionSource") == "USER_SELECTED":
424
414
target_stream_id = extract_ref_id(select_stream[i].get("next"))
415
provider_info["modelLabel"] = selection.get("shortLabel")
416
provider_info["modelUrl"] = selection.get("externalUrl")
425
417
log_debug(f"Found target stream ID: {target_stream_id}")
426
418
else:
427
419
variant_stream_id = extract_ref_id(select_stream[i].get("next"))
420
provider_info["variantLabel"] = selection.get("shortLabel")
421
provider_info["variantUrl"] = selection.get("externalUrl")
428
422
log_debug(f"Found variant stream ID: {variant_stream_id}")
423
yield ProviderInfo.from_dict(provider_info)
429
424
430
425
# Process target stream content
431
426
elif target_stream_id and chunk_id == target_stream_id:
@@ -435,8 +430,7 @@ class Yupp(AbstractProvider, ProviderModelMixin):
435
430
content = data.get("curr", "")
436
431
if content:
437
432
for chunk in process_content_chunk(content, chunk_id, line_count):
438
if isinstance(chunk, ImageResponse):
439
found_image = chunk
433
is_started = True
440
434
yield chunk
441
435
442
436
elif variant_stream_id and chunk_id == variant_stream_id:
@@ -449,9 +443,10 @@ class Yupp(AbstractProvider, ProviderModelMixin):
449
443
if isinstance(chunk, ImageResponse):
450
444
variant_image = chunk
451
445
yield PreviewResponse(str(variant_image))
452
elif found_image is None:
446
else:
453
447
variant_text += str(chunk)
454
yield PreviewResponse(variant_text)
448
if not is_started:
449
yield PreviewResponse(variant_text)
455
450
456
451
elif quick_response_id and chunk_id == quick_response_id:
457
452
yield PlainTextResponse("[Quick] " + line.decode(errors="ignore"))
@@ -468,6 +463,8 @@ class Yupp(AbstractProvider, ProviderModelMixin):
468
463
469
464
if variant_image is not None:
470
465
yield variant_image
466
elif variant_text:
467
yield PreviewResponse(variant_text)
471
468
472
469
log_debug(f"Finished processing {line_count} lines")
473
470