webscout 7.9__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.

Files changed (69) hide show
  1. webscout/Extra/GitToolkit/__init__.py +10 -0
  2. webscout/Extra/GitToolkit/gitapi/__init__.py +12 -0
  3. webscout/Extra/GitToolkit/gitapi/repository.py +195 -0
  4. webscout/Extra/GitToolkit/gitapi/user.py +96 -0
  5. webscout/Extra/GitToolkit/gitapi/utils.py +62 -0
  6. webscout/Extra/YTToolkit/ytapi/video.py +232 -103
  7. webscout/Provider/AISEARCH/DeepFind.py +1 -1
  8. webscout/Provider/AISEARCH/ISou.py +1 -1
  9. webscout/Provider/AISEARCH/__init__.py +6 -1
  10. webscout/Provider/AISEARCH/felo_search.py +1 -1
  11. webscout/Provider/AISEARCH/genspark_search.py +1 -1
  12. webscout/Provider/AISEARCH/hika_search.py +194 -0
  13. webscout/Provider/AISEARCH/iask_search.py +436 -0
  14. webscout/Provider/AISEARCH/monica_search.py +246 -0
  15. webscout/Provider/AISEARCH/scira_search.py +320 -0
  16. webscout/Provider/AISEARCH/webpilotai_search.py +281 -0
  17. webscout/Provider/AllenAI.py +255 -122
  18. webscout/Provider/DeepSeek.py +1 -2
  19. webscout/Provider/Deepinfra.py +17 -9
  20. webscout/Provider/ExaAI.py +261 -0
  21. webscout/Provider/ExaChat.py +8 -1
  22. webscout/Provider/GithubChat.py +2 -1
  23. webscout/Provider/Jadve.py +2 -2
  24. webscout/Provider/Netwrck.py +3 -2
  25. webscout/Provider/OPENAI/__init__.py +17 -0
  26. webscout/Provider/OPENAI/base.py +46 -0
  27. webscout/Provider/OPENAI/c4ai.py +347 -0
  28. webscout/Provider/OPENAI/chatgptclone.py +460 -0
  29. webscout/Provider/OPENAI/deepinfra.py +284 -0
  30. webscout/Provider/OPENAI/exaai.py +419 -0
  31. webscout/Provider/OPENAI/exachat.py +421 -0
  32. webscout/Provider/OPENAI/freeaichat.py +355 -0
  33. webscout/Provider/OPENAI/glider.py +314 -0
  34. webscout/Provider/OPENAI/heckai.py +337 -0
  35. webscout/Provider/OPENAI/llmchatco.py +325 -0
  36. webscout/Provider/OPENAI/netwrck.py +348 -0
  37. webscout/Provider/OPENAI/scirachat.py +459 -0
  38. webscout/Provider/OPENAI/sonus.py +294 -0
  39. webscout/Provider/OPENAI/typegpt.py +361 -0
  40. webscout/Provider/OPENAI/utils.py +211 -0
  41. webscout/Provider/OPENAI/venice.py +428 -0
  42. webscout/Provider/OPENAI/wisecat.py +381 -0
  43. webscout/Provider/OPENAI/x0gpt.py +389 -0
  44. webscout/Provider/OPENAI/yep.py +329 -0
  45. webscout/Provider/OpenGPT.py +199 -0
  46. webscout/Provider/PI.py +39 -24
  47. webscout/Provider/Venice.py +1 -1
  48. webscout/Provider/Youchat.py +326 -296
  49. webscout/Provider/__init__.py +16 -6
  50. webscout/Provider/ai4chat.py +58 -56
  51. webscout/Provider/akashgpt.py +34 -22
  52. webscout/Provider/freeaichat.py +1 -1
  53. webscout/Provider/labyrinth.py +121 -20
  54. webscout/Provider/llmchatco.py +306 -0
  55. webscout/Provider/scira_chat.py +274 -0
  56. webscout/Provider/typefully.py +280 -0
  57. webscout/Provider/typegpt.py +3 -184
  58. webscout/prompt_manager.py +2 -1
  59. webscout/version.py +1 -1
  60. webscout/webscout_search.py +118 -54
  61. webscout/webscout_search_async.py +109 -45
  62. webscout-8.1.dist-info/METADATA +683 -0
  63. {webscout-7.9.dist-info → webscout-8.1.dist-info}/RECORD +67 -33
  64. webscout/Provider/flowith.py +0 -207
  65. webscout-7.9.dist-info/METADATA +0 -995
  66. {webscout-7.9.dist-info → webscout-8.1.dist-info}/LICENSE.md +0 -0
  67. {webscout-7.9.dist-info → webscout-8.1.dist-info}/WHEEL +0 -0
  68. {webscout-7.9.dist-info → webscout-8.1.dist-info}/entry_points.txt +0 -0
  69. {webscout-7.9.dist-info → webscout-8.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,294 @@
1
+ import time
2
+ import uuid
3
+ import requests
4
+ import json
5
+ from typing import List, Dict, Optional, Union, Generator, Any
6
+
7
+ from webscout.litagent import LitAgent
8
+ from .base import BaseChat, BaseCompletions, OpenAICompatibleProvider
9
+ from .utils import (
10
+ ChatCompletion,
11
+ ChatCompletionChunk,
12
+ Choice,
13
+ ChatCompletionMessage,
14
+ ChoiceDelta,
15
+ CompletionUsage,
16
+ format_prompt
17
+ )
18
+
19
+ # ANSI escape codes for formatting
20
+ BOLD = "\033[1m"
21
+ RED = "\033[91m"
22
+ RESET = "\033[0m"
23
+
24
+ class Completions(BaseCompletions):
25
+ def __init__(self, client: 'SonusAI'):
26
+ self._client = client
27
+
28
+ def create(
29
+ self,
30
+ *,
31
+ model: str,
32
+ messages: List[Dict[str, str]],
33
+ max_tokens: Optional[int] = None, # Not used by SonusAI but kept for compatibility
34
+ stream: bool = False,
35
+ temperature: Optional[float] = None, # Not used by SonusAI but kept for compatibility
36
+ top_p: Optional[float] = None, # Not used by SonusAI but kept for compatibility
37
+ **kwargs: Any # Not used by SonusAI but kept for compatibility
38
+ ) -> Union[ChatCompletion, Generator[ChatCompletionChunk, None, None]]:
39
+ """
40
+ Creates a model response for the given chat conversation.
41
+ Mimics openai.chat.completions.create
42
+ """
43
+ # Format the messages using the format_prompt utility
44
+ # This creates a conversation in the format: "User: message\nAssistant: response\nUser: message\nAssistant:"
45
+ # SonusAI works better with a properly formatted conversation
46
+ question = format_prompt(messages, add_special_tokens=True, do_continue=True)
47
+
48
+ # Extract reasoning parameter if provided
49
+ reasoning = kwargs.get('reasoning', False)
50
+
51
+ # Prepare the multipart form data for SonusAI API
52
+ files = {
53
+ 'message': (None, question),
54
+ 'history': (None),
55
+ 'reasoning': (None, str(reasoning).lower()),
56
+ 'model': (None, self._client.convert_model_name(model))
57
+ }
58
+
59
+ request_id = f"chatcmpl-{uuid.uuid4()}"
60
+ created_time = int(time.time())
61
+
62
+ if stream:
63
+ return self._create_stream(request_id, created_time, model, files)
64
+ else:
65
+ return self._create_non_stream(request_id, created_time, model, files)
66
+
67
+ def _create_stream(
68
+ self, request_id: str, created_time: int, model: str, files: Dict[str, Any]
69
+ ) -> Generator[ChatCompletionChunk, None, None]:
70
+ try:
71
+ response = requests.post(
72
+ self._client.url,
73
+ files=files,
74
+ headers=self._client.headers,
75
+ stream=True,
76
+ timeout=self._client.timeout
77
+ )
78
+ response.raise_for_status()
79
+
80
+ # Track token usage across chunks
81
+ completion_tokens = 0
82
+ streaming_text = ""
83
+
84
+ for line in response.iter_lines():
85
+ if not line:
86
+ continue
87
+
88
+ try:
89
+ # Decode the line and remove 'data: ' prefix if present
90
+ line_text = line.decode('utf-8')
91
+ if line_text.startswith('data: '):
92
+ line_text = line_text[6:]
93
+
94
+ data = json.loads(line_text)
95
+ if "content" in data:
96
+ content = data["content"]
97
+ streaming_text += content
98
+ completion_tokens += len(content) // 4 # Rough estimate
99
+
100
+ # Create a delta object for this chunk
101
+ delta = ChoiceDelta(content=content)
102
+ choice = Choice(index=0, delta=delta, finish_reason=None)
103
+
104
+ chunk = ChatCompletionChunk(
105
+ id=request_id,
106
+ choices=[choice],
107
+ created=created_time,
108
+ model=model,
109
+ )
110
+
111
+ yield chunk
112
+ except (json.JSONDecodeError, UnicodeDecodeError):
113
+ continue
114
+
115
+ # Final chunk with finish_reason
116
+ delta = ChoiceDelta(content=None)
117
+ choice = Choice(index=0, delta=delta, finish_reason="stop")
118
+
119
+ chunk = ChatCompletionChunk(
120
+ id=request_id,
121
+ choices=[choice],
122
+ created=created_time,
123
+ model=model,
124
+ )
125
+
126
+ yield chunk
127
+
128
+ except requests.exceptions.RequestException as e:
129
+ print(f"{RED}Error during SonusAI stream request: {e}{RESET}")
130
+ raise IOError(f"SonusAI request failed: {e}") from e
131
+
132
+ def _create_non_stream(
133
+ self, request_id: str, created_time: int, model: str, files: Dict[str, Any]
134
+ ) -> ChatCompletion:
135
+ try:
136
+ response = requests.post(
137
+ self._client.url,
138
+ files=files,
139
+ headers=self._client.headers,
140
+ timeout=self._client.timeout
141
+ )
142
+ response.raise_for_status()
143
+
144
+ full_response = ""
145
+ for line in response.iter_lines():
146
+ if line:
147
+ try:
148
+ line_text = line.decode('utf-8')
149
+ if line_text.startswith('data: '):
150
+ line_text = line_text[6:]
151
+ data = json.loads(line_text)
152
+ if "content" in data:
153
+ full_response += data["content"]
154
+ except (json.JSONDecodeError, UnicodeDecodeError):
155
+ continue
156
+
157
+ # Create usage statistics (estimated)
158
+ prompt_tokens = len(files['message'][1]) // 4
159
+ completion_tokens = len(full_response) // 4
160
+ total_tokens = prompt_tokens + completion_tokens
161
+
162
+ usage = CompletionUsage(
163
+ prompt_tokens=prompt_tokens,
164
+ completion_tokens=completion_tokens,
165
+ total_tokens=total_tokens
166
+ )
167
+
168
+ # Create the message object
169
+ message = ChatCompletionMessage(
170
+ role="assistant",
171
+ content=full_response
172
+ )
173
+
174
+ # Create the choice object
175
+ choice = Choice(
176
+ index=0,
177
+ message=message,
178
+ finish_reason="stop"
179
+ )
180
+
181
+ # Create the completion object
182
+ completion = ChatCompletion(
183
+ id=request_id,
184
+ choices=[choice],
185
+ created=created_time,
186
+ model=model,
187
+ usage=usage,
188
+ )
189
+
190
+ return completion
191
+
192
+ except Exception as e:
193
+ print(f"{RED}Error during SonusAI non-stream request: {e}{RESET}")
194
+ raise IOError(f"SonusAI request failed: {e}") from e
195
+
196
+ class Chat(BaseChat):
197
+ def __init__(self, client: 'SonusAI'):
198
+ self.completions = Completions(client)
199
+
200
+ class SonusAI(OpenAICompatibleProvider):
201
+ """
202
+ OpenAI-compatible client for Sonus AI API.
203
+
204
+ Usage:
205
+ client = SonusAI()
206
+ response = client.chat.completions.create(
207
+ model="pro",
208
+ messages=[{"role": "user", "content": "Hello!"}]
209
+ )
210
+ print(response.choices[0].message.content)
211
+ """
212
+
213
+ AVAILABLE_MODELS = [
214
+ "pro",
215
+ "air",
216
+ "mini"
217
+ ]
218
+
219
+ def __init__(
220
+ self,
221
+ timeout: int = 30
222
+ ):
223
+ """
224
+ Initialize the SonusAI client.
225
+
226
+ Args:
227
+ timeout: Request timeout in seconds.
228
+ """
229
+ self.timeout = timeout
230
+ self.url = "https://chat.sonus.ai/chat.php"
231
+
232
+ # Headers for the request
233
+ agent = LitAgent()
234
+ self.headers = {
235
+ 'Accept': '*/*',
236
+ 'Accept-Language': 'en-US,en;q=0.9',
237
+ 'Origin': 'https://chat.sonus.ai',
238
+ 'Referer': 'https://chat.sonus.ai/',
239
+ 'User-Agent': agent.random()
240
+ }
241
+
242
+ self.session = requests.Session()
243
+ self.session.headers.update(self.headers)
244
+
245
+ # Initialize the chat interface
246
+ self.chat = Chat(self)
247
+
248
+ def convert_model_name(self, model: str) -> str:
249
+ """
250
+ Ensure the model name is in the correct format.
251
+ """
252
+ if model in self.AVAILABLE_MODELS:
253
+ return model
254
+
255
+ # Try to find a matching model
256
+ for available_model in self.AVAILABLE_MODELS:
257
+ if model.lower() in available_model.lower():
258
+ return available_model
259
+
260
+ # Default to pro if no match
261
+ print(f"{BOLD}Warning: Model '{model}' not found, using default model 'pro'{RESET}")
262
+ return "pro"
263
+
264
+
265
+ # Simple test if run directly
266
+ if __name__ == "__main__":
267
+ print("-" * 80)
268
+ print(f"{'Model':<50} {'Status':<10} {'Response'}")
269
+ print("-" * 80)
270
+
271
+ for model in SonusAI.AVAILABLE_MODELS:
272
+ try:
273
+ client = SonusAI(timeout=60)
274
+ # Test with a simple conversation to demonstrate format_prompt usage
275
+ response = client.chat.completions.create(
276
+ model=model,
277
+ messages=[
278
+ {"role": "system", "content": "You are a helpful assistant."},
279
+ {"role": "user", "content": "Say 'Hello' in one word"},
280
+ ],
281
+ stream=False
282
+ )
283
+
284
+ if response and response.choices and response.choices[0].message.content:
285
+ status = "✓"
286
+ # Truncate response if too long
287
+ display_text = response.choices[0].message.content.strip()
288
+ display_text = display_text[:50] + "..." if len(display_text) > 50 else display_text
289
+ else:
290
+ status = "✗"
291
+ display_text = "Empty or invalid response"
292
+ print(f"{model:<50} {status:<10} {display_text}")
293
+ except Exception as e:
294
+ print(f"{model:<50} {'✗':<10} {str(e)}")
@@ -0,0 +1,361 @@
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 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
+ def random(self) -> str:
33
+ return "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36"
34
+
35
+ # --- TypeGPT Client ---
36
+
37
+ class Completions(BaseCompletions):
38
+ def __init__(self, client: 'TypeGPT'):
39
+ self._client = client
40
+
41
+ def create(
42
+ self,
43
+ *,
44
+ model: str,
45
+ messages: List[Dict[str, str]],
46
+ max_tokens: Optional[int] = None,
47
+ stream: bool = False,
48
+ temperature: Optional[float] = None,
49
+ top_p: Optional[float] = None,
50
+ presence_penalty: Optional[float] = None,
51
+ frequency_penalty: Optional[float] = None,
52
+ **kwargs: Any
53
+ ) -> Union[ChatCompletion, Generator[ChatCompletionChunk, None, None]]:
54
+ """
55
+ Creates a model response for the given chat conversation.
56
+ Mimics openai.chat.completions.create
57
+ """
58
+ # Prepare the payload for TypeGPT API
59
+ payload = {
60
+ "messages": messages,
61
+ "stream": stream,
62
+ "model": self._client.convert_model_name(model),
63
+ "temperature": temperature if temperature is not None else self._client.temperature,
64
+ "top_p": top_p if top_p is not None else self._client.top_p,
65
+ "presence_penalty": presence_penalty if presence_penalty is not None else self._client.presence_penalty,
66
+ "frequency_penalty": frequency_penalty if frequency_penalty is not None else self._client.frequency_penalty,
67
+ "max_tokens": max_tokens if max_tokens is not None else self._client.max_tokens,
68
+ }
69
+
70
+ # Add any additional parameters
71
+ for key, value in kwargs.items():
72
+ if key not in payload:
73
+ payload[key] = value
74
+
75
+ request_id = f"chatcmpl-{uuid.uuid4()}"
76
+ created_time = int(time.time())
77
+
78
+ if stream:
79
+ return self._create_stream(request_id, created_time, model, payload)
80
+ else:
81
+ return self._create_non_stream(request_id, created_time, model, payload)
82
+
83
+ def _create_stream(
84
+ self, request_id: str, created_time: int, model: str, payload: Dict[str, Any]
85
+ ) -> Generator[ChatCompletionChunk, None, None]:
86
+ try:
87
+ response = self._client.session.post(
88
+ self._client.api_endpoint,
89
+ headers=self._client.headers,
90
+ json=payload,
91
+ stream=True,
92
+ timeout=self._client.timeout
93
+ )
94
+
95
+ # Handle non-200 responses
96
+ if not response.ok:
97
+ raise IOError(
98
+ f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
99
+ )
100
+
101
+ # Track token usage across chunks
102
+ prompt_tokens = 0
103
+ completion_tokens = 0
104
+ total_tokens = 0
105
+
106
+ # Estimate prompt tokens based on message length
107
+ for msg in payload.get("messages", []):
108
+ prompt_tokens += len(msg.get("content", "").split())
109
+
110
+ for line in response.iter_lines():
111
+ if not line:
112
+ continue
113
+
114
+ decoded_line = line.decode('utf-8').strip()
115
+
116
+ if decoded_line.startswith("data: "):
117
+ json_str = decoded_line[6:]
118
+ if json_str == "[DONE]":
119
+ break
120
+
121
+ try:
122
+ data = json.loads(json_str)
123
+ choice_data = data.get('choices', [{}])[0]
124
+ delta_data = choice_data.get('delta', {})
125
+ finish_reason = choice_data.get('finish_reason')
126
+
127
+ # Update token counts if available
128
+ usage_data = data.get('usage', {})
129
+ if usage_data:
130
+ prompt_tokens = usage_data.get('prompt_tokens', prompt_tokens)
131
+ completion_tokens = usage_data.get('completion_tokens', completion_tokens)
132
+ total_tokens = usage_data.get('total_tokens', total_tokens)
133
+
134
+ # Create the delta object
135
+ delta = ChoiceDelta(
136
+ content=delta_data.get('content'),
137
+ role=delta_data.get('role'),
138
+ tool_calls=delta_data.get('tool_calls')
139
+ )
140
+
141
+ # Create the choice object
142
+ choice = Choice(
143
+ index=choice_data.get('index', 0),
144
+ delta=delta,
145
+ finish_reason=finish_reason,
146
+ logprobs=choice_data.get('logprobs')
147
+ )
148
+
149
+ # Create the chunk object
150
+ chunk = ChatCompletionChunk(
151
+ id=request_id,
152
+ choices=[choice],
153
+ created=created_time,
154
+ model=model,
155
+ system_fingerprint=data.get('system_fingerprint')
156
+ )
157
+
158
+ # Convert to dict for proper formatting
159
+ chunk_dict = chunk.to_dict()
160
+
161
+ # Add usage information to match OpenAI format
162
+ usage_dict = {
163
+ "prompt_tokens": prompt_tokens or 10,
164
+ "completion_tokens": completion_tokens or (len(delta_data.get('content', '')) if delta_data.get('content') else 0),
165
+ "total_tokens": total_tokens or (10 + (len(delta_data.get('content', '')) if delta_data.get('content') else 0)),
166
+ "estimated_cost": None
167
+ }
168
+
169
+ # Update completion_tokens and total_tokens as we receive more content
170
+ if delta_data.get('content'):
171
+ completion_tokens += 1
172
+ total_tokens = prompt_tokens + completion_tokens
173
+ usage_dict["completion_tokens"] = completion_tokens
174
+ usage_dict["total_tokens"] = total_tokens
175
+
176
+ chunk_dict["usage"] = usage_dict
177
+
178
+ # Return the chunk object for internal processing
179
+ yield chunk
180
+ except json.JSONDecodeError:
181
+ print(f"Warning: Could not decode JSON line: {json_str}")
182
+ continue
183
+
184
+ # Final chunk with finish_reason="stop"
185
+ delta = ChoiceDelta(
186
+ content=None,
187
+ role=None,
188
+ tool_calls=None
189
+ )
190
+
191
+ choice = Choice(
192
+ index=0,
193
+ delta=delta,
194
+ finish_reason="stop",
195
+ logprobs=None
196
+ )
197
+
198
+ chunk = ChatCompletionChunk(
199
+ id=request_id,
200
+ choices=[choice],
201
+ created=created_time,
202
+ model=model,
203
+ system_fingerprint=None
204
+ )
205
+
206
+ chunk_dict = chunk.to_dict()
207
+ chunk_dict["usage"] = {
208
+ "prompt_tokens": prompt_tokens,
209
+ "completion_tokens": completion_tokens,
210
+ "total_tokens": total_tokens,
211
+ "estimated_cost": None
212
+ }
213
+
214
+ yield chunk
215
+
216
+ except Exception as e:
217
+ print(f"Error during TypeGPT stream request: {e}")
218
+ raise IOError(f"TypeGPT request failed: {e}") from e
219
+
220
+ def _create_non_stream(
221
+ self, request_id: str, created_time: int, model: str, payload: Dict[str, Any]
222
+ ) -> ChatCompletion:
223
+ try:
224
+ response = self._client.session.post(
225
+ self._client.api_endpoint,
226
+ headers=self._client.headers,
227
+ json=payload,
228
+ timeout=self._client.timeout
229
+ )
230
+
231
+ # Handle non-200 responses
232
+ if not response.ok:
233
+ raise IOError(
234
+ f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
235
+ )
236
+
237
+ # Parse the response
238
+ data = response.json()
239
+
240
+ choices_data = data.get('choices', [])
241
+ usage_data = data.get('usage', {})
242
+
243
+ choices = []
244
+ for choice_d in choices_data:
245
+ message_d = choice_d.get('message', {})
246
+ message = ChatCompletionMessage(
247
+ role=message_d.get('role', 'assistant'),
248
+ content=message_d.get('content', '')
249
+ )
250
+ choice = Choice(
251
+ index=choice_d.get('index', 0),
252
+ message=message,
253
+ finish_reason=choice_d.get('finish_reason', 'stop')
254
+ )
255
+ choices.append(choice)
256
+
257
+ usage = CompletionUsage(
258
+ prompt_tokens=usage_data.get('prompt_tokens', 0),
259
+ completion_tokens=usage_data.get('completion_tokens', 0),
260
+ total_tokens=usage_data.get('total_tokens', 0)
261
+ )
262
+
263
+ completion = ChatCompletion(
264
+ id=request_id,
265
+ choices=choices,
266
+ created=created_time,
267
+ model=data.get('model', model),
268
+ usage=usage,
269
+ )
270
+ return completion
271
+
272
+ except Exception as e:
273
+ print(f"Error during TypeGPT non-stream request: {e}")
274
+ raise IOError(f"TypeGPT request failed: {e}") from e
275
+
276
+ class Chat(BaseChat):
277
+ def __init__(self, client: 'TypeGPT'):
278
+ self.completions = Completions(client)
279
+
280
+ class TypeGPT(OpenAICompatibleProvider):
281
+ """
282
+ OpenAI-compatible client for TypeGPT API.
283
+
284
+ Usage:
285
+ client = TypeGPT()
286
+ response = client.chat.completions.create(
287
+ model="gpt-4o",
288
+ messages=[{"role": "user", "content": "Hello!"}]
289
+ )
290
+ """
291
+
292
+ AVAILABLE_MODELS = [
293
+ # Working Models (based on testing)
294
+ "gpt-4o-mini-2024-07-18",
295
+ "chatgpt-4o-latest",
296
+ "deepseek-r1",
297
+ "deepseek-v3",
298
+ "uncensored-r1",
299
+ "Image-Generator",
300
+ ]
301
+
302
+ def __init__(
303
+ self,
304
+ timeout: Optional[int] = None,
305
+ browser: str = "chrome"
306
+ ):
307
+ """
308
+ Initialize the TypeGPT client.
309
+
310
+ Args:
311
+ timeout: Request timeout in seconds (None for no timeout)
312
+ browser: Browser to emulate in user agent
313
+ """
314
+ self.timeout = timeout or 60 # Default to 30 seconds if None
315
+ self.api_endpoint = "https://chat.typegpt.net/api/openai/v1/chat/completions"
316
+ self.session = requests.Session()
317
+
318
+ # Default parameters
319
+ self.max_tokens = 4000
320
+ self.temperature = 0.5
321
+ self.presence_penalty = 0
322
+ self.frequency_penalty = 0
323
+ self.top_p = 1
324
+
325
+ # Initialize LitAgent for user agent generation
326
+ agent = LitAgent()
327
+ self.fingerprint = agent.generate_fingerprint(browser)
328
+
329
+ # Headers for the request
330
+ self.headers = {
331
+ "authority": "chat.typegpt.net",
332
+ "accept": "application/json, text/event-stream",
333
+ "accept-language": self.fingerprint["accept_language"],
334
+ "content-type": "application/json",
335
+ "origin": "https://chat.typegpt.net",
336
+ "referer": "https://chat.typegpt.net/",
337
+ "user-agent": self.fingerprint["user_agent"]
338
+ }
339
+
340
+ self.session.headers.update(self.headers)
341
+
342
+ # Initialize the chat interface
343
+ self.chat = Chat(self)
344
+
345
+ def convert_model_name(self, model: str) -> str:
346
+ """
347
+ Convert model names to ones supported by TypeGPT.
348
+
349
+ Args:
350
+ model: Model name to convert
351
+
352
+ Returns:
353
+ TypeGPT model name
354
+ """
355
+ # If the model is already a valid TypeGPT model, return it
356
+ if model in self.AVAILABLE_MODELS:
357
+ return model
358
+
359
+ # Default to chatgpt-4o-latest if model not found (this one works reliably)
360
+ print(f"Warning: Unknown model '{model}'. Using 'chatgpt-4o-latest' instead.")
361
+ return "chatgpt-4o-latest"