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

XFEstudio/gpt4free

Add QwenCode provider and OAuth2 support with token management

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

代码差异

9 个文件 +640 -3
Modified .github/workflows/build-packages.yml +2 -0
@@ -441,6 +441,7 @@ jobs:
441 441 **Executables:**
442 442 - Windows x64: `g4f-windows-${{ needs.prepare.outputs.version }}-x64.zip`
443 443 - Linux x64: `g4f-linux-${{ needs.prepare.outputs.version }}-x64`
444 - Linux ARM64: `g4f-linux-${{ needs.prepare.outputs.version }}-arm64`
444 445 - macOS x64: `g4f-macos-${{ needs.prepare.outputs.version }}-x64`
445 446 - macOS ARM64: `g4f-macos-${{ needs.prepare.outputs.version }}-arm64`
446 447
@@ -456,6 +457,7 @@ jobs:
456 457 ./artifacts/pypi-package/*
457 458 ./artifacts/windows-exe-x64/*
458 459 ./artifacts/linux-exe-x64/*
460 ./artifacts/linux-exe-arm64/*
459 461 ./artifacts/macos-exe-x64/*
460 462 ./artifacts/macos-exe-arm64/*
461 463 ./artifacts/debian-amd64/*
Modified g4f/Provider/__init__.py +4 -3
@@ -6,14 +6,15 @@ from ..providers.base_provider import AsyncProvider, AsyncGeneratorProvider
6 6 from ..providers.create_images import CreateImagesProvider
7 7 from .. import debug
8 8
9 from .needs_auth import *
10 from .needs_auth.hf import HuggingFace, HuggingChat, HuggingFaceAPI, HuggingFaceInference, HuggingFaceMedia
9 from .needs_auth import *
10 from .needs_auth.hf import HuggingFace, HuggingChat, HuggingFaceAPI, HuggingFaceInference, HuggingFaceMedia
11 11 try:
12 12 from .needs_auth.mini_max import HailuoAI, MiniMax
13 13 except ImportError as e:
14 14 debug.error("MiniMax providers not loaded:", e)
15 15
16 from .template import OpenaiTemplate, BackendApi
16 from .template import OpenaiTemplate, BackendApi
17 from .qwen.QwenCode import QwenCode
17 18 try:
18 19 from .not_working import *
19 20 except ImportError as e:
Modified g4f/Provider/needs_auth/LMArena.py +2 -0
@@ -651,6 +651,8 @@ class LMArena(AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin):
651 651 args = None
652 652 debug.log(f"{cls.__name__}: Cloudflare error")
653 653 continue
654 except:
655 raise
654 656 if args and os.getenv("G4F_SHARE_AUTH"):
655 657 yield "\n" * 10
656 658 yield "<!--"
Added g4f/Provider/qwen/QwenCode.py +60 -0
@@ -0,0 +1,60 @@
1 from __future__ import annotations
2
3 from ...typing import Messages, AsyncResult
4 from ...errors import MissingAuthError
5 from ..template import OpenaiTemplate
6 from .qwenContentGenerator import QwenContentGenerator
7 from .qwenOAuth2 import QwenOAuth2Client
8 from .sharedTokenManager import TokenManagerError
9
10 class QwenCode(OpenaiTemplate):
11 label = "Qwen Code 🤖"
12 url = "https://qwen.ai"
13 login_url = "https://github.com/QwenLM/qwen-code"
14 working = True
15 needs_auth = True
16 active_by_default = True
17 default_model = "qwen3-coder-plus"
18 models = [default_model]
19 client = QwenContentGenerator(QwenOAuth2Client())
20
21 @classmethod
22 async def create_async_generator(
23 cls,
24 model: str,
25 messages: Messages,
26 api_key: str = None,
27 api_base: str = None,
28 **kwargs
29 ) -> AsyncResult:
30 try:
31 creds = await cls.client.get_valid_token()
32 last_chunk = None
33 async for chunk in super().create_async_generator(
34 model,
35 messages,
36 api_key=creds.get("token", api_key),
37 api_base=creds.get("endpoint", api_base),
38 **kwargs
39 ):
40 if chunk != last_chunk:
41 yield chunk
42 last_chunk = chunk
43 except TokenManagerError:
44 raise MissingAuthError("QwenCode: No valid authentication available. Run the oauth flow to authenticate. | python -m g4f.Provider.qwen.oauthFlow")
45 except MissingAuthError:
46 await cls.client.shared_manager.getValidCredentials(cls.client.qwen_client, True)
47 creds = await cls.client.get_valid_token()
48 last_chunk = None
49 async for chunk in super().create_async_generator(
50 model,
51 messages,
52 api_key=creds.get("token"),
53 api_base=creds.get("endpoint"),
54 **kwargs
55 ):
56 if chunk != last_chunk:
57 yield chunk
58 last_chunk = chunk
59 except:
60 raise
Added g4f/Provider/qwen/oauthFlow.py +89 -0
@@ -0,0 +1,89 @@
1 import asyncio
2 import webbrowser
3 import time
4 from .qwenOAuth2 import generatePKCEPair, QwenOAuth2Client
5
6 # Configuration
7 AUTHORIZATION_URL = "https://chat.qwen.ai/api/v1/oauth2/device/code"
8 TOKEN_URL = "https://chat.qwen.ai/api/v1/oauth2/token"
9 CLIENT_ID = "f0304373b74a44d2b584a3fb70ca9e56"
10 SCOPES = "openid profile email model.completion"
11
12 # Local redirect URL for redirect-based flow (if used)
13 REDIRECT_URI = "http://localhost:8080/callback"
14
15 async def launch_browser_for_oauth():
16 # Generate PKCE parameters
17 pkce_pair = generatePKCEPair()
18 code_verifier = pkce_pair['code_verifier']
19 code_challenge = pkce_pair['code_challenge']
20
21 # Initialize OAuth client
22 client = QwenOAuth2Client()
23
24 # Request device code
25 device_auth = await client.requestDeviceAuthorization({
26 "scope": SCOPES,
27 "code_challenge": code_challenge,
28 "code_challenge_method": "S256",
29 })
30
31 # Check device auth success
32 if not isinstance(device_auth, dict) or "device_code" not in device_auth:
33 print("Failed to receive device code")
34 return
35
36 # Show user instructions
37 print("Please visit the following URL to authorize:")
38 print(device_auth.get("verification_uri_complete") or device_auth["verification_uri"])
39 # Attempt to automatically open the URL
40 url_to_open = device_auth.get("verification_uri_complete") or device_auth["verification_uri"]
41 try:
42 webbrowser.open(url_to_open)
43 except:
44 print(f"Open the URL manually in your browser: {url_to_open}")
45
46 # Start polling for token
47 device_code = device_auth["device_code"]
48 expires_in = device_auth.get("expires_in", 1800) # default 30 min
49 start_time = time.time()
50
51 print("Waiting for authorization... Press Ctrl+C to cancel.")
52
53 while True:
54 if time.time() - start_time > expires_in:
55 print("Authorization timed out.")
56 break
57
58 # Poll for token
59 token_response = await client.pollDeviceToken({
60 "device_code": device_code,
61 "code_verifier": code_verifier,
62 })
63
64 if isinstance(token_response, dict):
65 if "status" in token_response and token_response["status"] == "pending":
66 print(".", end="", flush=True)
67 await asyncio.sleep(2) # polling interval
68 continue
69 elif "access_token" in token_response:
70 # Success
71 print("\nAuthorization successful.")
72 print("Access Token:", token_response["access_token"])
73 # Save token_response to a file or config
74 await client.sharedManager.saveCredentialsToFile(token_response)
75 print(f"Credentials saved to: {client.sharedManager.getCredentialFilePath()}")
76 return
77 else:
78 print(f"\nError during polling: {token_response}")
79 break
80 else:
81 print(f"\nUnexpected response: {token_response}")
82 break
83
84 # Run the entire process
85 async def main():
86 await launch_browser_for_oauth()
87
88 if __name__ == "__main__":
89 asyncio.run(main())
Added g4f/Provider/qwen/qwenContentGenerator.py +40 -0
@@ -0,0 +1,40 @@
1 from typing import Optional, Dict
2
3 from .sharedTokenManager import SharedTokenManager
4 from .qwenOAuth2 import IQwenOAuth2Client
5
6 # Default base URL if not specified
7 DEFAULT_QWEN_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
8
9
10 class QwenContentGenerator:
11 def __init__(
12 self,
13 qwen_client: IQwenOAuth2Client
14 ):
15 self.qwen_client = qwen_client
16 self.base_url = DEFAULT_QWEN_BASE_URL
17 self.shared_manager = SharedTokenManager.getInstance()
18
19 # Initialize API URL with default, may be updated later
20 self.api_base = self.base_url
21
22 def get_current_endpoint(self, resource_url: Optional[str]) -> str:
23 url = resource_url if resource_url else self.base_url
24 if not url.startswith("http"):
25 url = "https://" + url
26 if not url.endswith("/v1"):
27 url = url.rstrip("/") + "/v1"
28 return url
29
30 async def get_valid_token(self) -> Dict[str, str]:
31 """
32 Obtain a valid token and endpoint from shared token manager.
33 """
34 credentials = await self.shared_manager.getValidCredentials(self.qwen_client)
35 token = credentials.get("access_token")
36 resource_url = credentials.get("resource_url")
37 endpoint = self.get_current_endpoint(resource_url)
38 if not token:
39 raise Exception("No valid access token obtained.")
40 return {"token": token, "endpoint": endpoint}
Added g4f/Provider/qwen/qwenOAuth2.py +178 -0
@@ -0,0 +1,178 @@
1 import base64
2 import hashlib
3 import secrets
4 import uuid
5 import time
6 from typing import Dict, Optional, Union
7
8 import aiohttp
9
10 from .stubs import IQwenOAuth2Client, QwenCredentials, ErrorDataDict
11 from .sharedTokenManager import SharedTokenManager
12
13
14 QWEN_OAUTH_BASE_URL = "https://chat.qwen.ai"
15 QWEN_OAUTH_DEVICE_CODE_ENDPOINT = f"{QWEN_OAUTH_BASE_URL}/api/v1/oauth2/device/code"
16 QWEN_OAUTH_TOKEN_ENDPOINT = f"{QWEN_OAUTH_BASE_URL}/api/v1/oauth2/token"
17
18 QWEN_OAUTH_CLIENT_ID = "f0304373b74a44d2b584a3fb70ca9e56"
19 QWEN_OAUTH_SCOPE = "openid profile email model.completion"
20 QWEN_OAUTH_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code"
21
22 QEN_DIR = ".qwen"
23 QWEN_CREDENTIAL_FILENAME = "oauth_creds.json"
24
25 TOKEN_REFRESH_BUFFER_MS = 30 * 1000 # 30 seconds
26
27
28 def generate_code_verifier() -> str:
29 return base64.urlsafe_b64encode(secrets.token_bytes(64)).decode().rstrip("=")
30
31
32 def generate_code_challenge(code_verifier: str) -> str:
33 sha256 = hashlib.sha256()
34 sha256.update(code_verifier.encode())
35 digest = sha256.digest()
36 return base64.urlsafe_b64encode(digest).decode().rstrip("=")
37
38
39 def generatePKCEPair():
40 code_verifier = generate_code_verifier()
41 code_challenge = generate_code_challenge(code_verifier)
42 return {"code_verifier": code_verifier, "code_challenge": code_challenge}
43
44
45 def object_to_urlencoded(data: Dict[str, str]) -> str:
46 return "&".join([f"{k}={v}" for k, v in data.items()])
47
48
49 def isDeviceAuthorizationSuccess(
50 response: Union[Dict, ErrorDataDict]
51 ) -> bool:
52 return "device_code" in response
53
54
55 def isDeviceTokenSuccess(
56 response: Union[Dict, ErrorDataDict]
57 ) -> bool:
58 return (
59 "access_token" in response
60 and response["access_token"]
61 and isinstance(response["access_token"], str)
62 and len(response["access_token"]) > 0
63 )
64
65
66 def isDeviceTokenPending(
67 response: Union[Dict, ErrorDataDict]
68 ) -> bool:
69 return response.get("status") == "pending"
70
71
72 def isErrorResponse(
73 response: Union[Dict, ErrorDataDict]
74 ) -> bool:
75 return "error" in response
76
77
78 def isTokenRefreshResponse(
79 response: Union[Dict, ErrorDataDict]
80 ) -> bool:
81 return "access_token" in response and "token_type" in response
82
83 class QwenOAuth2Client(IQwenOAuth2Client):
84 def __init__(self):
85 self.credentials: QwenCredentials = QwenCredentials()
86 self.sharedManager = SharedTokenManager.getInstance()
87
88 def setCredentials(self, credentials: QwenCredentials):
89 self.credentials = credentials
90
91 def getCredentials(self) -> QwenCredentials:
92 return self.credentials
93
94 async def getAccessToken(self) -> Dict[str, Optional[str]]:
95 try:
96 credentials = await self.sharedManager.getValidCredentials(self)
97 return {"token": credentials.get("access_token")}
98 except Exception:
99 # fallback to internal credentials if valid
100 if (
101 self.credentials.get("access_token")
102 and self.isTokenValid(self.credentials)
103 ):
104 return {"token": self.credentials["access_token"]}
105 return {"token": None}
106
107 async def requestDeviceAuthorization(self, options: dict) -> Union[Dict, ErrorDataDict]:
108 body_data = {
109 "client_id": QWEN_OAUTH_CLIENT_ID,
110 "scope": options["scope"],
111 "code_challenge": options["code_challenge"],
112 "code_challenge_method": options["code_challenge_method"],
113 }
114 async with aiohttp.ClientSession() as session:
115 async with session.post(QWEN_OAUTH_DEVICE_CODE_ENDPOINT, headers={
116 "Content-Type": "application/x-www-form-urlencoded",
117 "Accept": "application/json",
118 "x-request-id": str(uuid.uuid4()),
119 }, data=object_to_urlencoded(body_data)) as resp:
120 resp_json = await resp.json()
121 if resp.status != 200:
122 raise Exception(f"Device authorization failed {resp.status}: {resp_json}")
123 if not isDeviceAuthorizationSuccess(resp_json):
124 raise Exception(
125 f"Device authorization error: {resp_json.get('error')} - {resp_json.get('error_description')}"
126 )
127 return resp_json
128
129 async def pollDeviceToken(self, options: dict) -> Union[Dict, ErrorDataDict]:
130 body_data = {
131 "grant_type": QWEN_OAUTH_GRANT_TYPE,
132 "client_id": QWEN_OAUTH_CLIENT_ID,
133 "device_code": options["device_code"],
134 "code_verifier": options["code_verifier"],
135 }
136 async with aiohttp.ClientSession() as session:
137 async with session.post(QWEN_OAUTH_TOKEN_ENDPOINT, headers={
138 "Content-Type": "application/x-www-form-urlencoded",
139 "Accept": "application/json",
140 }, data=object_to_urlencoded(body_data)) as resp:
141 resp_json = await resp.json()
142 if resp.status != 200:
143 # Check for OAuth RFC 8628 responses
144 if resp.status == 400:
145 if "error" in resp_json:
146 if resp_json["error"] == "authorization_pending":
147 return {"status": "pending"}
148 if resp_json["error"] == "slow_down":
149 return {"status": "pending", "slowDown": True}
150 raise Exception(f"Token poll failed {resp.status}: {resp_json}")
151 return resp_json
152
153 async def refreshAccessToken(self) -> Union[Dict, ErrorDataDict]:
154 if not self.credentials.get("refresh_token"):
155 raise Exception("No refresh token")
156 body_data = {
157 "grant_type": "refresh_token",
158 "refresh_token": self.credentials["refresh_token"],
159 "client_id": QWEN_OAUTH_CLIENT_ID,
160 }
161 async with aiohttp.ClientSession() as session:
162 async with session.post(QWEN_OAUTH_TOKEN_ENDPOINT, headers={
163 "Content-Type": "application/x-www-form-urlencoded",
164 "Accept": "application/json",
165 }, data=object_to_urlencoded(body_data)) as resp:
166 resp_json = await resp.json()
167 if resp.status != 200:
168 if resp.status == 400:
169 # Handle token expiration
170 self.credentials = QwenCredentials()
171 raise Exception("Refresh token expired or invalid")
172 raise Exception(f"Token refresh failed {resp.status}: {resp_json}")
173 return resp_json
174
175 def isTokenValid(self, credentials: QwenCredentials) -> bool:
176 if not credentials.get("expiry_date"):
177 return False
178 return time.time() * 1000 < credentials["expiry_date"] - TOKEN_REFRESH_BUFFER_MS
Added g4f/Provider/qwen/sharedTokenManager.py +239 -0
@@ -0,0 +1,239 @@
1 import os
2 import json
3 import time
4 import asyncio
5 import uuid
6 from typing import Optional, Dict, Union
7 from .stubs import IQwenOAuth2Client, ErrorDataDict
8 from pathlib import Path
9 import threading
10
11 from ..base_provider import AuthFileMixin
12
13 QWEN_DIR = ".qwen"
14 QWEN_CREDENTIAL_FILENAME = "oauth_creds.json"
15 QWEN_LOCK_FILENAME = "oauth_creds.lock"
16 TOKEN_REFRESH_BUFFER_MS = 30 * 1000
17 LOCK_TIMEOUT_MS = 10000
18 CACHE_CHECK_INTERVAL_MS = 1000
19
20
21 def isErrorResponse(
22 response: Union[Dict, ErrorDataDict]
23 ) -> bool:
24 return "error" in response
25
26
27 class TokenError:
28 REFRESH_FAILED = "REFRESH_FAILED"
29 NO_REFRESH_TOKEN = "NO_REFRESH_TOKEN"
30 LOCK_TIMEOUT = "LOCK_TIMEOUT"
31 FILE_ACCESS_ERROR = "FILE_ACCESS_ERROR"
32 NETWORK_ERROR = "NETWORK_ERROR"
33
34
35 class TokenManagerError(Exception):
36 def __init__(self, type_: str, message: str, original_error: Optional[Exception] = None):
37 super().__init__(message)
38 self.type = type_
39 self.original_error = original_error
40
41
42 class SharedTokenManager(AuthFileMixin):
43 parent = "QwenCode"
44 _instance: Optional["SharedTokenManager"] = None
45 _lock = threading.Lock()
46
47 def __init__(self):
48 self.memory_cache = {
49 "credentials": None,
50 "file_mod_time": 0,
51 "last_check": 0,
52 }
53 self.refresh_promise = None
54
55 @classmethod
56 def getInstance(cls):
57 with cls._lock:
58 if cls._instance is None:
59 cls._instance = cls()
60 return cls._instance
61
62 def getCredentialFilePath(self):
63 path = SharedTokenManager.get_cache_file()
64 if path.is_file():
65 return path
66 return Path(os.path.expanduser(f"~/{QWEN_DIR}/{QWEN_CREDENTIAL_FILENAME}"))
67
68 def getLockFilePath(self):
69 return Path(os.path.expanduser(f"~/{QWEN_DIR}/{QWEN_LOCK_FILENAME}"))
70
71 def setLockConfig(self, config: dict):
72 # Optional: allow lock config override
73 pass
74
75 def registerCleanupHandlers(self):
76 import atexit
77
78 def cleanup():
79 try:
80 lock_path = self.getLockFilePath()
81 lock_path.unlink()
82 except:
83 pass
84
85 atexit.register(cleanup)
86
87 async def getValidCredentials(self, qwen_client: IQwenOAuth2Client, force_refresh: bool = False):
88 try:
89 await self.checkAndReloadIfNeeded()
90
91 if (
92 self.memory_cache["credentials"]
93 and not force_refresh
94 and self.isTokenValid(self.memory_cache["credentials"])
95 ):
96 return self.memory_cache["credentials"]
97
98 if self.refresh_promise:
99 return await self.refresh_promise
100
101 self.refresh_promise = asyncio.create_task(self.performTokenRefresh(qwen_client, force_refresh))
102 credentials = await self.refresh_promise
103 self.refresh_promise = None
104 return credentials
105 except Exception as e:
106 if isinstance(e, TokenManagerError):
107 raise
108 raise TokenManagerError(TokenError.REFRESH_FAILED, str(e), e)
109
110 async def checkAndReloadIfNeeded(self):
111 now = int(time.time() * 1000)
112 if now - self.memory_cache["last_check"] < CACHE_CHECK_INTERVAL_MS:
113 return
114 self.memory_cache["last_check"] = now
115
116 try:
117 file_path = self.getCredentialFilePath()
118 stat = file_path.stat()
119 file_mod_time = int(stat.st_mtime * 1000)
120 if file_mod_time > self.memory_cache["file_mod_time"]:
121 await self.reloadCredentialsFromFile()
122 self.memory_cache["file_mod_time"] = file_mod_time
123 except FileNotFoundError:
124 self.memory_cache["file_mod_time"] = 0
125 except Exception as e:
126 self.memory_cache["credentials"] = None
127 raise TokenManagerError(TokenError.FILE_ACCESS_ERROR, str(e), e)
128
129 async def reloadCredentialsFromFile(self):
130 file_path = self.getCredentialFilePath()
131 try:
132 with open(file_path, "r") as fs:
133 data = json.load(fs)
134 credentials = self.validateCredentials(data)
135 self.memory_cache["credentials"] = credentials
136 except Exception as e:
137 self.memory_cache["credentials"] = None
138
139 def validateCredentials(self, data):
140 if not data or not isinstance(data, dict):
141 raise ValueError("Invalid credentials format")
142 for field in ["access_token", "refresh_token", "token_type"]:
143 if field not in data or not isinstance(data[field], str):
144 raise ValueError(f"Invalid credentials: missing {field}")
145 if "expiry_date" not in data or not isinstance(data["expiry_date"], (int, float)):
146 raise ValueError("Invalid credentials: missing expiry_date")
147 return data
148
149 async def performTokenRefresh(self, qwen_client: IQwenOAuth2Client, force_refresh: bool):
150 lock_path = self.getLockFilePath()
151 try:
152 current_credentials = qwen_client.getCredentials()
153 if not current_credentials.get("refresh_token"):
154 raise TokenManagerError(TokenError.NO_REFRESH_TOKEN, "No refresh token")
155 await self.acquireLock(lock_path)
156
157 await self.checkAndReloadIfNeeded()
158
159 if (
160 not force_refresh
161 and self.memory_cache["credentials"]
162 and self.isTokenValid(self.memory_cache["credentials"])
163 ):
164 qwen_client.setCredentials(self.memory_cache["credentials"])
165 return self.memory_cache["credentials"]
166
167 response = await qwen_client.refreshAccessToken()
168 if not response or isErrorResponse(response):
169 raise TokenManagerError(TokenError.REFRESH_FAILED, str(response))
170 token_data = response
171 if "access_token" not in token_data:
172 raise TokenManagerError(TokenError.REFRESH_FAILED, "No access_token returned")
173
174 credentials = {
175 "access_token": token_data["access_token"],
176 "token_type": token_data["token_type"],
177 "refresh_token": token_data.get("refresh_token", current_credentials.get("refresh_token")),
178 "resource_url": token_data.get("resource_url"),
179 "expiry_date": int(time.time() * 1000) + token_data.get("expires_in", 0) * 1000,
180 }
181 self.memory_cache["credentials"] = credentials
182 qwen_client.setCredentials(credentials)
183
184 await self.saveCredentialsToFile(credentials)
185 return credentials
186 except Exception as e:
187 if isinstance(e, TokenManagerError):
188 raise
189 raise
190
191 finally:
192 await self.releaseLock(lock_path)
193
194 async def acquireLock(self, lock_path: Path):
195 max_attempts = 50
196 attempt_interval = 200 # ms
197 lock_id = str(uuid.uuid4())
198
199 for _ in range(max_attempts):
200 try:
201 with open(lock_path, "w") as f:
202 f.write(lock_id)
203 return
204 except:
205 try:
206 stat = os.stat(str(lock_path))
207 lock_age = int(time.time() * 1000) - int(stat.st_mtime * 1000)
208 if lock_age > LOCK_TIMEOUT_MS:
209 try:
210 await os.unlink(str(lock_path))
211 except:
212 pass
213 except:
214 pass
215 await asyncio.sleep(attempt_interval / 1000)
216 raise TokenManagerError(TokenError.LOCK_TIMEOUT, "Failed to acquire lock")
217
218 async def releaseLock(self, lock_path: Path):
219 try:
220 await os.unlink(str(lock_path))
221 except:
222 pass
223
224 async def saveCredentialsToFile(self, credentials: dict):
225 file_path = self.getCredentialFilePath()
226 os.makedirs(file_path.parent, exist_ok=True)
227 with open(file_path, "w") as f:
228 f.write(json.dumps(credentials, indent=2))
229 stat = os.stat(str(file_path))
230 self.memory_cache["file_mod_time"] = int(stat.st_mtime * 1000)
231
232 def isTokenValid(self, credentials: dict) -> bool:
233 expiry_date = credentials.get("expiry_date")
234 if not expiry_date:
235 return False
236 return time.time() * 1000 < expiry_date - TOKEN_REFRESH_BUFFER_MS
237
238 def getCurrentCredentials(self):
239 return self.memory_cache["credentials"]
Added g4f/Provider/qwen/stubs.py +26 -0
@@ -0,0 +1,26 @@
1 from typing import Dict, Optional, Union
2
3 class ErrorDataDict(Dict):
4 pass
5
6 class QwenCredentials(Dict):
7 pass
8
9 class IQwenOAuth2Client:
10 def setCredentials(self, credentials: QwenCredentials):
11 raise NotImplementedError
12
13 def getCredentials(self) -> QwenCredentials:
14 raise NotImplementedError
15
16 async def getAccessToken(self) -> Dict[str, Optional[str]]:
17 raise NotImplementedError
18
19 async def requestDeviceAuthorization(self, options: dict) -> Union[Dict, ErrorDataDict]:
20 raise NotImplementedError
21
22 async def pollDeviceToken(self, options: dict) -> Union[Dict, ErrorDataDict]:
23 raise NotImplementedError
24
25 async def refreshAccessToken(self) -> Union[Dict, ErrorDataDict]:
26 raise NotImplementedError