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

XFEstudio/gpt4free

Add Yupp provider implementation with account management and model fetching

d1df33ef
hlohaus <983577+hlohaus@users.noreply.github.com>
提交于

代码差异

4 个文件 +775 -0
Added g4f/Provider/Yupp.py +477 -0
@@ -0,0 +1,477 @@
1 import json
2 import time
3 import uuid
4 import re
5 import os
6 from typing import Optional, Dict, Any, Generator, List
7 import threading
8 from ..providers.base_provider import AbstractProvider, ProviderModelMixin
9 from ..providers.response import Reasoning, PlainTextResponse, PreviewResponse
10 from ..errors import RateLimitError, ProviderException
11 from ..cookies import get_cookies
12 from .yupp.models import YuppModelManager
13 from ..debug import log
14
15 # Global variables to manage Yupp accounts (should be set by your main application)
16 YUPP_ACCOUNTS: List[Dict[str, Any]] = []
17 YUPP_MODELS: List[Dict[str, Any]] = []
18 account_rotation_lock = threading.Lock()
19
20 class YuppAccount:
21 """Yupp account representation"""
22 def __init__(self, token: str, is_valid: bool = True, error_count: int = 0, last_used: float = 0):
23 self.token = token
24 self.is_valid = is_valid
25 self.error_count = error_count
26 self.last_used = last_used
27
28 def load_yupp_accounts(tokens_str: str):
29 """Load Yupp accounts from token string (compatible with your existing system)"""
30 global YUPP_ACCOUNTS
31 if not tokens_str:
32 return
33
34 tokens = [token.strip() for token in tokens_str.split(',') if token.strip()]
35 YUPP_ACCOUNTS = [
36 {
37 "token": token,
38 "is_valid": True,
39 "error_count": 0,
40 "last_used": 0.0
41 }
42 for token in tokens
43 ]
44
45 def create_requests_session():
46 """Create a requests session with proper headers"""
47 import requests
48 session = requests.Session()
49 session.headers.update({
50 "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",
51 "Accept": "text/x-component, */*",
52 "Accept-Encoding": "gzip, deflate, br, zstd",
53 "Accept-Language": "en-US,en;q=0.9",
54 "Sec-Fetch-Dest": "empty",
55 "Sec-Fetch-Mode": "cors",
56 "Sec-Fetch-Site": "same-origin",
57 })
58 return session
59
60 def get_best_yupp_account() -> Optional[Dict[str, Any]]:
61 """Get the best available Yupp account using a smart selection algorithm."""
62 max_error_count = int(os.getenv("MAX_ERROR_COUNT", "3"))
63 error_cooldown = int(os.getenv("ERROR_COOLDOWN", "300"))
64
65 with account_rotation_lock:
66 now = time.time()
67 valid_accounts = [
68 acc
69 for acc in YUPP_ACCOUNTS
70 if acc["is_valid"]
71 and (
72 acc["error_count"] < max_error_count
73 or now - acc["last_used"] > error_cooldown
74 )
75 ]
76
77 if not valid_accounts:
78 return None
79
80 # Reset error count for accounts that have been in cooldown
81 for acc in valid_accounts:
82 if (
83 acc["error_count"] >= max_error_count
84 and now - acc["last_used"] > error_cooldown
85 ):
86 acc["error_count"] = 0
87
88 # Sort by last used (oldest first) and error count (lowest first)
89 valid_accounts.sort(key=lambda x: (x["last_used"], x["error_count"]))
90 account = valid_accounts[0]
91 account["last_used"] = now
92 return account
93
94 def format_messages_for_yupp(messages: List[Dict[str, str]]) -> str:
95 """Format multi-turn conversation for Yupp single-turn format"""
96 formatted = []
97
98 # Handle system messages
99 system_messages = [msg for msg in messages if msg.get("role") == "system"]
100 if system_messages:
101 for sys_msg in system_messages:
102 content = sys_msg.get("content", "")
103 formatted.append(content)
104
105 # Handle user and assistant messages
106 user_assistant_msgs = [msg for msg in messages if msg.get("role") != "system"]
107 for msg in user_assistant_msgs:
108 role = "Human" if msg.get("role") == "user" else "Assistant"
109 content = msg.get("content", "")
110 formatted.append(f"\n\n{role}: {content}")
111
112 # Ensure it ends with Assistant:
113 if not formatted or not formatted[-1].strip().startswith("Assistant:"):
114 formatted.append("\n\nAssistant:")
115
116 result = "".join(formatted)
117 # Remove leading \n\n if present
118 if result.startswith("\n\n"):
119 result = result[2:]
120
121 return result
122
123 def claim_yupp_reward(account: Dict[str, Any], reward_id: str):
124 """Claim Yupp reward synchronously"""
125 try:
126 import requests
127 log_debug(f"Claiming reward {reward_id}...")
128 url = "https://yupp.ai/api/trpc/reward.claim?batch=1"
129 payload = {"0": {"json": {"rewardId": reward_id}}}
130 headers = {
131 "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",
132 "Content-Type": "application/json",
133 "sec-fetch-site": "same-origin",
134 "Cookie": f"__Secure-yupp.session-token={account['token']}",
135 }
136 session = create_requests_session()
137 response = session.post(url, json=payload, headers=headers)
138 response.raise_for_status()
139 data = response.json()
140 balance = data[0]["result"]["data"]["json"]["currentCreditBalance"]
141 log_debug(f"Reward claimed successfully. New balance: {balance}")
142 return balance
143 except Exception as e:
144 log_debug(f"Failed to claim reward {reward_id}. Error: {e}")
145 return None
146
147 def log_debug(message: str):
148 """Debug logging (can be replaced with your logging system)"""
149 if os.getenv("DEBUG_MODE", "false").lower() == "true":
150 print(f"[DEBUG] {message}")
151 else:
152 log(f"[Yupp] {message}")
153
154 class Yupp(AbstractProvider, ProviderModelMixin):
155 """
156 Yupp.ai Provider for g4f
157 Uses multiple account rotation and smart error handling
158 """
159
160 working = True
161 active_by_default = True
162
163 @classmethod
164 def get_models(cls) -> List[Dict[str, Any]]:
165 if not cls.models:
166 manager = YuppModelManager()
167 models = manager.client.fetch_models()
168 cls.models = [model.get("name") for model in models]
169 return cls.models
170
171 @classmethod
172 def create_completion(
173 cls,
174 model: str,
175 messages: List[Dict[str, str]] = None,
176 stream: bool = False,
177 api_key: Optional[str] = None,
178 temperature: float = 0.7,
179 max_tokens: int = 1000,
180 **kwargs,
181 ) -> Generator[str, Any, None]:
182 if not api_key:
183 api_key = get_cookies("yupp.ai", False).get("__Secure-yupp.session-token")
184
185 # Initialize Yupp accounts and models
186 if api_key:
187 load_yupp_accounts(api_key)
188
189 log_debug(f"Yupp provider initialized with {len(YUPP_ACCOUNTS)} accounts")
190
191 """
192 Create completion using Yupp.ai API with account rotation
193 """
194 if messages is None:
195 messages = []
196
197 if not YUPP_ACCOUNTS:
198 raise ProviderException("No Yupp accounts configured. Set YUPP_API_KEY environment variable.")
199
200 # Format messages
201 question = format_messages_for_yupp(messages)
202 log_debug(f"Formatted question length: {len(question)}")
203
204 # Try all accounts with rotation
205 max_attempts = len(YUPP_ACCOUNTS)
206 for attempt in range(max_attempts):
207 account = get_best_yupp_account()
208 if not account:
209 raise ProviderException("No valid Yupp accounts available")
210
211 try:
212 yield from cls._make_yupp_request(
213 account, question, model, model, stream,
214 temperature, max_tokens, **kwargs
215 )
216 return # Success, exit the loop
217
218 except RateLimitError:
219 log_debug(f"Account ...{account['token'][-4:]} hit rate limit, rotating")
220 with account_rotation_lock:
221 account["error_count"] += 1
222 continue
223 except ProviderException as e:
224 log_debug(f"Account ...{account['token'][-4:]} failed: {str(e)}")
225 with account_rotation_lock:
226 if "auth" in str(e).lower() or "401" in str(e) or "403" in str(e):
227 account["is_valid"] = False
228 else:
229 account["error_count"] += 1
230 continue
231 except Exception as e:
232 log_debug(f"Unexpected error with account ...{account['token'][-4:]}: {str(e)}")
233 with account_rotation_lock:
234 account["error_count"] += 1
235 raise ProviderException(f"Yupp request failed: {str(e)}") from e
236
237 raise ProviderException("All Yupp accounts failed after rotation attempts")
238
239 @classmethod
240 def _make_yupp_request(
241 cls,
242 account: Dict[str, Any],
243 question: str,
244 model_name: str,
245 model_id: str,
246 stream: bool,
247 temperature: float,
248 max_tokens: int,
249 **kwargs
250 ) -> Generator[str, Any, None]:
251 """Make actual request to Yupp.ai"""
252
253 # Build request
254 url_uuid = str(uuid.uuid4())
255 url = f"https://yupp.ai/chat/{url_uuid}?stream=true"
256
257 headers = {
258 "accept": "text/x-component",
259 "accept-language": "de,en-US;q=0.9,en;q=0.8,zh-CN;q=0.7,zh;q=0.6",
260 "cache-control": "no-cache",
261 "content-type": "text/plain;charset=UTF-8",
262 "next-action": "7f2a2308b5fc462a2c26df714cb2cccd02a9c10fbb",
263 "pragma": "no-cache",
264 "priority": "u=1, i",
265 "sec-ch-ua": "\"Chromium\";v=\"140\", \"Not=A?Brand\";v=\"24\", \"Google Chrome\";v=\"140\"",
266 "sec-ch-ua-mobile": "?0",
267 "sec-ch-ua-platform": "\"Linux\"",
268 "sec-fetch-dest": "empty",
269 "sec-fetch-mode": "cors",
270 "sec-fetch-site": "same-origin",
271 "cookie": f"__Secure-yupp.session-token={account['token']}",
272 }
273
274 log_debug(f"Sending request to Yupp.ai with account ...{account['token'][-4:]}")
275
276 payload = [
277 url_uuid,
278 str(uuid.uuid4()),
279 question,
280 "$undefined",
281 "$undefined",
282 [],
283 "$undefined",
284 [{"modelName": model_name, "promptModifierId": "$undefined"}] if model_name else "none",
285 "text",
286 False,
287 "$undefined",
288 ]
289
290 # Send request
291 session = create_requests_session()
292 response = session.post(
293 url,
294 data=json.dumps(payload),
295 headers=headers,
296 stream=True,
297 timeout=60
298 )
299 response.raise_for_status()
300
301 yield from cls._process_stream_response(
302 response.iter_lines(), account
303 )
304
305 @classmethod
306 def _process_stream_response(
307 cls,
308 response_lines,
309 account: Dict[str, Any]
310 ) -> Generator[str, Any, None]:
311 """Process Yupp stream response and convert to OpenAI format"""
312
313 line_pattern = re.compile(b"^([0-9a-fA-F]+):(.*)")
314 chunks = {}
315 target_stream_id = None
316 reward_info = None
317 is_thinking = False
318 thinking_content = ""
319 normal_content = ""
320 select_stream = [None, None]
321 processed_content = set()
322
323 def extract_ref_id(ref):
324 """Extract ID from reference string, e.g., from '$@123' extract '123'"""
325 return ref[2:] if ref and isinstance(ref, str) and ref.startswith("$@") else None
326
327 def is_valid_content(content: str) -> bool:
328 """Check if content is valid, avoid over-filtering"""
329 if not content or content in [None, "", "$undefined"]:
330 return False
331
332 if content.startswith("\\n\\<streaming stopped") or content.startswith("\n\\<streaming stopped"):
333 return False
334
335 if re.match(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", content.strip()):
336 return False
337
338 if len(content.strip()) == 0:
339 return False
340
341 if content.strip() in ["$undefined", "undefined", "null", "NULL"]:
342 return False
343
344 return True
345
346 def process_content_chunk(content: str, chunk_id: str, line_count: int):
347 """Process single content chunk"""
348 nonlocal is_thinking, thinking_content, normal_content
349
350 if not is_valid_content(content):
351 return
352
353 # log_debug(f"Processing chunk #{line_count} with content: '{content[:50]}...'")
354
355 if is_thinking:
356 yield Reasoning(content)
357 else:
358 normal_content += content
359 yield content
360
361 try:
362 # log_debug("Starting to process Yupp stream response...")
363 line_count = 0
364 quick_response_id = None
365
366 for line in response_lines:
367
368 line_count += 1
369
370 match = line_pattern.match(line)
371 if not match:
372 log_debug(f"Line {line_count}: No pattern match")
373 continue
374
375 chunk_id, chunk_data = match.groups()
376 chunk_id = chunk_id.decode()
377
378 try:
379 data = json.loads(chunk_data) if chunk_data != b"{}" else {}
380 chunks[chunk_id] = data
381 except json.JSONDecodeError:
382 log_debug(f"Failed to parse JSON for chunk {chunk_id}")
383 continue
384
385 # Process reward info
386 if chunk_id == "a":
387 reward_info = data
388 log_debug(f"Found reward info")
389
390 # Process initial setup
391 elif chunk_id == "1":
392 yield PlainTextResponse(line.decode(errors="ignore"))
393 if isinstance(data, dict):
394 left_stream = data.get("leftStream", {})
395 right_stream = data.get("rightStream", {})
396 quick_response_id = extract_ref_id(data.get("quickResponse", {}).get("stream", {}).get("next"))
397 select_stream = [left_stream, right_stream]
398
399 elif chunk_id == "e":
400 yield PlainTextResponse(line.decode(errors="ignore"))
401 if isinstance(data, dict):
402 for i, selection in enumerate(data.get("modelSelections", [])):
403 if selection.get("selectionSource") == "USER_SELECTED":
404 if i < len(select_stream) and isinstance(select_stream[i], dict):
405 target_stream_id = extract_ref_id(select_stream[i].get("next"))
406 log_debug(f"Found target stream ID: {target_stream_id}")
407 break
408
409 # Process target stream content
410 elif target_stream_id and chunk_id == target_stream_id:
411 yield PlainTextResponse(line.decode(errors="ignore"))
412 if isinstance(data, dict):
413 target_stream_id = extract_ref_id(data.get("next"))
414 content = data.get("curr", "")
415 if content:
416 yield from process_content_chunk(content, chunk_id, line_count)
417
418 elif quick_response_id and chunk_id == quick_response_id:
419 yield PlainTextResponse(line.decode(errors="ignore"))
420 if isinstance(data, dict):
421 content = data.get("curr", "")
422 if content:
423 yield PreviewResponse(content)
424
425 # Fallback: process any chunk with "curr"
426 elif isinstance(data, dict) and "curr" in data:
427 content = data.get("curr", "")
428 if content:
429 pass #yield from process_content_chunk(content, chunk_id)
430
431 log_debug(f"Finished processing {line_count} lines")
432
433 except:
434 raise
435
436 finally:
437 # Claim reward in background
438 if reward_info and "unclaimedRewardInfo" in reward_info:
439 reward_id = reward_info["unclaimedRewardInfo"].get("rewardId")
440 if reward_id:
441 try:
442 claim_yupp_reward(account, reward_id)
443 except Exception as e:
444 log_debug(f"Failed to claim reward: {e}")
445
446 # log_debug(f"Stream completed. Content length: {len(normal_content)}")
447
448 # Initialize the provider
449 def init_yupp_provider():
450 """Initialize Yupp provider with environment configuration"""
451 tokens = os.getenv("YUPP_TOKENS", "")
452 if tokens:
453 load_yupp_accounts(tokens)
454
455 log_debug(f"Yupp provider initialized: {len(YUPP_ACCOUNTS)} accounts, {len(YUPP_MODELS)} models")
456 return Yupp
457
458 # Example usage and testing
459 if __name__ == "__main__":
460 # Set up environment for testing
461 # os.environ["DEBUG_MODE"] = "true"
462
463 # Initialize provider
464 provider = init_yupp_provider()
465
466 # Test stream completion
467 try:
468 print("\nTesting stream completion...")
469 for chunk in provider.create_completion(
470 model="claude-sonnet-4-5-20250929<>thinking",
471 messages=[{"role": "user", "content": "What is Python?"}],
472 stream=True
473 ):
474 if isinstance(chunk, str) and chunk.strip():
475 print(chunk, end="")
476 except Exception as e:
477 print(f"\nStream test failed: {e}")
Modified g4f/Provider/__init__.py +1 -0
@@ -61,6 +61,7 @@ from .StringableInference import StringableInference
61 61 from .TeachAnything import TeachAnything
62 62 from .WeWordle import WeWordle
63 63 from .Yqcloud import Yqcloud
64 from .Yupp import Yupp
64 65
65 66 import sys
66 67
Added g4f/Provider/yupp/models.py +293 -0
@@ -0,0 +1,293 @@
1 import json
2 import os
3 import requests
4 from typing import Dict, List, Optional, Any
5 from dataclasses import dataclass
6 from dotenv import load_dotenv
7
8
9 @dataclass
10 class ModelConfig:
11 """Configuration for API requests"""
12 base_url: str = "https://yupp.ai"
13 api_endpoint: str = "/api/trpc/model.getModelInfoList,scribble.getScribbleByLabel"
14 timeout: int = 30
15 fallback_file: str = "models.json"
16 output_file: str = "model.json"
17
18
19 class YuppAPIClient:
20 """Yupp API client for fetching model data"""
21
22 def __init__(self, config: ModelConfig = None):
23 self.config = config or ModelConfig()
24 self.session = requests.Session()
25 self._setup_session()
26
27 def _setup_session(self) -> None:
28 """Setup session with headers and cookies"""
29 self.session.headers.update(self._get_headers())
30 self._set_cookies()
31
32 def _get_headers(self) -> Dict[str, str]:
33 """Get request headers"""
34 return {
35 "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
36 "Accept": "application/json, text/plain, */*",
37 "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
38 "Referer": f"{self.config.base_url}/",
39 "Origin": self.config.base_url,
40 "Sec-Fetch-Dest": "empty",
41 "Sec-Fetch-Mode": "cors",
42 "Sec-Fetch-Site": "same-origin",
43 }
44
45 def _set_cookies(self) -> None:
46 """Set cookies from environment variable"""
47 token = self._get_session_token()
48 if token:
49 self.session.cookies.set("__Secure-yupp.session-token", token)
50
51 def _get_session_token(self) -> Optional[str]:
52 """Get session token from environment variable"""
53 env_tokens = os.getenv("YUPP_TOKENS")
54 if not env_tokens:
55 return None
56
57 try:
58 tokens = [t.strip() for t in env_tokens.split(",") if t.strip()]
59 return tokens[0] if tokens else None
60 except Exception as e:
61 print(f"Warning: Failed to parse YUPP_TOKENS: {e}")
62 return None
63
64 def _build_api_url(self) -> str:
65 """Build the complete API URL"""
66 params = "batch=1&input=%7B%220%22%3A%7B%22json%22%3Anull%2C%22meta%22%3A%7B%22values%22%3A%5B%22undefined%22%5D%7D%7D%2C%221%22%3A%7B%22json%22%3A%7B%22label%22%3A%22homepage_banner%22%7D%7D%7D"
67 return f"{self.config.base_url}{self.config.api_endpoint}?{params}"
68
69 def fetch_models(self) -> Optional[List[Dict[str, Any]]]:
70 """Fetch model data from API"""
71 url = self._build_api_url()
72
73 try:
74 print(f"Fetching data from: {url}")
75 response = self.session.get(url, timeout=self.config.timeout)
76 response.raise_for_status()
77
78 data = response.json()
79 print("Successfully fetched and parsed model data")
80
81 # Extract model list from response structure
82 if data and isinstance(data, list) and len(data) > 0:
83 return data[0]["result"]["data"]["json"]
84 else:
85 print("Unexpected response format")
86 return None
87
88 except requests.exceptions.RequestException as e:
89 print(f"Request failed: {e}")
90 return None
91 except (ValueError, json.JSONDecodeError) as e:
92 print(f"JSON parsing failed: {e}")
93 return None
94 except KeyError as e:
95 print(f"Data structure error - missing key: {e}")
96 return None
97
98
99 class ModelProcessor:
100 """Process and filter model data"""
101
102 SUPPORTED_FAMILIES = {
103 "GPT", "Claude", "Gemini", "Qwen", "DeepSeek", "Perplexity", "Kimi"
104 }
105
106 TAG_MAPPING = {
107 "isPro": "☀️",
108 "isMax": "🔥",
109 "isNew": "🆕",
110 "isLive": "🎤",
111 "isAgent": "🤖",
112 "isFast": "🚀",
113 "isReasoning": "🧠",
114 "isImageGeneration": "🎨",
115 }
116
117 @classmethod
118 def generate_tags(cls, item: Dict[str, Any]) -> List[str]:
119 """Generate tags for model display"""
120 tags = []
121
122 # Add emoji tags based on boolean flags
123 for key, emoji in cls.TAG_MAPPING.items():
124 if item.get(key, False):
125 tags.append(emoji)
126
127 # Add attachment tag if supported
128 if item.get("supportedAttachmentMimeTypes"):
129 tags.append("📎")
130
131 return tags
132
133 @classmethod
134 def should_include_model(cls, item: Dict[str, Any]) -> bool:
135 """Check if model should be included in output"""
136 family = item.get("family")
137
138 # Include if in supported families or has special features
139 return (
140 family in cls.SUPPORTED_FAMILIES or
141 item.get("isImageGeneration") or
142 item.get("isAgent") or
143 item.get("isLive")
144 )
145
146 @classmethod
147 def process_model_item(cls, item: Dict[str, Any]) -> Dict[str, Any]:
148 """Process individual model item"""
149 tags = cls.generate_tags(item)
150 label = item.get("label", "")
151
152 # Add tags to label if present
153 if tags:
154 label += "\n" + " | ".join(tags)
155
156 return {
157 "id": item.get("id"),
158 "name": item.get("name"),
159 "label": label,
160 "shortLabel": item.get("shortLabel"),
161 "publisher": item.get("publisher"),
162 "family": item.get("family"),
163 "isPro": item.get("isPro", False),
164 "isInternal": item.get("isInternal", False),
165 "isMax": item.get("isMax", False),
166 "isLive": item.get("isLive", False),
167 "isNew": item.get("isNew", False),
168 "isImageGeneration": item.get("isImageGeneration", False),
169 "isAgent": item.get("isAgent", False),
170 "isReasoning": item.get("isReasoning", False),
171 "isFast": item.get("isFast", False),
172 }
173
174 @classmethod
175 def filter_and_process(cls, data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
176 """Filter and process model data"""
177 return [
178 cls.process_model_item(item)
179 for item in data
180 if cls.should_include_model(item)
181 ]
182
183
184 class DataManager:
185 """Handle data loading and saving operations"""
186
187 @staticmethod
188 def load_fallback_data(filename: str) -> List[Dict[str, Any]]:
189 """Load fallback data from local file"""
190 try:
191 with open(filename, "r", encoding="utf-8") as f:
192 return json.load(f)
193 except FileNotFoundError:
194 print(f"Fallback file not found: {filename}")
195 return []
196 except json.JSONDecodeError as e:
197 print(f"Failed to parse fallback file: {e}")
198 return []
199
200 @staticmethod
201 def save_data(data: List[Dict[str, Any]], filename: str) -> bool:
202 """Save data to JSON file"""
203 try:
204 # Create directory if needed
205 os.makedirs(os.path.dirname(filename) if os.path.dirname(filename) else ".",
206 exist_ok=True)
207
208 # Create file if it doesn't exist
209 if not os.path.exists(filename):
210 open(filename, "a", encoding="utf-8").close()
211
212 with open(filename, "w", encoding="utf-8") as f:
213 json.dump(data, f, indent=4, ensure_ascii=False)
214
215 print(f"Successfully saved {len(data)} models to {filename}")
216 return True
217
218 except Exception as e:
219 print(f"Failed to save data: {e}")
220 return False
221
222
223 class YuppModelManager:
224 """Main manager class for Yupp model operations"""
225
226 def __init__(self, config: ModelConfig = None):
227 self.config = config or ModelConfig()
228 self.client = YuppAPIClient(config)
229 self.processor = ModelProcessor()
230 self.data_manager = DataManager()
231
232 def has_valid_token(self) -> bool:
233 """Check if valid token is available"""
234 return self.client._get_session_token() is not None
235
236 def fetch_and_save_models(self, output_file: str = None) -> bool:
237 """Main method to fetch and save model data"""
238 output_file = output_file or self.config.output_file
239
240 print("=== Yupp Model Data Fetcher ===")
241
242 if not self.has_valid_token():
243 print("Warning: YUPP_TOKENS environment variable not set")
244 return False
245
246 # Try to fetch from API
247 data = self.client.fetch_models()
248
249 # Fallback to local data if API fails
250 if not data:
251 print("API request failed, trying fallback data...")
252 data = self.data_manager.load_fallback_data(self.config.fallback_file)
253
254 if not data:
255 print("No model data available")
256 return False
257
258 print(f"Processing {len(data)} models...")
259 processed_models = self.processor.filter_and_process(data)
260
261 return self.data_manager.save_data(processed_models, output_file)
262
263 def run_interactive(self) -> bool:
264 """Run in interactive mode (for CLI use)"""
265 load_dotenv()
266
267 print("=== Yupp Model Data Tool ===")
268
269 if not self.has_valid_token():
270 print("Error: YUPP_TOKENS environment variable not set")
271 print("Please set YUPP_TOKENS environment variable, e.g.:")
272 print("export YUPP_TOKENS='your_token_here'")
273 return False
274
275 return self.fetch_and_save_models()
276
277
278 def main():
279 """Main entry point"""
280 manager = YuppModelManager()
281 success = manager.run_interactive()
282
283 if success:
284 print("Operation completed successfully")
285 else:
286 print("Operation failed")
287 return 1
288
289 return 0
290
291
292 if __name__ == "__main__":
293 exit(main())
Modified g4f/errors.py +4 -0
@@ -100,4 +100,8 @@ class TimeoutError(G4FError):
100 100
101 101 class ConversationLimitError(G4FError):
102 102 """Raised when a conversation limit is reached on the provider."""
103 pass
104
105 class ProviderException(G4FError):
106 """Raised for general provider-related exceptions."""
103 107 pass