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

XFEstudio/gpt4free

feat: add new GPT-5 support and improve captcha handling

- **g4f/Provider/Copilot.py** - Added `"Smart (GPT-5)"` to `models` list. - Added `"gpt-5"` alias mapping to `"GPT-5"` in `model_aliases`. - Introduced `mode` selection logic to support `"smart"` mode for GPT-5 models alongside existing `"reasoning"` and `"chat"` modes. - **g4f/Provider/EasyChat.py** - Added `get_models` class method to map `-free` models to aliases and store them in `cls.models`. - Resolved model via `cls.get_model(model)` at start of `create_async_generator`. - Reset `cls.captchaToken` to `None` at the beginning of `callback`. - Wrapped main generator logic in a loop to allow retry once if `CLEAR-CAPTCHA-TOKEN` error occurs, clearing auth file and resetting args. - **g4f/Provider/needs_auth/OpenaiChat.py** - Added handling for image models: detect and set `image_model` flag, use `default_model` when sending requests if image model selected, and include `"picture_v2"` in `system_hints` when applicable. - Replaced textarea/button detection code in page load sequence with `nodriver` `select` calls, sending "Hello" before clicking send button, and included profile button selection if class needs auth. - **g4f/Provider/openai/models.py** - Changed `default_image_model` from `"dall-e-3"` to `"gpt-image"`. - Added `"gpt-5"` and `"gpt-5-thinking"` to `text_models` list. - Added alias mapping for `"dall-e-3"` pointing to new `default_image_model`.

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

代码差异

5 个文件 +75 -46
Modified etc/tool/commit.py +3 -0
@@ -100,6 +100,7 @@ from typing import Optional, Any, List
100 100
101 101 from g4f.client import Client
102 102 from g4f.models import ModelUtils
103 from g4f.cookies import read_cookie_files
103 104
104 105 from g4f import debug
105 106 debug.logging = True
@@ -295,6 +296,8 @@ def generate_commit_message(diff_text: str, model: str = DEFAULT_MODEL, max_retr
295 296 if not diff_text or diff_text.strip() == "":
296 297 return "No changes staged for commit"
297 298
299 read_cookie_files() # Load cookies for g4f client
300
298 301 # Filter sensitive data
299 302 filtered_diff = filter_sensitive_data(diff_text)
300 303
Modified g4f/Provider/Copilot.py +9 -2
@@ -46,11 +46,12 @@ class Copilot(AsyncAuthedProvider, ProviderModelMixin):
46 46 active_by_default = True
47 47
48 48 default_model = "Copilot"
49 models = [default_model, "Think Deeper"]
49 models = [default_model, "Think Deeper", "Smart (GPT-5)"]
50 50 model_aliases = {
51 51 "o1": "Think Deeper",
52 52 "gpt-4": default_model,
53 53 "gpt-4o": default_model,
54 "gpt-5": "GPT-5",
54 55 }
55 56
56 57 websocket_url = "wss://copilot.microsoft.com/c/api/chat?api-version=2"
@@ -172,6 +173,12 @@ class Copilot(AsyncAuthedProvider, ProviderModelMixin):
172 173 uploaded_images.append({"type":"image", "url": media})
173 174
174 175 wss = await session.ws_connect(cls.websocket_url, timeout=3)
176 if "Think" in model:
177 mode = "reasoning"
178 elif model.startswith("gpt-5") or "GPT-5" in model:
179 mode = "smart"
180 else:
181 mode = "chat"
175 182 await wss.send(json.dumps({
176 183 "event": "send",
177 184 "conversationId": conversation_id,
@@ -179,7 +186,7 @@ class Copilot(AsyncAuthedProvider, ProviderModelMixin):
179 186 "type": "text",
180 187 "text": prompt,
181 188 }],
182 "mode": "reasoning" if "Think" in model else "chat",
189 "mode": mode,
183 190 }).encode(), CurlWsFlag.TEXT)
184 191
185 192 done = False
Modified g4f/Provider/EasyChat.py +39 -25
@@ -29,6 +29,15 @@ class EasyChat(OpenaiTemplate, AuthFileMixin):
29 29
30 30 captchaToken: dict = None
31 31
32 @classmethod
33 def get_models(cls, **kwargs) -> list[str]:
34 if not cls.models:
35 models = super().get_models(**kwargs)
36 models = {m.replace("-free", ""): m for m in models if m.endswith("-free")}
37 cls.model_aliases.update(models)
38 cls.models = list(models)
39 return cls.models
40
32 41 @classmethod
33 42 async def create_async_generator(
34 43 cls,
@@ -38,6 +47,7 @@ class EasyChat(OpenaiTemplate, AuthFileMixin):
38 47 extra_body: dict = None,
39 48 **kwargs
40 49 ) -> AsyncResult:
50 model = cls.get_model(model)
41 51 args = None
42 52 auth_file = cls.get_cache_file()
43 53 if auth_file.exists():
@@ -47,6 +57,7 @@ class EasyChat(OpenaiTemplate, AuthFileMixin):
47 57 if cls.captchaToken:
48 58 debug.log("EasyChat: Using cached captchaToken.")
49 59 async def callback(page):
60 cls.captchaToken = None
50 61 def on_request(event: nodriver.cdp.network.RequestWillBeSent, page=None):
51 62 if event.request.url != cls.api_endpoint:
52 63 return
@@ -81,30 +92,33 @@ class EasyChat(OpenaiTemplate, AuthFileMixin):
81 92 if cls.captchaToken:
82 93 break
83 94 await asyncio.sleep(3)
84 if not args:
85 args = await get_args_from_nodriver(cls.url, proxy=proxy, callback=callback)
86 if extra_body is None:
87 extra_body = {}
88 extra_body.setdefault("captchaToken", cls.captchaToken)
89 try:
90 last_chunk = None
91 async for chunk in super().create_async_generator(
92 model=model,
93 messages=messages,
94 extra_body=extra_body,
95 **args
96 ):
97 # Remove provided by
98 if last_chunk == "\n" and chunk == "\n":
99 break
100 last_chunk = chunk
101 yield chunk
102 except Exception as e:
103 if "CLEAR-CAPTCHA-TOKEN" in str(e):
104 auth_file.unlink(missing_ok=True)
105 cls.captchaToken = None
106 debug.log("EasyChat: Captcha token cleared, please try again.")
107 raise e
95 for _ in range(2):
96 if not args:
97 args = await get_args_from_nodriver(cls.url, proxy=proxy, callback=callback)
98 if extra_body is None:
99 extra_body = {}
100 extra_body.setdefault("captchaToken", cls.captchaToken)
101 try:
102 last_chunk = None
103 async for chunk in super().create_async_generator(
104 model=model,
105 messages=messages,
106 extra_body=extra_body,
107 **args
108 ):
109 # Remove provided by
110 if last_chunk == "\n" and chunk == "\n":
111 break
112 last_chunk = chunk
113 yield chunk
114 except Exception as e:
115 if "CLEAR-CAPTCHA-TOKEN" in str(e):
116 debug.log("EasyChat: Captcha token expired, clearing auth file.")
117 auth_file.unlink(missing_ok=True)
118 args = None
119 continue
120 raise e
121 break
108 122 with auth_file.open("w") as f:
109 123 json.dump({**args, "captchaToken": cls.captchaToken}, f)
110
124
Modified g4f/Provider/needs_auth/OpenaiChat.py +21 -17
@@ -362,6 +362,10 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
362 362 model = cls.get_model(model)
363 363 except ModelNotFoundError:
364 364 pass
365 image_model = False
366 if model in cls.image_models:
367 image_model = True
368 model = cls.default_model
365 369 if conversation is None:
366 370 conversation = Conversation(None, str(uuid.uuid4()), getattr(auth_result, "cookies", {}).get("oai-did"))
367 371 else:
@@ -378,15 +382,17 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
378 382 if cls._api_key is not None:
379 383 data = {
380 384 "action": "next",
381 "fork_from_shared_post":False,
385 "fork_from_shared_post": False,
382 386 "parent_message_id": conversation.message_id,
383 387 "model": model,
384 "timezone_offset_min":-120,
385 "timezone":"Europe/Berlin",
386 "conversation_mode":{"kind":"primary_assistant"},
387 "system_hints":[],
388 "supports_buffering":True,
389 "supported_encodings":["v1"]
388 "timezone_offset_min": -120,
389 "timezone": "Europe/Berlin",
390 "conversation_mode": {"kind": "primary_assistant"},
391 "system_hints": [
392 "picture_v2"
393 ] if image_model else [],
394 "supports_buffering": True,
395 "supported_encodings": ["v1"]
390 396 }
391 397 async with session.post(
392 398 prepare_url,
@@ -835,16 +841,14 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
835 841 page.add_handler(nodriver.cdp.network.RequestWillBeSent, on_request)
836 842 await page.reload()
837 843 user_agent = await page.evaluate("window.navigator.userAgent", return_by_value=True)
838 textarea = None
839 while not textarea:
840 try:
841 textarea = await page.evaluate("document.getElementById('prompt-textarea')?.id")
842 except:
843 pass
844 await asyncio.sleep(1)
845 while not await page.evaluate("document.querySelector('[data-testid=\"send-button\"]')?.type"):
846 await asyncio.sleep(1)
847 await page.evaluate("document.querySelector('[data-testid=\"send-button\"]').click()")
844 if cls.needs_auth:
845 await page.select('[data-testid="accounts-profile-button"]', 300)
846 textarea = await page.select("#prompt-textarea", 300)
847 await textarea.send_keys("Hello")
848 await asyncio.sleep(1)
849 button = await page.select("[data-testid=\"send-button\"]")
850 if button:
851 await button.click()
848 852 while True:
849 853 body = await page.evaluate("JSON.stringify(window.__remixContext)", return_by_value=True)
850 854 if hasattr(body, "value"):
Modified g4f/Provider/openai/models.py +3 -2
@@ -1,11 +1,12 @@
1 1 default_model = "auto"
2 default_image_model = "dall-e-3"
2 default_image_model = "gpt-image"
3 3 image_models = [default_image_model]
4 text_models = [default_model, "gpt-4", "gpt-4.1", "gpt-4.1-mini", "gpt-4.5", "gpt-4o", "gpt-4o-mini", "o1", "o1-mini", "o3-mini", "o3-mini-high", "o4-mini", "o4-mini-high"]
4 text_models = [default_model, "gpt-5", "gpt-5-thinking", "gpt-4", "gpt-4.1", "gpt-4.1-mini", "gpt-4.5", "gpt-4o", "gpt-4o-mini", "o1", "o1-mini", "o3-mini", "o3-mini-high", "o4-mini", "o4-mini-high"]
5 5 vision_models = text_models
6 6 models = text_models + image_models
7 7 model_aliases = {
8 8 "gpt-4.1": "gpt-4-1",
9 9 "gpt-4.1-mini": "gpt-4-1-mini",
10 10 "gpt-4.5": "gpt-4-5",
11 "dall-e-3": default_image_model,
11 12 }