XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet
公开
关注 0 Fork 0 Star 1
返回提交历史

XFEstudio/gpt4free

Refactor Qwen and Yupp providers for improved async handling

Updated Qwen provider to handle timeout via kwargs and improved type annotations. Refactored Yupp provider for better code organization, formatting, and async account rotation logic. Enhanced readability and maintainability by reordering imports, adding whitespace, and clarifying function implementations.

3235caf1
Ammar <ammar.alkotb@gmail.com>
提交于

代码差异

2 个文件 +77 -56
Modified g4f/Provider/Qwen.py +8 -4
@@ -122,14 +122,14 @@ class Qwen(AsyncGeneratorProvider, ProviderModelMixin):
122 122 image_models = image_models
123 123 text_models = text_models
124 124 vision_models = vision_models
125 models: list = models
125 models: list[str] = models
126 126 default_model = "qwen3-235b-a22b"
127 127
128 128 _midtoken: str = None
129 129 _midtoken_uses: int = 0
130 130
131 131 @classmethod
132 def get_models(cls) -> list[str]:
132 def get_models(cls, **kwargs) -> list[str]:
133 133 if not cls._models_loaded and has_curl_cffi:
134 134 response = curl_cffi.get(f"{cls.url}/api/models")
135 135 if response.ok:
@@ -264,7 +264,6 @@ class Qwen(AsyncGeneratorProvider, ProviderModelMixin):
264 264 media: MediaListType = None,
265 265 conversation: JsonConversation = None,
266 266 proxy: str = None,
267 timeout: int = 120,
268 267 stream: bool = True,
269 268 enable_thinking: bool = True,
270 269 chat_type: Literal[
@@ -303,7 +302,12 @@ class Qwen(AsyncGeneratorProvider, ProviderModelMixin):
303 302 }
304 303
305 304 prompt = get_last_user_message(messages)
306
305 _timeout = kwargs.get("timeout")
306 if isinstance(_timeout, aiohttp.ClientTimeout):
307 timeout = _timeout
308 else:
309 total = float(_timeout) if isinstance(_timeout, (int, float)) else 5 * 60
310 timeout = aiohttp.ClientTimeout(total=total)
307 311 async with StreamSession(headers=headers) as session:
308 312 try:
309 313 async with session.get('https://chat.qwen.ai/api/v1/auths/', proxy=proxy) as user_info_res:
Modified g4f/Provider/Yupp.py +69 -52
@@ -1,24 +1,26 @@
1 import asyncio
1 2 import hashlib
2 3 import json
4 import os
5 import re
3 6 import time
4 7 import uuid
5 import re
6 import os
7 import asyncio
8
8 9 import aiohttp
9 from ..requests.aiohttp import StreamSession
10 from ..typing import AsyncResult, Messages, Optional, Dict, Any, List
10
11 from .helper import get_last_user_message
12 from .yupp.models import YuppModelManager
13 from ..cookies import get_cookies
14 from ..debug import log
15 from ..errors import RateLimitError, ProviderException, MissingAuthError
16 from ..image import is_accepted_format, to_bytes
11 17 from ..providers.base_provider import AsyncGeneratorProvider, ProviderModelMixin
12 18 from ..providers.response import Reasoning, PlainTextResponse, PreviewResponse, JsonConversation, ImageResponse, \
13 19 ProviderInfo, FinishReason, JsonResponse
14 from ..errors import RateLimitError, ProviderException, MissingAuthError
15 from ..cookies import get_cookies
20 from ..requests.aiohttp import StreamSession
16 21 from ..tools.auth import AuthManager
17 22 from ..tools.media import merge_media
18 from ..image import is_accepted_format, to_bytes
19 from .yupp.models import YuppModelManager
20 from .helper import get_last_user_message
21 from ..debug import log
23 from ..typing import AsyncResult, Messages, Optional, Dict, Any, List
22 24
23 25 # Global variables to manage Yupp accounts
24 26 YUPP_ACCOUNT = Dict[str, Any]
@@ -26,16 +28,19 @@ YUPP_ACCOUNTS: List[YUPP_ACCOUNT] = []
26 28 account_rotation_lock = asyncio.Lock()
27 29
28 30 # Global variables to manage Yupp Image Cache
29 ImagesCache:Dict[str, dict] = {}
31 ImagesCache: Dict[str, dict] = {}
32
30 33
31 34 class YuppAccount:
32 35 """Yupp account representation"""
36
33 37 def __init__(self, token: str, is_valid: bool = True, error_count: int = 0, last_used: float = 0):
34 38 self.token = token
35 39 self.is_valid = is_valid
36 40 self.error_count = error_count
37 41 self.last_used = last_used
38 42
43
39 44 def load_yupp_accounts(tokens_str: str):
40 45 """Load Yupp accounts from token string"""
41 46 global YUPP_ACCOUNTS
@@ -52,6 +57,7 @@ def load_yupp_accounts(tokens_str: str):
52 57 for token in tokens
53 58 ]
54 59
60
55 61 def create_headers() -> Dict[str, str]:
56 62 """Create headers for requests"""
57 63 return {
@@ -64,6 +70,7 @@ def create_headers() -> Dict[str, str]:
64 70 "Sec-Fetch-Site": "same-origin",
65 71 }
66 72
73
67 74 async def get_best_yupp_account() -> Optional[YUPP_ACCOUNT]:
68 75 """Get the best available Yupp account using smart selection algorithm"""
69 76 max_error_count = int(os.getenv("MAX_ERROR_COUNT", "3"))
@@ -75,10 +82,10 @@ async def get_best_yupp_account() -> Optional[YUPP_ACCOUNT]:
75 82 acc
76 83 for acc in YUPP_ACCOUNTS
77 84 if acc["is_valid"]
78 and (
79 acc["error_count"] < max_error_count
80 or now - acc["last_used"] > error_cooldown
81 )
85 and (
86 acc["error_count"] < max_error_count
87 or now - acc["last_used"] > error_cooldown
88 )
82 89 ]
83 90
84 91 if not valid_accounts:
@@ -87,8 +94,8 @@ async def get_best_yupp_account() -> Optional[YUPP_ACCOUNT]:
87 94 # Reset error count for accounts in cooldown
88 95 for acc in valid_accounts:
89 96 if (
90 acc["error_count"] >= max_error_count
91 and now - acc["last_used"] > error_cooldown
97 acc["error_count"] >= max_error_count
98 and now - acc["last_used"] > error_cooldown
92 99 ):
93 100 acc["error_count"] = 0
94 101
@@ -98,6 +105,7 @@ async def get_best_yupp_account() -> Optional[YUPP_ACCOUNT]:
98 105 account["last_used"] = now
99 106 return account
100 107
108
101 109 async def claim_yupp_reward(session: aiohttp.ClientSession, account: YUPP_ACCOUNT, reward_id: str):
102 110 """Claim Yupp reward asynchronously"""
103 111 try:
@@ -107,7 +115,7 @@ async def claim_yupp_reward(session: aiohttp.ClientSession, account: YUPP_ACCOUN
107 115 headers = {
108 116 "Content-Type": "application/json",
109 117 "Cookie": f"__Secure-yupp.session-token={account['token']}",
110 "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",
118 "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",
111 119
112 120 }
113 121 async with session.post(url, json=payload, headers=headers) as response:
@@ -120,6 +128,7 @@ async def claim_yupp_reward(session: aiohttp.ClientSession, account: YUPP_ACCOUN
120 128 log_debug(f"Failed to claim reward {reward_id}. Error: {e}")
121 129 return None
122 130
131
123 132 async def make_chat_private(session: aiohttp.ClientSession, account: YUPP_ACCOUNT, chat_id: str) -> bool:
124 133 """Set a Yupp chat's sharing status to PRIVATE"""
125 134 try:
@@ -136,7 +145,7 @@ async def make_chat_private(session: aiohttp.ClientSession, account: YUPP_ACCOUN
136 145 headers = {
137 146 "Content-Type": "application/json",
138 147 "Cookie": f"__Secure-yupp.session-token={account['token']}",
139 "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",
148 "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",
140 149
141 150 }
142 151
@@ -144,8 +153,8 @@ async def make_chat_private(session: aiohttp.ClientSession, account: YUPP_ACCOUN
144 153 response.raise_for_status()
145 154 data = await response.json()
146 155 if (
147 isinstance(data, list) and len(data) > 0
148 and "json" in data[0].get("result", {}).get("data", {})
156 isinstance(data, list) and len(data) > 0
157 and "json" in data[0].get("result", {}).get("data", {})
149 158 ):
150 159 log_debug(f"Chat {chat_id} is now PRIVATE ✅")
151 160 return True
@@ -157,6 +166,7 @@ async def make_chat_private(session: aiohttp.ClientSession, account: YUPP_ACCOUN
157 166 log_debug(f"Failed to make chat {chat_id} private: {e}")
158 167 return False
159 168
169
160 170 def log_debug(message: str):
161 171 """Debug logging"""
162 172 if os.getenv("DEBUG_MODE", "false").lower() == "true":
@@ -164,11 +174,12 @@ def log_debug(message: str):
164 174 else:
165 175 log(f"[Yupp] {message}")
166 176
177
167 178 def format_messages_for_yupp(messages: Messages) -> str:
168 179 """Format multi-turn conversation for Yupp single-turn format"""
169 180 if not messages:
170 181 return ""
171
182
172 183 if len(messages) == 1 and isinstance(messages[0].get("content"), str):
173 184 return messages[0].get("content", "").strip()
174 185
@@ -200,6 +211,7 @@ def format_messages_for_yupp(messages: Messages) -> str:
200 211
201 212 return result
202 213
214
203 215 class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
204 216 """
205 217 Yupp.ai Provider for g4f
@@ -212,7 +224,7 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
212 224 active_by_default = True
213 225 supports_stream = True
214 226 image_cache = True
215
227
216 228 @classmethod
217 229 def get_models(cls, api_key: str = None, **kwargs) -> List[str]:
218 230 if not cls.models:
@@ -228,11 +240,12 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
228 240 cls.models_tags = {model.get("name"): manager.processor.generate_tags(model) for model in models}
229 241 cls.models = [model.get("name") for model in models]
230 242 cls.image_models = [model.get("name") for model in models if model.get("isImageGeneration")]
231 cls.vision_models = [model.get("name") for model in models if "image/*" in model.get("supportedAttachmentMimeTypes", [])]
243 cls.vision_models = [model.get("name") for model in models if
244 "image/*" in model.get("supportedAttachmentMimeTypes", [])]
232 245 return cls.models
233 246
234 247 @classmethod
235 async def prepare_files(cls, media, session:aiohttp.ClientSession, account:YUPP_ACCOUNT)->list:
248 async def prepare_files(cls, media, session: aiohttp.ClientSession, account: YUPP_ACCOUNT) -> list:
236 249 files = []
237 250 if not media:
238 251 return files
@@ -289,11 +302,11 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
289 302
290 303 @classmethod
291 304 async def create_async_generator(
292 cls,
293 model: str,
294 messages: Messages,
295 proxy: str = None,
296 **kwargs,
305 cls,
306 model: str,
307 messages: Messages,
308 proxy: str = None,
309 **kwargs,
297 310 ) -> AsyncResult:
298 311 """
299 312 Create async completion using Yupp.ai API with account rotation
@@ -312,15 +325,16 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
312 325 conversation = kwargs.get("conversation")
313 326 url_uuid = conversation.url_uuid if conversation else None
314 327 is_new_conversation = url_uuid is None
315
328
316 329 prompt = kwargs.get("prompt")
317 330 if prompt is None:
318 331 if is_new_conversation:
319 332 prompt = format_messages_for_yupp(messages)
320 333 else:
321 334 prompt = get_last_user_message(messages, prompt)
322
323 log_debug(f"Use url_uuid: {url_uuid}, Formatted prompt length: {len(prompt)}, Is new conversation: {is_new_conversation}")
335
336 log_debug(
337 f"Use url_uuid: {url_uuid}, Formatted prompt length: {len(prompt)}, Is new conversation: {is_new_conversation}")
324 338
325 339 # Try all accounts with rotation
326 340 max_attempts = len(YUPP_ACCOUNTS)
@@ -333,7 +347,6 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
333 347 async with StreamSession() as session:
334 348 turn_id = str(uuid.uuid4())
335 349
336
337 350 # Handle media attachments
338 351 media = kwargs.get("media")
339 352 if media:
@@ -395,14 +408,16 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
395 408 total = float(_timeout) if isinstance(_timeout, (int, float)) else 5 * 60
396 409 timeout = aiohttp.ClientTimeout(total=total)
397 410 # Send request
398 async with session.post(url, json=payload, headers=headers, proxy=proxy, timeout=timeout) as response:
411 async with session.post(url, json=payload, headers=headers, proxy=proxy,
412 timeout=timeout) as response:
399 413 response.raise_for_status()
400 414
401 415 # Make chat private in background
402 416 asyncio.create_task(make_chat_private(session, account, url_uuid))
403 417
404 418 # Process stream
405 async for chunk in cls._process_stream_response(response.content, account, session, prompt, model):
419 async for chunk in cls._process_stream_response(response.content, account, session, prompt,
420 model):
406 421 yield chunk
407 422
408 423 return
@@ -442,12 +457,12 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
442 457
443 458 @classmethod
444 459 async def _process_stream_response(
445 cls,
446 response_content,
447 account: YUPP_ACCOUNT,
448 session: aiohttp.ClientSession,
449 prompt: str,
450 model_id: str
460 cls,
461 response_content,
462 account: YUPP_ACCOUNT,
463 session: aiohttp.ClientSession,
464 prompt: str,
465 model_id: str
451 466 ) -> AsyncResult:
452 467 """Process Yupp stream response asynchronously"""
453 468
@@ -464,7 +479,7 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
464 479 "target": [],
465 480 "variant": [],
466 481 "quick": [],
467 "thinking": [] ,
482 "thinking": [],
468 483 "extra": []
469 484 }
470 485 # Holds leftStream / rightStream definitions to determine target/variant
@@ -490,6 +505,7 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
490 505 if ref.startswith("$") and len(ref) > 1:
491 506 return ref[1:]
492 507 return None
508
493 509 def is_valid_content(content: str) -> bool:
494 510 """Check if content is valid"""
495 511 if not content or content in [None, "", "$undefined"]:
@@ -578,7 +594,7 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
578 594 capturing_lines.append(line)
579 595
580 596 # Check if this line closes the <yapp> block; after that, block is complete
581 if b"</yapp>" in line: # or b':{"curr"' in line:
597 if b"</yapp>" in line: # or b':{"curr"' in line:
582 598 # We may have trailing "2:{...}" after </yapp> on the same line
583 599 # Get id using re
584 600 idx = line.find(b"</yapp>")
@@ -628,7 +644,7 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
628 644 if chunk_id == reward_id and isinstance(data, dict) and "unclaimedRewardInfo" in data:
629 645 reward_info = data
630 646 log_debug(f"Found reward info")
631
647
632 648 # Process initial setup
633 649 elif chunk_id == "1":
634 650 yield PlainTextResponse(line.decode(errors="ignore"))
@@ -636,7 +652,8 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
636 652 left_stream = data.get("leftStream", {})
637 653 right_stream = data.get("rightStream", {})
638 654 if data.get("quickResponse", {}) != "$undefined":
639 quick_response_id = extract_ref_id(data.get("quickResponse", {}).get("stream", {}).get("next"))
655 quick_response_id = extract_ref_id(
656 data.get("quickResponse", {}).get("stream", {}).get("next"))
640 657
641 658 if data.get("turnId", {}) != "$undefined":
642 659 turn_id = extract_ref_id(data.get("turnId", {}).get("next"))
@@ -670,7 +687,7 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
670 687 provider_info["variantUrl"] = selection.get("externalUrl")
671 688 log_debug(f"Found variant stream ID: {variant_stream_id}")
672 689 yield ProviderInfo.from_dict(provider_info)
673
690
674 691 # Process target stream content
675 692 elif target_stream_id and chunk_id == target_stream_id:
676 693 yield PlainTextResponse(line.decode(errors="ignore"))
@@ -766,11 +783,11 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
766 783 for_target=False
767 784 ):
768 785 stream["extra"].append(chunk)
769 if isinstance(chunk,str) and "<streaming stopped unexpectedly" in chunk:
786 if isinstance(chunk, str) and "<streaming stopped unexpectedly" in chunk:
770 787 yield FinishReason(chunk)
771 788
772 789 yield PlainTextResponse("[Extra] " + line.decode(errors="ignore"))
773
790
774 791 if variant_image is not None:
775 792 yield variant_image
776 793 elif variant_text:
@@ -779,10 +796,10 @@ class Yupp(AsyncGeneratorProvider, ProviderModelMixin):
779 796 log_debug(f"Finished processing {line_count} lines")
780 797 except:
781 798 raise
782
799
783 800 finally:
784 801 # Claim reward in background
785 802 if reward_info and "unclaimedRewardInfo" in reward_info:
786 803 reward_id = reward_info["unclaimedRewardInfo"].get("rewardId")
787 804 if reward_id:
788 await claim_yupp_reward(session, account, reward_id)
805 await claim_yupp_reward(session, account, reward_id)