返回提交历史
Modified
g4f/Provider/DDG.py
+28
-5
XFEstudio/gpt4free
Update g4f/Provider/DDG.py
f028acfe
代码差异
1 个文件
+28
-5
@@ -3,9 +3,16 @@ from __future__ import annotations
3
3
from aiohttp import ClientSession, ClientTimeout, ClientError
4
4
import json
5
5
from ..typing import AsyncResult, Messages
6
from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
6
from .base_provider import AsyncGeneratorProvider, ProviderModelMixin, BaseConversation
7
7
from .helper import format_prompt
8
8
9
class Conversation(BaseConversation):
10
vqd: str = None
11
message_history: Messages = []
12
13
def __init__(self, model: str):
14
self.model = model
15
9
16
class DDG(AsyncGeneratorProvider, ProviderModelMixin):
10
17
label = "DuckDuckGo AI Chat"
11
18
url = "https://duckduckgo.com/aichat"
@@ -55,6 +62,8 @@ class DDG(AsyncGeneratorProvider, ProviderModelMixin):
55
62
cls,
56
63
model: str,
57
64
messages: Messages,
65
conversation: Conversation = None,
66
return_conversation: bool = False,
58
67
proxy: str = None,
59
68
**kwargs
60
69
) -> AsyncResult:
@@ -63,16 +72,30 @@ class DDG(AsyncGeneratorProvider, ProviderModelMixin):
63
72
}
64
73
async with ClientSession(headers=headers, timeout=ClientTimeout(total=30)) as session:
65
74
# Fetch VQD token
66
vqd = await cls.fetch_vqd(session)
67
headers["x-vqd-4"] = vqd
75
if conversation is None:
76
conversation = Conversation(model)
77
78
if conversation.vqd is None:
79
conversation.vqd = await cls.fetch_vqd(session)
80
81
headers["x-vqd-4"] = conversation.vqd
82
83
if return_conversation:
84
yield conversation
85
86
if len(messages) >= 2:
87
conversation.message_history.extend([messages[-2], messages[-1]])
88
elif len(messages) == 1:
89
conversation.message_history.append(messages[-1])
68
90
69
91
payload = {
70
"model": model,
71
"messages": [{"role": "user", "content": format_prompt(messages)}],
92
"model": conversation.model,
93
"messages": conversation.message_history,
72
94
}
73
95
74
96
try:
75
97
async with session.post(cls.api_endpoint, headers=headers, json=payload, proxy=proxy) as response:
98
conversation.vqd = response.headers.get("x-vqd-4")
76
99
response.raise_for_status()
77
100
async for line in response.content:
78
101
line = line.decode("utf-8").strip()