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

XFEstudio/gpt4free

Updates (#3362)

Co-authored-by: H Lohaus <heiner.loh789@gmail.com>

6f027fed
H Lohaus <hlohaus@users.noreply.github.com>
提交于

代码差异

5 个文件 +135 -35
Modified g4f/Provider/github/GithubCopilot.py +15 -11
@@ -17,7 +17,6 @@ from .sharedTokenManager import TokenManagerError, SharedTokenManager
17 17 from .githubOAuth2 import GithubOAuth2Client
18 18 from .oauthFlow import launch_browser_for_oauth
19 19
20
21 20 class GithubCopilot(OpenaiTemplate):
22 21 """
23 22 GitHub Copilot provider with OAuth authentication.
@@ -116,8 +115,8 @@ class GithubCopilot(OpenaiTemplate):
116 115 cls,
117 116 model: str,
118 117 messages: Messages,
119 api_key: str = None,
120 base_url: str = None,
118 api_key: Optional[str] = None,
119 base_url: Optional[str] = None,
121 120 **kwargs
122 121 ) -> AsyncResult:
123 122 """
@@ -132,13 +131,18 @@ class GithubCopilot(OpenaiTemplate):
132 131 token_provider = cls._get_token_provider()
133 132 creds = await token_provider.get_valid_token()
134 133 api_key = creds.get("token")
134 if not api_key:
135 raise RuntimeError(
136 "GitHub Copilot OAuth not configured. "
137 "Please run 'g4f auth github-copilot' to authenticate."
138 )
135 139 if not base_url:
136 140 base_url = creds.get("endpoint", cls.base_url)
137 141 except TokenManagerError as e:
138 142 if "login" in str(e).lower() or "credentials" in str(e).lower():
139 143 raise RuntimeError(
140 144 "GitHub Copilot OAuth not configured. "
141 "Please run 'g4f-github-copilot login' to authenticate."
145 "Please run 'g4f auth github-copilot' to authenticate."
142 146 ) from e
143 147 raise
144 148
@@ -153,7 +157,7 @@ class GithubCopilot(OpenaiTemplate):
153 157 yield chunk
154 158
155 159 @classmethod
156 def get_models(cls, api_key = None, base_url = None, timeout = None):
160 def get_models(cls, api_key: Optional[str] = None, base_url: Optional[str] = None, timeout: Optional[int] = None):
157 161 # If no API key provided, use OAuth token
158 162 if api_key is None:
159 163 try:
@@ -167,24 +171,24 @@ class GithubCopilot(OpenaiTemplate):
167 171 if "login" in str(e).lower() or "credentials" in str(e).lower():
168 172 raise RuntimeError(
169 173 "GitHub Copilot OAuth not configured. "
170 "Please run 'g4f-github-copilot login' to authenticate."
174 "Please run 'g4f auth github-copilot' to authenticate."
171 175 ) from e
172 176 raise
173 177 return super().get_models(api_key, base_url, timeout)
174 178
175 179 @classmethod
176 def get_headers(cls, stream: bool, api_key: str = None, headers: dict = None) -> dict:
177 headers = super().get_headers(stream, api_key, headers)
180 def get_headers(cls, stream: bool, api_key: str | None = None, headers: dict[str, str] | None = None) -> dict[str, str]:
181 headers_result = super().get_headers(stream, api_key or "", headers or {})
178 182 # Add required Copilot headers
179 copilot_headers = {
183 copilot_headers: dict[str, str] = {
180 184 "Editor-Version": EDITOR_VERSION,
181 185 "Editor-Plugin-Version": EDITOR_PLUGIN_VERSION,
182 186 "Openai-Organization": "github-copilot",
183 187 "Copilot-Integration-Id": "vscode-chat",
184 188 "X-GitHub-Api-Version": "2024-12-15",
185 189 }
186 if headers:
187 copilot_headers.update(headers)
190 if headers_result:
191 copilot_headers.update(headers_result)
188 192 return copilot_headers
189 193
190 194 @classmethod
Modified g4f/Provider/needs_auth/Antigravity.py +71 -18
@@ -651,7 +651,57 @@ class AntigravityAuthManager(AuthFileMixin):
651 651 except Exception as e:
652 652 debug.log(f"Project discovery failed at {base_url}: {e}")
653 653 continue
654
654 # If discovery failed, attempt to onboard a managed project for the user.
655 # Read optional configuration from environment
656 attempts = int(os.environ.get("ANTIGRAVITY_ONBOARD_ATTEMPTS", "10"))
657 delay_seconds = float(os.environ.get("ANTIGRAVITY_ONBOARD_DELAY_S", "5"))
658 tier_id = os.environ.get("ANTIGRAVITY_TIER_ID", "free-tier")
659 # Use any preconfigured project id as metadata if available
660 configured_project = os.environ.get("ANTIGRAVITY_PROJECT_ID", "")
661
662 if tier_id:
663 onboard_request_body = {"tierId": tier_id, "metadata": {}}
664 if configured_project:
665 # include requested project id in metadata
666 onboard_request_body["metadata"]["cloudaicompanionProject"] = configured_project
667
668 # Try onboarding across endpoints with retries
669 for base_url in BASE_URLS:
670 for attempt in range(attempts):
671 try:
672 url = f"{base_url}:onboardUser"
673 onboard_headers = {
674 "Authorization": f"Bearer {access_token}",
675 "Content-Type": "application/json",
676 **ANTIGRAVITY_HEADERS,
677 }
678 async with session.post(url, headers=onboard_headers, json=onboard_request_body, timeout=timeout) as resp:
679 if not resp.ok:
680 print(f"Onboarding attempt {attempt+1} at {base_url} failed with status {resp.status}")
681 print(await resp.text())
682 # Stop attempts on this endpoint and try next base_url
683 break
684
685 payload = await resp.json()
686 # payload.response?.cloudaicompanionProject?.id
687 response_obj = payload.get("response") or {}
688 managed = response_obj.get("cloudaicompanionProject")
689 if isinstance(managed, dict):
690 managed_id = managed.get("id")
691 else:
692 managed_id = None
693
694 done = bool(payload.get("done", False))
695 if done and managed_id:
696 return managed_id
697 if done and configured_project:
698 return configured_project
699 except Exception as e:
700 debug.log(f"Failed to onboard managed project at {base_url}: {e}")
701 break
702
703 await asyncio.sleep(delay_seconds)
704
655 705 return ""
656 706
657 707 @classmethod
@@ -858,24 +908,18 @@ class AntigravityProvider:
858 908
859 909 # Fall back to API discovery
860 910 try:
861 load_response = await self.auth_manager.call_endpoint(
862 "loadCodeAssist",
863 {
864 "cloudaicompanionProject": "default-project",
865 "metadata": {"duetProject": "default-project"},
866 },
867 use_auth_headers=True,
868 )
869
870 # Handle both string and object formats for cloudaicompanionProject
871 project = load_response.get("cloudaicompanionProject")
872 if isinstance(project, dict):
873 project = project.get("id")
911 access_token = self.auth_manager.get_access_token()
912 if not access_token:
913 raise RuntimeError("No valid access token available for project discovery")
874 914
915 async with aiohttp.ClientSession() as session:
916 project = await self.auth_manager._fetch_project_id(
917 session=session,
918 access_token=access_token
919 )
875 920 if project:
876 921 self._project_id = project
877 922 return project
878
879 923 raise RuntimeError(
880 924 "Project ID discovery failed - set ANTIGRAVITY_PROJECT_ID in environment."
881 925 )
@@ -1143,6 +1187,17 @@ class AntigravityProvider:
1143 1187
1144 1188 async with ClientSession(headers=headers, timeout=timeout, connector=connector) as session:
1145 1189 async with session.post(url, json=req_body) as resp:
1190 if not resp.ok:
1191 if resp.status == 503:
1192 try:
1193 max_retry_delay = int(max([d.get("retryDelay", 0) for d in (await resp.json(content_type=None)).get("error", {}).get("details", [])]))
1194 except ValueError:
1195 max_retry_delay = 30 # Default retry delay if not specified
1196 debug.log(f"Received 503 error, retrying after {max_retry_delay}")
1197 await asyncio.sleep(max_retry_delay)
1198 resp = await session.post(url, json=req_body)
1199 if not resp.ok:
1200 debug.error(f"Retry after 503 failed with status {resp.status}")
1146 1201 if not resp.ok:
1147 1202 if resp.status == 401:
1148 1203 raise MissingAuthError("Unauthorized (401) from Antigravity API")
@@ -1221,14 +1276,13 @@ class Antigravity(AsyncGeneratorProvider, ProviderModelMixin):
1221 1276 login_url = "https://cloud.google.com/code-assist"
1222 1277 url = "https://antigravity.google"
1223 1278
1224 default_model = "gemini-3-pro-preview"
1279 default_model = "gemini-3-flash"
1225 1280 fallback_models = [
1226 1281 # Gemini 2.5 models
1227 1282 "gemini-2.5-pro",
1228 1283 "gemini-2.5-flash",
1229 1284 "gemini-2.5-flash-lite",
1230 1285 # Gemini 3 models
1231 "gemini-3-pro-preview",
1232 1286 "gemini-3-flash",
1233 1287 # Claude models (via Antigravity proxy)
1234 1288 "claude-sonnet-4.5",
@@ -1248,7 +1302,6 @@ class Antigravity(AsyncGeneratorProvider, ProviderModelMixin):
1248 1302 active_by_default = True
1249 1303
1250 1304 auth_manager: AntigravityAuthManager = None
1251 _dynamic_models: List[str] = None
1252 1305
1253 1306 @classmethod
1254 1307 def get_models(cls, **kwargs) -> List[str]:
Modified g4f/Provider/needs_auth/GeminiCLI.py +39 -3
@@ -9,6 +9,7 @@ import hashlib
9 9 import asyncio
10 10 import webbrowser
11 11 import threading
12 import platform
12 13 from pathlib import Path
13 14 from typing import Any, AsyncGenerator, Dict, List, Optional, Union, Tuple
14 15 from urllib.parse import urlencode, parse_qs, urlparse
@@ -22,6 +23,7 @@ from ...errors import MissingAuthError
22 23 from ...image.copy_images import save_response_media
23 24 from ...image import to_bytes, is_data_an_media
24 25 from ...providers.response import Usage, ImageResponse, ToolCalls, Reasoning
26 from ...providers.asyncio import get_running_loop
25 27 from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin
26 28 from ..helper import get_connector, get_system_prompt, format_media_prompt
27 29 from ... import debug
@@ -56,6 +58,24 @@ def encode_oauth_state(verifier: str) -> str:
56 58 return base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip('=')
57 59
58 60
61 def get_gemini_cli_user_agent(model: str = "gemini-2.5-pro") -> str:
62 """Generate Gemini CLI user-agent string with platform and architecture.
63
64 This user-agent is required to access CLI quota buckets instead of Antigravity buckets.
65 """
66 system_platform = platform.system().lower()
67 if system_platform == "darwin":
68 system_platform = "macos"
69
70 arch = platform.machine().lower()
71 if arch == "x86_64":
72 arch = "x64"
73 elif arch == "arm64" or arch == "aarch64":
74 arch = "arm64"
75
76 return f"GeminiCLI/1.0.0/{model} ({system_platform}; {arch})"
77
78
59 79 def decode_oauth_state(state: str) -> Dict[str, str]:
60 80 """Decode OAuth state parameter back to verifier."""
61 81 padded = state + '=' * (4 - len(state) % 4) if len(state) % 4 else state
@@ -369,11 +389,23 @@ class AuthManager(AuthFileMixin):
369 389 return self._access_token
370 390 return None
371 391
372 async def call_endpoint(self, method: str, body: Dict[str, Any], is_retry=False) -> Any:
392 async def call_endpoint(
393 self,
394 method: str,
395 body: Dict[str, Any],
396 is_retry=False,
397 user_agent: Optional[str] = None,
398 ) -> Any:
373 399 """
374 400 Call Google Code Assist API endpoint with JSON body.
375 401
376 402 Automatically retries once on 401 Unauthorized by refreshing auth.
403
404 Args:
405 method: API method name
406 body: Request body
407 is_retry: Whether this is a retry attempt
408 user_agent: Custom user-agent string (defaults to standard one)
377 409 """
378 410 if not self.get_access_token():
379 411 await self.initialize_auth()
@@ -383,6 +415,8 @@ class AuthManager(AuthFileMixin):
383 415 "Content-Type": "application/json",
384 416 "Authorization": f"Bearer {self.get_access_token()}",
385 417 }
418 if user_agent:
419 headers["User-Agent"] = user_agent
386 420
387 421 async with aiohttp.ClientSession() as session:
388 422 async with session.post(url, headers=headers, json=body) as resp:
@@ -390,7 +424,9 @@ class AuthManager(AuthFileMixin):
390 424 # Token likely expired, clear and retry once
391 425 await self.clear_token_cache()
392 426 await self.initialize_auth()
393 return await self.call_endpoint(method, body, is_retry=True)
427 return await self.call_endpoint(
428 method, body, is_retry=True, user_agent=user_agent
429 )
394 430 elif not resp.ok:
395 431 text = await resp.text()
396 432 raise RuntimeError(f"API call failed with status {resp.status}: {text}")
@@ -840,7 +876,7 @@ class GeminiCLI(AsyncGeneratorProvider, ProviderModelMixin):
840 876 needs_auth = True
841 877 active_by_default = True
842 878
843 auth_manager: AuthManager = None
879 auth_manager: Optional[AuthManager] = None
844 880
845 881 @classmethod
846 882 def get_models(cls, **kwargs):
Modified g4f/cli/client.py +9 -2
@@ -10,7 +10,7 @@ import requests
10 10
11 11 from pathlib import Path
12 12 from typing import Optional, List, Dict
13 from g4f.client import AsyncClient
13 from g4f.client import AsyncClient, ClientFactory
14 14 from g4f.providers.response import JsonConversation, MediaResponse, is_content
15 15 from g4f.cookies import set_cookies_dir, read_cookie_files
16 16 from g4f.Provider import ProviderUtils
@@ -253,7 +253,14 @@ async def run_args(input_val, args):
253 253 set_cookies_dir(str(args.cookies_dir))
254 254 read_cookie_files()
255 255
256 client = AsyncClient(provider=conv.provider)
256 client = ClientFactory.create_async_client(provider=conv.provider)
257
258 if input_val == "models":
259 models = client.models.get_all()
260 print("\nAvailable models:")
261 for m in models:
262 print(f"- {m}")
263 return
257 264
258 265 if isinstance(args.edit, Path):
259 266 file_to_edit = args.edit
Modified g4f/client/__init__.py +1 -1
@@ -929,7 +929,7 @@ class ClientFactory:
929 929 )
930 930 """
931 931 return AsyncClient(
932 provider=cls.create_provider(provider, base_url, api_key, **kwargs),
932 provider=cls.create_provider(None, provider, base_url, api_key, **kwargs),
933 933 media_provider=media_provider,
934 934 api_key=api_key,
935 935 base_url=base_url,