webscout 8.0__py3-none-any.whl → 8.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of webscout might be problematic. Click here for more details.
- webscout/Provider/AISEARCH/DeepFind.py +1 -1
- webscout/Provider/AISEARCH/ISou.py +1 -1
- webscout/Provider/AISEARCH/__init__.py +2 -1
- webscout/Provider/AISEARCH/felo_search.py +1 -1
- webscout/Provider/AISEARCH/genspark_search.py +1 -1
- webscout/Provider/AISEARCH/hika_search.py +1 -1
- webscout/Provider/AISEARCH/iask_search.py +436 -0
- webscout/Provider/AISEARCH/scira_search.py +1 -1
- webscout/Provider/AISEARCH/webpilotai_search.py +1 -1
- webscout/Provider/ExaAI.py +1 -1
- webscout/Provider/Jadve.py +2 -2
- webscout/Provider/OPENAI/__init__.py +17 -0
- webscout/Provider/OPENAI/base.py +46 -0
- webscout/Provider/OPENAI/c4ai.py +347 -0
- webscout/Provider/OPENAI/chatgptclone.py +460 -0
- webscout/Provider/OPENAI/deepinfra.py +284 -0
- webscout/Provider/OPENAI/exaai.py +419 -0
- webscout/Provider/OPENAI/exachat.py +421 -0
- webscout/Provider/OPENAI/freeaichat.py +355 -0
- webscout/Provider/OPENAI/glider.py +314 -0
- webscout/Provider/OPENAI/heckai.py +337 -0
- webscout/Provider/OPENAI/llmchatco.py +325 -0
- webscout/Provider/OPENAI/netwrck.py +348 -0
- webscout/Provider/OPENAI/scirachat.py +459 -0
- webscout/Provider/OPENAI/sonus.py +294 -0
- webscout/Provider/OPENAI/typegpt.py +361 -0
- webscout/Provider/OPENAI/utils.py +211 -0
- webscout/Provider/OPENAI/venice.py +428 -0
- webscout/Provider/OPENAI/wisecat.py +381 -0
- webscout/Provider/OPENAI/x0gpt.py +389 -0
- webscout/Provider/OPENAI/yep.py +329 -0
- webscout/Provider/Venice.py +1 -1
- webscout/Provider/__init__.py +6 -6
- webscout/Provider/scira_chat.py +13 -10
- webscout/Provider/typegpt.py +3 -184
- webscout/prompt_manager.py +2 -1
- webscout/version.py +1 -1
- webscout-8.1.dist-info/METADATA +683 -0
- {webscout-8.0.dist-info → webscout-8.1.dist-info}/RECORD +43 -23
- webscout/Provider/flowith.py +0 -207
- webscout-8.0.dist-info/METADATA +0 -995
- {webscout-8.0.dist-info → webscout-8.1.dist-info}/LICENSE.md +0 -0
- {webscout-8.0.dist-info → webscout-8.1.dist-info}/WHEEL +0 -0
- {webscout-8.0.dist-info → webscout-8.1.dist-info}/entry_points.txt +0 -0
- {webscout-8.0.dist-info → webscout-8.1.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import uuid
|
|
3
|
+
import requests
|
|
4
|
+
import json
|
|
5
|
+
from typing import List, Dict, Optional, Union, Generator, Any
|
|
6
|
+
|
|
7
|
+
# Import base classes and utility structures
|
|
8
|
+
from .base import OpenAICompatibleProvider, BaseChat, BaseCompletions
|
|
9
|
+
from .utils import (
|
|
10
|
+
ChatCompletionChunk, ChatCompletion, Choice, ChoiceDelta,
|
|
11
|
+
ChatCompletionMessage, CompletionUsage
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
# Attempt to import LitAgent, fallback if not available
|
|
15
|
+
try:
|
|
16
|
+
from webscout.litagent import LitAgent
|
|
17
|
+
except ImportError:
|
|
18
|
+
# Define a dummy LitAgent if webscout is not installed or accessible
|
|
19
|
+
class LitAgent:
|
|
20
|
+
def random(self) -> str:
|
|
21
|
+
return "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36"
|
|
22
|
+
|
|
23
|
+
# --- FreeAIChat Client ---
|
|
24
|
+
|
|
25
|
+
class Completions(BaseCompletions):
|
|
26
|
+
def __init__(self, client: 'FreeAIChat'):
|
|
27
|
+
self._client = client
|
|
28
|
+
|
|
29
|
+
def create(
|
|
30
|
+
self,
|
|
31
|
+
*,
|
|
32
|
+
model: str,
|
|
33
|
+
messages: List[Dict[str, str]],
|
|
34
|
+
max_tokens: Optional[int] = 2049,
|
|
35
|
+
stream: bool = False,
|
|
36
|
+
temperature: Optional[float] = None,
|
|
37
|
+
top_p: Optional[float] = None,
|
|
38
|
+
**kwargs: Any
|
|
39
|
+
) -> Union[ChatCompletion, Generator[ChatCompletionChunk, None, None]]:
|
|
40
|
+
"""
|
|
41
|
+
Creates a model response for the given chat conversation.
|
|
42
|
+
Mimics openai.chat.completions.create
|
|
43
|
+
"""
|
|
44
|
+
payload = {
|
|
45
|
+
"model": model,
|
|
46
|
+
"messages": messages,
|
|
47
|
+
"max_tokens": max_tokens,
|
|
48
|
+
"stream": stream,
|
|
49
|
+
}
|
|
50
|
+
if temperature is not None:
|
|
51
|
+
payload["temperature"] = temperature
|
|
52
|
+
if top_p is not None:
|
|
53
|
+
payload["top_p"] = top_p
|
|
54
|
+
|
|
55
|
+
payload.update(kwargs)
|
|
56
|
+
|
|
57
|
+
request_id = f"chatcmpl-{uuid.uuid4()}"
|
|
58
|
+
created_time = int(time.time())
|
|
59
|
+
|
|
60
|
+
if stream:
|
|
61
|
+
return self._create_stream(request_id, created_time, model, payload)
|
|
62
|
+
else:
|
|
63
|
+
return self._create_non_stream(request_id, created_time, model, payload)
|
|
64
|
+
|
|
65
|
+
def _create_stream(
|
|
66
|
+
self, request_id: str, created_time: int, model: str, payload: Dict[str, Any]
|
|
67
|
+
) -> Generator[ChatCompletionChunk, None, None]:
|
|
68
|
+
try:
|
|
69
|
+
response = self._client.session.post(
|
|
70
|
+
self._client.api_endpoint,
|
|
71
|
+
headers=self._client.headers,
|
|
72
|
+
json=payload,
|
|
73
|
+
stream=True,
|
|
74
|
+
timeout=self._client.timeout
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
# Handle non-200 responses
|
|
78
|
+
if not response.ok:
|
|
79
|
+
raise IOError(
|
|
80
|
+
f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
# Track token usage across chunks
|
|
84
|
+
prompt_tokens = 0
|
|
85
|
+
completion_tokens = 0
|
|
86
|
+
total_tokens = 0
|
|
87
|
+
|
|
88
|
+
# Estimate prompt tokens based on message length
|
|
89
|
+
for msg in payload.get("messages", []):
|
|
90
|
+
prompt_tokens += len(msg.get("content", "").split())
|
|
91
|
+
|
|
92
|
+
for line in response.iter_lines():
|
|
93
|
+
if not line:
|
|
94
|
+
continue
|
|
95
|
+
|
|
96
|
+
line_str = line.decode('utf-8').strip()
|
|
97
|
+
|
|
98
|
+
if line_str.startswith("data: "):
|
|
99
|
+
json_str = line_str[6:] # Remove "data: " prefix
|
|
100
|
+
if json_str == "[DONE]":
|
|
101
|
+
break
|
|
102
|
+
|
|
103
|
+
try:
|
|
104
|
+
data = json.loads(json_str)
|
|
105
|
+
choice_data = data.get('choices', [{}])[0]
|
|
106
|
+
delta_data = choice_data.get('delta', {})
|
|
107
|
+
finish_reason = choice_data.get('finish_reason')
|
|
108
|
+
|
|
109
|
+
# Update token counts if available
|
|
110
|
+
usage_data = data.get('usage', {})
|
|
111
|
+
if usage_data:
|
|
112
|
+
prompt_tokens = usage_data.get('prompt_tokens', prompt_tokens)
|
|
113
|
+
completion_tokens = usage_data.get('completion_tokens', completion_tokens)
|
|
114
|
+
total_tokens = usage_data.get('total_tokens', total_tokens)
|
|
115
|
+
|
|
116
|
+
# Create the delta object
|
|
117
|
+
delta = ChoiceDelta(
|
|
118
|
+
content=delta_data.get('content'),
|
|
119
|
+
role=delta_data.get('role'),
|
|
120
|
+
tool_calls=delta_data.get('tool_calls')
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
# Create the choice object
|
|
124
|
+
choice = Choice(
|
|
125
|
+
index=choice_data.get('index', 0),
|
|
126
|
+
delta=delta,
|
|
127
|
+
finish_reason=finish_reason,
|
|
128
|
+
logprobs=choice_data.get('logprobs')
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
# Create the chunk object
|
|
132
|
+
chunk = ChatCompletionChunk(
|
|
133
|
+
id=request_id,
|
|
134
|
+
choices=[choice],
|
|
135
|
+
created=created_time,
|
|
136
|
+
model=model,
|
|
137
|
+
system_fingerprint=data.get('system_fingerprint')
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
# Return the chunk object
|
|
141
|
+
yield chunk
|
|
142
|
+
except json.JSONDecodeError:
|
|
143
|
+
print(f"Warning: Could not decode JSON line: {json_str}")
|
|
144
|
+
continue
|
|
145
|
+
|
|
146
|
+
# Final chunk with finish_reason="stop"
|
|
147
|
+
delta = ChoiceDelta(
|
|
148
|
+
content=None,
|
|
149
|
+
role=None,
|
|
150
|
+
tool_calls=None
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
choice = Choice(
|
|
154
|
+
index=0,
|
|
155
|
+
delta=delta,
|
|
156
|
+
finish_reason="stop",
|
|
157
|
+
logprobs=None
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
chunk = ChatCompletionChunk(
|
|
161
|
+
id=request_id,
|
|
162
|
+
choices=[choice],
|
|
163
|
+
created=created_time,
|
|
164
|
+
model=model,
|
|
165
|
+
system_fingerprint=None
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
yield chunk
|
|
169
|
+
|
|
170
|
+
except Exception as e:
|
|
171
|
+
print(f"Error during FreeAIChat stream request: {e}")
|
|
172
|
+
raise IOError(f"FreeAIChat request failed: {e}") from e
|
|
173
|
+
|
|
174
|
+
def _create_non_stream(
|
|
175
|
+
self, request_id: str, created_time: int, model: str, payload: Dict[str, Any]
|
|
176
|
+
) -> ChatCompletion:
|
|
177
|
+
try:
|
|
178
|
+
response = self._client.session.post(
|
|
179
|
+
self._client.api_endpoint,
|
|
180
|
+
headers=self._client.headers,
|
|
181
|
+
json=payload,
|
|
182
|
+
timeout=self._client.timeout
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
# Handle non-200 responses
|
|
186
|
+
if not response.ok:
|
|
187
|
+
raise IOError(
|
|
188
|
+
f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
# Parse the response
|
|
192
|
+
data = response.json()
|
|
193
|
+
|
|
194
|
+
choices_data = data.get('choices', [])
|
|
195
|
+
usage_data = data.get('usage', {})
|
|
196
|
+
|
|
197
|
+
choices = []
|
|
198
|
+
for choice_d in choices_data:
|
|
199
|
+
message_d = choice_d.get('message', {})
|
|
200
|
+
message = ChatCompletionMessage(
|
|
201
|
+
role=message_d.get('role', 'assistant'),
|
|
202
|
+
content=message_d.get('content', '')
|
|
203
|
+
)
|
|
204
|
+
choice = Choice(
|
|
205
|
+
index=choice_d.get('index', 0),
|
|
206
|
+
message=message,
|
|
207
|
+
finish_reason=choice_d.get('finish_reason', 'stop')
|
|
208
|
+
)
|
|
209
|
+
choices.append(choice)
|
|
210
|
+
|
|
211
|
+
usage = CompletionUsage(
|
|
212
|
+
prompt_tokens=usage_data.get('prompt_tokens', 0),
|
|
213
|
+
completion_tokens=usage_data.get('completion_tokens', 0),
|
|
214
|
+
total_tokens=usage_data.get('total_tokens', 0)
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
completion = ChatCompletion(
|
|
218
|
+
id=request_id,
|
|
219
|
+
choices=choices,
|
|
220
|
+
created=created_time,
|
|
221
|
+
model=data.get('model', model),
|
|
222
|
+
usage=usage,
|
|
223
|
+
)
|
|
224
|
+
return completion
|
|
225
|
+
|
|
226
|
+
except Exception as e:
|
|
227
|
+
print(f"Error during FreeAIChat non-stream request: {e}")
|
|
228
|
+
raise IOError(f"FreeAIChat request failed: {e}") from e
|
|
229
|
+
|
|
230
|
+
class Chat(BaseChat):
|
|
231
|
+
def __init__(self, client: 'FreeAIChat'):
|
|
232
|
+
self.completions = Completions(client)
|
|
233
|
+
|
|
234
|
+
class FreeAIChat(OpenAICompatibleProvider):
|
|
235
|
+
"""
|
|
236
|
+
OpenAI-compatible client for FreeAIChat API.
|
|
237
|
+
|
|
238
|
+
Usage:
|
|
239
|
+
client = FreeAIChat()
|
|
240
|
+
response = client.chat.completions.create(
|
|
241
|
+
model="GPT 4o",
|
|
242
|
+
messages=[{"role": "user", "content": "Hello!"}]
|
|
243
|
+
)
|
|
244
|
+
"""
|
|
245
|
+
|
|
246
|
+
AVAILABLE_MODELS = [
|
|
247
|
+
# OpenAI Models
|
|
248
|
+
"GPT 4o",
|
|
249
|
+
"GPT 4.5 Preview",
|
|
250
|
+
"GPT 4o Latest",
|
|
251
|
+
"GPT 4o mini",
|
|
252
|
+
"GPT 4o Search Preview",
|
|
253
|
+
"O1",
|
|
254
|
+
"O1 Mini",
|
|
255
|
+
"O3 Mini",
|
|
256
|
+
"O3 Mini High",
|
|
257
|
+
"O3 Mini Low",
|
|
258
|
+
|
|
259
|
+
# Anthropic Models
|
|
260
|
+
"Claude 3.5 haiku",
|
|
261
|
+
"claude 3.5 sonnet",
|
|
262
|
+
"Claude 3.7 Sonnet",
|
|
263
|
+
"Claude 3.7 Sonnet (Thinking)",
|
|
264
|
+
|
|
265
|
+
# Deepseek Models
|
|
266
|
+
"Deepseek R1",
|
|
267
|
+
"Deepseek R1 Fast",
|
|
268
|
+
"Deepseek V3",
|
|
269
|
+
"Deepseek v3 0324",
|
|
270
|
+
|
|
271
|
+
# Google Models
|
|
272
|
+
"Gemini 1.5 Flash",
|
|
273
|
+
"Gemini 1.5 Pro",
|
|
274
|
+
"Gemini 2.0 Flash",
|
|
275
|
+
"Gemini 2.0 Pro",
|
|
276
|
+
"Gemini 2.5 Pro",
|
|
277
|
+
|
|
278
|
+
# Llama Models
|
|
279
|
+
"Llama 3.1 405B",
|
|
280
|
+
"Llama 3.1 70B Fast",
|
|
281
|
+
"Llama 3.3 70B",
|
|
282
|
+
"Llama 3.2 90B Vision",
|
|
283
|
+
"Llama 4 Scout",
|
|
284
|
+
"Llama 4 Maverick",
|
|
285
|
+
|
|
286
|
+
# Mistral Models
|
|
287
|
+
"Mistral Large",
|
|
288
|
+
"Mistral Nemo",
|
|
289
|
+
"Mixtral 8x22B",
|
|
290
|
+
|
|
291
|
+
# Qwen Models
|
|
292
|
+
"Qwen Max",
|
|
293
|
+
"Qwen Plus",
|
|
294
|
+
"Qwen Turbo",
|
|
295
|
+
"QwQ 32B",
|
|
296
|
+
"QwQ Plus",
|
|
297
|
+
|
|
298
|
+
# XAI Models
|
|
299
|
+
"Grok 2",
|
|
300
|
+
"Grok 3",
|
|
301
|
+
]
|
|
302
|
+
|
|
303
|
+
def __init__(
|
|
304
|
+
self,
|
|
305
|
+
timeout: Optional[int] = None,
|
|
306
|
+
browser: str = "chrome"
|
|
307
|
+
):
|
|
308
|
+
"""
|
|
309
|
+
Initialize the FreeAIChat client.
|
|
310
|
+
|
|
311
|
+
Args:
|
|
312
|
+
timeout: Request timeout in seconds (None for no timeout)
|
|
313
|
+
browser: Browser to emulate in user agent
|
|
314
|
+
"""
|
|
315
|
+
self.timeout = timeout
|
|
316
|
+
self.api_endpoint = "https://freeaichatplayground.com/api/v1/chat/completions"
|
|
317
|
+
self.session = requests.Session()
|
|
318
|
+
|
|
319
|
+
# Initialize LitAgent for user agent generation
|
|
320
|
+
agent = LitAgent()
|
|
321
|
+
self.fingerprint = agent.generate_fingerprint(browser)
|
|
322
|
+
|
|
323
|
+
# Initialize headers
|
|
324
|
+
self.headers = {
|
|
325
|
+
'User-Agent': self.fingerprint["user_agent"],
|
|
326
|
+
'Accept': '*/*',
|
|
327
|
+
'Content-Type': 'application/json',
|
|
328
|
+
'Origin': 'https://freeaichatplayground.com',
|
|
329
|
+
'Referer': 'https://freeaichatplayground.com/',
|
|
330
|
+
'Sec-Fetch-Mode': 'cors',
|
|
331
|
+
'Sec-Fetch-Site': 'same-origin'
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
self.session.headers.update(self.headers)
|
|
335
|
+
|
|
336
|
+
# Initialize the chat interface
|
|
337
|
+
self.chat = Chat(self)
|
|
338
|
+
|
|
339
|
+
def convert_model_name(self, model: str) -> str:
|
|
340
|
+
"""
|
|
341
|
+
Convert model names to ones supported by FreeAIChat.
|
|
342
|
+
|
|
343
|
+
Args:
|
|
344
|
+
model: Model name to convert
|
|
345
|
+
|
|
346
|
+
Returns:
|
|
347
|
+
FreeAIChat model name
|
|
348
|
+
"""
|
|
349
|
+
# If the model is already a valid FreeAIChat model, return it
|
|
350
|
+
if model in self.AVAILABLE_MODELS:
|
|
351
|
+
return model
|
|
352
|
+
|
|
353
|
+
# Default to GPT 4o if model not found
|
|
354
|
+
print(f"Warning: Unknown model '{model}'. Using 'GPT 4o' instead.")
|
|
355
|
+
return "GPT 4o"
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import requests
|
|
2
|
+
import json
|
|
3
|
+
import time
|
|
4
|
+
import uuid
|
|
5
|
+
from typing import List, Dict, Optional, Union, Generator, Any
|
|
6
|
+
|
|
7
|
+
# Import base classes and utility structures
|
|
8
|
+
from .base import OpenAICompatibleProvider, BaseChat, BaseCompletions
|
|
9
|
+
from .utils import (
|
|
10
|
+
ChatCompletionChunk, ChatCompletion, Choice, ChoiceDelta,
|
|
11
|
+
ChatCompletionMessage, CompletionUsage
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
# Attempt to import LitAgent, fallback if not available
|
|
15
|
+
try:
|
|
16
|
+
from webscout.litagent import LitAgent
|
|
17
|
+
except ImportError:
|
|
18
|
+
# Define a dummy LitAgent if webscout is not installed or accessible
|
|
19
|
+
class LitAgent:
|
|
20
|
+
def generate_fingerprint(self, browser: str = "chrome") -> Dict[str, Any]:
|
|
21
|
+
# Return minimal default headers if LitAgent is unavailable
|
|
22
|
+
print("Warning: LitAgent not found. Using default minimal headers.")
|
|
23
|
+
return {
|
|
24
|
+
"accept": "*/*",
|
|
25
|
+
"accept_language": "en-US,en;q=0.9",
|
|
26
|
+
"platform": "Windows",
|
|
27
|
+
"sec_ch_ua": '"Not/A)Brand";v="99", "Google Chrome";v="127", "Chromium";v="127"',
|
|
28
|
+
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
|
|
29
|
+
"browser_type": browser,
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
# --- Glider Client ---
|
|
33
|
+
|
|
34
|
+
class Completions(BaseCompletions):
|
|
35
|
+
def __init__(self, client: 'Glider'):
|
|
36
|
+
self._client = client
|
|
37
|
+
|
|
38
|
+
def create(
|
|
39
|
+
self,
|
|
40
|
+
*,
|
|
41
|
+
model: str,
|
|
42
|
+
messages: List[Dict[str, str]],
|
|
43
|
+
max_tokens: Optional[int] = 2049,
|
|
44
|
+
stream: bool = False,
|
|
45
|
+
temperature: Optional[float] = None,
|
|
46
|
+
top_p: Optional[float] = None,
|
|
47
|
+
**kwargs: Any
|
|
48
|
+
) -> Union[ChatCompletion, Generator[ChatCompletionChunk, None, None]]:
|
|
49
|
+
"""
|
|
50
|
+
Creates a model response for the given chat conversation.
|
|
51
|
+
Mimics openai.chat.completions.create
|
|
52
|
+
"""
|
|
53
|
+
# Prepare the payload for Glider API
|
|
54
|
+
payload = {
|
|
55
|
+
"messages": messages,
|
|
56
|
+
"model": self._client.convert_model_name(model),
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
# Add optional parameters if provided
|
|
60
|
+
if max_tokens is not None and max_tokens > 0:
|
|
61
|
+
payload["max_tokens"] = max_tokens
|
|
62
|
+
|
|
63
|
+
if temperature is not None:
|
|
64
|
+
payload["temperature"] = temperature
|
|
65
|
+
|
|
66
|
+
if top_p is not None:
|
|
67
|
+
payload["top_p"] = top_p
|
|
68
|
+
|
|
69
|
+
# Add any additional parameters
|
|
70
|
+
payload.update(kwargs)
|
|
71
|
+
|
|
72
|
+
request_id = f"chatcmpl-{uuid.uuid4()}"
|
|
73
|
+
created_time = int(time.time())
|
|
74
|
+
|
|
75
|
+
if stream:
|
|
76
|
+
return self._create_stream(request_id, created_time, model, payload)
|
|
77
|
+
else:
|
|
78
|
+
return self._create_non_stream(request_id, created_time, model, payload)
|
|
79
|
+
|
|
80
|
+
def _create_stream(
|
|
81
|
+
self, request_id: str, created_time: int, model: str, payload: Dict[str, Any]
|
|
82
|
+
) -> Generator[ChatCompletionChunk, None, None]:
|
|
83
|
+
try:
|
|
84
|
+
response = self._client.session.post(
|
|
85
|
+
self._client.api_endpoint,
|
|
86
|
+
headers=self._client.headers,
|
|
87
|
+
json=payload,
|
|
88
|
+
stream=True,
|
|
89
|
+
timeout=self._client.timeout
|
|
90
|
+
)
|
|
91
|
+
response.raise_for_status()
|
|
92
|
+
|
|
93
|
+
# Track token usage across chunks
|
|
94
|
+
prompt_tokens = 0
|
|
95
|
+
completion_tokens = 0
|
|
96
|
+
total_tokens = 0
|
|
97
|
+
|
|
98
|
+
for line in response.iter_lines():
|
|
99
|
+
if line:
|
|
100
|
+
decoded_line = line.decode('utf-8').strip()
|
|
101
|
+
|
|
102
|
+
if decoded_line.startswith("data: "):
|
|
103
|
+
json_str = decoded_line[6:]
|
|
104
|
+
if json_str == "[DONE]":
|
|
105
|
+
# Format the final [DONE] marker in OpenAI format
|
|
106
|
+
# print("data: [DONE]")
|
|
107
|
+
break
|
|
108
|
+
|
|
109
|
+
try:
|
|
110
|
+
data = json.loads(json_str)
|
|
111
|
+
choice_data = data.get('choices', [{}])[0]
|
|
112
|
+
delta_data = choice_data.get('delta', {})
|
|
113
|
+
finish_reason = choice_data.get('finish_reason')
|
|
114
|
+
|
|
115
|
+
# Update token counts if available
|
|
116
|
+
usage_data = data.get('usage', {})
|
|
117
|
+
if usage_data:
|
|
118
|
+
prompt_tokens = usage_data.get('prompt_tokens', prompt_tokens)
|
|
119
|
+
completion_tokens = usage_data.get('completion_tokens', completion_tokens)
|
|
120
|
+
total_tokens = usage_data.get('total_tokens', total_tokens)
|
|
121
|
+
|
|
122
|
+
# Create the delta object
|
|
123
|
+
delta = ChoiceDelta(
|
|
124
|
+
content=delta_data.get('content'),
|
|
125
|
+
role=delta_data.get('role'),
|
|
126
|
+
tool_calls=delta_data.get('tool_calls')
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
# Create the choice object
|
|
130
|
+
choice = Choice(
|
|
131
|
+
index=choice_data.get('index', 0),
|
|
132
|
+
delta=delta,
|
|
133
|
+
finish_reason=finish_reason,
|
|
134
|
+
logprobs=choice_data.get('logprobs')
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
# Create the chunk object
|
|
138
|
+
chunk = ChatCompletionChunk(
|
|
139
|
+
id=request_id,
|
|
140
|
+
choices=[choice],
|
|
141
|
+
created=created_time,
|
|
142
|
+
model=model,
|
|
143
|
+
system_fingerprint=data.get('system_fingerprint')
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
# Convert to dict for proper formatting
|
|
147
|
+
chunk_dict = chunk.to_dict()
|
|
148
|
+
|
|
149
|
+
# Add usage information to match OpenAI format
|
|
150
|
+
# Even if we don't have real token counts, include estimated usage
|
|
151
|
+
# This matches the format in the examples
|
|
152
|
+
usage_dict = {
|
|
153
|
+
"prompt_tokens": prompt_tokens or 10,
|
|
154
|
+
"completion_tokens": completion_tokens or (len(delta_data.get('content', '')) if delta_data.get('content') else 0),
|
|
155
|
+
"total_tokens": total_tokens or (10 + (len(delta_data.get('content', '')) if delta_data.get('content') else 0)),
|
|
156
|
+
"estimated_cost": None
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
# Update completion_tokens and total_tokens as we receive more content
|
|
160
|
+
if delta_data.get('content'):
|
|
161
|
+
completion_tokens += 1
|
|
162
|
+
total_tokens = prompt_tokens + completion_tokens
|
|
163
|
+
usage_dict["completion_tokens"] = completion_tokens
|
|
164
|
+
usage_dict["total_tokens"] = total_tokens
|
|
165
|
+
|
|
166
|
+
chunk_dict["usage"] = usage_dict
|
|
167
|
+
|
|
168
|
+
# Format the response in OpenAI format exactly as requested
|
|
169
|
+
# We need to print the raw string and also yield the chunk object
|
|
170
|
+
# This ensures both the console output and the returned object are correct
|
|
171
|
+
# print(f"data: {json.dumps(chunk_dict)}")
|
|
172
|
+
|
|
173
|
+
# Return the chunk object for internal processing
|
|
174
|
+
yield chunk
|
|
175
|
+
except json.JSONDecodeError:
|
|
176
|
+
print(f"Warning: Could not decode JSON line: {json_str}")
|
|
177
|
+
continue
|
|
178
|
+
except requests.exceptions.RequestException as e:
|
|
179
|
+
print(f"Error during Glider stream request: {e}")
|
|
180
|
+
raise IOError(f"Glider request failed: {e}") from e
|
|
181
|
+
except Exception as e:
|
|
182
|
+
print(f"Error processing Glider stream: {e}")
|
|
183
|
+
raise
|
|
184
|
+
|
|
185
|
+
def _create_non_stream(
|
|
186
|
+
self, request_id: str, created_time: int, model: str, payload: Dict[str, Any]
|
|
187
|
+
) -> ChatCompletion:
|
|
188
|
+
try:
|
|
189
|
+
response = self._client.session.post(
|
|
190
|
+
self._client.api_endpoint,
|
|
191
|
+
headers=self._client.headers,
|
|
192
|
+
json=payload,
|
|
193
|
+
timeout=self._client.timeout
|
|
194
|
+
)
|
|
195
|
+
response.raise_for_status()
|
|
196
|
+
data = response.json()
|
|
197
|
+
|
|
198
|
+
choices_data = data.get('choices', [])
|
|
199
|
+
usage_data = data.get('usage', {})
|
|
200
|
+
|
|
201
|
+
choices = []
|
|
202
|
+
for choice_d in choices_data:
|
|
203
|
+
message_d = choice_d.get('message', {})
|
|
204
|
+
message = ChatCompletionMessage(
|
|
205
|
+
role=message_d.get('role', 'assistant'),
|
|
206
|
+
content=message_d.get('content', '')
|
|
207
|
+
)
|
|
208
|
+
choice = Choice(
|
|
209
|
+
index=choice_d.get('index', 0),
|
|
210
|
+
message=message,
|
|
211
|
+
finish_reason=choice_d.get('finish_reason', 'stop')
|
|
212
|
+
)
|
|
213
|
+
choices.append(choice)
|
|
214
|
+
|
|
215
|
+
usage = CompletionUsage(
|
|
216
|
+
prompt_tokens=usage_data.get('prompt_tokens', 0),
|
|
217
|
+
completion_tokens=usage_data.get('completion_tokens', 0),
|
|
218
|
+
total_tokens=usage_data.get('total_tokens', 0)
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
completion = ChatCompletion(
|
|
222
|
+
id=request_id,
|
|
223
|
+
choices=choices,
|
|
224
|
+
created=created_time,
|
|
225
|
+
model=data.get('model', model),
|
|
226
|
+
usage=usage,
|
|
227
|
+
)
|
|
228
|
+
return completion
|
|
229
|
+
|
|
230
|
+
except requests.exceptions.RequestException as e:
|
|
231
|
+
print(f"Error during Glider non-stream request: {e}")
|
|
232
|
+
raise IOError(f"Glider request failed: {e}") from e
|
|
233
|
+
except Exception as e:
|
|
234
|
+
print(f"Error processing Glider response: {e}")
|
|
235
|
+
raise
|
|
236
|
+
|
|
237
|
+
class Chat(BaseChat):
|
|
238
|
+
def __init__(self, client: 'Glider'):
|
|
239
|
+
self.completions = Completions(client)
|
|
240
|
+
|
|
241
|
+
class Glider(OpenAICompatibleProvider):
|
|
242
|
+
"""
|
|
243
|
+
OpenAI-compatible client for Glider.so API.
|
|
244
|
+
|
|
245
|
+
Usage:
|
|
246
|
+
client = Glider()
|
|
247
|
+
response = client.chat.completions.create(
|
|
248
|
+
model="chat-llama-3-1-70b",
|
|
249
|
+
messages=[{"role": "user", "content": "Hello!"}]
|
|
250
|
+
)
|
|
251
|
+
"""
|
|
252
|
+
|
|
253
|
+
AVAILABLE_MODELS = [
|
|
254
|
+
"chat-llama-3-1-70b",
|
|
255
|
+
"chat-llama-3-1-8b",
|
|
256
|
+
"chat-llama-3-2-3b",
|
|
257
|
+
"deepseek-ai/DeepSeek-R1",
|
|
258
|
+
]
|
|
259
|
+
|
|
260
|
+
# No model mapping needed as we use the model names directly
|
|
261
|
+
|
|
262
|
+
def __init__(self, timeout: Optional[int] = None, browser: str = "chrome"):
|
|
263
|
+
"""
|
|
264
|
+
Initialize the Glider client.
|
|
265
|
+
|
|
266
|
+
Args:
|
|
267
|
+
timeout: Request timeout in seconds (None for no timeout)
|
|
268
|
+
browser: Browser to emulate in user agent
|
|
269
|
+
"""
|
|
270
|
+
self.timeout = timeout
|
|
271
|
+
self.api_endpoint = "https://glider.so/api/chat"
|
|
272
|
+
self.session = requests.Session()
|
|
273
|
+
|
|
274
|
+
agent = LitAgent()
|
|
275
|
+
fingerprint = agent.generate_fingerprint(browser)
|
|
276
|
+
|
|
277
|
+
self.headers = {
|
|
278
|
+
"Accept": fingerprint["accept"],
|
|
279
|
+
"Accept-Encoding": "gzip, deflate, br, zstd",
|
|
280
|
+
"Accept-Language": fingerprint["accept_language"],
|
|
281
|
+
"Content-Type": "application/json",
|
|
282
|
+
"Cache-Control": "no-cache",
|
|
283
|
+
"Connection": "keep-alive",
|
|
284
|
+
"Origin": "https://glider.so",
|
|
285
|
+
"Pragma": "no-cache",
|
|
286
|
+
"Referer": "https://glider.so/",
|
|
287
|
+
"Sec-Fetch-Dest": "empty",
|
|
288
|
+
"Sec-Fetch-Mode": "cors",
|
|
289
|
+
"Sec-Fetch-Site": "same-site",
|
|
290
|
+
"Sec-CH-UA": fingerprint["sec_ch_ua"] or '"Not)A;Brand";v="99", "Microsoft Edge";v="127", "Chromium";v="127"',
|
|
291
|
+
"Sec-CH-UA-Mobile": "?0",
|
|
292
|
+
"Sec-CH-UA-Platform": f'"{fingerprint["platform"]}"',
|
|
293
|
+
"User-Agent": fingerprint["user_agent"],
|
|
294
|
+
}
|
|
295
|
+
self.session.headers.update(self.headers)
|
|
296
|
+
self.chat = Chat(self)
|
|
297
|
+
|
|
298
|
+
def convert_model_name(self, model: str) -> str:
|
|
299
|
+
"""
|
|
300
|
+
Convert model names to ones supported by Glider.
|
|
301
|
+
|
|
302
|
+
Args:
|
|
303
|
+
model: Model name to convert
|
|
304
|
+
|
|
305
|
+
Returns:
|
|
306
|
+
Glider model name
|
|
307
|
+
"""
|
|
308
|
+
# If the model is already a valid Glider model, return it
|
|
309
|
+
if model in self.AVAILABLE_MODELS:
|
|
310
|
+
return model
|
|
311
|
+
|
|
312
|
+
# Default to the most capable model
|
|
313
|
+
print(f"Warning: Unknown model '{model}'. Using 'chat-llama-3-1-70b' instead.")
|
|
314
|
+
return "chat-llama-3-1-70b"
|