webscout 7.3__py3-none-any.whl → 7.5__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 (62) hide show
  1. webscout/Provider/AISEARCH/__init__.py +4 -3
  2. webscout/Provider/AISEARCH/genspark_search.py +208 -0
  3. webscout/Provider/AllenAI.py +282 -0
  4. webscout/Provider/C4ai.py +414 -0
  5. webscout/Provider/Cloudflare.py +18 -21
  6. webscout/Provider/DeepSeek.py +3 -32
  7. webscout/Provider/Deepinfra.py +52 -44
  8. webscout/Provider/ElectronHub.py +634 -0
  9. webscout/Provider/GithubChat.py +362 -0
  10. webscout/Provider/Glider.py +7 -41
  11. webscout/Provider/HeckAI.py +217 -0
  12. webscout/Provider/HuggingFaceChat.py +462 -0
  13. webscout/Provider/Jadve.py +49 -63
  14. webscout/Provider/Marcus.py +7 -50
  15. webscout/Provider/Netwrck.py +6 -53
  16. webscout/Provider/PI.py +106 -93
  17. webscout/Provider/Perplexitylabs.py +395 -0
  18. webscout/Provider/Phind.py +29 -3
  19. webscout/Provider/QwenLM.py +7 -61
  20. webscout/Provider/TTI/__init__.py +1 -0
  21. webscout/Provider/TTI/aiarta/__init__.py +2 -0
  22. webscout/Provider/TTI/aiarta/async_aiarta.py +482 -0
  23. webscout/Provider/TTI/aiarta/sync_aiarta.py +409 -0
  24. webscout/Provider/TTI/piclumen/__init__.py +23 -0
  25. webscout/Provider/TTI/piclumen/async_piclumen.py +268 -0
  26. webscout/Provider/TTI/piclumen/sync_piclumen.py +233 -0
  27. webscout/Provider/TextPollinationsAI.py +3 -2
  28. webscout/Provider/TwoAI.py +200 -0
  29. webscout/Provider/Venice.py +200 -0
  30. webscout/Provider/WiseCat.py +1 -18
  31. webscout/Provider/Youchat.py +1 -1
  32. webscout/Provider/__init__.py +25 -2
  33. webscout/Provider/akashgpt.py +315 -0
  34. webscout/Provider/chatglm.py +5 -5
  35. webscout/Provider/copilot.py +416 -0
  36. webscout/Provider/flowith.py +181 -0
  37. webscout/Provider/freeaichat.py +251 -221
  38. webscout/Provider/granite.py +17 -53
  39. webscout/Provider/koala.py +9 -1
  40. webscout/Provider/llamatutor.py +6 -46
  41. webscout/Provider/llmchat.py +7 -46
  42. webscout/Provider/multichat.py +29 -91
  43. webscout/Provider/yep.py +4 -24
  44. webscout/exceptions.py +19 -9
  45. webscout/update_checker.py +55 -93
  46. webscout/version.py +1 -1
  47. webscout-7.5.dist-info/LICENSE.md +146 -0
  48. {webscout-7.3.dist-info → webscout-7.5.dist-info}/METADATA +46 -172
  49. {webscout-7.3.dist-info → webscout-7.5.dist-info}/RECORD +52 -42
  50. webscout/Local/__init__.py +0 -10
  51. webscout/Local/_version.py +0 -3
  52. webscout/Local/formats.py +0 -747
  53. webscout/Local/model.py +0 -1368
  54. webscout/Local/samplers.py +0 -125
  55. webscout/Local/thread.py +0 -539
  56. webscout/Local/ui.py +0 -401
  57. webscout/Local/utils.py +0 -388
  58. webscout/Provider/dgaf.py +0 -214
  59. webscout-7.3.dist-info/LICENSE.md +0 -211
  60. {webscout-7.3.dist-info → webscout-7.5.dist-info}/WHEEL +0 -0
  61. {webscout-7.3.dist-info → webscout-7.5.dist-info}/entry_points.txt +0 -0
  62. {webscout-7.3.dist-info → webscout-7.5.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,362 @@
1
+ import requests
2
+ import json
3
+ import time
4
+ from typing import Any, Dict, List, Optional, Union, Generator
5
+
6
+ from webscout.AIutel import Conversation
7
+ from webscout.AIutel import Optimizers
8
+ from webscout.AIutel import AwesomePrompts
9
+ from webscout.AIbase import Provider
10
+ from webscout import exceptions
11
+ from webscout import LitAgent
12
+
13
+ class GithubChat(Provider):
14
+ """
15
+ A class to interact with the GitHub Copilot Chat API.
16
+ Uses cookies for authentication and supports streaming responses.
17
+ """
18
+
19
+ # Available models
20
+ AVAILABLE_MODELS = [
21
+ "gpt-4o",
22
+ "o3-mini",
23
+ "o1",
24
+ "claude-3.5-sonnet",
25
+ "claude-3.7-sonnet",
26
+ "claude-3.7-sonnet-thought",
27
+ "gemini-2.0-flash-001"
28
+
29
+ ]
30
+
31
+ def __init__(
32
+ self,
33
+ is_conversation: bool = True,
34
+ max_tokens: int = 2000,
35
+ timeout: int = 60,
36
+ intro: str = None,
37
+ filepath: str = None,
38
+ update_file: bool = True,
39
+ proxies: dict = {},
40
+ history_offset: int = 10250,
41
+ act: str = None,
42
+ model: str = "gpt-4o",
43
+ cookie_path: str = "cookies.json"
44
+ ):
45
+ """Initialize the GithubChat client."""
46
+ if model not in self.AVAILABLE_MODELS:
47
+ raise ValueError(f"Invalid model: {model}. Choose from: {', '.join(self.AVAILABLE_MODELS)}")
48
+
49
+ self.url = "https://github.com/copilot"
50
+ self.api_url = "https://api.individual.githubcopilot.com"
51
+ self.cookie_path = cookie_path
52
+ self.session = requests.Session()
53
+ self.session.proxies.update(proxies)
54
+
55
+ # Load cookies for authentication
56
+ self.cookies = self.load_cookies()
57
+
58
+ # Set up headers for all requests
59
+ self.headers = {
60
+ "Content-Type": "application/json",
61
+ "User-Agent": LitAgent().random(),
62
+ "Accept": "*/*",
63
+ "Accept-Encoding": "gzip, deflate, br",
64
+ "Accept-Language": "en-US,en;q=0.5",
65
+ "Origin": "https://github.com",
66
+ "Referer": "https://github.com/copilot",
67
+ "GitHub-Verified-Fetch": "true",
68
+ "X-Requested-With": "XMLHttpRequest",
69
+ "Connection": "keep-alive",
70
+ "Sec-Fetch-Dest": "empty",
71
+ "Sec-Fetch-Mode": "cors",
72
+ "Sec-Fetch-Site": "same-origin",
73
+ }
74
+
75
+ # Apply cookies to session
76
+ if self.cookies:
77
+ self.session.cookies.update(self.cookies)
78
+
79
+ # Set default model
80
+ self.model = model
81
+
82
+ # Provider settings
83
+ self.is_conversation = is_conversation
84
+ self.max_tokens_to_sample = max_tokens
85
+ self.timeout = timeout
86
+ self.last_response = {}
87
+
88
+ # Available optimizers
89
+ self.__available_optimizers = (
90
+ method
91
+ for method in dir(Optimizers)
92
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
93
+ )
94
+
95
+ # Set up conversation
96
+ Conversation.intro = (
97
+ AwesomePrompts().get_act(
98
+ act, raise_not_found=True, default=None, case_insensitive=True
99
+ )
100
+ if act
101
+ else intro or Conversation.intro
102
+ )
103
+
104
+ self.conversation = Conversation(
105
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
106
+ )
107
+ self.conversation.history_offset = history_offset
108
+
109
+ # Store conversation data
110
+ self._conversation_id = None
111
+ self._access_token = None
112
+
113
+ def load_cookies(self):
114
+ """Load cookies from a JSON file"""
115
+ try:
116
+ with open(self.cookie_path, 'r') as f:
117
+ cookies_data = json.load(f)
118
+
119
+ # Convert the cookie list to a dictionary format for requests
120
+ cookies = {}
121
+ for cookie in cookies_data:
122
+ # Only include cookies that are not expired and have a name and value
123
+ if 'name' in cookie and 'value':
124
+ # Check if the cookie hasn't expired
125
+ if 'expirationDate' not in cookie or cookie['expirationDate'] > time.time():
126
+ cookies[cookie['name']] = cookie['value']
127
+
128
+ return cookies
129
+ except Exception:
130
+ return {}
131
+
132
+ def get_access_token(self):
133
+ """Get GitHub Copilot access token."""
134
+ if self._access_token:
135
+ return self._access_token
136
+
137
+ url = "https://github.com/github-copilot/chat/token"
138
+
139
+ try:
140
+ response = self.session.post(url, headers=self.headers)
141
+
142
+ if response.status_code == 401:
143
+ raise exceptions.AuthenticationError("Authentication failed. Please check your cookies.")
144
+
145
+ if response.status_code != 200:
146
+ raise exceptions.FailedToGenerateResponseError(f"Failed to get access token: {response.status_code}")
147
+
148
+ data = response.json()
149
+ self._access_token = data.get("token")
150
+
151
+ if not self._access_token:
152
+ raise exceptions.FailedToGenerateResponseError("Failed to extract access token from response")
153
+
154
+ return self._access_token
155
+
156
+ except requests.exceptions.RequestException as e:
157
+ raise exceptions.FailedToGenerateResponseError(f"Failed to get access token: {str(e)}")
158
+
159
+ def create_conversation(self):
160
+ """Create a new conversation with GitHub Copilot."""
161
+ if self._conversation_id:
162
+ return self._conversation_id
163
+
164
+ access_token = self.get_access_token()
165
+ url = f"{self.api_url}/github/chat/threads"
166
+
167
+ headers = self.headers.copy()
168
+ headers["Authorization"] = f"GitHub-Bearer {access_token}"
169
+
170
+ try:
171
+ response = self.session.post(url, headers=headers)
172
+
173
+ if response.status_code == 401:
174
+ # Token might be expired, try refreshing
175
+ self._access_token = None
176
+ access_token = self.get_access_token()
177
+ headers["Authorization"] = f"GitHub-Bearer {access_token}"
178
+ response = self.session.post(url, headers=headers)
179
+
180
+ if response.status_code not in [200, 201]:
181
+ raise exceptions.FailedToGenerateResponseError(f"Failed to create conversation: {response.status_code}")
182
+
183
+ data = response.json()
184
+ self._conversation_id = data.get("thread_id")
185
+
186
+ if not self._conversation_id:
187
+ raise exceptions.FailedToGenerateResponseError("Failed to extract conversation ID from response")
188
+
189
+ return self._conversation_id
190
+
191
+ except requests.exceptions.RequestException as e:
192
+ raise exceptions.FailedToGenerateResponseError(f"Failed to create conversation: {str(e)}")
193
+
194
+ def process_response(self, response, prompt: str):
195
+ """Process streaming response and extract content."""
196
+ full_text = ""
197
+
198
+ for line in response.iter_lines(decode_unicode=True):
199
+ if not line or not line.startswith("data: "):
200
+ continue
201
+
202
+ try:
203
+ # Parse each line (remove "data: " prefix)
204
+ json_str = line[6:]
205
+ if json_str == "[DONE]":
206
+ break
207
+
208
+ data = json.loads(json_str)
209
+
210
+ # Handle different response types
211
+ if data.get("type") == "content":
212
+ token = data.get("body", "")
213
+ full_text += token
214
+ resp = {"text": token}
215
+ yield resp
216
+
217
+ except json.JSONDecodeError:
218
+ continue
219
+
220
+ # Update conversation history only for saving to file if needed
221
+ if full_text:
222
+ self.last_response = {"text": full_text}
223
+ self.conversation.update_chat_history(prompt, full_text)
224
+
225
+ def ask(
226
+ self,
227
+ prompt: str,
228
+ stream: bool = False,
229
+ raw: bool = False,
230
+ optimizer: str = None,
231
+ conversationally: bool = False,
232
+ ) -> Union[Dict[str, Any], Generator]:
233
+ """Send a message to the GitHub Copilot Chat API"""
234
+
235
+ # Apply optimizers if specified
236
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
237
+ if optimizer:
238
+ if optimizer in self.__available_optimizers:
239
+ conversation_prompt = getattr(Optimizers, optimizer)(
240
+ conversation_prompt if conversationally else prompt
241
+ )
242
+ else:
243
+ raise Exception(f"Optimizer is not one of {self.__available_optimizers}")
244
+
245
+ # Make sure we have a conversation ID
246
+ try:
247
+ conversation_id = self.create_conversation()
248
+ except exceptions.FailedToGenerateResponseError as e:
249
+ raise exceptions.FailedToGenerateResponseError(f"Failed to create conversation: {e}")
250
+
251
+ access_token = self.get_access_token()
252
+
253
+ url = f"{self.api_url}/github/chat/threads/{conversation_id}/messages"
254
+
255
+ # Update headers for this specific request
256
+ headers = self.headers.copy()
257
+ headers["Authorization"] = f"GitHub-Bearer {access_token}"
258
+
259
+ # Prepare the request payload
260
+ request_data = {
261
+ "content": conversation_prompt,
262
+ "intent": "conversation",
263
+ "references": [],
264
+ "context": [],
265
+ "currentURL": f"https://github.com/copilot/c/{conversation_id}",
266
+ "streaming": True,
267
+ "confirmations": [],
268
+ "customInstructions": [],
269
+ "model": self.model,
270
+ "mode": "immersive"
271
+ }
272
+
273
+ def for_stream():
274
+ try:
275
+ response = self.session.post(
276
+ url,
277
+ json=request_data,
278
+ headers=headers,
279
+ stream=True,
280
+ timeout=self.timeout
281
+ )
282
+
283
+ if response.status_code == 401:
284
+ # Token might be expired, try refreshing
285
+ self._access_token = None
286
+ access_token = self.get_access_token()
287
+ headers["Authorization"] = f"GitHub-Bearer {access_token}"
288
+ response = self.session.post(
289
+ url,
290
+ json=request_data,
291
+ headers=headers,
292
+ stream=True,
293
+ timeout=self.timeout
294
+ )
295
+
296
+ # If still not successful, raise exception
297
+ if response.status_code != 200:
298
+ raise exceptions.FailedToGenerateResponseError(f"Request failed with status code {response.status_code}")
299
+
300
+ # Process the streaming response
301
+ yield from self.process_response(response, prompt)
302
+
303
+ except Exception as e:
304
+ if isinstance(e, requests.exceptions.RequestException):
305
+ if hasattr(e, 'response') and e.response is not None:
306
+ status_code = e.response.status_code
307
+ if status_code == 401:
308
+ raise exceptions.AuthenticationError("Authentication failed. Please check your cookies.")
309
+
310
+ # If anything else fails
311
+ raise exceptions.FailedToGenerateResponseError(f"Request failed: {str(e)}")
312
+
313
+ def for_non_stream():
314
+ response_text = ""
315
+ for response in for_stream():
316
+ if "text" in response:
317
+ response_text += response["text"]
318
+ self.last_response = {"text": response_text}
319
+ return self.last_response
320
+
321
+ return for_stream() if stream else for_non_stream()
322
+
323
+ def chat(
324
+ self,
325
+ prompt: str,
326
+ stream: bool = False,
327
+ optimizer: str = None,
328
+ conversationally: bool = False,
329
+ ) -> Union[str, Generator]:
330
+ """Generate a response to a prompt"""
331
+ def for_stream():
332
+ for response in self.ask(
333
+ prompt, True, optimizer=optimizer, conversationally=conversationally
334
+ ):
335
+ yield self.get_message(response)
336
+
337
+ def for_non_stream():
338
+ return self.get_message(
339
+ self.ask(
340
+ prompt, False, optimizer=optimizer, conversationally=conversationally
341
+ )
342
+ )
343
+
344
+ return for_stream() if stream else for_non_stream()
345
+
346
+ def get_message(self, response: dict) -> str:
347
+ """Extract message text from response"""
348
+ assert isinstance(response, dict), "Response should be of dict data-type only"
349
+ return response.get("text", "")
350
+
351
+ if __name__ == "__main__":
352
+ # Simple test code
353
+ from rich import print
354
+
355
+ try:
356
+ ai = GithubChat()
357
+ response = ai.chat("Python code to count r in strawberry", stream=True)
358
+ for chunk in response:
359
+ print(chunk, end="", flush=True)
360
+ print()
361
+ except Exception as e:
362
+ print(f"An error occurred: {e}")
@@ -5,12 +5,11 @@ from typing import Any, Dict, Generator, Optional
5
5
  from webscout.AIutel import Optimizers, Conversation, AwesomePrompts
6
6
  from webscout.AIbase import Provider
7
7
  from webscout import exceptions
8
- from webscout.Litlogger import Logger, LogFormat
9
8
  from webscout import LitAgent as Lit
10
9
 
11
10
  class GliderAI(Provider):
12
11
  """
13
- A class to interact with the Glider.so API with comprehensive logging.
12
+ A class to interact with the Glider.so API.
14
13
  """
15
14
 
16
15
  AVAILABLE_MODELS = {
@@ -32,22 +31,12 @@ class GliderAI(Provider):
32
31
  history_offset: int = 10250,
33
32
  act: Optional[str] = None,
34
33
  model: str = "chat-llama-3-1-70b",
35
- system_prompt: str = "You are a helpful AI assistant.",
36
- logging: bool = False
34
+ system_prompt: str = "You are a helpful AI assistant."
37
35
  ):
38
- """Initializes the GliderAI API client with logging capabilities."""
36
+ """Initializes the GliderAI API client."""
39
37
  if model not in self.AVAILABLE_MODELS:
40
38
  raise ValueError(f"Invalid model: {model}. Choose from: {', '.join(self.AVAILABLE_MODELS)}")
41
39
 
42
- self.logger = Logger(
43
- name="GliderAI",
44
- format=LogFormat.MODERN_EMOJI,
45
-
46
- ) if logging else None
47
-
48
- if self.logger:
49
- self.logger.info(f"Initializing GliderAI with model: {model}")
50
-
51
40
  self.session = requests.Session()
52
41
  self.is_conversation = is_conversation
53
42
  self.max_tokens_to_sample = max_tokens
@@ -85,9 +74,6 @@ class GliderAI(Provider):
85
74
  )
86
75
  self.conversation.history_offset = history_offset
87
76
 
88
- if self.logger:
89
- self.logger.info("GliderAI initialized successfully")
90
-
91
77
  def ask(
92
78
  self,
93
79
  prompt: str,
@@ -96,7 +82,7 @@ class GliderAI(Provider):
96
82
  optimizer: Optional[str] = None,
97
83
  conversationally: bool = False,
98
84
  ) -> Dict[str, Any] | Generator[Dict[str, Any], None, None]:
99
- """Chat with AI with logging capabilities.
85
+ """Chat with AI.
100
86
 
101
87
  Args:
102
88
  prompt (str): Prompt to be sent.
@@ -107,21 +93,13 @@ class GliderAI(Provider):
107
93
  Returns:
108
94
  dict or Generator[dict, None, None]: The response from the API.
109
95
  """
110
- if self.logger:
111
- self.logger.debug(f"Processing request - Prompt: {prompt[:50]}...")
112
- self.logger.debug(f"Stream: {stream}, Optimizer: {optimizer}")
113
-
114
96
  conversation_prompt = self.conversation.gen_complete_prompt(prompt)
115
97
  if optimizer:
116
98
  if optimizer in self.__available_optimizers:
117
99
  conversation_prompt = getattr(Optimizers, optimizer)(
118
100
  conversation_prompt if conversationally else prompt
119
101
  )
120
- if self.logger:
121
- self.logger.debug(f"Applied optimizer: {optimizer}")
122
102
  else:
123
- if self.logger:
124
- self.logger.error(f"Invalid optimizer requested: {optimizer}")
125
103
  raise Exception(f"Optimizer is not one of {list(self.__available_optimizers)}")
126
104
 
127
105
  payload = {
@@ -133,16 +111,10 @@ class GliderAI(Provider):
133
111
  }
134
112
 
135
113
  def for_stream():
136
- if self.logger:
137
- self.logger.debug("Initiating streaming request to API")
138
114
  response = self.session.post(
139
115
  self.api_endpoint, json=payload, stream=True, timeout=self.timeout
140
116
  )
141
117
  if not response.ok:
142
- if self.logger:
143
- self.logger.error(
144
- f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
145
- )
146
118
  raise exceptions.FailedToGenerateResponseError(
147
119
  f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
148
120
  )
@@ -161,12 +133,8 @@ class GliderAI(Provider):
161
133
  break
162
134
  self.last_response.update(dict(text=streaming_text))
163
135
  self.conversation.update_chat_history(prompt, self.get_message(self.last_response))
164
- if self.logger:
165
- self.logger.debug("Response processing completed")
166
136
 
167
137
  def for_non_stream():
168
- if self.logger:
169
- self.logger.debug("Processing non-streaming request")
170
138
  for _ in for_stream():
171
139
  pass
172
140
  return self.last_response
@@ -180,7 +148,7 @@ class GliderAI(Provider):
180
148
  optimizer: Optional[str] = None,
181
149
  conversationally: bool = False,
182
150
  ) -> str | Generator[str, None, None]:
183
- """Generate response as a string with logging.
151
+ """Generate response as a string.
184
152
 
185
153
  Args:
186
154
  prompt (str): Prompt to be sent.
@@ -190,8 +158,6 @@ class GliderAI(Provider):
190
158
  Returns:
191
159
  str or Generator[str, None, None]: The response generated.
192
160
  """
193
- if self.logger:
194
- self.logger.debug(f"Chat request initiated - Prompt: {prompt[:50]}...")
195
161
  def for_stream():
196
162
  for response in self.ask(
197
163
  prompt, True, optimizer=optimizer, conversationally=conversationally
@@ -215,8 +181,8 @@ class GliderAI(Provider):
215
181
 
216
182
  if __name__ == "__main__":
217
183
  from rich import print
218
- # For testing with logging enabled
219
- ai = GliderAI(model="chat-llama-3-1-70b", logging=True)
184
+ # For testing
185
+ ai = GliderAI(model="chat-llama-3-1-70b")
220
186
  response = ai.chat("Meaning of Life", stream=True)
221
187
  for chunk in response:
222
188
  print(chunk, end="", flush=True)