webscout 8.3.4__py3-none-any.whl → 8.3.6__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.

Files changed (98) hide show
  1. webscout/AIutel.py +52 -1016
  2. webscout/Bard.py +12 -6
  3. webscout/DWEBS.py +66 -57
  4. webscout/Provider/AISEARCH/PERPLEXED_search.py +214 -0
  5. webscout/Provider/AISEARCH/__init__.py +11 -10
  6. webscout/Provider/AISEARCH/felo_search.py +7 -3
  7. webscout/Provider/AISEARCH/scira_search.py +2 -0
  8. webscout/Provider/AISEARCH/stellar_search.py +53 -8
  9. webscout/Provider/Deepinfra.py +13 -1
  10. webscout/Provider/Flowith.py +6 -1
  11. webscout/Provider/GithubChat.py +1 -0
  12. webscout/Provider/GptOss.py +207 -0
  13. webscout/Provider/Kimi.py +445 -0
  14. webscout/Provider/Netwrck.py +3 -6
  15. webscout/Provider/OPENAI/README.md +2 -1
  16. webscout/Provider/OPENAI/TogetherAI.py +12 -8
  17. webscout/Provider/OPENAI/TwoAI.py +94 -1
  18. webscout/Provider/OPENAI/__init__.py +4 -4
  19. webscout/Provider/OPENAI/copilot.py +20 -4
  20. webscout/Provider/OPENAI/deepinfra.py +12 -0
  21. webscout/Provider/OPENAI/e2b.py +60 -8
  22. webscout/Provider/OPENAI/flowith.py +4 -3
  23. webscout/Provider/OPENAI/generate_api_key.py +48 -0
  24. webscout/Provider/OPENAI/gptoss.py +288 -0
  25. webscout/Provider/OPENAI/kimi.py +469 -0
  26. webscout/Provider/OPENAI/netwrck.py +8 -12
  27. webscout/Provider/OPENAI/refact.py +274 -0
  28. webscout/Provider/OPENAI/scirachat.py +4 -0
  29. webscout/Provider/OPENAI/textpollinations.py +11 -10
  30. webscout/Provider/OPENAI/toolbaz.py +1 -0
  31. webscout/Provider/OPENAI/venice.py +1 -0
  32. webscout/Provider/Perplexitylabs.py +163 -147
  33. webscout/Provider/Qodo.py +30 -6
  34. webscout/Provider/TTI/__init__.py +1 -0
  35. webscout/Provider/TTI/bing.py +14 -2
  36. webscout/Provider/TTI/together.py +11 -9
  37. webscout/Provider/TTI/venice.py +368 -0
  38. webscout/Provider/TTS/README.md +0 -1
  39. webscout/Provider/TTS/__init__.py +0 -1
  40. webscout/Provider/TTS/base.py +479 -159
  41. webscout/Provider/TTS/deepgram.py +409 -156
  42. webscout/Provider/TTS/elevenlabs.py +425 -111
  43. webscout/Provider/TTS/freetts.py +317 -140
  44. webscout/Provider/TTS/gesserit.py +192 -128
  45. webscout/Provider/TTS/murfai.py +248 -113
  46. webscout/Provider/TTS/openai_fm.py +347 -129
  47. webscout/Provider/TTS/speechma.py +620 -586
  48. webscout/Provider/TextPollinationsAI.py +11 -10
  49. webscout/Provider/TogetherAI.py +12 -4
  50. webscout/Provider/TwoAI.py +96 -2
  51. webscout/Provider/TypliAI.py +33 -27
  52. webscout/Provider/UNFINISHED/VercelAIGateway.py +339 -0
  53. webscout/Provider/UNFINISHED/fetch_together_models.py +6 -11
  54. webscout/Provider/Venice.py +1 -0
  55. webscout/Provider/WiseCat.py +18 -20
  56. webscout/Provider/__init__.py +2 -96
  57. webscout/Provider/cerebras.py +83 -33
  58. webscout/Provider/copilot.py +42 -23
  59. webscout/Provider/scira_chat.py +4 -0
  60. webscout/Provider/toolbaz.py +6 -10
  61. webscout/Provider/typefully.py +1 -11
  62. webscout/__init__.py +3 -15
  63. webscout/auth/__init__.py +19 -4
  64. webscout/auth/api_key_manager.py +189 -189
  65. webscout/auth/auth_system.py +25 -40
  66. webscout/auth/config.py +105 -6
  67. webscout/auth/database.py +377 -22
  68. webscout/auth/models.py +185 -130
  69. webscout/auth/request_processing.py +175 -11
  70. webscout/auth/routes.py +99 -2
  71. webscout/auth/server.py +9 -2
  72. webscout/auth/simple_logger.py +236 -0
  73. webscout/conversation.py +22 -20
  74. webscout/sanitize.py +1078 -0
  75. webscout/scout/README.md +20 -23
  76. webscout/scout/core/crawler.py +125 -38
  77. webscout/scout/core/scout.py +26 -5
  78. webscout/version.py +1 -1
  79. webscout/webscout_search.py +13 -6
  80. webscout/webscout_search_async.py +10 -8
  81. webscout/yep_search.py +13 -5
  82. {webscout-8.3.4.dist-info → webscout-8.3.6.dist-info}/METADATA +10 -149
  83. {webscout-8.3.4.dist-info → webscout-8.3.6.dist-info}/RECORD +88 -87
  84. webscout/Provider/Glider.py +0 -225
  85. webscout/Provider/OPENAI/README_AUTOPROXY.md +0 -238
  86. webscout/Provider/OPENAI/c4ai.py +0 -394
  87. webscout/Provider/OPENAI/glider.py +0 -330
  88. webscout/Provider/OPENAI/typegpt.py +0 -368
  89. webscout/Provider/OPENAI/uncovrAI.py +0 -477
  90. webscout/Provider/TTS/sthir.py +0 -94
  91. webscout/Provider/WritingMate.py +0 -273
  92. webscout/Provider/typegpt.py +0 -284
  93. webscout/Provider/uncovr.py +0 -333
  94. /webscout/Provider/{samurai.py → UNFINISHED/samurai.py} +0 -0
  95. {webscout-8.3.4.dist-info → webscout-8.3.6.dist-info}/WHEEL +0 -0
  96. {webscout-8.3.4.dist-info → webscout-8.3.6.dist-info}/entry_points.txt +0 -0
  97. {webscout-8.3.4.dist-info → webscout-8.3.6.dist-info}/licenses/LICENSE.md +0 -0
  98. {webscout-8.3.4.dist-info → webscout-8.3.6.dist-info}/top_level.txt +0 -0
@@ -1,330 +0,0 @@
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
- timeout: Optional[int] = None,
48
- proxies: Optional[Dict[str, str]] = None,
49
- **kwargs: Any
50
- ) -> Union[ChatCompletion, Generator[ChatCompletionChunk, None, None]]:
51
- """
52
- Creates a model response for the given chat conversation.
53
- Mimics openai.chat.completions.create
54
- """
55
- # Prepare the payload for Glider API
56
- payload = {
57
- "messages": messages,
58
- "model": self._client.convert_model_name(model),
59
- }
60
-
61
- # Add optional parameters if provided
62
- if max_tokens is not None and max_tokens > 0:
63
- payload["max_tokens"] = max_tokens
64
-
65
- if temperature is not None:
66
- payload["temperature"] = temperature
67
-
68
- if top_p is not None:
69
- payload["top_p"] = top_p
70
-
71
- # Add any additional parameters
72
- payload.update(kwargs)
73
-
74
- request_id = f"chatcmpl-{uuid.uuid4()}"
75
- created_time = int(time.time())
76
-
77
- if stream:
78
- return self._create_stream(request_id, created_time, model, payload, timeout, proxies)
79
- else:
80
- return self._create_non_stream(request_id, created_time, model, payload, timeout, proxies)
81
-
82
- def _create_stream(
83
- self, request_id: str, created_time: int, model: str, payload: Dict[str, Any], timeout: Optional[int] = None, proxies: Optional[Dict[str, str]] = None
84
- ) -> Generator[ChatCompletionChunk, None, None]:
85
- try:
86
- response = self._client.session.post(
87
- self._client.api_endpoint,
88
- headers=self._client.headers,
89
- json=payload,
90
- stream=True,
91
- timeout=timeout or self._client.timeout,
92
- proxies=proxies or getattr(self._client, "proxies", None)
93
- )
94
- response.raise_for_status()
95
-
96
- # Track token usage across chunks
97
- prompt_tokens = 0
98
- completion_tokens = 0
99
- total_tokens = 0
100
-
101
- for line in response.iter_lines():
102
- if line:
103
- decoded_line = line.decode('utf-8').strip()
104
-
105
- if decoded_line.startswith("data: "):
106
- json_str = decoded_line[6:]
107
- if json_str == "[DONE]":
108
- # Format the final [DONE] marker in OpenAI format
109
- # print("data: [DONE]")
110
- break
111
-
112
- try:
113
- data = json.loads(json_str)
114
- choice_data = data.get('choices', [{}])[0]
115
- delta_data = choice_data.get('delta', {})
116
- finish_reason = choice_data.get('finish_reason')
117
-
118
- # Update token counts if available
119
- usage_data = data.get('usage', {})
120
- if usage_data:
121
- prompt_tokens = usage_data.get('prompt_tokens', prompt_tokens)
122
- completion_tokens = usage_data.get('completion_tokens', completion_tokens)
123
- total_tokens = usage_data.get('total_tokens', total_tokens)
124
-
125
- # Create the delta object
126
- delta = ChoiceDelta(
127
- content=delta_data.get('content'),
128
- role=delta_data.get('role'),
129
- tool_calls=delta_data.get('tool_calls')
130
- )
131
-
132
- # Create the choice object
133
- choice = Choice(
134
- index=choice_data.get('index', 0),
135
- delta=delta,
136
- finish_reason=finish_reason,
137
- logprobs=choice_data.get('logprobs')
138
- )
139
-
140
- # Create the chunk object
141
- chunk = ChatCompletionChunk(
142
- id=request_id,
143
- choices=[choice],
144
- created=created_time,
145
- model=model,
146
- system_fingerprint=data.get('system_fingerprint')
147
- )
148
-
149
- # Convert chunk to dict using Pydantic's API
150
- if hasattr(chunk, "model_dump"):
151
- chunk_dict = chunk.model_dump(exclude_none=True)
152
- else:
153
- chunk_dict = chunk.dict(exclude_none=True)
154
-
155
- # Add usage information to match OpenAI format
156
- # Even if we don't have real token counts, include estimated usage
157
- # This matches the format in the examples
158
- usage_dict = {
159
- "prompt_tokens": prompt_tokens or 10,
160
- "completion_tokens": completion_tokens or (len(delta_data.get('content', '')) if delta_data.get('content') else 0),
161
- "total_tokens": total_tokens or (10 + (len(delta_data.get('content', '')) if delta_data.get('content') else 0)),
162
- "estimated_cost": None
163
- }
164
-
165
- # Update completion_tokens and total_tokens as we receive more content
166
- if delta_data.get('content'):
167
- completion_tokens += 1
168
- total_tokens = prompt_tokens + completion_tokens
169
- usage_dict["completion_tokens"] = completion_tokens
170
- usage_dict["total_tokens"] = total_tokens
171
-
172
- chunk_dict["usage"] = usage_dict
173
-
174
- # Format the response in OpenAI format exactly as requested
175
- # We need to print the raw string and also yield the chunk object
176
- # This ensures both the console output and the returned object are correct
177
- # print(f"data: {json.dumps(chunk_dict)}")
178
-
179
- # Return the chunk object for internal processing
180
- yield chunk
181
- except json.JSONDecodeError:
182
- print(f"Warning: Could not decode JSON line: {json_str}")
183
- continue
184
- except requests.exceptions.RequestException as e:
185
- print(f"Error during Glider stream request: {e}")
186
- raise IOError(f"Glider request failed: {e}") from e
187
- except Exception as e:
188
- print(f"Error processing Glider stream: {e}")
189
- raise
190
-
191
- def _create_non_stream(
192
- self, request_id: str, created_time: int, model: str, payload: Dict[str, Any], timeout: Optional[int] = None, proxies: Optional[Dict[str, str]] = None
193
- ) -> ChatCompletion:
194
- try:
195
- response = self._client.session.post(
196
- self._client.api_endpoint,
197
- headers=self._client.headers,
198
- json=payload,
199
- timeout=timeout or self._client.timeout,
200
- proxies=proxies or getattr(self._client, "proxies", None)
201
- )
202
- response.raise_for_status()
203
- data = response.json()
204
-
205
- choices_data = data.get('choices', [])
206
- usage_data = data.get('usage', {})
207
-
208
- choices = []
209
- for choice_d in choices_data:
210
- message_d = choice_d.get('message', {})
211
- message = ChatCompletionMessage(
212
- role=message_d.get('role', 'assistant'),
213
- content=message_d.get('content', '')
214
- )
215
- choice = Choice(
216
- index=choice_d.get('index', 0),
217
- message=message,
218
- finish_reason=choice_d.get('finish_reason', 'stop')
219
- )
220
- choices.append(choice)
221
-
222
- usage = CompletionUsage(
223
- prompt_tokens=usage_data.get('prompt_tokens', 0),
224
- completion_tokens=usage_data.get('completion_tokens', 0),
225
- total_tokens=usage_data.get('total_tokens', 0)
226
- )
227
-
228
- completion = ChatCompletion(
229
- id=request_id,
230
- choices=choices,
231
- created=created_time,
232
- model=data.get('model', model),
233
- usage=usage,
234
- )
235
- return completion
236
-
237
- except requests.exceptions.RequestException as e:
238
- print(f"Error during Glider non-stream request: {e}")
239
- raise IOError(f"Glider request failed: {e}") from e
240
- except Exception as e:
241
- print(f"Error processing Glider response: {e}")
242
- raise
243
-
244
- class Chat(BaseChat):
245
- def __init__(self, client: 'Glider'):
246
- self.completions = Completions(client)
247
-
248
- class Glider(OpenAICompatibleProvider):
249
- """
250
- OpenAI-compatible client for Glider.so API.
251
-
252
- Usage:
253
- client = Glider()
254
- response = client.chat.completions.create(
255
- model="chat-llama-3-1-70b",
256
- messages=[{"role": "user", "content": "Hello!"}]
257
- )
258
- """
259
-
260
- AVAILABLE_MODELS = [
261
- "chat-llama-3-1-8b",
262
- "chat-llama-3-2-3b",
263
- "chat-deepseek-r1-qwen-32b",
264
- "chat-qwen-2-5-7b",
265
- "chat-qwen-qwq-32b",
266
- "deepseek-ai/DeepSeek-R1",
267
- ]
268
-
269
- # No model mapping needed as we use the model names directly
270
-
271
- def __init__(self, timeout: Optional[int] = None, browser: str = "chrome"):
272
- """
273
- Initialize the Glider client.
274
-
275
- Args:
276
- timeout: Request timeout in seconds (None for no timeout)
277
- browser: Browser to emulate in user agent
278
- """
279
- self.timeout = timeout
280
- self.api_endpoint = "https://glider.so/api/chat"
281
- self.session = requests.Session()
282
-
283
- agent = LitAgent()
284
- fingerprint = agent.generate_fingerprint(browser)
285
-
286
- self.headers = {
287
- "Accept": fingerprint["accept"],
288
- "Accept-Encoding": "gzip, deflate, br, zstd",
289
- "Accept-Language": fingerprint["accept_language"],
290
- "Content-Type": "application/json",
291
- "Cache-Control": "no-cache",
292
- "Connection": "keep-alive",
293
- "Origin": "https://glider.so",
294
- "Pragma": "no-cache",
295
- "Referer": "https://glider.so/",
296
- "Sec-Fetch-Dest": "empty",
297
- "Sec-Fetch-Mode": "cors",
298
- "Sec-Fetch-Site": "same-site",
299
- "Sec-CH-UA": fingerprint["sec_ch_ua"] or '"Not)A;Brand";v="99", "Microsoft Edge";v="127", "Chromium";v="127"',
300
- "Sec-CH-UA-Mobile": "?0",
301
- "Sec-CH-UA-Platform": f'"{fingerprint["platform"]}"',
302
- "User-Agent": fingerprint["user_agent"],
303
- }
304
- self.session.headers.update(self.headers)
305
- self.chat = Chat(self)
306
-
307
- def convert_model_name(self, model: str) -> str:
308
- """
309
- Convert model names to ones supported by Glider.
310
-
311
- Args:
312
- model: Model name to convert
313
-
314
- Returns:
315
- Glider model name
316
- """
317
- # If the model is already a valid Glider model, return it
318
- if model in self.AVAILABLE_MODELS:
319
- return model
320
-
321
- # Default to the most capable model
322
- print(f"Warning: Unknown model '{model}'. Using 'chat-llama-3-1-70b' instead.")
323
- return "chat-llama-3-1-70b"
324
-
325
- @property
326
- def models(self):
327
- class _ModelList:
328
- def list(inner_self):
329
- return type(self).AVAILABLE_MODELS
330
- return _ModelList()
@@ -1,368 +0,0 @@
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, count_tokens
12
- )
13
-
14
- # Attempt to import LitAgent, fallback if not available
15
- try:
16
- from webscout.litagent import LitAgent
17
- except ImportError:
18
- print("Warning: LitAgent not found. Functionality may be limited.")
19
-
20
- # --- TypeGPT Client ---
21
-
22
- class Completions(BaseCompletions):
23
- def __init__(self, client: 'TypeGPT'):
24
- self._client = client
25
-
26
- def create(
27
- self,
28
- *,
29
- model: str,
30
- messages: List[Dict[str, str]],
31
- max_tokens: Optional[int] = None,
32
- stream: bool = False,
33
- temperature: Optional[float] = None,
34
- top_p: Optional[float] = None,
35
- presence_penalty: Optional[float] = None,
36
- frequency_penalty: Optional[float] = None,
37
- timeout: Optional[int] = None,
38
- proxies: Optional[Dict[str, str]] = None,
39
- **kwargs: Any
40
- ) -> Union[ChatCompletion, Generator[ChatCompletionChunk, None, None]]:
41
- """
42
- Creates a model response for the given chat conversation.
43
- Mimics openai.chat.completions.create
44
- """
45
- # Prepare the payload for TypeGPT API
46
- payload = {
47
- "messages": messages,
48
- "stream": stream,
49
- "model": self._client.convert_model_name(model),
50
- "temperature": temperature if temperature is not None else self._client.temperature,
51
- "top_p": top_p if top_p is not None else self._client.top_p,
52
- "presence_penalty": presence_penalty if presence_penalty is not None else self._client.presence_penalty,
53
- "frequency_penalty": frequency_penalty if frequency_penalty is not None else self._client.frequency_penalty,
54
- "max_tokens": max_tokens if max_tokens is not None else self._client.max_tokens,
55
- }
56
-
57
- # Add any additional parameters
58
- for key, value in kwargs.items():
59
- if key not in payload:
60
- payload[key] = value
61
-
62
- request_id = f"chatcmpl-{uuid.uuid4()}"
63
- created_time = int(time.time())
64
-
65
- if stream:
66
- return self._create_stream(request_id, created_time, model, payload, timeout, proxies)
67
- else:
68
- return self._create_non_stream(request_id, created_time, model, payload, timeout, proxies)
69
-
70
- def _create_stream(
71
- self, request_id: str, created_time: int, model: str, payload: Dict[str, Any], timeout: Optional[int] = None, proxies: Optional[Dict[str, str]] = None
72
- ) -> Generator[ChatCompletionChunk, None, None]:
73
- try:
74
- response = self._client.session.post(
75
- self._client.api_endpoint,
76
- headers=self._client.headers,
77
- json=payload,
78
- stream=True,
79
- timeout=timeout or self._client.timeout,
80
- proxies=proxies or getattr(self._client, "proxies", None)
81
- )
82
-
83
- # Handle non-200 responses
84
- if not response.ok:
85
- raise IOError(
86
- f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
87
- )
88
-
89
- # Track token usage across chunks
90
- prompt_tokens = 0
91
- completion_tokens = 0
92
- total_tokens = 0
93
-
94
- # Estimate prompt tokens based on message length
95
- for msg in payload.get("messages", []):
96
- prompt_tokens += count_tokens(msg.get("content", ""))
97
-
98
- for line in response.iter_lines():
99
- if not line:
100
- continue
101
-
102
- decoded_line = line.decode('utf-8').strip()
103
-
104
- if decoded_line.startswith("data: "):
105
- json_str = decoded_line[6:]
106
- if json_str == "[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 chunk to dict using Pydantic's API
147
- if hasattr(chunk, "model_dump"):
148
- chunk_dict = chunk.model_dump(exclude_none=True)
149
- else:
150
- chunk_dict = chunk.dict(exclude_none=True)
151
-
152
- # Add usage information to match OpenAI format
153
- usage_dict = {
154
- "prompt_tokens": prompt_tokens or 10,
155
- "completion_tokens": completion_tokens or (len(delta_data.get('content', '')) if delta_data.get('content') else 0),
156
- "total_tokens": total_tokens or (10 + (len(delta_data.get('content', '')) if delta_data.get('content') else 0)),
157
- "estimated_cost": None
158
- }
159
-
160
- # Update completion_tokens and total_tokens as we receive more content
161
- if delta_data.get('content'):
162
- completion_tokens += 1
163
- total_tokens = prompt_tokens + completion_tokens
164
- usage_dict["completion_tokens"] = completion_tokens
165
- usage_dict["total_tokens"] = total_tokens
166
-
167
- chunk_dict["usage"] = usage_dict
168
-
169
- # Return the chunk object for internal processing
170
- yield chunk
171
- except json.JSONDecodeError:
172
- print(f"Warning: Could not decode JSON line: {json_str}")
173
- continue
174
-
175
- # Final chunk with finish_reason="stop"
176
- delta = ChoiceDelta(
177
- content=None,
178
- role=None,
179
- tool_calls=None
180
- )
181
-
182
- choice = Choice(
183
- index=0,
184
- delta=delta,
185
- finish_reason="stop",
186
- logprobs=None
187
- )
188
-
189
- chunk = ChatCompletionChunk(
190
- id=request_id,
191
- choices=[choice],
192
- created=created_time,
193
- model=model,
194
- system_fingerprint=None
195
- )
196
-
197
- if hasattr(chunk, "model_dump"):
198
- chunk_dict = chunk.model_dump(exclude_none=True)
199
- else:
200
- chunk_dict = chunk.dict(exclude_none=True)
201
- chunk_dict["usage"] = {
202
- "prompt_tokens": prompt_tokens,
203
- "completion_tokens": completion_tokens,
204
- "total_tokens": total_tokens,
205
- "estimated_cost": None
206
- }
207
-
208
- yield chunk
209
-
210
- except Exception as e:
211
- print(f"Error during TypeGPT stream request: {e}")
212
- raise IOError(f"TypeGPT request failed: {e}") from e
213
-
214
- def _create_non_stream(
215
- self, request_id: str, created_time: int, model: str, payload: Dict[str, Any], timeout: Optional[int] = None, proxies: Optional[Dict[str, str]] = None
216
- ) -> ChatCompletion:
217
- try:
218
- response = self._client.session.post(
219
- self._client.api_endpoint,
220
- headers=self._client.headers,
221
- json=payload,
222
- timeout=timeout or self._client.timeout,
223
- proxies=proxies or getattr(self._client, "proxies", None)
224
- )
225
-
226
- # Handle non-200 responses
227
- if not response.ok:
228
- raise IOError(
229
- f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
230
- )
231
-
232
- # Parse the response
233
- data = response.json()
234
-
235
- choices_data = data.get('choices', [])
236
- usage_data = data.get('usage', {})
237
-
238
- choices = []
239
- for choice_d in choices_data:
240
- message_d = choice_d.get('message', {})
241
- message = ChatCompletionMessage(
242
- role=message_d.get('role', 'assistant'),
243
- content=message_d.get('content', '')
244
- )
245
- choice = Choice(
246
- index=choice_d.get('index', 0),
247
- message=message,
248
- finish_reason=choice_d.get('finish_reason', 'stop')
249
- )
250
- choices.append(choice)
251
-
252
- usage = CompletionUsage(
253
- prompt_tokens=usage_data.get('prompt_tokens', 0),
254
- completion_tokens=usage_data.get('completion_tokens', 0),
255
- total_tokens=usage_data.get('total_tokens', 0)
256
- )
257
-
258
- completion = ChatCompletion(
259
- id=request_id,
260
- choices=choices,
261
- created=created_time,
262
- model=data.get('model', model),
263
- usage=usage,
264
- )
265
- return completion
266
-
267
- except Exception as e:
268
- print(f"Error during TypeGPT non-stream request: {e}")
269
- raise IOError(f"TypeGPT request failed: {e}") from e
270
-
271
- class Chat(BaseChat):
272
- def __init__(self, client: 'TypeGPT'):
273
- self.completions = Completions(client)
274
-
275
- class TypeGPT(OpenAICompatibleProvider):
276
- """
277
- OpenAI-compatible client for TypeGPT API.
278
-
279
- Usage:
280
- client = TypeGPT()
281
- response = client.chat.completions.create(
282
- model="gpt-4o",
283
- messages=[{"role": "user", "content": "Hello!"}]
284
- )
285
- """
286
-
287
- AVAILABLE_MODELS = [
288
- # Working Models (based on testing)
289
- "gpt-4o-mini",
290
- "chatgpt-4o-latest",
291
- # "deepseek-r1",
292
- "deepseek-v3",
293
- # "uncensored-r1",
294
- # "Image-Generator",
295
- ]
296
-
297
- def __init__(
298
- self,
299
- timeout: Optional[int] = None,
300
- browser: str = "chrome"
301
- ):
302
- """
303
- Initialize the TypeGPT client.
304
-
305
- Args:
306
- timeout: Request timeout in seconds (None for no timeout)
307
- browser: Browser to emulate in user agent
308
- """
309
- self.timeout = timeout or 60 # Default to 30 seconds if None
310
- self.api_endpoint = "https://chat.typegpt.net/api/openai/v1/chat/completions"
311
- self.session = requests.Session()
312
-
313
- # Default parameters
314
- self.max_tokens = 4000
315
- self.temperature = 0.5
316
- self.presence_penalty = 0
317
- self.frequency_penalty = 0
318
- self.top_p = 1
319
-
320
- # Initialize LitAgent for user agent generation
321
- agent = LitAgent()
322
- self.fingerprint = agent.generate_fingerprint(browser)
323
-
324
- # Headers for the request
325
- self.headers = {
326
- "authority": "chat.typegpt.net",
327
- "accept": "application/json, text/event-stream",
328
- "accept-language": self.fingerprint["accept_language"],
329
- "content-type": "application/json",
330
- "origin": "https://chat.typegpt.net",
331
- "referer": "https://chat.typegpt.net/",
332
- "user-agent": self.fingerprint["user_agent"]
333
- }
334
-
335
- self.session.headers.update(self.headers)
336
-
337
- # Initialize the chat interface
338
- self.chat = Chat(self)
339
-
340
- def convert_model_name(self, model: str) -> str:
341
- """
342
- Convert model names to ones supported by TypeGPT.
343
-
344
- Args:
345
- model: Model name to convert
346
-
347
- Returns:
348
- TypeGPT model name
349
- """
350
- # If the model is already a valid TypeGPT model, return it
351
- if model in self.AVAILABLE_MODELS:
352
- return model
353
-
354
- # Default to chatgpt-4o-latest if model not found (this one works reliably)
355
- print(f"Warning: Unknown model '{model}'. Using 'chatgpt-4o-latest' instead.")
356
- return "chatgpt-4o-latest"
357
-
358
- @property
359
- def models(self):
360
- class _ModelList:
361
- def list(inner_self):
362
- return type(self).AVAILABLE_MODELS
363
- return _ModelList()
364
-
365
- @classmethod
366
- def models(cls):
367
- """Return the list of available models for TypeGPT."""
368
- return cls.AVAILABLE_MODELS