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

XFEstudio/gpt4free

Add new ChatGPT provider

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

代码差异

9 个文件 +625 -63
Added g4f/Provider/ChatGPT.py +306 -0
@@ -0,0 +1,306 @@
1 from __future__ import annotations
2
3 import html
4 import json
5 import re
6 import urllib.parse
7
8 from ..typing import AsyncResult, Messages
9 from ..requests import StreamSession
10 from ..requests.cdp import CDPSession
11 from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
12 from .helper import format_prompt
13 from ..providers.response import JsonConversation, FinishReason
14 from .. import debug
15
16
17 class Conversation(JsonConversation):
18 """Tracks the intercepted browser chat session.
19
20 ``message_id`` is the last assistant message; passing the conversation
21 back into the provider continues that chat instead of starting a new one.
22 """
23
24 def __init__(self, model: str):
25 self.model = model
26 self.conversation_id: str = None
27 self.message_id: str = None
28 self.user_message_count: int = 0
29
30
31 # The reply arrives as a DPU partial document with assistant stream blocks;
32 # prose lives in <p> tags, code in <pre>, headlines in <h1>-<h6>, quotes in
33 # <blockquote>, lists in <ul>/<ol> and writing documents in <section>; a
34 # gate rejection carries a failure status instead.
35 _RE_ASSISTANT_BLOCK = re.compile(
36 r'<(p|pre|h[1-6]|blockquote|ul|ol|section)\b([^>]*\bdata-assistant-stream-block(?:="")?[^>]*)>(.*?)</\1>',
37 re.DOTALL,
38 )
39 # Blocks nested inside sections carry no stream-block attributes.
40 _RE_INNER_BLOCK = re.compile(
41 r"<(h[1-6]|p|pre|ul|ol|blockquote)\b[^>]*>(.*?)</\1>",
42 re.DOTALL,
43 )
44 _RE_LIST_ITEM = re.compile(r"<li\b[^>]*>(.*?)</li>", re.DOTALL)
45 _RE_BLOCK_INDEX = re.compile(r'data-assistant-stream-block-index="(\d+)"')
46 _RE_FAILURE_STATUS = re.compile(r'data-failure-status="(\d+)"')
47 _RE_GATE_KIND = re.compile(r'data-gate-kind="(\w+)"')
48 _RE_XML_MARKER = re.compile(r"<\?[^>]*>")
49 _RE_CODE_LANGUAGE = re.compile(r'language-([\w+-]+)')
50
51
52 class ChatGPT(AsyncGeneratorProvider, ProviderModelMixin):
53 """ChatGPT anonymous guest chat driven entirely by a real browser.
54
55 Instead of simulating the anti-bot pipeline (proof-of-work, turnstile,
56 requirements tokens) in Python, this provider lets the real browser mint
57 every token naturally: it opens the guest page, triggers a chat with a
58 seed prompt, intercepts the browser's own "conversation/updates" request
59 via the CDP Fetch domain, aborts it, and replays it from Python with only
60 the "prompt" form field swapped for the real prompt. The reply is read
61 from the DPU partial document the endpoint returns.
62
63 No proof tokens, no turnstile VM, no requirements simulation — the
64 browser does all of that itself, so the request is byte-identical to a
65 genuine one except for the prompt text. A fresh browser request
66 replayed from Python passes the gate (verified), so no TLS/session
67 binding blocks the replay.
68
69 Long (pasted) prompts are supported: the prompt is swapped into the
70 form body directly (nothing is typed into the page) and the reply
71 timeout scales with the prompt length.
72 """
73
74 label = "ChatGPT"
75 url = "https://chatgpt.com"
76 working = True
77 active_by_default = True
78 needs_auth = False
79 supports_stream = True
80 supports_system_message = False
81 supports_message_history = False
82
83 default_model = "auto"
84 # The guest surface routes to ChatGPT's default model; it is advertised
85 # for the models it can serve so model/provider validation passes.
86 models = [default_model, "gpt-4o-mini", "gpt-4o", "gpt-4.1-mini", "gpt-5"]
87
88 updates_url_pattern = "*conversation/updates*"
89 seed_prompt = "Hello"
90
91 @classmethod
92 async def create_async_generator(
93 cls,
94 model: str,
95 messages: Messages,
96 proxy: str = None,
97 timeout: int = 180,
98 conversation: Conversation = None,
99 return_conversation: bool = True,
100 **kwargs,
101 ) -> AsyncResult:
102 model = cls.get_model(model)
103 prompt = format_prompt(messages)
104 if conversation is None:
105 conversation = Conversation(model)
106
107 async with CDPSession(proxy=proxy) as session:
108 # Pause the browser's own updates request before it leaves.
109 await session.call("Network.enable")
110 await session.call(
111 "Fetch.enable",
112 patterns=[{"urlPattern": cls.updates_url_pattern, "requestStage": "Request"}],
113 )
114 # The "#q=" fragment makes the guest UI auto-submit a chat; the
115 # explicit submit is a fallback for when it does not fire.
116 await session.navigate(f"{cls.url}/#q={cls.seed_prompt}")
117 paused = None
118 try:
119 paused = await session.wait_for_event("Fetch.requestPaused", timeout=30)
120 except TimeoutError:
121 try:
122 await session.insert_text_and_submit()
123 paused = await session.wait_for_event("Fetch.requestPaused", timeout=45)
124 except TimeoutError:
125 pass
126 if paused is None:
127 raise RuntimeError("ChatGPT: no updates request intercepted")
128
129 request = paused.get("request") or {}
130 post_data = request.get("postData") or ""
131 request_id = paused.get("requestId")
132 if not post_data:
133 await session.call("Fetch.failRequest", requestId=request_id, errorReason="Aborted")
134 raise RuntimeError("ChatGPT: intercepted request has no form body")
135
136 # Capture everything the browser was about to send: url, headers
137 # (HTTP/2 pseudo-headers are added by the client itself) and the
138 # cookies the request was authenticated with.
139 url = request["url"]
140 headers = {
141 key: value for key, value in (request.get("headers") or {}).items()
142 if not key.startswith(":")
143 }
144 cookies = await session.get_cookies([f"{cls.url}/"])
145
146 # Stop the browser's request: the tokens are single-use, so the
147 # replay below is the only consumer.
148 await session.call("Fetch.failRequest", requestId=request_id, errorReason="Aborted")
149
150 # Swap the seed prompt for the real one. Everything else —
151 # requirements token, proof token, turnstile token, cookies,
152 # headers — stays exactly as the browser minted it.
153 fields = urllib.parse.parse_qsl(post_data, keep_blank_values=True)
154 fields = [(key, prompt if key == "prompt" else value) for key, value in fields]
155 # Followup: point the form at the previous assistant message so the
156 # server appends to the existing conversation instead of a new one.
157 if conversation.message_id:
158 fields = [
159 (key, cls._continue_state(value, conversation) if key == "conversationState" else value)
160 for key, value in fields
161 ]
162 body = urllib.parse.urlencode(fields).encode()
163
164 # Long (pasted) prompts take proportionally longer to answer:
165 # scale the reply timeout with the prompt length.
166 reply_timeout = min(max(timeout, 60 + len(prompt) // 20), 1800)
167
168 # Replay the captured request from Python and read the DPU partial
169 # document from the response.
170 async with StreamSession(
171 impersonate="chrome", timeout=reply_timeout, proxy=proxy, cookies=cookies,
172 ) as stream_session:
173 async with stream_session.post(url, data=body, headers=headers) as response:
174 text = await response.text()
175
176 reply = cls._parse_dpu(text, conversation)
177 if reply is None:
178 raise RuntimeError("ChatGPT: no reply received (gate rejection)")
179 conversation.user_message_count += 1
180 yield reply
181 if return_conversation:
182 yield conversation
183 yield FinishReason("stop")
184
185 @staticmethod
186 def _continue_state(state: str, conversation: Conversation) -> str:
187 """Rewrite a conversationState form value to continue an existing chat.
188
189 Captured followup format (browser ground truth):
190 {"backendConversationId": "<id>", "messages": [],
191 "parentMessageId": "<last message id>", "userMessageCount": 1}
192 """
193 try:
194 state = json.loads(state)
195 except ValueError:
196 return state
197 if isinstance(state, dict):
198 state["backendConversationId"] = conversation.conversation_id
199 state["parentMessageId"] = conversation.message_id
200 state["userMessageCount"] = conversation.user_message_count
201 state.pop("safety", None)
202 return json.dumps(state)
203 return state
204
205 @classmethod
206 def _parse_dpu(cls, text: str, conversation: Conversation) -> str:
207 """Extract the assistant reply from the DPU partial document."""
208 failure = _RE_FAILURE_STATUS.search(text)
209 if failure is not None:
210 gate = _RE_GATE_KIND.search(text)
211 debug.log(
212 f"ChatGPT: gate rejected chat "
213 f"(status={failure.group(1)}, kind={gate.group(1) if gate else 'unknown'})"
214 )
215 return None
216 conversation_id = re.search(r'data-conversation-id="([\w-]+)"', text)
217 if conversation_id:
218 conversation.conversation_id = conversation_id.group(1)
219 # The reply DPU renders the newest message last; the followup form
220 # needs that message id as parentMessageId.
221 message_ids = re.findall(r'data-message-id="([\w-]+)"', text)
222 if message_ids:
223 conversation.message_id = message_ids[-1]
224 # Later blocks with the same index are streaming updates that
225 # supersede earlier (partial) ones — keep only the last per index.
226 blocks = {}
227 for match in _RE_ASSISTANT_BLOCK.finditer(text):
228 index_match = _RE_BLOCK_INDEX.search(match.group(2))
229 index = int(index_match.group(1)) if index_match else 0
230 blocks[index] = cls._convert_block(match.group(1), match.group(0), match.group(3))
231 if not blocks:
232 debug.log(f"ChatGPT: no assistant block in response: {text[:300]!r}")
233 return None
234 text = "\n".join(blocks[index] for index in sorted(blocks))
235 return html.unescape(text)
236
237 @staticmethod
238 def _convert_block(tag: str, full_tag: str, content: str) -> str:
239 """Convert one DPU block to markdown (code fences, headlines, quotes, lists)."""
240 content = _RE_XML_MARKER.sub("", content)
241 if tag == "section":
242 return ChatGPT._convert_section(content)
243 if tag == "pre":
244 # Code: strip syntax-highlight spans, keep newlines, add fences
245 # with the language from the inner <code class="language-…"> tag.
246 lang_match = _RE_CODE_LANGUAGE.search(full_tag)
247 lang = lang_match.group(1) if lang_match else ""
248 code = re.sub(r"<[^>]+>", "", content).strip()
249 return f"```{lang}\n{code}\n```"
250 if tag in ("ul", "ol"):
251 # Lists: each <li> becomes a markdown list entry.
252 items = []
253 for i, item in enumerate(_RE_LIST_ITEM.findall(content), 1):
254 item = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", "", item)).strip()
255 if item:
256 marker = f"{i}." if tag == "ol" else "-"
257 items.append(f"{marker} {item}")
258 return "\n".join(items)
259 # <br> is a line break, not markup to delete.
260 content = re.sub(r"<br\s*/?>", "\n", content)
261 text = re.sub(r"<[^>]+>", "", content).strip()
262 if tag.startswith("h"):
263 # Headlines: <h1>-<h6> map to markdown #-levels.
264 return f"{'#' * int(tag[1])} {text}"
265 if tag == "blockquote":
266 return "\n".join(f"> {line}" for line in text.splitlines())
267 return text
268
269 @staticmethod
270 def _convert_section(content: str) -> str:
271 """Convert a writing/document section to markdown.
272
273 The section chrome (header with title and edit/copy buttons,
274 metadata spans) is dropped; the document body is converted with
275 the same block rules as a top-level reply.
276 """
277 content = re.sub(r"<header\b.*?</header>", "", content, flags=re.DOTALL)
278 parts = []
279 pos = 0
280 for inner in _RE_INNER_BLOCK.finditer(content):
281 before = re.sub(r"<br\s*/?>", "\n", content[pos:inner.start()])
282 before = re.sub(r"[ \t]+", " ", re.sub(r"<[^>]+>", " ", before)).strip()
283 if before:
284 parts.append(before)
285 parts.append(ChatGPT._convert_block(inner.group(1), inner.group(0), inner.group(2)))
286 pos = inner.end()
287 tail = re.sub(r"<br\s*/?>", "\n", content[pos:])
288 tail = re.sub(r"[ \t]+", " ", re.sub(r"<[^>]+>", " ", tail)).strip()
289 if tail:
290 parts.append(tail)
291 return "\n\n".join(part for part in parts if part)
292
293
294 if __name__ == "__main__":
295 debug.logging = True
296 import asyncio
297
298 async def main():
299 async for chunk in ChatGPT.create_async_generator(
300 "auto", [{"role": "user", "content": "Guten Tag"}]
301 ):
302 if isinstance(chunk, (FinishReason, JsonConversation)):
303 continue
304 print(chunk)
305
306 asyncio.run(main())
Modified g4f/Provider/ChatGPTLightweight.py +236 -52
@@ -8,6 +8,7 @@ import random
8 8 import re
9 9 import time
10 10 import uuid
11 from datetime import datetime, timedelta, timezone
11 12
12 13 from ..typing import AsyncResult, Messages
13 14 from ..requests import StreamSession
@@ -16,7 +17,8 @@ from ..requests.raise_for_status import raise_for_status
16 17 from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
17 18 from .helper import format_prompt
18 19 from .openai.proofofwork import generate_proof_token
19 from .openai.new import get_requirements_token, get_config
20 from .openai.new import get_requirements_token
21 from .openai.har_file import RequestConfig
20 22 from .openai.turnstile_vm import process_turnstile_new
21 23 from ..providers.response import JsonConversation, FinishReason
22 24 from ..cookies import get_cookies
@@ -74,7 +76,7 @@ class ChatGPTLightweight(AsyncGeneratorProvider, ProviderModelMixin):
74 76
75 77 label = "ChatGPT (Lightweight)"
76 78 url = "https://chatgpt.com"
77 working = True
79 working = False
78 80 needs_auth = False
79 81 supports_stream = True
80 82 supports_system_message = True
@@ -92,18 +94,28 @@ class ChatGPTLightweight(AsyncGeneratorProvider, ProviderModelMixin):
92 94 _auth_state = None
93 95 _auth_state_loaded_at = 0.0
94 96 _AUTH_STATE_TTL = 600.0
95
96 # Static app-version headers worth copying from a captured session.
97 # Note: the worker-version headers ("cloudflare-workers-version-overrides",
98 # "x-web-mobile-document-worker-version") are deliberately NOT copied:
99 # they are validated against the signed
100 # "x-web-mobile-conversation-document-affinity" token, which is minted
101 # client-side per session and cannot be reused. Sending the version
102 # headers without a matching affinity fails with a hard 403 "Invalid
103 # conversation document affinity"; sending neither reaches the app gate.
97 # Document script srcs captured during the last CDP harvest. The
98 # turnstile VM probes them with regexes (op 11); without the real
99 # sentinel sdk.js URL the resolved token is short and the gate rejects
100 # the chat with 403.
101 _script_srcs: list = []
102
103 # Static fingerprint headers worth copying from a captured session.
104 # Session-bound headers are deliberately NOT copied:
105 # - "x-web-mobile-conversation-document-affinity" is signed client-side
106 # per session (its payload binds the worker version AND the
107 # oai-session-id) and cannot be reused; the worker-version headers
108 # ("x-web-mobile-document-worker-version",
109 # "cloudflare-workers-version-overrides") are validated against it.
110 # Replaying any of them fails with a hard 403 ("Invalid conversation
111 # document affinity" / gate rejection) — sending neither reaches the
112 # app gate.
113 # - "oai-session-id" must match the id sent in the form field, so a
114 # fresh one is generated per request instead of replaying a captured
115 # one.
104 116 _AUTH_HEADERS_WHITELIST = (
105 "x-web-mobile-document-renderer",
106 "x-web-mobile-connectivity-effective-type",
117 "x-web-mobile-conversation-renderer",
118 "x-web-mobile-prepare-state",
107 119 "sec-ch-ua",
108 120 "sec-ch-ua-arch",
109 121 "sec-ch-ua-bitness",
@@ -139,6 +151,75 @@ class ChatGPTLightweight(AsyncGeneratorProvider, ProviderModelMixin):
139 151 "time_since_loaded": random.randint(1, 10),
140 152 })
141 153
154 @classmethod
155 def _get_proof_config(cls, user_agent: str, kind: str = "proof") -> list:
156 """Build the sentinel config in the shape the guest surface sends.
157
158 Captured from a real guest session: the mweb surface uses the full
159 sentinel config (25 elements) extended by seven trailing zeros. The
160 browser mints the requirements token and the proof-of-work token
161 from two different script contexts, so the configs are NOT shared:
162 the requirements token carries the
163 "declarative-partial-updates-<hash>.js" script URL while the
164 proof-of-work token carries "assets/octane-home-client-<hash>.js"
165 with its own element values. Sharing one config between both tokens
166 gets the issued chat requirements token flagged and the updates
167 request gated with "Chat verification required".
168 """
169 now = datetime.now(timezone(timedelta(hours=2)))
170 parse_time = now.strftime("%a %b %d %Y %H:%M:%S") + \
171 " GMT+0200 (Mitteleuropäische Sommerzeit)"
172 if kind == "requirements":
173 # Context: the partial-updates page script that rebuilds the
174 # requirements token (captured). Prefer the fresh src from the
175 # harvest over the stale hardcoded fallback.
176 script_url = next(
177 (s for s in cls._script_srcs
178 if re.search(r"declarative-partial-updates-[0-9a-f]+\.js$", s)),
179 "https://chatgpt.com/unauth-mweb/scripts/declarative-partial-updates-1222007e7648.js",
180 )
181 pow_counter = 20
182 nav_entry = 207
183 feature_probe = "cookieEnabled−true"
184 early_intent = "__webMobileConversationAnnouncements"
185 event_probe = "onclick"
186 perf_now = random.randint(800, 3000)
187 else:
188 # Context: the octane home bundle that mints the proof token
189 # (captured).
190 script_url = next(
191 (s for s in cls._script_srcs
192 if re.search(r"octane-home-client-[0-9a-zA-Z]+\.js$", s)),
193 "https://chatgpt.com/unauth-mweb/assets/octane-home-client-DUBzS6ZD.js",
194 )
195 pow_counter = 0 # PoW counter, overwritten while solving
196 nav_entry = 9
197 feature_probe = "product−Gecko"
198 early_intent = "__octaneEarlyHydrationIntents"
199 event_probe = "onbeforematch"
200 perf_now = random.uniform(400, 2500)
201 return [
202 2500,
203 parse_time,
204 4395630592,
205 pow_counter,
206 user_agent,
207 script_url,
208 RequestConfig.data_build,
209 "de-DE",
210 "en-US,en",
211 nav_entry,
212 feature_probe,
213 early_intent,
214 event_probe,
215 perf_now,
216 str(uuid.uuid4()),
217 "model",
218 8,
219 time.time() * 1000,
220 0, 0, 0, 0, 0, 0, 0,
221 ]
222
142 223 @classmethod
143 224 async def create_async_generator(
144 225 cls,
@@ -162,8 +243,6 @@ class ChatGPTLightweight(AsyncGeneratorProvider, ProviderModelMixin):
162 243 # flagged, so reusing it would poison every retry.
163 244 if attempt > 0:
164 245 conversation.oai_did = str(uuid.uuid4())
165 if attempt >= 3:
166 cls._auth_state = None
167 246 reply = await cls._fetch_reply(prompt=prompt, conversation=conversation, proxy=proxy, timeout=timeout)
168 247 if reply is not None:
169 248 yield reply
@@ -237,7 +316,15 @@ class ChatGPTLightweight(AsyncGeneratorProvider, ProviderModelMixin):
237 316 cookies.setdefault(cookie["name"], cookie["value"])
238 317 if "x-web-mobile-conversation-document-affinity" in entry_headers:
239 318 for name, value in entry_headers.items():
240 if name not in ("cookie", "content-length"):
319 # Session-bound headers must not be replayed: the
320 # affinity token and the worker-version headers are
321 # validated against each other and expire per session
322 # (replaying them fails with 403 "Invalid conversation
323 # document affinity"). Only stable fingerprint headers
324 # from the whitelist are safe to copy.
325 if name in cls._AUTH_HEADERS_WHITELIST or name in (
326 "user-agent", "accept-language",
327 ):
241 328 headers.setdefault(name, value)
242 329 if cookies:
243 330 debug.log(
@@ -258,25 +345,41 @@ class ChatGPTLightweight(AsyncGeneratorProvider, ProviderModelMixin):
258 345 match the fingerprint the cookies were issued for.
259 346 """
260 347 async with CDPSession(proxy=proxy, headless=False) as session:
261 try:
262 await session.navigate(f"{cls.url}/?q=Hello")
263 except Exception as e:
264 # A load-event race must not discard an otherwise good session.
265 debug.log(f"ChatGPTLightweight: CDP navigate: {e}")
266 # Wait for a pending Cloudflare challenge to resolve.
267 for _ in range(30):
268 title = await session.evaluate_js("document.title") or ""
269 if title and "Just a moment" not in title and "Attention Required" not in title:
270 break
271 await asyncio.sleep(1)
348 await session.navigate(f"{cls.url}/#q=Hello")
349 debug.log("ChatGPTLightweight: navigated to chat page")
350 await session.bypass_turnstile()
351 debug.log("ChatGPTLightweight: bypassing turnstile")
352 await session.insert_text_and_submit()
272 353 debug.log("ChatGPTLightweight: waiting for network idle")
273 354 await session.wait_for_network_idle()
274 355 debug.log("ChatGPTLightweight: network idle reached")
356 # The "?q=" parameter makes the guest UI auto-submit a chat. Watch
357 # the browser's own turn: a rendered reply proves this IP and
358 # fingerprint pass the gate, a failure marker means they are
359 # flagged. A reload then gives Cloudflare a second chance to
360 # serve a challenge and mint a "cf_clearance" cookie.
361 outcome = None
362 for _ in range(20):
363 await asyncio.sleep(1)
364 outcome = await session.evaluate_js(
365 "(() => { const el = document.querySelector("
366 "'[data-failure-status],[data-assistant-stream-block]');"
367 " return el ? (el.getAttribute('data-failure-status') || 'reply') : ''; })()"
368 )
369 if outcome:
370 break
371 if outcome and outcome != "reply":
372 debug.log(f"ChatGPTLightweight: browser chat rejected (status={outcome})")
373 try:
374 await session.navigate(f"{cls.url}/?q=Hello")
375 await session.wait_for_network_idle()
376 except Exception as e:
377 debug.log(f"ChatGPTLightweight: CDP reload: {e}")
275 378 cookies = await session.get_cookies([f"{cls.url}/"])
276 379 if not cookies.get("cf_clearance"):
277 # The clearance cookie is minted once the challenge resolves;
380 # The clearance cookie is minted once a challenge resolves;
278 381 # give it a moment to show up.
279 for _ in range(10):
382 for _ in range(15):
280 383 await asyncio.sleep(1)
281 384 cookies = await session.get_cookies([f"{cls.url}/"])
282 385 if cookies.get("cf_clearance"):
@@ -288,7 +391,7 @@ class ChatGPTLightweight(AsyncGeneratorProvider, ProviderModelMixin):
288 391 headers = {}
289 392 for params in session.network_requests:
290 393 request = params.get("request", {})
291 if "chatgpt.com" not in request.get("url", ""):
394 if "https://chatgpt.com/unauth-mweb/conversation/" not in request.get("url", ""):
292 395 continue
293 396 sent = {
294 397 name.lower(): value
@@ -304,10 +407,49 @@ class ChatGPTLightweight(AsyncGeneratorProvider, ProviderModelMixin):
304 407 cls.user_agent = sent["user-agent"]
305 408 if "accept-language" in sent:
306 409 headers.setdefault("accept-language", sent["accept-language"])
410 # Report how the browser's own auto-submitted chat fared: its
411 # response status is the ground truth for whether this IP and
412 # fingerprint pass the app gate at all.
413 for params in session.network_responses:
414 response = params.get("response", {})
415 url = params.get("request", {}).get("url", "") or response.get("url", "")
416 if "unauth-mweb/conversation/updates" in url:
417 debug.log(
418 f"ChatGPTLightweight: browser chat status {response.get('status')}"
419 f" ({response.get('mimeType', '').split(';')[0]})"
420 )
421 break
422 # Dump the browser's successful updates request (headers + form)
423 # so the replayed request can be aligned with it field by field.
424 for params in session.network_requests:
425 request = params.get("request", {})
426 if "unauth-mweb/conversation/updates" not in request.get("url", ""):
427 continue
428 sent_headers = {
429 name.lower(): value
430 for name, value in request.get("headers", {}).items()
431 }
432 debug.log(
433 "ChatGPTLightweight: browser request headers: "
434 + json.dumps(sorted(sent_headers))
435 )
436 break
437 # Capture the document script srcs: the turnstile challenge
438 # probes them with regexes (e.g. the sentinel sdk.js URL) and
439 # folds the matches into the token.
440 try:
441 srcs_json = await session.evaluate_js(
442 "JSON.stringify([...document.scripts].map(s => s.src).filter(Boolean))"
443 )
444 srcs = json.loads(srcs_json) if srcs_json else []
445 if srcs:
446 cls._script_srcs = srcs
447 except Exception as e:
448 debug.log(f"ChatGPTLightweight: script src capture failed: {e}")
307 449 debug.log(
308 450 f"ChatGPTLightweight: CDP harvest: {len(cookies)} cookies"
309 451 f" (cf_clearance={'yes' if cookies.get('cf_clearance') else 'no'}),"
310 f" {len(headers)} headers"
452 f" {len(headers)} headers, {len(cls._script_srcs)} script srcs"
311 453 )
312 454 return cookies, headers
313 455
@@ -319,28 +461,33 @@ class ChatGPTLightweight(AsyncGeneratorProvider, ProviderModelMixin):
319 461 proxy: str = None,
320 462 timeout: int = 120,
321 463 ) -> str:
322 # if cls._auth_state is None:
464 if cls._auth_state is None:
323 465 # Harvest fresh cookies and headers from a real browser before
324 466 # falling back to cached HAR captures: a cf_clearance minted for
325 467 # the current IP passes the gate far more reliably.
326 # try:
327 # cls._auth_state = await cls._harvest_via_cdp(proxy=proxy)
328 # cls._auth_state_loaded_at = time.time()
329 # except Exception as e:
330 # debug.log(f"ChatGPTLightweight: CDP harvest failed: {e}")
468 try:
469 cls._auth_state = await cls._harvest_via_cdp(proxy=proxy)
470 cls._auth_state_loaded_at = time.time()
471 except Exception as e:
472 debug.log(f"ChatGPTLightweight: CDP harvest failed: {e}")
331 473 auth_cookies, auth_headers = cls._load_auth_state()
332 474 # Reuse the captured visitor id when available so the session stays
333 475 # consistent with the cf_clearance cookie it was issued with.
334 476 oai_did = conversation.oai_did = auth_cookies.get("oai-did") or str(uuid.uuid4())
335 477 session_id = str(uuid.uuid4())
478 # The guest UI does not send an "oai-did" header on the mweb calls
479 # (captured); the device id travels in the cookie and request bodies.
336 480 headers = {
337 481 **DEFAULT_HEADERS,
338 "oai-did": oai_did,
339 482 "oai-session-id": session_id,
340 483 **auth_headers,
341 484 }
342 485 cookies = {**auth_cookies, "oai-did": oai_did}
343 config = get_config(cls.user_agent)
486 # The browser mints the requirements token and the proof-of-work
487 # token from two different script contexts, so each token gets its
488 # own config (captured); sharing one gets the chat token flagged.
489 config = cls._get_proof_config(cls.user_agent, kind="requirements")
490 proof_config = cls._get_proof_config(cls.user_agent, kind="proof")
344 491 requirements_token = get_requirements_token(config)
345 492
346 493 async with StreamSession(
@@ -349,6 +496,9 @@ class ChatGPTLightweight(AsyncGeneratorProvider, ProviderModelMixin):
349 496 ) as session:
350 497 json_headers = {
351 498 **headers,
499 # No "oai-did" header here: the guest UI does not send one on
500 # the mweb calls (captured); the device id travels in the
501 # cookie and request bodies only.
352 502 "accept": "application/json",
353 503 "content-type": "application/json",
354 504 }
@@ -373,7 +523,8 @@ class ChatGPTLightweight(AsyncGeneratorProvider, ProviderModelMixin):
373 523
374 524 # 3. Solve the hashcash challenge
375 525 proof_token = generate_proof_token(
376 True, pow_config.get("seed", ""), pow_config.get("difficulty", ""), cls.user_agent
526 True, pow_config.get("seed", ""), pow_config.get("difficulty", ""),
527 cls.user_agent, proof_token=proof_config
377 528 )
378 529
379 530 # 3b. Solve the invisible turnstile challenge. The "dx" payload is
@@ -384,19 +535,35 @@ class ChatGPTLightweight(AsyncGeneratorProvider, ProviderModelMixin):
384 535 turnstile_token = ""
385 536 if turnstile_config.get("required"):
386 537 turnstile_token = process_turnstile_new(
387 turnstile_config.get("dx", ""), requirements_token, cls.user_agent
538 turnstile_config.get("dx", ""), requirements_token, cls.user_agent,
539 script_srcs=cls._script_srcs,
388 540 )
389 541 debug.log(f"ChatGPTLightweight: turnstile token len {len(turnstile_token)}")
390 542
391 # 4. Finalize: exchange prepare token + proof for a chat requirements token
543 # 4. Finalize: exchange prepare token + proof for a chat requirements
544 # token. The turnstile token MUST be included here: the server
545 # binds it to the issued requirements token (captured finalize
546 # body: {"prepare_token", "proofofwork", "turnstile"}). Without
547 # it the updates request is rejected with 403 "Chat verification
548 # required" even though the token itself is valid.
549 finalize_body = {"prepare_token": prepare_token, "proofofwork": proof_token}
550 if turnstile_token:
551 finalize_body["turnstile"] = turnstile_token
392 552 async with session.post(
393 553 cls.requirements_finalize_url,
394 json={"prepare_token": prepare_token, "proofofwork": proof_token},
554 json=finalize_body,
395 555 headers=json_headers,
396 556 ) as response:
397 557 await raise_for_status(response)
398 558 chat_requirements_token = (await response.json())["token"]
399 559
560 # The session observer token is minted by the sentinel script in
561 # the browser and bound to the requirements token (captured: a
562 # ~640 char blob). Without a browser we cannot compute one; the
563 # gate accepts an empty value (the browser sends it only when a
564 # sentinel observer ran).
565 session_observer_token = ""
566
400 567 client_context = cls.get_client_context()
401 568 retry_owner = json.dumps({"mode": "anonymous", "sessionEpoch": None})
402 569 form_headers = dict(headers)
@@ -413,7 +580,7 @@ class ChatGPTLightweight(AsyncGeneratorProvider, ProviderModelMixin):
413 580 }),
414 581 "clientContextualInfo": client_context,
415 582 "timezone": "Europe/Berlin",
416 "timezoneOffsetMinutes": "-120",
583 "timezoneOffsetMinutes": -120,
417 584 },
418 585 headers=form_headers,
419 586 ) as response:
@@ -423,12 +590,15 @@ class ChatGPTLightweight(AsyncGeneratorProvider, ProviderModelMixin):
423 590
424 591 # 6. Send the message and read the DPU partial document
425 592 operation_id = str(uuid.uuid4())
593 # Captured sessions use two distinct uuids here: the operation id
594 # in the URL and a separate turn trace id in the headers.
595 trace_id = str(uuid.uuid4())
426 596 form = {
427 597 "conversationState": json.dumps({
428 598 "messages": [],
429 599 "parentMessageId": "client-created-root",
430 600 "safety": {"dismissedInterventionIds": []},
431 "userMessageCount": 1,
601 "userMessageCount": 0,
432 602 }),
433 603 "messageMetadata": "{}",
434 604 "oai-session-id": session_id,
@@ -438,15 +608,23 @@ class ChatGPTLightweight(AsyncGeneratorProvider, ProviderModelMixin):
438 608 "chatRequirementsToken": chat_requirements_token,
439 609 "proofToken": proof_token,
440 610 "turnstileToken": turnstile_token,
611 # Captured: the browser sends an EMPTY telemetry token.
441 612 "telemetryToken": "",
442 # Real browsers send measured turn timings; "[1,null]" is a
443 # bot signal that feeds the "Chat verification required" gate.
444 "timingToken": "[1,%.1f,70,0,21,2,0,88]" % random.uniform(40.0, 150.0),
613 # The real guest UI sends a constant "[1,null]" here (captured),
614 # so a fabricated timing array stands out more than it helps.
615 "timingToken": "[1,null]",
616 # Captured: set to "1" when the chat was started from the
617 # instant-query URL parameter.
618 "__web_mobile_instant_query": "1",
445 619 "clientContextualInfo": client_context,
446 620 "imageSaveData": "off",
447 621 "imageEffectiveType": "4g",
448 622 "timezone": "Europe/Berlin",
449 "timezoneOffsetMinutes": "-120",
623 "timezoneOffsetMinutes": -120,
624 # Captured: the prepare token from step 1 is echoed in the
625 # form alongside the finalized requirements token.
626 "chatRequirementsPrepareToken": prepare_token,
627 "sessionObserverToken": session_observer_token,
450 628 "conversationRetryOwner": retry_owner,
451 629 "assistantMessageId": f"pending-{str(uuid.uuid4())}",
452 630 "userMessageId": str(uuid.uuid4()),
@@ -455,7 +633,7 @@ class ChatGPTLightweight(AsyncGeneratorProvider, ProviderModelMixin):
455 633 **form_headers,
456 634 "accept": "text/vnd.openai.web-mobile-partial+html",
457 635 "x-conduit-token": conduit_token,
458 "x-oai-turn-trace-id": operation_id,
636 "x-oai-turn-trace-id": trace_id,
459 637 "x-web-mobile-conversation-renderer": "octane",
460 638 "x-web-mobile-conversation-stream-protocol": "1",
461 639 "x-web-mobile-prepare-state": "success",
@@ -508,7 +686,13 @@ if __name__ == "__main__":
508 686 import asyncio
509 687
510 688 async def main():
511 response = await ChatGPTLightweight._fetch_reply("Hello", Conversation("auto"))
512 print(response)
689 # Exercise the full retry path (fresh sessions + re-harvests), not
690 # just a single _fetch_reply attempt.
691 async for chunk in ChatGPTLightweight.create_async_generator(
692 "auto", [{"role": "user", "content": "Guten Tag"}]
693 ):
694 if isinstance(chunk, (FinishReason, JsonConversation)):
695 continue
696 print(chunk)
513 697
514 698 asyncio.run(main())
Modified g4f/Provider/__init__.py +5 -0
@@ -90,6 +90,7 @@ class ProviderLoader:
90 90 "OpenaiAccount",
91 91 "OpenaiChat",
92 92 "ChatGPTLightweight",
93 "ChatGPT",
93 94 "OpenaiTemplate",
94 95 "OperaAria",
95 96 "Perplexity",
@@ -441,6 +442,10 @@ class ProviderLoader:
441 442 from g4f.Provider.ChatGPTLightweight import ChatGPTLightweight
442 443
443 444 return ChatGPTLightweight
445 elif name == "ChatGPT":
446 from g4f.Provider.ChatGPT import ChatGPT
447
448 return ChatGPT
444 449 elif name == "OpenaiTemplate":
445 450 from g4f.Provider.template.OpenaiTemplate import OpenaiTemplate
446 451
Modified g4f/Provider/openai/har_file.py +1 -1
@@ -35,7 +35,7 @@ class RequestConfig:
35 35 turnstile_token: str = None
36 36 arkose_request: arkReq = None
37 37 arkose_token: str = None
38 data_build: str = "prod-db8e51e8414e068257091cf5003a62d3d4ee6ed0"
38 data_build: str = "prod-329d9af90bc80a50b17d4b6f95c261f7c70f5a9b"
39 39
40 40
41 41 class arkReq:
Modified g4f/Provider/openai/turnstile_vm.py +69 -3
@@ -195,13 +195,71 @@ class TurnstileVM:
195 195 def now() -> float:
196 196 return (time.time() - vm.start) * 1000.0 + random.random()
197 197
198 class Element:
199 """Minimal DOM element: the sentinel program measures font
200 metrics of a hidden probe div (getBoundingClientRect)."""
201
202 def __init__(self, tag: str = "div"):
203 self.tag = tag
204 self.style: dict = {}
205 self._inner_text = ""
206 self._rect = (0.0, 0.0, 0.0, 0.0)
207
208 def setAttribute(self, name: str, value) -> None:
209 pass
210
211 def appendChild(self, child) -> None:
212 pass
213
214 def removeChild(self, child) -> None:
215 pass
216
217 def getBoundingClientRect(self) -> dict:
218 # Deterministic Arial 12px metrics for the probe glyph
219 # (captured from a real desktop Chrome: 24.6875 x 18).
220 # Combining marks (U+0300-U+036F etc.) are zero-width, so a
221 # naive len() estimate would overstate the width ~3.5x.
222 width, height = self.style.get("_rect", (24.6875, 18.0))
223 return {"width": width, "height": height, "x": 0.0, "y": 0.0,
224 "top": 0.0, "left": 0.0, "right": width, "bottom": height}
225
226 @property
227 def innerText(self) -> str:
228 return self._inner_text
229
230 @innerText.setter
231 def innerText(self, value: str) -> None:
232 # Keep the captured default rect: Chrome's shaping of the
233 # probe glyph (base chars + combining marks) cannot be
234 # reproduced by per-glyph estimation, and the sentinel
235 # program always measures the same fixed string.
236 self._inner_text = value
237
238 # The sentinel VM runs inside the frame.html iframe (captured:
239 # https://chatgpt.com/backend-api/sentinel/frame.html?sv=<version>),
240 # so document.location must be the frame URL, not the host page.
241 document = {
242 "location": "https://chatgpt.com/backend-api/sentinel/frame.html?sv=20260810913b",
243 "visibilityState": "visible",
244 "body": {
245 "appendChild": lambda child: None,
246 "removeChild": lambda child: None,
247 },
248 "createElement": lambda tag="div": Element(tag),
249 }
250
198 251 return {
199 "document": {"location": "https://chatgpt.com/", "visibilityState": "visible"},
252 "document": document,
200 253 "navigator": {
201 254 "userAgent": user_agent,
202 255 "language": "en-US",
203 256 "languages": ["en-US"],
257 "vendor": "Google Inc.",
258 "platform": "Linux x86_64",
259 "deviceMemory": 16,
260 "maxTouchPoints": 0,
204 261 "hardwareConcurrency": 8,
262 "cookieEnabled": True,
205 263 },
206 264 "localStorage": {
207 265 "STATSIG_LOCAL_STORAGE_INTERNAL_STORE_V4": "{}",
@@ -211,12 +269,20 @@ class TurnstileVM:
211 269 "oai-did": "",
212 270 "STATSIG_LOCAL_STORAGE_LOGGING_REQUEST": "",
213 271 "UiState.isNavigationCollapsed.1": "",
272 "setItem": lambda k, v: None,
273 },
274 # Desktop Chrome values (captured); the mobile 412x915 shape
275 # contradicted the desktop Linux user agent.
276 "screen": {
277 "width": 1600, "height": 900,
278 "availWidth": 1600, "availHeight": 900,
279 "availLeft": 0, "availTop": 0,
280 "colorDepth": 24, "pixelDepth": 24,
214 281 },
215 "screen": {"width": 412, "height": 915, "availWidth": 412, "availHeight": 915},
216 282 "history": {"length": 2},
217 283 "performance": Performance,
218 284 "Math": {"random": lambda: random.random()},
219 "Object": {"create": lambda _proto=None: {}},
285 "Object": {"create": lambda _proto=None: {}, "keys": lambda obj: list(obj.keys()) if isinstance(obj, dict) else []},
220 286 "Reflect": {"set": lambda obj, k, v: obj.__setitem__(k, v) if isinstance(obj, dict) else None},
221 287 }
222 288
Modified g4f/api/__init__.py +1 -1
@@ -2685,7 +2685,7 @@ def run_api(
2685 2685 "backlog": 2048,
2686 2686 # Avoid hanging forever on shutdown when a long-running request (e.g.
2687 2687 # a browser-based provider login) is still in-flight.
2688 "timeout_graceful_shutdown": 10,
2688 "timeout_graceful_shutdown": 600,
2689 2689 }
2690 2690 uvicorn_options.update(filter_none(**kwargs))
2691 2691
Modified g4f/cli/__init__.py +2 -1
@@ -127,6 +127,7 @@ def get_api_parser(exit_on_error: bool = True) -> ArgumentParser:
127 127 )
128 128
129 129 api_parser.add_argument("--reload", action="store_true", help="Enable hot reload.")
130 api_parser.add_argument("--no-reload", action="store_true", help="Disable hot reload.")
130 131 api_parser.add_argument("--demo", action="store_true", help="Enable demo mode.")
131 132
132 133 api_parser.add_argument(
@@ -279,7 +280,7 @@ def run_api_args(args):
279 280 debug=args.debug,
280 281 workers=args.workers,
281 282 use_colors=not args.disable_colors,
282 reload=args.reload,
283 reload=args.reload and not args.no_reload,
283 284 ssl_keyfile=args.ssl_keyfile,
284 285 ssl_certfile=args.ssl_certfile,
285 286 log_config=args.log_config,
Modified g4f/requests/aiohttp.py +4 -4
@@ -75,7 +75,7 @@ class StreamSession:
75 75 def __init__(
76 76 self,
77 77 headers=None,
78 timeout: int = None,
78 timeout: int = 0,
79 79 connector: BaseConnector = None,
80 80 proxy: str = None,
81 81 proxies=None,
@@ -91,11 +91,11 @@ class StreamSession:
91 91 headers = {**DEFAULT_HEADERS, **headers}
92 92 if not has_brotli and "br" in headers.get("accept-encoding", ""):
93 93 headers["accept-encoding"] = "gzip, deflate"
94 connect = None
95 94 if isinstance(timeout, tuple):
96 connect, timeout = timeout
97 if timeout is not None:
95 timeout, connect = timeout
98 96 timeout = ClientTimeout(timeout, connect)
97 elif timeout is not None:
98 timeout = ClientTimeout(timeout)
99 99 if proxy is None:
100 100 proxy = proxies.get("all", proxies.get("https"))
101 101
Modified g4f/requests/cdp.py +1 -1
@@ -1393,7 +1393,7 @@ const sendButton = document.querySelector(sendButtonSelectors.join(', '));
1393 1393 if (sendButton) {
1394 1394 setTimeout(() => {
1395 1395 sendButton.click();
1396 }, 1000);
1396 }, 2000);
1397 1397 }
1398 1398
1399 1399 // Click the send button on gemini.google.com