返回提交历史
Modified
etc/unittest/__main__.py
+1
-0
Added
etc/unittest/thinking.py
+59
-0
Modified
g4f/Provider/AllenAI.py
+1
-1
Modified
g4f/Provider/Cloudflare.py
+3
-7
Modified
g4f/Provider/GizAI.py
+7
-4
Modified
g4f/Provider/Glider.py
+5
-76
Modified
g4f/Provider/Goabror.py
+3
-5
Modified
g4f/Provider/LambdaChat.py
+10
-158
Modified
g4f/Provider/PerplexityLabs.py
+1
-1
Modified
g4f/Provider/TypeGPT.py
+8
-76
Modified
g4f/Provider/hf/HuggingChat.py
+25
-15
Modified
g4f/Provider/needs_auth/OpenaiChat.py
+7
-19
Modified
g4f/Provider/template/OpenaiTemplate.py
+4
-1
Modified
g4f/client/helper.py
+1
-1
Modified
g4f/providers/base_provider.py
+7
-5
Modified
g4f/providers/helper.py
+5
-1
Modified
g4f/providers/response.py
+5
-0
Modified
g4f/requests/defaults.py
+1
-7
Modified
g4f/tools/run_tools.py
+10
-29
XFEstudio/gpt4free
Improve TypeGPT, GizAI, Goabror and LambdaChat provider Update conversation body in OpenaiChat provider Update ThinkingProcessor in run_tools Add unittests for ThinkingProcessor Update default headers in requests module Add AuthFileMixin to base_provider
10d32a4c
代码差异
19 个文件
+163
-406
@@ -12,6 +12,7 @@ from .client import *
12
12
from .image_client import *
13
13
from .include import *
14
14
from .retry_provider import *
15
from .thinking import *
15
16
from .web_search import *
16
17
from .models import *
17
18
@@ -0,0 +1,59 @@
1
import unittest
2
import time
3
4
from g4f.tools.run_tools import ThinkingProcessor, Reasoning
5
6
class TestThinkingProcessor(unittest.TestCase):
7
def test_non_thinking_chunk(self):
8
chunk = "This is a regular text."
9
expected_time, expected_result = 0, [chunk]
10
actual_time, actual_result = ThinkingProcessor.process_thinking_chunk(chunk)
11
self.assertEqual(actual_time, expected_time)
12
self.assertEqual(actual_result, expected_result)
13
14
def test_thinking_start(self):
15
chunk = "Hello <think>World"
16
expected_time = time.time()
17
expected_result = ["Hello ", Reasoning(status="🤔 Is thinking...", is_thinking="<think>"), Reasoning("World")]
18
actual_time, actual_result = ThinkingProcessor.process_thinking_chunk(chunk)
19
self.assertAlmostEqual(actual_time, expected_time, delta=1)
20
self.assertEqual(actual_result[0], expected_result[0])
21
self.assertEqual(actual_result[1], expected_result[1])
22
self.assertEqual(actual_result[2], expected_result[2])
23
24
def test_thinking_end(self):
25
start_time = time.time()
26
chunk = "token</think> content after"
27
expected_result = [Reasoning("token"), Reasoning(status="Finished", is_thinking="</think>"), " content after"]
28
actual_time, actual_result = ThinkingProcessor.process_thinking_chunk(chunk, start_time)
29
self.assertEqual(actual_time, 0)
30
self.assertEqual(actual_result[0], expected_result[0])
31
self.assertEqual(actual_result[1], expected_result[1])
32
self.assertEqual(actual_result[2], expected_result[2])
33
34
def test_thinking_start_and_end(self):
35
start_time = time.time()
36
chunk = "<think>token</think> content after"
37
expected_result = [Reasoning(status="🤔 Is thinking...", is_thinking="<think>"), Reasoning("token"), Reasoning(status="Finished", is_thinking="</think>"), " content after"]
38
actual_time, actual_result = ThinkingProcessor.process_thinking_chunk(chunk, start_time)
39
self.assertEqual(actual_time, 0)
40
self.assertEqual(actual_result[0], expected_result[0])
41
self.assertEqual(actual_result[1], expected_result[1])
42
self.assertEqual(actual_result[2], expected_result[2])
43
self.assertEqual(actual_result[3], expected_result[3])
44
45
def test_ongoing_thinking(self):
46
start_time = time.time()
47
chunk = "Still thinking..."
48
expected_result = [Reasoning("Still thinking...")]
49
actual_time, actual_result = ThinkingProcessor.process_thinking_chunk(chunk, start_time)
50
self.assertEqual(actual_time, start_time)
51
self.assertEqual(actual_result, expected_result)
52
53
def test_chunk_with_text_after_think(self):
54
chunk = "Start <think>Middle</think>End"
55
expected_time = 0
56
expected_result = ["Start ", Reasoning(status="🤔 Is thinking...", is_thinking="<think>"), Reasoning("Middle"), Reasoning(status="Finished", is_thinking="</think>"), "End"]
57
actual_time, actual_result = ThinkingProcessor.process_thinking_chunk(chunk)
58
self.assertEqual(actual_time, expected_time)
59
self.assertEqual(actual_result, expected_result)
@@ -48,7 +48,7 @@ class AllenAI(AsyncGeneratorProvider, ProviderModelMixin):
48
48
"olmo-2-13b": "OLMo-2-1124-13B-Instruct",
49
49
"tulu-3-1-8b": "tulu-3-1-8b",
50
50
"tulu-3-70b": "Llama-3-1-Tulu-3-70B",
51
"llama-3.1-405b": "Llama-3-1-Tulu-3-70B",
51
"llama-3.1-405b": "tulu-3-405b",
52
52
"llama-3.1-8b": "tulu-3-1-8b",
53
53
"llama-3.1-70b": "Llama-3-1-Tulu-3-70B",
54
54
}
@@ -5,14 +5,14 @@ import json
5
5
from pathlib import Path
6
6
7
7
from ..typing import AsyncResult, Messages, Cookies
8
from .base_provider import AsyncGeneratorProvider, ProviderModelMixin, get_running_loop
8
from .base_provider import AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin, get_running_loop
9
9
from ..requests import Session, StreamSession, get_args_from_nodriver, raise_for_status, merge_cookies
10
10
from ..requests import DEFAULT_HEADERS, has_nodriver, has_curl_cffi
11
11
from ..providers.response import FinishReason
12
12
from ..cookies import get_cookies_dir
13
13
from ..errors import ResponseStatusError, ModelNotFoundError
14
14
15
class Cloudflare(AsyncGeneratorProvider, ProviderModelMixin):
15
class Cloudflare(AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin):
16
16
label = "Cloudflare AI"
17
17
url = "https://playground.ai.cloudflare.com"
18
18
working = True
@@ -36,10 +36,6 @@ class Cloudflare(AsyncGeneratorProvider, ProviderModelMixin):
36
36
}
37
37
_args: dict = None
38
38
39
@classmethod
40
def get_cache_file(cls) -> Path:
41
return Path(get_cookies_dir()) / f"auth_{cls.parent if hasattr(cls, 'parent') else cls.__name__}.json"
42
43
39
@classmethod
44
40
def get_models(cls) -> str:
45
41
if not cls.models:
@@ -79,7 +75,7 @@ class Cloudflare(AsyncGeneratorProvider, ProviderModelMixin):
79
75
if cache_file.exists():
80
76
with cache_file.open("r") as f:
81
77
cls._args = json.load(f)
82
if has_nodriver:
78
elif has_nodriver:
83
79
cls._args = await get_args_from_nodriver(cls.url, proxy, timeout, cookies)
84
80
else:
85
81
cls._args = {"headers": DEFAULT_HEADERS, "cookies": {}}
@@ -56,13 +56,16 @@ class GizAI(AsyncGeneratorProvider, ProviderModelMixin):
56
56
'sec-ch-ua-platform': '"Linux"'
57
57
}
58
58
59
prompt = format_prompt(messages)
60
61
59
async with ClientSession(headers=headers) as session:
62
60
data = {
63
61
"model": model,
64
62
"input": {
65
"messages": [{"type": "human", "content": prompt}],
63
"messages": [
64
{"content": message.get("content")}
65
if message.get("role") == "system" else
66
{"type": "human" if message.get("role") == "user" else "ai", "content": message.get("content")}
67
for message in messages
68
],
66
69
"mode": "plan"
67
70
},
68
71
"noStream": True
@@ -72,4 +75,4 @@ class GizAI(AsyncGeneratorProvider, ProviderModelMixin):
72
75
result = await response.json()
73
76
yield result['output'].strip()
74
77
else:
75
raise Exception(f"Unexpected response status: {response.status}")
78
raise Exception(f"Unexpected response status: {response.status}\n{await response.text()}")
@@ -1,24 +1,13 @@
1
1
from __future__ import annotations
2
import json
3
from aiohttp import ClientSession
4
2
5
from ..typing import AsyncResult, Messages
6
from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
7
from ..requests.raise_for_status import raise_for_status
8
from ..providers.response import FinishReason
9
from .helper import format_prompt
3
from .template import OpenaiTemplate
10
4
11
class Glider(AsyncGeneratorProvider, ProviderModelMixin):
5
class Glider(OpenaiTemplate):
12
6
label = "Glider"
13
7
url = "https://glider.so"
14
8
api_endpoint = "https://glider.so/api/chat"
15
16
9
working = True
17
needs_auth = False
18
supports_stream = True
19
supports_system_message = True
20
supports_message_history = True
21
10
22
11
default_model = 'chat-llama-3-1-70b'
23
12
models = [
24
13
'chat-llama-3-1-70b',
@@ -26,70 +15,10 @@ class Glider(AsyncGeneratorProvider, ProviderModelMixin):
26
15
'chat-llama-3-2-3b',
27
16
'deepseek-ai/DeepSeek-R1'
28
17
]
29
18
30
19
model_aliases = {
31
20
"llama-3.1-70b": "chat-llama-3-1-70b",
32
21
"llama-3.1-8b": "chat-llama-3-1-8b",
33
22
"llama-3.2-3b": "chat-llama-3-2-3b",
34
23
"deepseek-r1": "deepseek-ai/DeepSeek-R1",
35
}
36
37
@classmethod
38
async def create_async_generator(
39
cls,
40
model: str,
41
messages: Messages,
42
proxy: str = None,
43
**kwargs
44
) -> AsyncResult:
45
model = cls.get_model(model)
46
47
headers = {
48
"accept": "*/*",
49
"accept-language": "en-US,en;q=0.9",
50
"content-type": "application/json",
51
"origin": cls.url,
52
"referer": f"{cls.url}/",
53
"user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"
54
}
55
56
async with ClientSession(headers=headers) as session:
57
data = {
58
"messages": [{
59
"role": "user",
60
"content": format_prompt(messages),
61
"id": "",
62
"chatId": "",
63
"createdOn": "",
64
"model": None
65
}],
66
"model": model
67
}
68
69
async with session.post(cls.api_endpoint, json=data, proxy=proxy) as response:
70
await raise_for_status(response)
71
72
async for chunk in response.content:
73
if not chunk:
74
continue
75
76
text = chunk.decode(errors="ignore")
77
78
if not text.startswith("data: "):
79
continue
80
81
if "[DONE]" in text:
82
yield FinishReason("stop")
83
return
84
85
try:
86
json_data = json.loads(text[6:])
87
content = json_data["choices"][0].get("delta", {}).get("content", "")
88
if content:
89
yield content
90
91
except json.JSONDecodeError:
92
continue
93
except Exception:
94
yield FinishReason("error")
95
return
24
}
@@ -6,13 +6,11 @@ from aiohttp import ClientSession
6
6
from ..typing import AsyncResult, Messages
7
7
from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
8
8
from ..requests.raise_for_status import raise_for_status
9
from .helper import format_prompt
10
9
from .helper import format_prompt, get_system_prompt
11
10
12
11
class Goabror(AsyncGeneratorProvider, ProviderModelMixin):
13
12
url = "https://goabror.uz"
14
13
api_endpoint = "https://goabror.uz/api/gpt.php"
15
16
14
working = True
17
15
18
16
default_model = 'gpt-4'
@@ -31,10 +29,10 @@ class Goabror(AsyncGeneratorProvider, ProviderModelMixin):
31
29
'accept-language': 'en-US,en;q=0.9',
32
30
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36'
33
31
}
34
35
32
async with ClientSession(headers=headers) as session:
36
33
params = {
37
"user": format_prompt(messages)
34
"user": format_prompt(messages, include_system=False),
35
"system": get_system_prompt(messages),
38
36
}
39
37
async with session.get(f"{cls.api_endpoint}", params=params, proxy=proxy) as response:
40
38
await raise_for_status(response)
@@ -1,26 +1,20 @@
1
1
from __future__ import annotations
2
2
3
import json
4
import re
5
import uuid
6
from aiohttp import ClientSession, FormData
3
from .hf.HuggingChat import HuggingChat
7
4
8
from ..typing import AsyncResult, Messages
9
from ..requests import raise_for_status
10
from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
11
from .helper import format_prompt, get_last_user_message
12
from ..providers.response import JsonConversation, TitleGeneration, Reasoning
13
14
class LambdaChat(AsyncGeneratorProvider, ProviderModelMixin):
5
class LambdaChat(HuggingChat):
15
6
label = "Lambda Chat"
16
url = "https://lambda.chat"
17
conversation_url = f"{url}/conversation"
18
7
domain = "lambda.chat"
8
origin = f"https://{domain}"
9
url = origin
19
10
working = True
11
use_nodriver = False
12
needs_auth = False
20
13
21
14
default_model = "deepseek-llama3.3-70b"
22
15
reasoning_model = "deepseek-r1"
23
models = [
16
image_models = []
17
fallback_models = [
24
18
default_model,
25
19
reasoning_model,
26
20
"hermes-3-llama-3.1-405b-fp8",
@@ -35,146 +29,4 @@ class LambdaChat(AsyncGeneratorProvider, ProviderModelMixin):
35
29
"hermes-3": "hermes3-405b-fp8-128k",
36
30
"nemotron-70b": "llama3.1-nemotron-70b-instruct",
37
31
"llama-3.3-70b": "llama3.3-70b-instruct-fp8"
38
}
39
40
@classmethod
41
async def create_async_generator(
42
cls, model: str, messages: Messages,
43
api_key: str = None,
44
proxy: str = None,
45
cookies: dict = None,
46
**kwargs
47
) -> AsyncResult:
48
model = cls.get_model(model)
49
headers = {
50
"Origin": cls.url,
51
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
52
"Accept": "*/*",
53
"Accept-Language": "en-US,en;q=0.9",
54
"Referer": cls.url,
55
"Sec-Fetch-Dest": "empty",
56
"Sec-Fetch-Mode": "cors",
57
"Sec-Fetch-Site": "same-origin",
58
"Priority": "u=1, i",
59
"Pragma": "no-cache",
60
"Cache-Control": "no-cache"
61
}
62
63
# Initialize cookies if not provided
64
if cookies is None:
65
cookies = {
66
"hf-chat": str(uuid.uuid4()) # Generate a session ID
67
}
68
69
async with ClientSession(headers=headers, cookies=cookies) as session:
70
# Step 1: Create a new conversation
71
data = {"model": model}
72
async with session.post(cls.conversation_url, json=data, proxy=proxy) as response:
73
await raise_for_status(response)
74
conversation_response = await response.json()
75
conversation_id = conversation_response["conversationId"]
76
77
# Update cookies with any new ones from the response
78
for cookie_name, cookie in response.cookies.items():
79
cookies[cookie_name] = cookie.value
80
81
# Step 2: Get data for this conversation to extract message ID
82
async with session.get(
83
f"{cls.conversation_url}/{conversation_id}/__data.json?x-sveltekit-invalidated=11",
84
proxy=proxy
85
) as response:
86
await raise_for_status(response)
87
response_text = await response.text()
88
89
# Update cookies again
90
for cookie_name, cookie in response.cookies.items():
91
cookies[cookie_name] = cookie.value
92
93
try:
94
data_line = response_text.splitlines()[0]
95
data_json = json.loads(data_line)
96
97
# Navigate to the data section containing message info
98
message_id = None
99
100
# For debugging, print the JSON structure
101
if "nodes" in data_json and len(data_json["nodes"]) > 1:
102
node = data_json["nodes"][1]
103
if "data" in node:
104
data = node["data"]
105
106
# Try to find the system message ID
107
if len(data) > 1 and isinstance(data[1], list) and len(data[1]) > 2:
108
for item in data[1]:
109
if isinstance(item, dict) and "id" in item:
110
# Found a potential message ID
111
message_id = item["id"]
112
break
113
114
if not message_id:
115
# Fallback: Just search for any UUID in the response
116
uuid_pattern = r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
117
uuids = re.findall(uuid_pattern, response_text)
118
if uuids:
119
message_id = uuids[0]
120
121
if not message_id:
122
raise ValueError("Could not find message ID in response")
123
124
except (IndexError, KeyError, ValueError, json.JSONDecodeError) as e:
125
raise RuntimeError(f"Failed to parse conversation data: {str(e)}")
126
127
# Step 3: Send the user message
128
user_message = get_last_user_message(messages)
129
130
# Prepare form data exactly
131
form_data = FormData()
132
form_data.add_field(
133
"data",
134
json.dumps({
135
"inputs": user_message,
136
"id": message_id,
137
"is_retry": False,
138
"is_continue": False,
139
"web_search": False,
140
"tools": []
141
}),
142
content_type="application/json"
143
)
144
145
async with session.post(
146
f"{cls.conversation_url}/{conversation_id}",
147
data=form_data,
148
proxy=proxy
149
) as response:
150
await raise_for_status(response)
151
152
async for chunk in response.content:
153
if not chunk:
154
continue
155
156
chunk_str = chunk.decode('utf-8', errors='ignore')
157
158
try:
159
data = json.loads(chunk_str)
160
except json.JSONDecodeError:
161
continue
162
163
# Handling different types of responses
164
if data.get("type") == "stream" and "token" in data:
165
token = data["token"].replace("\u0000", "")
166
if token:
167
yield token
168
elif data.get("type") == "title":
169
yield TitleGeneration(data.get("title", ""))
170
elif data.get("type") == "reasoning" and model == cls.reasoning_model: # Only process reasoning for reasoning_model
171
subtype = data.get("subtype")
172
token = data.get("token", "").replace("\u0000", "")
173
status = data.get("status", "")
174
175
if subtype == "stream" and token:
176
yield Reasoning(token=token)
177
elif subtype == "status" and status:
178
yield Reasoning(status=status)
179
elif data.get("type") == "finalAnswer":
180
break
32
}
@@ -14,7 +14,7 @@ WS_URL = "wss://www.perplexity.ai/socket.io/"
14
14
15
15
class PerplexityLabs(AsyncGeneratorProvider, ProviderModelMixin):
16
16
url = "https://labs.perplexity.ai"
17
working = True
17
working = False
18
18
19
19
default_model = "r1-1776"
20
20
models = [
@@ -1,85 +1,17 @@
1
1
from __future__ import annotations
2
import json
3
from aiohttp import ClientSession
4
2
5
from ..typing import AsyncResult, Messages
6
from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
7
from ..requests.raise_for_status import raise_for_status
8
from ..providers.response import FinishReason
9
from .helper import format_prompt
3
from .template import OpenaiTemplate
10
4
11
class TypeGPT(AsyncGeneratorProvider, ProviderModelMixin):
5
class TypeGPT(OpenaiTemplate):
12
6
label = "TypeGpt"
13
7
url = "https://chat.typegpt.net"
14
api_endpoint = "https://chat.typegpt.net/api/openai/v1/chat/completions"
15
8
api_endpoint = "https://chat.typegpt.net/api/openai/typegpt/v1/chat/completions"
16
9
working = True
17
supports_stream = True
18
supports_system_message = True
19
supports_message_history = True
20
10
21
default_model = 'o3-mini'
11
default_model = "gpt-4o-mini-2024-07-18"
22
12
models = [
23
default_model,"gemini-1.5-flash","deepseek-r1","gemini-pro",
13
default_model, "o1", "o3-mini", "gemini-1.5-flash", "deepseek-r1", "deepseek-v3", "gemini-pro", "evil"
24
14
]
25
26
@classmethod
27
async def create_async_generator(
28
cls,
29
model: str,
30
messages: Messages,
31
proxy: str = None,
32
**kwargs
33
) -> AsyncResult:
34
model = cls.get_model(model)
35
36
headers = {
37
"accept": "application/json, text/event-stream",
38
"accept-language": "en-US,en;q=0.9",
39
"content-type": "application/json",
40
"origin": cls.url,
41
"referer": f"{cls.url}/",
42
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36"
43
}
44
45
# Prepare the prompt from messages; adjust as needed.
46
prompt = format_prompt(messages)
47
data = {
48
"messages": [{"role": "user", "content": prompt}],
49
"stream": True,
50
"model": model,
51
"temperature": 0.5,
52
"presence_penalty": 0,
53
"frequency_penalty": 0,
54
"top_p": 1
55
}
56
57
async with ClientSession(headers=headers) as session:
58
async with session.post(cls.api_endpoint, json=data, proxy=proxy) as response:
59
await raise_for_status(response)
60
61
async for chunk in response.content:
62
if not chunk:
63
continue
64
65
text = chunk.decode(errors="ignore")
66
67
# The stream returns lines prefixed with "data: "
68
if not text.startswith("data: "):
69
continue
70
71
# Check for finish signal in the stream
72
if "[DONE]" in text:
73
yield FinishReason("stop")
74
return
75
76
try:
77
json_data = json.loads(text[6:])
78
content = json_data["choices"][0].get("delta", {}).get("content", "")
79
if content:
80
yield content
81
except json.JSONDecodeError:
82
continue
83
except Exception:
84
yield FinishReason("error")
85
return
15
model_aliases = {
16
"gpt-4o-mini": "gpt-4o-mini-2024-07-18",
17
}
@@ -5,6 +5,7 @@ import re
5
5
import os
6
6
import requests
7
7
import base64
8
import uuid
8
9
from typing import AsyncIterator
9
10
10
11
try:
@@ -31,7 +32,9 @@ class Conversation(JsonConversation):
31
32
self.models: dict = models
32
33
33
34
class HuggingChat(AsyncAuthedProvider, ProviderModelMixin):
34
url = "https://huggingface.co/chat"
35
domain = "huggingface.co"
36
origin = f"https://{domain}"
37
url = f"{origin}/chat"
35
38
36
39
working = True
37
40
use_nodriver = True
@@ -65,7 +68,7 @@ class HuggingChat(AsyncAuthedProvider, ProviderModelMixin):
65
68
@classmethod
66
69
async def on_auth_async(cls, cookies: Cookies = None, proxy: str = None, **kwargs) -> AsyncIterator:
67
70
if cookies is None:
68
cookies = get_cookies("huggingface.co", single_browser=True)
71
cookies = get_cookies(cls.domain, single_browser=True)
69
72
if "hf-chat" in cookies:
70
73
yield AuthResult(
71
74
cookies=cookies,
@@ -73,14 +76,21 @@ class HuggingChat(AsyncAuthedProvider, ProviderModelMixin):
73
76
headers=DEFAULT_HEADERS
74
77
)
75
78
return
76
yield RequestLogin(cls.__name__, os.environ.get("G4F_LOGIN_URL") or "")
77
yield AuthResult(
78
**await get_args_from_nodriver(
79
cls.url,
80
proxy=proxy,
81
wait_for='form[action="/chat/logout"]'
79
if cls.needs_auth:
80
yield RequestLogin(cls.__name__, os.environ.get("G4F_LOGIN_URL") or "")
81
yield AuthResult(
82
**await get_args_from_nodriver(
83
cls.url,
84
proxy=proxy,
85
wait_for='form[action$="/logout"]'
86
)
87
)
88
else:
89
yield AuthResult(
90
cookies = {
91
"hf-chat": str(uuid.uuid4()) # Generate a session ID
92
}
82
93
)
83
)
84
94
85
95
@classmethod
86
96
async def create_authed(
@@ -130,8 +140,8 @@ class HuggingChat(AsyncAuthedProvider, ProviderModelMixin):
130
140
131
141
headers = {
132
142
'accept': '*/*',
133
'origin': 'https://huggingface.co',
134
'referer': f'https://huggingface.co/chat/conversation/{conversationId}',
143
'origin': cls.origin,
144
'referer': f'{cls.url}/conversation/{conversationId}',
135
145
}
136
146
data = CurlMime()
137
147
data.addpart('data', data=json.dumps(settings, separators=(',', ':')))
@@ -144,7 +154,7 @@ class HuggingChat(AsyncAuthedProvider, ProviderModelMixin):
144
154
)
145
155
146
156
response = session.post(
147
f'https://huggingface.co/chat/conversation/{conversationId}',
157
f'{cls.url}/conversation/{conversationId}',
148
158
headers=headers,
149
159
multipart=data,
150
160
stream=True
@@ -167,7 +177,7 @@ class HuggingChat(AsyncAuthedProvider, ProviderModelMixin):
167
177
elif line["type"] == "finalAnswer":
168
178
break
169
179
elif line["type"] == "file":
170
url = f"https://huggingface.co/chat/conversation/{conversationId}/output/{line['sha']}"
180
url = f"{cls.url}/conversation/{conversationId}/output/{line['sha']}"
171
181
yield ImageResponse(url, format_image_prompt(messages, prompt), options={"cookies": auth_result.cookies})
172
182
elif line["type"] == "webSearch" and "sources" in line:
173
183
sources = Sources(line["sources"])
@@ -186,7 +196,7 @@ class HuggingChat(AsyncAuthedProvider, ProviderModelMixin):
186
196
json_data = {
187
197
'model': model,
188
198
}
189
response = session.post('https://huggingface.co/chat/conversation', json=json_data)
199
response = session.post(f'{cls.url}/conversation', json=json_data)
190
200
if response.status_code == 401:
191
201
raise MissingAuthError(response.text)
192
202
if response.status_code == 400:
@@ -197,7 +207,7 @@ class HuggingChat(AsyncAuthedProvider, ProviderModelMixin):
197
207
@classmethod
198
208
def fetch_message_id(cls, session: Session, conversation_id: str):
199
209
# Get the data response and parse it properly
200
response = session.get(f'https://huggingface.co/chat/conversation/{conversation_id}/__data.json?x-sveltekit-invalidated=11')
210
response = session.get(f'{cls.url}/conversation/{conversation_id}/__data.json?x-sveltekit-invalidated=11')
201
211
raise_for_status(response)
202
212
203
213
# Split the response content by newlines and parse each line as JSON
@@ -266,13 +266,10 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
266
266
proxy: str = None,
267
267
timeout: int = 180,
268
268
auto_continue: bool = False,
269
history_disabled: bool = False,
270
269
action: str = "next",
271
conversation_id: str = None,
272
270
conversation: Conversation = None,
273
271
images: ImagesType = None,
274
272
return_conversation: bool = False,
275
max_retries: int = 0,
276
273
web_search: bool = False,
277
274
**kwargs
278
275
) -> AsyncResult:
@@ -286,7 +283,6 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
286
283
timeout (int): Timeout for requests.
287
284
api_key (str): Access token for authentication.
288
285
auto_continue (bool): Flag to automatically continue the conversation.
289
history_disabled (bool): Flag to disable history and training.
290
286
action (str): Type of action ('next', 'continue', 'variant').
291
287
conversation_id (str): ID of the conversation.
292
288
images (ImagesType): Images to include in the conversation.
@@ -326,7 +322,7 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
326
322
debug.error(e)
327
323
model = cls.get_model(model)
328
324
if conversation is None:
329
conversation = Conversation(conversation_id, str(uuid.uuid4()), getattr(auth_result, "cookies", {}).get("oai-did"))
325
conversation = Conversation(None, str(uuid.uuid4()), getattr(auth_result, "cookies", {}).get("oai-did"))
330
326
else:
331
327
conversation = copy(conversation)
332
328
if getattr(auth_result, "cookies", {}).get("oai-did") != getattr(conversation, "user_id", None):
@@ -382,21 +378,13 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
382
378
"model": model,
383
379
"timezone_offset_min":-60,
384
380
"timezone":"Europe/Berlin",
385
"suggestions":[],
386
"history_and_training_disabled": history_disabled and not auto_continue and not return_conversation or not cls.needs_auth,
387
"conversation_mode":{"kind":"primary_assistant","plugin_ids":None},
388
"force_paragen":False,
389
"force_paragen_model_slug":"",
390
"force_rate_limit":False,
391
"reset_rate_limits":False,
392
"websocket_request_id": str(uuid.uuid4()),
381
"conversation_mode":{"kind":"primary_assistant"},
382
"enable_message_followups":True,
393
383
"system_hints": ["search"] if web_search else None,
384
"supports_buffering":True,
394
385
"supported_encodings":["v1"],
395
"conversation_origin":None,
396
386
"client_contextual_info":{"is_dark_mode":False,"time_since_loaded":random.randint(20, 500),"page_height":578,"page_width":1850,"pixel_ratio":1,"screen_height":1080,"screen_width":1920},
397
"paragen_stream_type_override":None,
398
"paragen_cot_summary_display_override":"allow",
399
"supports_buffering":True
387
"paragen_cot_summary_display_override":"allow"
400
388
}
401
389
if conversation.conversation_id is not None:
402
390
data["conversation_id"] = conversation.conversation_id
@@ -404,7 +392,7 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
404
392
if action != "continue":
405
393
data["parent_message_id"] = getattr(conversation, "parent_message_id", conversation.message_id)
406
394
conversation.parent_message_id = None
407
messages = messages if conversation_id is None else [{"role": "user", "content": get_last_user_message(messages)}]
395
messages = messages if conversation.conversation_id is None else [{"role": "user", "content": get_last_user_message(messages)}]
408
396
data["messages"] = cls.create_messages(messages, image_requests, ["search"] if web_search else None)
409
397
headers = {
410
398
**cls._headers,
@@ -458,7 +446,7 @@ class OpenaiChat(AsyncAuthedProvider, ProviderModelMixin):
458
446
yield sources
459
447
if return_conversation:
460
448
yield conversation
461
if not history_disabled and auth_result.api_key is not None:
449
if auth_result.api_key is not None:
462
450
yield SynthesizeData(cls.__name__, {
463
451
"conversation_id": conversation.conversation_id,
464
452
"message_id": conversation.message_id,