返回提交历史
Modified
g4f/Provider/needs_auth/DeepSeek.py
+109
-58
Modified
g4f/Provider/search/GoogleAiMode.py
+3
-0
Modified
g4f/Provider/search/GoogleSearch.py
+16
-17
Modified
g4f/api/__init__.py
+1
-0
Modified
g4f/providers/response.py
+1
-1
Modified
g4f/requests/cdp.py
+12
-34
XFEstudio/gpt4free
Update DeepSeek provider
e363d644
代码差异
6 个文件
+142
-110
@@ -2,26 +2,27 @@ from __future__ import annotations
2
2
3
3
import asyncio
4
4
import mimetypes
5
import os
6
import time
5
7
from datetime import datetime
6
8
from typing import Any, Optional, Literal
7
9
8
10
from g4f import debug
9
from g4f.cookies import get_cookies, get_cookies_async, get_headers
10
11
from g4f.errors import MissingAuthError, ResponseError
11
12
from g4f.image import to_bytes, detect_file_type
12
from g4f.providers.base_provider import AsyncGeneratorProvider, ProviderModelMixin
13
from g4f.providers.base_provider import AsyncAuthedProvider, ProviderModelMixin
13
14
from g4f.providers.helper import get_last_user_message
14
15
from g4f.providers.response import (
16
AuthResult,
15
17
FinishReason,
16
18
JsonConversation,
17
19
JsonRequest,
20
RequestLogin,
18
21
)
19
from g4f.requests import StreamSession, raise_for_status, FormData
20
from g4f.typing import AsyncResult, Messages, Cookies
22
from g4f.requests import StreamSession, raise_for_status, FormData, DEFAULT_HEADERS
23
from g4f.typing import AsyncResult, Messages
21
24
from .deepseek.pow import (
22
25
DEEPSEEK_POW_ALGORITHM,
23
WASM_PATH,
24
DeepSeekHash,
25
26
DeepSeekPOW,
26
27
has_wasmtime_and_numpy,
27
28
)
@@ -243,16 +244,19 @@ def _build_completion_payload(
243
244
}
244
245
245
246
246
class DeepSeek(AsyncGeneratorProvider, ProviderModelMixin):
247
class DeepSeek(AsyncAuthedProvider, ProviderModelMixin):
247
248
"""
248
DeepSeek provider using browser emulation with HAR file support.
249
DeepSeek provider using browser emulation with CDP-based authentication.
249
250
250
This provider extends DeepSeek implementation with HAR file support
251
for easier authentication management. It uses curl_cffi's Chrome impersonation
252
for realistic browser-like requests.
251
Authentication is handled by ``on_auth_async``: a CDPSession opens
252
chat.deepseek.com, waits for the user to log in and captures both the
253
session cookies and the ``authorization`` header the web app sends with
254
its API requests. The result is persisted by ``AsyncAuthedProvider`` and
255
replayed to ``create_authed`` until it becomes invalid.
256
257
It uses curl_cffi's Chrome impersonation for realistic browser-like requests.
253
258
"""
254
259
255
label = "DeepSeek (HAR Auth)"
256
260
url = DEEPSEEK_URL
257
261
cookie_domain = DEEPSEEK_DOMAIN
258
262
working = has_wasmtime_and_numpy
@@ -260,19 +264,82 @@ class DeepSeek(AsyncGeneratorProvider, ProviderModelMixin):
260
264
needs_auth = True
261
265
supports_file_upload = True
262
266
263
default_model = "deepseek-v3"
264
models = ["deepseek-v3", "deepseek-r1"]
265
model_aliases = {"deepseek-chat": "deepseek-v3"}
267
default_model = "deepseek-chat"
268
models = ["deepseek-chat", "deepseek-r1"]
269
model_aliases = {"deepseek-v3": "deepseek-chat"}
270
271
@classmethod
272
async def on_auth_async(cls, proxy: str = None, **kwargs) -> AsyncResult:
273
"""
274
Authenticate with a CDP-driven browser session.
275
276
Opens chat.deepseek.com, waits for the user to log in and captures
277
the session cookies plus the ``authorization`` header from outgoing
278
API requests (with a localStorage fallback for the bearer token).
279
"""
280
from ...requests.cdp import CDPSession
281
282
auth_result = AuthResult(
283
headers=dict(DEFAULT_HEADERS), cookies={}, impersonate="chrome"
284
)
285
auth_result.headers["referer"] = f"{cls.url}/a/chat/"
286
authorization = None
287
288
debug.log("DeepSeekAuth: Starting CDPSession for login...")
289
session = CDPSession(proxy=proxy)
290
await session.start()
291
try:
292
yield RequestLogin(cls.__name__, os.environ.get("G4F_LOGIN_URL") or cls.url)
293
# Watch outgoing requests to capture the live authorization header
294
request_queue = asyncio.Queue()
295
session.add_event_handler("Network.requestWillBeSent", request_queue)
296
await session.navigate(cls.url)
297
298
# Wait for the login token (allows the user to log in manually)
299
deadline = time.time() + 300
300
while time.time() < deadline:
301
debug.log("DeepSeek: Waiting for authorization header...")
302
cookies = await session.get_cookies_list([cls.url])
303
auth_result.cookies = {c["name"]: c["value"] for c in cookies}
304
305
if not authorization:
306
# Fallback: the web app persists its token in localStorage
307
token = await session.evaluate_js(
308
"JSON.parse(window.localStorage.getItem('userToken') || '{}').value||''"
309
)
310
if token:
311
authorization = f"Bearer {token}"
312
313
# The authorization header is only sent once logged in
314
if authorization:
315
break
316
await asyncio.sleep(2)
317
318
if not authorization:
319
raise MissingAuthError(
320
"DeepSeekAuth: Login timed out. "
321
"No authorization token was captured from the browser."
322
)
323
auth_result.headers["user-agent"] = await session.get_user_agent()
324
auth_result.headers["authorization"] = authorization
325
finally:
326
await session.close()
327
328
debug.log(
329
"DeepSeekAuth: Login successful, captured "
330
f"{len(auth_result.cookies)} cookies and authorization header"
331
)
332
yield auth_result
266
333
267
334
@classmethod
268
335
async def create_pow_response(
269
336
cls, session: StreamSession, target_path: str
270
337
) -> str:
271
338
"""Request and solve a PoW challenge for one exact API target path."""
272
debug.log(
273
f"DeepSeekAuth: Requesting PoW challenge for {target_path} "
274
f"from {POW_CHALLENGE_ENDPOINT}"
275
)
339
# debug.log(
340
# f"DeepSeekAuth: Requesting PoW challenge for {target_path} "
341
# f"from {POW_CHALLENGE_ENDPOINT}"
342
# )
276
343
async with session.post(
277
344
POW_CHALLENGE_ENDPOINT,
278
345
json={"target_path": target_path},
@@ -311,7 +378,7 @@ class DeepSeek(AsyncGeneratorProvider, ProviderModelMixin):
311
378
pow_response = await loop.run_in_executor(
312
379
None, _solve_pow_challenge, challenge
313
380
)
314
debug.log(f"DeepSeekAuth: PoW challenge solved for {target_path}")
381
# debug.log(f"DeepSeekAuth: PoW challenge solved for {target_path}")
315
382
return pow_response
316
383
317
384
@classmethod
@@ -471,10 +538,10 @@ class DeepSeek(AsyncGeneratorProvider, ProviderModelMixin):
471
538
return True
472
539
473
540
@classmethod
474
async def get_quota(cls, **kwargs):
475
cookies = await get_cookies_async(cls.cookie_domain, False)
476
headers = _normalized_headers(get_headers(cls.cookie_domain) or {})
477
if cookies and headers.get("authorization"):
541
async def get_quota(cls, api_key: Optional[str] = None, **kwargs):
542
auth_result = cls.get_auth_result()
543
headers = _normalized_headers(getattr(auth_result, "headers", None) or {})
544
if headers.get("authorization"):
478
545
return {"success": True}
479
546
raise MissingAuthError("DeepSeekAuth: No authentication found.")
480
547
@@ -760,11 +827,11 @@ class DeepSeek(AsyncGeneratorProvider, ProviderModelMixin):
760
827
request_headers = None
761
828
762
829
@classmethod
763
async def create_async_generator(
830
async def create_authed(
764
831
cls,
765
832
model: str,
766
833
messages: Messages,
767
cookies: Cookies = None,
834
auth_result: AuthResult,
768
835
headers: dict = None,
769
836
proxy: str = None,
770
837
conversation: JsonConversation = None,
@@ -780,19 +847,19 @@ class DeepSeek(AsyncGeneratorProvider, ProviderModelMixin):
780
847
**kwargs,
781
848
) -> AsyncResult:
782
849
"""
783
Create async generator for DeepSeek requests with HAR file support.
850
Create async generator for DeepSeek requests using cached browser auth.
784
851
785
Authentication priority:
786
1. HAR file cookies and auth token (har_and_cookies/deepseek*.har)
787
2. Cookie jar from get_cookies()
852
Authentication is provided by ``auth_result`` from ``on_auth_async``
853
(CDP browser login) or the persisted auth cache file.
788
854
789
Note: DeepSeek requires proof-of-work challenge which may require
790
additional handling. This implementation provides basic HAR-based auth.
855
Note: DeepSeek requires proof-of-work challenge which is solved
856
with the WASM solver before each completion request.
791
857
792
858
Args:
793
859
model: Model name to use
794
860
messages: Message history
795
cookies: Optional cookies
861
auth_result: Authentication result with cookies and headers
862
headers: Optional header overrides
796
863
proxy: Optional proxy
797
864
conversation: JsonConversation object for continuing sessions
798
865
web_search: Enable web search
@@ -804,27 +871,12 @@ class DeepSeek(AsyncGeneratorProvider, ProviderModelMixin):
804
871
if not model:
805
872
model = cls.default_model
806
873
807
source_headers = dict(headers or {})
808
# Try to get auth from HAR file first
809
if cookies is None:
810
cookies = await get_cookies_async(cls.cookie_domain, False)
811
discovered_headers = get_headers(cls.cookie_domain) or {}
812
# Explicit caller headers override browser/HAR values, including when
813
# their casing differs (normalization happens below).
814
source_headers = {**discovered_headers, **source_headers}
815
normalized_source_headers = _normalized_headers(source_headers)
816
if cookies and normalized_source_headers.get("authorization"):
817
debug.log(
818
"DeepSeekAuth: Using "
819
f"{len(cookies)} cookies and {len(source_headers)} headers "
820
"from cookie jar"
821
)
822
# else:
823
# raise MissingAuthError(
824
# "DeepSeekAuth: No authentication found. "
825
# "Please add a DeepSeek HAR file to har_and_cookies/ directory "
826
# "with an authorization token."
827
# )
874
# Browser cookies and headers captured during login (CDP session)
875
cookies = auth_result.cookies or {}
876
source_headers = dict(auth_result.headers or {})
877
# Explicit caller headers override the captured values, including when
878
# their casing differs (normalization happens below).
879
source_headers = {**source_headers, **(headers or {})}
828
880
829
881
# Initialize conversation if needed
830
882
if conversation is None:
@@ -832,7 +884,7 @@ class DeepSeek(AsyncGeneratorProvider, ProviderModelMixin):
832
884
833
885
token = kwargs.get("token", "") or kwargs.get("api_key", "")
834
886
authorization = (token if token.lower().startswith("bearer ") else f"Bearer {token}") if token else ""
835
# Get auth token from HAR data or conversation
887
# Get auth token from the captured headers or conversation
836
888
if not authorization:
837
889
authorization = _normalized_headers(source_headers).get("authorization")
838
890
if not authorization and hasattr(conversation, "authorization"):
@@ -841,7 +893,7 @@ class DeepSeek(AsyncGeneratorProvider, ProviderModelMixin):
841
893
if not authorization:
842
894
raise MissingAuthError(
843
895
"DeepSeekAuth: Authorization token required. "
844
"Please ensure HAR file contains authorization header."
896
"Please log in again to refresh the authorization header."
845
897
)
846
898
847
899
headers = _build_chat_headers(source_headers, authorization)
@@ -869,7 +921,7 @@ class DeepSeek(AsyncGeneratorProvider, ProviderModelMixin):
869
921
not hasattr(conversation, "chat_session_id")
870
922
or not conversation.chat_session_id
871
923
):
872
debug.log(f"DeepSeekAuth: Creating new chat session...")
924
# debug.log(f"DeepSeekAuth: Creating new chat session...")
873
925
async with StreamSession(
874
926
headers=headers, cookies=cookies, proxy=proxy, impersonate="chrome"
875
927
) as session:
@@ -921,7 +973,6 @@ class DeepSeek(AsyncGeneratorProvider, ProviderModelMixin):
921
973
)
922
974
923
975
# Build request data
924
925
976
json_data = _build_completion_payload(
926
977
conversation,
927
978
prompt=prompt,
@@ -61,6 +61,9 @@ class GoogleAiMode(GoogleSearch):
61
61
await session.wait_for_network_idle(idle_time=1, timeout=10.0)
62
62
result = await session.evaluate_js("""
63
63
const rootElement = document.querySelector('[decode-data-ved="1"]');
64
if (!rootElement) {
65
throw new Error("Root element not found");
66
}
64
67
function getTextNodes(element) {
65
68
const textNodes = [];
66
69
for (const child of element.childNodes) {
@@ -5,7 +5,7 @@ import urllib.parse
5
5
6
6
from ...typing import AsyncResult, Messages
7
7
from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin
8
from ...providers.response import SearchResults
8
from ...providers.response import SearchResults, format_link
9
9
from ...requests.cdp import CDPSession
10
10
from ... import debug
11
11
from ..helper import get_last_user_message
@@ -29,30 +29,36 @@ class GoogleSearch(AsyncGeneratorProvider, ProviderModelMixin):
29
29
**kwargs,
30
30
) -> AsyncResult:
31
31
query = get_last_user_message(messages)
32
search_url = f"{cls.url}/search?q={urllib.parse.quote_plus(query)}"
32
search_url = f"{cls.url}/search?q={urllib.parse.quote(query)}"
33
33
34
34
debug.log(f"Google Search: Starting CDPSession for query: {query}")
35
35
session = CDPSession()
36
36
await session.start()
37
37
38
38
try:
39
debug.log(f"Google Search: Navigating to search URL: {search_url}")
39
40
await session.navigate(search_url)
40
await session.click_accept_button()
41
# debug.log(f"Google Search: Waiting for the page to load...")
42
await session.click_accept_button(False)
43
# debug.log(f"Google Search: Clicking accept button if present...")
41
44
42
45
# Wait for Google search results page to load
43
46
for _ in range(10):
44
47
has_results = None
45
48
try:
46
49
has_results = await session.evaluate_js(
47
"document.querySelectorAll('div.g, h3').length > 0"
50
"document.querySelectorAll('h3').length > 0"
48
51
)
49
52
except Exception as e:
50
53
debug.log(f"Google Search: Error checking for results: {e}")
51
54
if not has_results:
55
debug.log(f"Google Search: No results yet, retrying...")
56
await asyncio.sleep(1)
52
57
continue
53
58
54
59
# Extract search results from the DOM
55
60
yield SearchResults(await cls._read_search_results(session))
61
yield f'\n\nSource: {format_link(search_url, "Google Search")}'
56
62
break
57
63
finally:
58
64
await session.close()
@@ -61,21 +67,14 @@ class GoogleSearch(AsyncGeneratorProvider, ProviderModelMixin):
61
67
return await session.evaluate_js("""
62
68
(() => {
63
69
const results = [];
64
const items = document.querySelectorAll('h3');
65
items.forEach(item => {
66
const linkEl = item.parentElement;
67
const title = item.innerText || '';
70
const boxes = document.querySelectorAll('[data-snhf="0"]')
71
boxes.forEach(box => {
72
const linkEl = box.querySelector('a');
73
const title = linkEl.querySelector('h3') ? linkEl.querySelector('h3').innerText : '';
68
74
const link = linkEl.href ? new URL(linkEl.href || '/') : null;
69
75
if (link) link.searchParams.delete("srsltid")
70
let parentEl = linkEl.parentElement.parentElement.parentElement;
71
let snippetEl = null;
72
while (parentEl) {
73
if (parentEl.nextElementSibling)
74
snippetEl = parentEl.nextElementSibling.querySelector("div div:not(:has(a, svg)) span:not(:has(div, span, a, svg)):not(:empty)");
75
if (snippetEl) break;
76
parentEl = parentEl.parentElement;
77
}
78
const snippet = snippetEl ? snippetEl.innerText : '';
76
const snippetEl = box.nextElementSibling;
77
const snippet = snippetEl ? snippetEl.innerText.replace('...Read more', '...') : undefined;
79
78
if (title && link) {
80
79
results.push({ title, link: link.toString(), snippet });
81
80
}
@@ -552,6 +552,7 @@ def create_app_debug():
552
552
def create_app_with_gui_and_debug():
553
553
g4f.debug.logging = True
554
554
AppConfig.gui = True
555
os.environ["G4F_ENABLE_AUDIT_LOG"] = os.environ.get("G4F_ENABLE_AUDIT_LOG", "1")
555
556
return create_app()
556
557
557
558
@@ -404,7 +404,7 @@ class SearchResults(ResponseType):
404
404
return (
405
405
"".join(
406
406
[
407
f"> **{format_link(link['link'], link.get('title', link.get('name', None)))}**\n> {link.get('snippet', '')}\n"
407
f"> **{format_link(link['link'], link.get('title', link.get('name', None)))}**\n> {link.get('snippet', '').replace('\n', '\n> ')}\n"
408
408
for link in self.list
409
409
]
410
410
)
@@ -1076,37 +1076,15 @@ class CDPSession:
1076
1076
1077
1077
async def navigate(self, url: str):
1078
1078
"""Navigate to a URL and wait for it to load."""
1079
fut = asyncio.get_running_loop().create_future()
1080
if "Page.loadEventFired" not in self._event_handlers:
1081
self._event_handlers["Page.loadEventFired"] = []
1082
self._event_handlers["Page.loadEventFired"].append(fut)
1083
1079
1084
1080
await self.call("Page.navigate", url=url)
1085
1086
try:
1087
await asyncio.wait_for(fut, timeout=30.0)
1088
except asyncio.TimeoutError:
1089
if fut in self._event_handlers.get("Page.loadEventFired", []):
1090
self._event_handlers["Page.loadEventFired"].remove(fut)
1091
logger.warning(
1092
f"Timeout waiting for Page.loadEventFired when navigating to {url}"
1093
)
1081
await self.evaluate_js("new Promise(resolve => window.addEventListener('load', resolve))")
1094
1082
1095
1083
async def reload(self):
1096
1084
"""Reload the current page and wait for it to load."""
1097
fut = asyncio.get_running_loop().create_future()
1098
if "Page.loadEventFired" not in self._event_handlers:
1099
self._event_handlers["Page.loadEventFired"] = []
1100
self._event_handlers["Page.loadEventFired"].append(fut)
1101
1085
1102
1086
await self.call("Page.reload")
1103
1104
try:
1105
await asyncio.wait_for(fut, timeout=30.0)
1106
except asyncio.TimeoutError:
1107
if fut in self._event_handlers.get("Page.loadEventFired", []):
1108
self._event_handlers["Page.loadEventFired"].remove(fut)
1109
logger.warning("Timeout waiting for Page.loadEventFired when reloading")
1087
await self.evaluate_js("new Promise(resolve => window.addEventListener('load', resolve))")
1110
1088
1111
1089
async def wait_for_network_idle(
1112
1090
self, idle_time: float = 0.5, timeout: float = 15.0
@@ -1235,15 +1213,15 @@ class CDPSession:
1235
1213
async def click_accept_button(self, do_submit: bool = True) -> bool:
1236
1214
"""Find and click an 'Accept' or 'Einwilligen' button, including inside iframes."""
1237
1215
js_code = """
1238
// 2. Get the current URL's search parameters
1216
// Get the current URL's search parameters
1239
1217
const params = new URLSearchParams(window.location.search || document.location.hash.substring(1));
1240
1218
const searchQuery = params.get('q');
1241
1219
1242
// 2b. Insert prompt in Flux HF before clicking on run button
1220
// Insert prompt in Flux HF before clicking on run button
1243
1221
const textbox = document.querySelector('[data-testid="textbox"]');
1244
1222
textbox ? textbox.value = searchQuery : null;
1245
1223
1246
// 3. Click any "Accept" button in the main document or nested iframes
1224
// Click any "Accept" button in the main document or nested iframes
1247
1225
const targetTexts = [
1248
1226
'Send', 'Accept', 'Accept all', 'Accept All',
1249
1227
'Accept All Cookies', 'Accept all cookies',
@@ -1317,7 +1295,7 @@ clickedTexts.join(', ');
1317
1295
if not do_submit:
1318
1296
return bool(rect)
1319
1297
js_code = """
1320
// 4. Enable Google AI Mode if the URL has the ai-mode parameter
1298
// Enable Google AI Mode if the URL has the ai-mode parameter
1321
1299
let googleAiModeButton = null;
1322
1300
function enableGoogleAiMode() {
1323
1301
// Enable Google AI Mode if the URL has the ai-mode parameter
@@ -1336,7 +1314,7 @@ function enableGoogleAiMode() {
1336
1314
}
1337
1315
enableGoogleAiMode();
1338
1316
1339
// 5. Find the textarea
1317
// Find the textarea
1340
1318
const fieldSelectors = [
1341
1319
'textarea[name="prompt"]',
1342
1320
'[class^="MessageInput__TextArea--"]',
@@ -1349,7 +1327,7 @@ const fieldSelectors = [
1349
1327
'[placeholder="Ask Meta AI..."]', // meta.ai
1350
1328
'[placeholder="Ask anything..."]', // cloudflare
1351
1329
];
1352
// 7. Handle special cases for specific sites (like DeepSeek, Gemini, etc.)
1330
// Handle special cases for specific sites (like DeepSeek, Gemini, etc.)
1353
1331
(function() {
1354
1332
if (!searchQuery) return;
1355
1333
const editor = document.querySelector(fieldSelectors.join(', '));
@@ -1379,7 +1357,7 @@ const fieldSelectors = [
1379
1357
})();
1380
1358
1381
1359
1382
// 8. Click the send / submit button if it exists
1360
// Click the send / submit button if it exists
1383
1361
const sendButtonSelectors = [
1384
1362
'[data-send-label="Send message"]',
1385
1363
'[class^="MessageInput__Submit--"]',
@@ -1399,7 +1377,7 @@ if (sendButton) {
1399
1377
}, 1000);
1400
1378
}
1401
1379
1402
// 8. Click the send button on gemini.google.com
1380
// Click the send button on gemini.google.com
1403
1381
const geminiSendButton = document.querySelector(`.send-button`);
1404
1382
if (geminiSendButton) {
1405
1383
setTimeout(() => {
@@ -1407,13 +1385,13 @@ if (geminiSendButton) {
1407
1385
}, 1000);
1408
1386
}
1409
1387
1410
// 8. Click the send button on chat.deepseek.com
1388
// Click the send button on chat.deepseek.com
1411
1389
const deepseekSendButton = document.querySelector('[style="width: fit-content;"] [role="button"]');
1412
1390
if (deepseekSendButton) {
1413
1391
deepseekSendButton.click();
1414
1392
}
1415
1393
1416
// 9. Return the text content of the first found send button for logging/debugging
1394
// Return the text content of the first found send button for logging/debugging
1417
1395
(
1418
1396
sendButton || geminiSendButton || deepseekSendButton || googleAiModeButton
1419
1397
)?.textContent.trim();