返回提交历史
Modified
g4f/Provider/DDG.py
+81
-173
XFEstudio/gpt4free
feat: Enhance DDG provider with user agent and hash generation
- Added `hashlib` import to enable hash generation. - Introduced `generate_user_agent` method to create a dynamic user agent string. - Modified `generate_fe_version` to accept `page_content` as a parameter and extract the feature hash. - Added `generate_x_vqd_hash_1` method to compute a hash based on `vqd` and `fe_version`. - Updated `create_async_generator` to use the new user agent and hash generation methods. - Simplified message history management by using a single line to find the last user message. - Removed unnecessary comments and improved code readability.
1ebe48b3
代码差异
1 个文件
+81
-173
@@ -4,6 +4,7 @@ import json
4
4
import base64
5
5
import time
6
6
import random
7
import hashlib
7
8
import asyncio
8
9
from datetime import datetime
9
10
from aiohttp import ClientSession
@@ -15,13 +16,8 @@ from ..providers.response import FinishReason, JsonConversation
15
16
16
17
17
18
class Conversation(JsonConversation):
18
"""Conversation class for DDG provider.
19
20
Note: DDG doesn't actually support conversation history through its API,
21
so we simulate it by including the history in the user message.
22
"""
23
19
message_history: Messages = []
24
20
25
21
def __init__(self, model: str):
26
22
self.model = model
27
23
self.message_history = []
@@ -37,7 +33,7 @@ class DDG(AsyncGeneratorProvider, ProviderModelMixin):
37
33
supports_stream = True
38
34
supports_system_message = True
39
35
supports_message_history = True
40
36
41
37
default_model = "gpt-4o-mini"
42
38
model_aliases = {
43
39
"gpt-4": default_model,
@@ -49,10 +45,12 @@ class DDG(AsyncGeneratorProvider, ProviderModelMixin):
49
45
models = [default_model, "o3-mini"] + list(model_aliases.keys())
50
46
51
47
@staticmethod
52
def generate_fe_signals():
53
"""Generate a fake x-fe-signals header value"""
48
def generate_user_agent() -> str:
49
return f"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.{random.randint(1000,9999)}.0 Safari/537.36"
50
51
@staticmethod
52
def generate_fe_signals() -> str:
54
53
current_time = int(time.time() * 1000)
55
56
54
signals_data = {
57
55
"start": current_time - 35000,
58
56
"events": [
@@ -64,14 +62,33 @@ class DDG(AsyncGeneratorProvider, ProviderModelMixin):
64
62
],
65
63
"end": 35163
66
64
}
67
68
signals_json = json.dumps(signals_data)
69
return base64.b64encode(signals_json.encode()).decode()
65
return base64.b64encode(json.dumps(signals_data).encode()).decode()
70
66
71
67
@staticmethod
72
def generate_fe_version():
73
"""Generate a fake x-fe-version header value"""
74
return "serp_20250510_052906_ET-ed4f51dc2e106020bc4b"
68
def generate_fe_version(page_content: str = "") -> str:
69
try:
70
fe_hash = page_content.split('__DDG_FE_CHAT_HASH__="', 1)[1].split('"', 1)[0]
71
return f"serp_20250510_052906_ET-{fe_hash}"
72
except Exception:
73
return "serp_20250510_052906_ET-ed4f51dc2e106020bc4b"
74
75
@staticmethod
76
def generate_x_vqd_hash_1(vqd: str, fe_version: str) -> str:
77
# Placeholder logic; in reality DuckDuckGo uses dynamic JS challenge
78
concat = f"{vqd}#{fe_version}"
79
hash_digest = hashlib.sha256(concat.encode()).digest()
80
b64 = base64.b64encode(hash_digest).decode()
81
return base64.b64encode(json.dumps({
82
"server_hashes": [],
83
"client_hashes": [b64],
84
"signals": {},
85
"meta": {
86
"v": "1",
87
"challenge_id": hashlib.md5(concat.encode()).hexdigest(),
88
"origin": "https://duckduckgo.com",
89
"stack": "Generated in Python"
90
}
91
}).encode()).decode()
75
92
76
93
@classmethod
77
94
async def create_async_generator(
@@ -85,24 +102,15 @@ class DDG(AsyncGeneratorProvider, ProviderModelMixin):
85
102
**kwargs
86
103
) -> AsyncResult:
87
104
model = cls.get_model(model)
88
89
# Initialize conversation if not provided
105
90
106
if conversation is None:
91
107
conversation = Conversation(model)
92
# Initialize message history from the provided messages
93
108
conversation.message_history = messages.copy()
94
109
else:
95
# Update message history with the last user message
96
last_message = None
97
for msg in reversed(messages):
98
if msg["role"] == "user":
99
last_message = msg
100
break
101
110
last_message = next((m for m in reversed(messages) if m["role"] == "user"), None)
102
111
if last_message and last_message not in conversation.message_history:
103
112
conversation.message_history.append(last_message)
104
105
# Base headers for all requests
113
106
114
base_headers = {
107
115
"accept-language": "en-US,en;q=0.9",
108
116
"dnt": "1",
@@ -114,185 +122,85 @@ class DDG(AsyncGeneratorProvider, ProviderModelMixin):
114
122
"sec-fetch-dest": "empty",
115
123
"sec-fetch-mode": "cors",
116
124
"sec-fetch-site": "same-origin",
117
"user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36",
125
"user-agent": cls.generate_user_agent(),
118
126
}
119
120
127
cookies = {'dcs': '1', 'dcm': '3'}
121
122
# Format the conversation history as a single prompt using format_prompt
123
if len(conversation.message_history) > 1:
124
# If we have conversation history, format it as a single prompt
125
formatted_prompt = format_prompt(conversation.message_history)
126
else:
127
# If we don't have conversation history, just use the last user message
128
formatted_prompt = get_last_user_message(messages)
129
130
# Prepare the request data
131
data = {
132
"model": model,
133
"messages": [{"role": "user", "content": formatted_prompt}],
134
"canUseTools": False
135
}
136
137
# Create a new session for each request
128
129
formatted_prompt = format_prompt(conversation.message_history) if len(conversation.message_history) > 1 else get_last_user_message(messages)
130
data = {"model": model, "messages": [{"role": "user", "content": formatted_prompt}], "canUseTools": False}
131
138
132
async with ClientSession(cookies=cookies) as session:
139
# Step 1: Visit the main page to get initial cookies
140
main_headers = base_headers.copy()
141
main_headers.update({
142
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
143
"priority": "u=0, i",
144
"upgrade-insecure-requests": "1",
145
})
146
147
133
try:
148
async with session.get(f"{cls.url}/?q=DuckDuckGo+AI+Chat&ia=chat&duckai=1",
149
headers=main_headers,
150
proxy=proxy) as main_response:
151
main_response.raise_for_status()
152
153
# Extract fe_version from the page
154
page_content = await main_response.text()
155
fe_version = cls.generate_fe_version()
156
try:
157
xfe1 = page_content.split('__DDG_BE_VERSION__="', 1)[1].split('"', 1)[0]
158
xfe2 = page_content.split('__DDG_FE_CHAT_HASH__="', 1)[1].split('"', 1)[0]
159
fe_version = f"serp_20250510_052906_ET-{xfe2}"
160
except Exception:
161
pass
162
163
# Step 2: Get the VQD token from the status endpoint
164
status_headers = base_headers.copy()
165
status_headers.update({
166
"accept": "*/*",
167
"cache-control": "no-store",
168
"priority": "u=1, i",
169
"x-vqd-accept": "1",
170
})
171
172
async with session.get(cls.status_url,
173
headers=status_headers,
174
proxy=proxy) as status_response:
175
status_response.raise_for_status()
176
177
# Get VQD token from headers
178
vqd = status_response.headers.get("x-vqd-4", "")
179
180
if not vqd:
181
# If we couldn't get a VQD token, try to generate one
182
vqd = f"4-{random.randint(10**29, 10**30 - 1)}"
183
184
# Step 3: Send the chat request
185
chat_headers = base_headers.copy()
186
chat_headers.update({
134
# Step 1: Initial page load
135
async with session.get(f"{cls.url}/?q=DuckDuckGo+AI+Chat&ia=chat&duckai=1",
136
headers={**base_headers, "accept": "text/html"}, proxy=proxy) as r:
137
r.raise_for_status()
138
page = await r.text()
139
fe_version = cls.generate_fe_version(page)
140
141
# Step 2: Get VQD
142
status_headers = {**base_headers, "accept": "*/*", "cache-control": "no-store", "x-vqd-accept": "1"}
143
async with session.get(cls.status_url, headers=status_headers, proxy=proxy) as r:
144
r.raise_for_status()
145
vqd = r.headers.get("x-vqd-4", "") or f"4-{random.randint(10**29, 10**30 - 1)}"
146
147
x_vqd_hash_1 = cls.generate_x_vqd_hash_1(vqd, fe_version)
148
149
# Step 3: Actual chat request
150
chat_headers = {
151
**base_headers,
187
152
"accept": "text/event-stream",
188
153
"content-type": "application/json",
189
"priority": "u=1, i",
190
154
"x-fe-signals": cls.generate_fe_signals(),
191
155
"x-fe-version": fe_version,
192
156
"x-vqd-4": vqd,
193
})
194
195
async with session.post(cls.api_endpoint,
196
json=data,
197
headers=chat_headers,
198
proxy=proxy) as response:
157
"x-vqd-hash-1": x_vqd_hash_1,
158
}
159
160
async with session.post(cls.api_endpoint, json=data, headers=chat_headers, proxy=proxy) as response:
199
161
if response.status != 200:
200
162
error_text = await response.text()
201
202
# If we get an ERR_INVALID_VQD error and haven't retried too many times, try again
163
if "ERR_BN_LIMIT" in error_text:
164
yield "Blocked by DuckDuckGo: Bot limit exceeded (ERR_BN_LIMIT)."
165
return
203
166
if "ERR_INVALID_VQD" in error_text and retry_count < 3:
204
# Wait a bit before retrying
205
await asyncio.sleep(1)
206
# Try again with a new session
167
await asyncio.sleep(random.uniform(2.5, 5.5))
207
168
async for chunk in cls.create_async_generator(
208
model=model,
209
messages=messages,
210
proxy=proxy,
211
conversation=conversation,
212
return_conversation=return_conversation,
213
retry_count=retry_count + 1,
214
**kwargs
169
model, messages, proxy, conversation, return_conversation, retry_count + 1, **kwargs
215
170
):
216
171
yield chunk
217
172
return
218
219
173
yield f"Error: HTTP {response.status} - {error_text}"
220
174
return
221
175
222
176
full_message = ""
223
224
177
async for line in response.content:
225
178
line_text = line.decode("utf-8").strip()
226
227
179
if line_text.startswith("data:"):
228
data_content = line_text[5:].strip()
229
230
# Handle [DONE] marker
231
if data_content == "[DONE]":
232
# Add the assistant's response to the conversation history
180
payload = line_text[5:].strip()
181
if payload == "[DONE]":
233
182
if full_message:
234
conversation.message_history.append({
235
"role": "assistant",
236
"content": full_message
237
})
238
239
# Return the conversation if requested
183
conversation.message_history.append({"role": "assistant", "content": full_message})
240
184
if return_conversation:
241
185
yield conversation
242
243
186
yield FinishReason("stop")
244
187
break
245
246
188
try:
247
message_data = json.loads(data_content)
248
249
# Handle error responses
250
if message_data.get("action") == "error":
251
error_type = message_data.get("type", "Unknown error")
252
253
# If we get an ERR_INVALID_VQD error and haven't retried too many times, try again
254
if error_type == "ERR_INVALID_VQD" and retry_count < 3:
255
# Wait a bit before retrying
256
await asyncio.sleep(1)
257
# Try again with a new session
258
async for chunk in cls.create_async_generator(
259
model=model,
260
messages=messages,
261
proxy=proxy,
262
conversation=conversation,
263
return_conversation=return_conversation,
264
retry_count=retry_count + 1,
265
**kwargs
266
):
267
yield chunk
268
return
269
270
yield f"Error: {error_type}"
189
msg = json.loads(payload)
190
if msg.get("action") == "error":
191
yield f"Error: {msg.get('type', 'unknown')}"
271
192
break
272
273
# Extract message content
274
if "message" in message_data:
275
message_content = message_data.get("message", "")
276
if message_content:
277
yield message_content
278
full_message += message_content
279
193
if "message" in msg:
194
content = msg["message"]
195
yield content
196
full_message += content
280
197
except json.JSONDecodeError:
281
198
continue
282
199
except Exception as e:
283
# If we get an exception and haven't retried too many times, try again
284
200
if retry_count < 3:
285
# Wait a bit before retrying
286
await asyncio.sleep(1)
287
# Try again with a new session
201
await asyncio.sleep(random.uniform(2.5, 5.5))
288
202
async for chunk in cls.create_async_generator(
289
model=model,
290
messages=messages,
291
proxy=proxy,
292
conversation=conversation,
293
return_conversation=return_conversation,
294
retry_count=retry_count + 1,
295
**kwargs
203
model, messages, proxy, conversation, return_conversation, retry_count + 1, **kwargs
296
204
):
297
205
yield chunk
298
206
else: