返回提交历史
Modified
g4f/Provider/Yupp.py
+115
-26
XFEstudio/gpt4free
Refactor Yupp stream handling and chunk processing
Improves stream segmentation in the Yupp provider by introducing buffers for target, variant, quick, thinking, and extra streams. Refactors chunk processing to better handle image-gen, quick responses, and variant outputs, and adds more robust stream ID extraction and routing logic. Yields a consolidated JsonResponse with all stream segments for downstream use.
1c8b7a87
代码差异
1 个文件
+115
-26
@@ -9,7 +9,8 @@ import aiohttp
9
9
10
10
from ..typing import AsyncResult, Messages, Optional, Dict, Any, List
11
11
from ..providers.base_provider import AsyncGeneratorProvider, ProviderModelMixin
12
from ..providers.response import Reasoning, PlainTextResponse, PreviewResponse, JsonConversation, ImageResponse, ProviderInfo
12
from ..providers.response import Reasoning, PlainTextResponse, PreviewResponse, JsonConversation, ImageResponse, \
13
ProviderInfo, FinishReason, JsonResponse
13
14
from ..errors import RateLimitError, ProviderException, MissingAuthError
14
15
from ..cookies import get_cookies
15
16
from ..tools.auth import AuthManager
@@ -428,9 +429,20 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
428
429
line_pattern = re.compile(b"^([0-9a-fA-F]+):(.*)")
429
430
target_stream_id = None
430
431
reward_info = None
432
# Stream segmentation buffers
431
433
is_thinking = False
432
thinking_content = ""
434
thinking_content = "" # model's "thinking" channel (if activated later)
433
435
normal_content = ""
436
quick_content = "" # quick-response short message
437
variant_text = "" # variant model output (comparison stream)
438
stream = {
439
"target": [],
440
"variant": [],
441
"quick": [],
442
"thinking": [] ,
443
"extra": []
444
}
445
# Holds leftStream / rightStream definitions to determine target/variant
434
446
select_stream = [None, None]
435
447
436
448
def extract_ref_id(ref):
@@ -442,28 +454,44 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
442
454
return False
443
455
return True
444
456
445
async def process_content_chunk(content: str, chunk_id: str, line_count: int):
446
"""Process single content chunk"""
447
nonlocal is_thinking, thinking_content, normal_content, session
448
457
async def process_content_chunk(content: str, chunk_id: str, line_count: int, *, for_target: bool = False):
458
"""
459
Process a single content chunk from a stream.
460
461
- If for_target=True → chunk belongs to the target model output.
462
"""
463
nonlocal is_thinking, thinking_content, normal_content, variant_text, session
464
449
465
if not is_valid_content(content):
450
466
return
451
467
468
# Handle image-gen chunks
452
469
if '<yapp class="image-gen">' in content:
453
content = content.split('<yapp class="image-gen">').pop().split('</yapp>')[0]
470
img_block = content.split('<yapp class="image-gen">').pop().split('</yapp>')[0]
454
471
url = "https://yupp.ai/api/trpc/chat.getSignedImage"
455
async with session.get(url, params={"batch": "1", "input": json.dumps({"0": {"json": {"imageId": json.loads(content).get("image_id")}}})}) as resp:
472
async with session.get(
473
url,
474
params={
475
"batch": "1",
476
"input": json.dumps(
477
{"0": {"json": {"imageId": json.loads(img_block).get("image_id")}}}
478
)
479
}
480
) as resp:
456
481
resp.raise_for_status()
457
482
data = await resp.json()
458
yield ImageResponse(data[0]["result"]["data"]["json"]["signed_url"], prompt)
483
img = ImageResponse(
484
data[0]["result"]["data"]["json"]["signed_url"],
485
prompt
486
)
487
yield img
459
488
return
460
461
# log_debug(f"Processing chunk #{line_count} with content: '{content[:50]}...'")
462
489
# Optional: thinking-mode support (disabled by default)
463
490
if is_thinking:
464
491
yield Reasoning(content)
465
492
else:
466
normal_content += content
493
if for_target:
494
normal_content += content
467
495
yield content
468
496
469
497
try:
@@ -472,8 +500,16 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
472
500
variant_stream_id = None
473
501
is_started: bool = False
474
502
variant_image: Optional[ImageResponse] = None
475
variant_text = ""
476
503
# "a" use as default then extract from "1"
504
reward_id = "a"
505
routing_id = "e"
506
turn_id = None
507
persisted_turn_id = None
508
left_message_id = None
509
right_message_id = None
510
nudge_new_chat_id = None
511
nudge_new_chat = False
512
477
513
async for line in response_content:
478
514
line_count += 1
479
515
@@ -488,9 +524,8 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
488
524
data = json.loads(chunk_data) if chunk_data != b"{}" else {}
489
525
except json.JSONDecodeError:
490
526
continue
491
492
527
# Process reward info
493
if chunk_id == "a":
528
if chunk_id == reward_id and isinstance(data, dict) and "unclaimedRewardInfo" in data:
494
529
reward_info = data
495
530
log_debug(f"Found reward info")
496
531
@@ -500,14 +535,29 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
500
535
if isinstance(data, dict):
501
536
left_stream = data.get("leftStream", {})
502
537
right_stream = data.get("rightStream", {})
503
quick_response_id = extract_ref_id(data.get("quickResponse", {}).get("stream", {}).get("next"))
538
if data.get("quickResponse", {}) != "$undefined":
539
quick_response_id = extract_ref_id(data.get("quickResponse", {}).get("stream", {}).get("next"))
540
541
if data.get("turnId", {}) != "$undefined":
542
turn_id = extract_ref_id(data.get("turnId", {}).get("next"))
543
if data.get("persistedTurn", {}) != "$undefined":
544
persisted_turn_id = extract_ref_id(data.get("persistedTurn", {}).get("next"))
545
if data.get("leftMessageId", {}) != "$undefined":
546
left_message_id = extract_ref_id(data.get("leftMessageId", {}).get("next"))
547
if data.get("rightMessageId", {}) != "$undefined":
548
right_message_id = extract_ref_id(data.get("rightMessageId", {}).get("next"))
549
550
reward_id = extract_ref_id(data.get("pendingRewardActionResult", "")) or reward_id
551
routing_id = extract_ref_id(data.get("routingResultPromise", "")) or routing_id
552
nudge_new_chat_id = extract_ref_id(data.get("nudgeNewChatPromise", "")) or nudge_new_chat_id
504
553
select_stream = [left_stream, right_stream]
505
506
elif chunk_id == "e":
554
# Routing / model selection block
555
elif chunk_id == routing_id:
507
556
yield PlainTextResponse(line.decode(errors="ignore"))
508
557
if isinstance(data, dict):
509
558
provider_info = cls.get_dict()
510
559
provider_info['model'] = model_id
560
# Determine target & variant stream IDs
511
561
for i, selection in enumerate(data.get("modelSelections", [])):
512
562
if selection.get("selectionSource") == "USER_SELECTED":
513
563
target_stream_id = extract_ref_id(select_stream[i].get("next"))
@@ -528,41 +578,80 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
528
578
target_stream_id = extract_ref_id(data.get("next"))
529
579
content = data.get("curr", "")
530
580
if content:
531
async for chunk in process_content_chunk(content, chunk_id, line_count):
581
async for chunk in process_content_chunk(
582
content,
583
chunk_id,
584
line_count,
585
for_target=True
586
):
587
stream["target"].append(chunk)
532
588
is_started = True
533
589
yield chunk
534
590
# Variant stream (comparison)
535
591
elif variant_stream_id and chunk_id == variant_stream_id:
536
592
yield PlainTextResponse("[Variant] " + line.decode(errors="ignore"))
537
593
if isinstance(data, dict):
538
594
variant_stream_id = extract_ref_id(data.get("next"))
539
595
content = data.get("curr", "")
540
596
if content:
541
async for chunk in process_content_chunk(content, chunk_id, line_count):
597
async for chunk in process_content_chunk(
598
content,
599
chunk_id,
600
line_count,
601
for_target=False
602
):
603
stream["variant"].append(chunk)
542
604
if isinstance(chunk, ImageResponse):
543
605
yield PreviewResponse(str(chunk))
544
606
else:
545
607
variant_text += str(chunk)
546
608
if not is_started:
547
609
yield PreviewResponse(variant_text)
548
610
# Quick response (short preview)
549
611
elif quick_response_id and chunk_id == quick_response_id:
550
612
yield PlainTextResponse("[Quick] " + line.decode(errors="ignore"))
551
613
if isinstance(data, dict):
552
614
content = data.get("curr", "")
553
615
if content:
616
async for chunk in process_content_chunk(
617
content,
618
chunk_id,
619
line_count,
620
for_target=False
621
):
622
stream["quick"].append(chunk)
623
quick_content += content
554
624
yield PreviewResponse(content)
555
625
626
elif chunk_id in [turn_id, persisted_turn_id]:
627
...
628
elif chunk_id == right_message_id:
629
...
630
elif chunk_id == left_message_id:
631
...
632
elif chunk_id == nudge_new_chat_id:
633
nudge_new_chat = data
634
# Miscellaneous extra content
556
635
elif isinstance(data, dict) and "curr" in data:
557
636
content = data.get("curr", "")
558
637
if content:
638
async for chunk in process_content_chunk(
639
content,
640
chunk_id,
641
line_count,
642
for_target=False
643
):
644
stream["extra"].append(chunk)
645
if isinstance(chunk,str) and "<streaming stopped unexpectedly" in chunk:
646
yield FinishReason(chunk)
647
559
648
yield PlainTextResponse("[Extra] " + line.decode(errors="ignore"))
560
649
561
650
if variant_image is not None:
562
651
yield variant_image
563
652
elif variant_text:
564
653
yield PreviewResponse(variant_text)
565
654
yield JsonResponse(**stream)
566
655
log_debug(f"Finished processing {line_count} lines")
567
656
568
657
except: