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

XFEstudio/gpt4free

fix: fix(again) DDG ERR_CHALLENGE

- [fix] Import base64, hashlib and initialize BeautifulSoup in g4f/Provider/DDG.py - [feat] Add helper methods (sha256_base64, parse_dom_fingerprint, etc.) in g4f/Provider/DDG.py - [fix] Refresh fe_version and adjust headers in g4f/Provider/DDG.py - [fix] Update ddg.py to refresh vqd tokens and conversation cookies - [docs] Insert inline comments for token and cookie updates in ddg.py

98f9b302
nazDridoy <nazDridoy399@gmail.com>
提交于

代码差异

1 个文件 +112 -3
Modified g4f/Provider/DDG.py +112 -3
@@ -5,6 +5,8 @@ from aiohttp import ClientSession, ClientTimeout
5 5 import json
6 6 import asyncio
7 7 import random
8 import base64
9 import hashlib
8 10 from yarl import URL
9 11
10 12 from ..typing import AsyncResult, Messages, Cookies
@@ -14,6 +16,12 @@ from .helper import format_prompt, get_last_user_message
14 16 from ..providers.response import FinishReason, JsonConversation
15 17 from ..errors import ModelNotSupportedError, ResponseStatusError, RateLimitError, TimeoutError, ConversationLimitError
16 18
19 try:
20 from bs4 import BeautifulSoup
21 has_bs4 = True
22 except ImportError:
23 has_bs4 = False
24
17 25
18 26 class DuckDuckGoSearchException(Exception):
19 27 """Base exception class for duckduckgo_search."""
@@ -23,6 +31,7 @@ class Conversation(JsonConversation):
23 31 vqd_hash_1: str = None
24 32 message_history: Messages = []
25 33 cookies: dict = {}
34 fe_version: str = None
26 35
27 36 def __init__(self, model: str):
28 37 self.model = model
@@ -51,6 +60,64 @@ class DDG(AsyncGeneratorProvider, ProviderModelMixin):
51 60 last_request_time = 0
52 61 max_retries = 3
53 62 base_delay = 2
63
64 # Class variable to store the x-fe-version across instances
65 _chat_xfe = ""
66
67 @staticmethod
68 def sha256_base64(text: str) -> str:
69 """Return the base64 encoding of the SHA256 digest of the text."""
70 sha256_hash = hashlib.sha256(text.encode("utf-8")).digest()
71 return base64.b64encode(sha256_hash).decode()
72
73 @staticmethod
74 def parse_dom_fingerprint(js_text: str) -> str:
75 if not has_bs4:
76 # Fallback if BeautifulSoup is not available
77 return "1000"
78
79 try:
80 html_snippet = js_text.split("e.innerHTML = '")[1].split("';")[0]
81 offset_value = js_text.split("return String(")[1].split(" ")[0]
82 soup = BeautifulSoup(html_snippet, "html.parser")
83 corrected_inner_html = soup.body.decode_contents()
84 inner_html_length = len(corrected_inner_html)
85 fingerprint = int(offset_value) + inner_html_length
86 return str(fingerprint)
87 except Exception:
88 # Return a fallback value if parsing fails
89 return "1000"
90
91 @staticmethod
92 def parse_server_hashes(js_text: str) -> list:
93 try:
94 return js_text.split('server_hashes: ["', maxsplit=1)[1].split('"]', maxsplit=1)[0].split('","')
95 except Exception:
96 # Return a fallback value if parsing fails
97 return ["1", "2"]
98
99 @classmethod
100 def build_x_vqd_hash_1(cls, vqd_hash_1: str, headers: dict) -> str:
101 """Build the x-vqd-hash-1 header value."""
102 try:
103 decoded = base64.b64decode(vqd_hash_1).decode()
104 server_hashes = cls.parse_server_hashes(decoded)
105 dom_fingerprint = cls.parse_dom_fingerprint(decoded)
106
107 ua_fingerprint = headers.get("User-Agent", "") + headers.get("sec-ch-ua", "")
108 ua_hash = cls.sha256_base64(ua_fingerprint)
109 dom_hash = cls.sha256_base64(dom_fingerprint)
110
111 final_result = {
112 "server_hashes": server_hashes,
113 "client_hashes": [ua_hash, dom_hash],
114 "signals": {},
115 }
116 base64_final_result = base64.b64encode(json.dumps(final_result).encode()).decode()
117 return base64_final_result
118 except Exception as e:
119 # If anything fails, return an empty string
120 return ""
54 121
55 122 @classmethod
56 123 def validate_model(cls, model: str) -> str:
@@ -92,6 +159,31 @@ class DDG(AsyncGeneratorProvider, ProviderModelMixin):
92 159 return cookies
93 160 except Exception as e:
94 161 return {}
162
163 @classmethod
164 async def fetch_fe_version(cls, session: ClientSession) -> str:
165 """Fetches the fe-version from the initial page load."""
166 if cls._chat_xfe:
167 return cls._chat_xfe
168
169 try:
170 url = "https://duckduckgo.com/?q=DuckDuckGo+AI+Chat&ia=chat&duckai=1"
171 await cls.sleep()
172 async with session.get(url) as response:
173 await raise_for_status(response)
174 content = await response.text()
175
176 # Extract x-fe-version components
177 try:
178 xfe1 = content.split('__DDG_BE_VERSION__="', 1)[1].split('"', 1)[0]
179 xfe2 = content.split('__DDG_FE_CHAT_HASH__="', 1)[1].split('"', 1)[0]
180 cls._chat_xfe = f"{xfe1}-{xfe2}"
181 return cls._chat_xfe
182 except Exception:
183 # If extraction fails, return an empty string
184 return ""
185 except Exception:
186 return ""
95 187
96 188 @classmethod
97 189 async def fetch_vqd_and_hash(cls, session: ClientSession, retry_count: int = 0) -> tuple[str, str]:
@@ -118,7 +210,6 @@ class DDG(AsyncGeneratorProvider, ProviderModelMixin):
118 210 await raise_for_status(response)
119 211
120 212 vqd = response.headers.get("x-vqd-4", "")
121 # Fetch the actual hash from the response header
122 213 vqd_hash_1 = response.headers.get("x-vqd-hash-1", "")
123 214
124 215 if vqd:
@@ -155,20 +246,31 @@ class DDG(AsyncGeneratorProvider, ProviderModelMixin):
155 246 try:
156 247 session_timeout = ClientTimeout(total=timeout)
157 248 async with ClientSession(timeout=session_timeout, cookies=cookies) as session:
249 # Step 1: Ensure we have the fe_version
250 if not cls._chat_xfe:
251 cls._chat_xfe = await cls.fetch_fe_version(session)
252
253 # Step 2: Initialize or update conversation
158 254 if conversation is None:
159 255 # Get initial cookies if not provided
160 256 if not cookies:
161 257 await cls.get_default_cookies(session)
162 258
259 # Create a new conversation
163 260 conversation = Conversation(model)
261 conversation.fe_version = cls._chat_xfe
262
263 # Step 3: Get VQD tokens
164 264 vqd, vqd_hash_1 = await cls.fetch_vqd_and_hash(session)
165 265 conversation.vqd = vqd
166 266 conversation.vqd_hash_1 = vqd_hash_1
167 267 conversation.message_history = [{"role": "user", "content": format_prompt(messages)}]
168 268 else:
269 # Update existing conversation with new message
169 270 last_message = get_last_user_message(messages.copy())
170 271 conversation.message_history.append({"role": "user", "content": last_message})
171
272
273 # Step 4: Prepare headers - IMPORTANT: send empty x-vqd-hash-1 for the first request
172 274 headers = {
173 275 "accept": "text/event-stream",
174 276 "accept-language": "en-US,en;q=0.9",
@@ -176,15 +278,19 @@ class DDG(AsyncGeneratorProvider, ProviderModelMixin):
176 278 "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
177 279 "origin": "https://duckduckgo.com",
178 280 "referer": "https://duckduckgo.com/",
281 "sec-ch-ua": '"Chromium";v="133", "Not_A Brand";v="8"',
282 "x-fe-version": conversation.fe_version or cls._chat_xfe,
179 283 "x-vqd-4": conversation.vqd,
180 "x-vqd-hash-1": "",
284 "x-vqd-hash-1": "", # Send empty string initially
181 285 }
182 286
287 # Step 5: Prepare the request data
183 288 data = {
184 289 "model": model,
185 290 "messages": conversation.message_history,
186 291 }
187 292
293 # Step 6: Send the request
188 294 await cls.sleep(multiplier=1.0 + retry_count * 0.5)
189 295 async with session.post(cls.api_endpoint, json=data, headers=headers, proxy=proxy) as response:
190 296 # Handle 429 errors specifically
@@ -206,6 +312,7 @@ class DDG(AsyncGeneratorProvider, ProviderModelMixin):
206 312 reason = None
207 313 full_message = ""
208 314
315 # Step 7: Process the streaming response
209 316 async for line in response.content:
210 317 line = line.decode("utf-8").strip()
211 318
@@ -231,8 +338,10 @@ class DDG(AsyncGeneratorProvider, ProviderModelMixin):
231 338 else:
232 339 reason = "stop"
233 340
341 # Step 8: Update conversation with response information
234 342 if return_conversation:
235 343 conversation.message_history.append({"role": "assistant", "content": full_message})
344 # Update tokens from response headers
236 345 conversation.vqd = response.headers.get("x-vqd-4", conversation.vqd)
237 346 conversation.vqd_hash_1 = response.headers.get("x-vqd-hash-1", conversation.vqd_hash_1)
238 347 conversation.cookies = {