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

@@ -146,7 +146,7 @@ class BLACKBOXAI:
146
146
  for value in response.iter_lines(
147
147
  decode_unicode=True,
148
148
  chunk_size=self.stream_chunk_size,
149
- delimiter="\n",
149
+
150
150
  ):
151
151
  try:
152
152
  if bool(value):
@@ -206,206 +206,6 @@ class BLACKBOXAI:
206
206
  def get_message(self, response: dict) -> str:
207
207
  """Retrieves message only from response
208
208
 
209
- Args:
210
- response (dict): Response generated by `self.ask`
211
-
212
- Returns:
213
- str: Message extracted
214
- """
215
- assert isinstance(response, dict), "Response should be of dict data-type only"
216
- return response["text"]
217
-
218
-
219
-
220
- class AsyncBLACKBOXAI(AsyncProvider):
221
- def __init__(
222
- self,
223
- is_conversation: bool = True,
224
- max_tokens: int = 600,
225
- timeout: int = 30,
226
- intro: str = None,
227
- filepath: str = None,
228
- update_file: bool = True,
229
- proxies: dict = {},
230
- history_offset: int = 10250,
231
- act: str = None,
232
- model: str = None,
233
- ):
234
- """Instantiates BLACKBOXAI
235
-
236
- Args:
237
- is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True
238
- max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
239
- timeout (int, optional): Http request timeout. Defaults to 30.
240
- intro (str, optional): Conversation introductory prompt. Defaults to None.
241
- filepath (str, optional): Path to file containing conversation history. Defaults to None.
242
- update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
243
- proxies (dict, optional): Http request proxies. Defaults to {}.
244
- history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
245
- act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
246
- model (str, optional): Model name. Defaults to "Phind Model".
247
- """
248
- self.max_tokens_to_sample = max_tokens
249
- self.is_conversation = is_conversation
250
- self.chat_endpoint = "https://www.blackbox.ai/api/chat"
251
- self.stream_chunk_size = 64
252
- self.timeout = timeout
253
- self.last_response = {}
254
- self.model = model
255
- self.previewToken: str = None
256
- self.userId: str = ""
257
- self.codeModelMode: bool = True
258
- self.id: str = ""
259
- self.agentMode: dict = {}
260
- self.trendingAgentMode: dict = {}
261
- self.isMicMode: bool = False
262
-
263
- self.headers = {
264
- "Content-Type": "application/json",
265
- "User-Agent": "",
266
- "Accept": "*/*",
267
- "Accept-Encoding": "Identity",
268
- }
269
-
270
- self.__available_optimizers = (
271
- method
272
- for method in dir(Optimizers)
273
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
274
- )
275
- Conversation.intro = (
276
- AwesomePrompts().get_act(
277
- act, raise_not_found=True, default=None, case_insensitive=True
278
- )
279
- if act
280
- else intro or Conversation.intro
281
- )
282
- self.conversation = Conversation(
283
- is_conversation, self.max_tokens_to_sample, filepath, update_file
284
- )
285
- self.conversation.history_offset = history_offset
286
- self.session = httpx.AsyncClient(headers=self.headers, proxies=proxies)
287
-
288
- async def ask(
289
- self,
290
- prompt: str,
291
- stream: bool = False,
292
- raw: bool = False,
293
- optimizer: str = None,
294
- conversationally: bool = False,
295
- ) -> dict | AsyncGenerator:
296
- """Chat with AI asynchronously.
297
-
298
- Args:
299
- prompt (str): Prompt to be send.
300
- stream (bool, optional): Flag for streaming response. Defaults to False.
301
- raw (bool, optional): Stream back raw response as received. Defaults to False.
302
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
303
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
304
- Returns:
305
- dict|AsyncGenerator : ai content
306
- ```json
307
- {
308
- "text" : "print('How may I help you today?')"
309
- }
310
- ```
311
- """
312
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
313
- if optimizer:
314
- if optimizer in self.__available_optimizers:
315
- conversation_prompt = getattr(Optimizers, optimizer)(
316
- conversation_prompt if conversationally else prompt
317
- )
318
- else:
319
- raise Exception(
320
- f"Optimizer is not one of {self.__available_optimizers}"
321
- )
322
-
323
- payload = {
324
- "messages": [
325
- # json.loads(prev_messages),
326
- {"content": conversation_prompt, "role": "user"}
327
- ],
328
- "id": self.id,
329
- "previewToken": self.previewToken,
330
- "userId": self.userId,
331
- "codeModelMode": self.codeModelMode,
332
- "agentMode": self.agentMode,
333
- "trendingAgentMode": self.trendingAgentMode,
334
- "isMicMode": self.isMicMode,
335
- }
336
-
337
- async def for_stream():
338
- async with self.session.stream(
339
- "POST", self.chat_endpoint, json=payload, timeout=self.timeout
340
- ) as response:
341
- if (
342
- not response.is_success
343
- or not response.headers.get("Content-Type")
344
- == "text/plain; charset=utf-8"
345
- ):
346
- raise exceptions.FailedToGenerateResponseError(
347
- f"Failed to generate response - ({response.status_code}, {response.reason_phrase})"
348
- )
349
- streaming_text = ""
350
- async for value in response.aiter_lines():
351
- try:
352
- if bool(value):
353
- streaming_text += value + ("\n" if stream else "")
354
- resp = dict(text=streaming_text)
355
- self.last_response.update(resp)
356
- yield value if raw else resp
357
- except json.decoder.JSONDecodeError:
358
- pass
359
- self.conversation.update_chat_history(
360
- prompt, await self.get_message(self.last_response)
361
- )
362
-
363
- async def for_non_stream():
364
- async for _ in for_stream():
365
- pass
366
- return self.last_response
367
-
368
- return for_stream() if stream else await for_non_stream()
369
-
370
- async def chat(
371
- self,
372
- prompt: str,
373
- stream: bool = False,
374
- optimizer: str = None,
375
- conversationally: bool = False,
376
- ) -> str | AsyncGenerator:
377
- """Generate response `str` asynchronously.
378
- Args:
379
- prompt (str): Prompt to be send.
380
- stream (bool, optional): Flag for streaming response. Defaults to False.
381
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
382
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
383
- Returns:
384
- str|AsyncGenerator: Response generated
385
- """
386
-
387
- async def for_stream():
388
- async_ask = await self.ask(
389
- prompt, True, optimizer=optimizer, conversationally=conversationally
390
- )
391
- async for response in async_ask:
392
- yield await self.get_message(response)
393
-
394
- async def for_non_stream():
395
- return await self.get_message(
396
- await self.ask(
397
- prompt,
398
- False,
399
- optimizer=optimizer,
400
- conversationally=conversationally,
401
- )
402
- )
403
-
404
- return for_stream() if stream else await for_non_stream()
405
-
406
- async def get_message(self, response: dict) -> str:
407
- """Retrieves message only from response
408
-
409
209
  Args:
410
210
  response (dict): Response generated by `self.ask`
411
211
 
@@ -418,10 +218,10 @@ class AsyncBLACKBOXAI(AsyncProvider):
418
218
  # Function to clean the response text
419
219
  def clean_response(response_text: str) -> str:
420
220
  # Remove web search results
421
- response_text = re.sub(r'\$@\$v=undefined-rv1\$@\$Sources:.*?\$~~~', '', response_text, flags=re.DOTALL)
221
+ cleaned_response = re.sub(r'\$~~~\$.*?\$~~~\$', '', response_text, flags=re.DOTALL)
422
222
  # Remove any remaining special characters or markers
423
- response_text = re.sub(r'\$~~~', '', response_text)
424
- return response_text
223
+ cleaned_response = re.sub(r'\$~~~', '', cleaned_response)
224
+ return cleaned_response.strip()
425
225
  if __name__ == '__main__':
426
226
  from rich import print
427
227
  ai = BLACKBOXAI()
@@ -0,0 +1,137 @@
1
+ import requests
2
+ import json
3
+ from typing import Any, Dict, Optional, Generator
4
+
5
+ from webscout.AIutel import Optimizers
6
+ from webscout.AIutel import Conversation
7
+ from webscout.AIutel import AwesomePrompts
8
+ from webscout.AIbase import Provider
9
+ from webscout import exceptions
10
+
11
+
12
+ class Marcus(Provider):
13
+ """
14
+ This class provides methods for interacting with the AskMarcus API.
15
+ Improved to match webscout provider standards.
16
+ """
17
+
18
+ def __init__(
19
+ self,
20
+ is_conversation: bool = True,
21
+ max_tokens: int = 2048, # Added max_tokens parameter
22
+ timeout: int = 30,
23
+ intro: str = None,
24
+ filepath: str = None,
25
+ update_file: bool = True,
26
+ proxies: dict = {},
27
+ history_offset: int = 10250,
28
+ act: str = None,
29
+ ):
30
+ """Initializes the Marcus API."""
31
+ self.session = requests.Session()
32
+ self.is_conversation = is_conversation
33
+ self.max_tokens_to_sample = max_tokens
34
+ self.api_endpoint = "https://www.askmarcus.app/api/response"
35
+ self.timeout = timeout
36
+ self.last_response = {}
37
+ self.headers = {
38
+ 'content-type': 'application/json',
39
+ 'accept': '*/*',
40
+ 'origin': 'https://www.askmarcus.app',
41
+ 'referer': 'https://www.askmarcus.app/chat',
42
+ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
43
+ }
44
+ self.__available_optimizers = (
45
+ method
46
+ for method in dir(Optimizers)
47
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
48
+ )
49
+ Conversation.intro = (
50
+ AwesomePrompts().get_act(
51
+ act, raise_not_found=True, default=None, case_insensitive=True
52
+ )
53
+ if act
54
+ else intro or Conversation.intro
55
+ )
56
+ self.conversation = Conversation(
57
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
58
+ )
59
+ self.conversation.history_offset = history_offset
60
+ self.session.proxies = proxies
61
+
62
+ def ask(
63
+ self,
64
+ prompt: str,
65
+ stream: bool = False,
66
+ raw: bool = False,
67
+ optimizer: str = None,
68
+ conversationally: bool = False,
69
+ ) -> Dict[str, Any] | Generator[str, None, None]:
70
+ """Sends a prompt to the AskMarcus API and returns the response."""
71
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
72
+ if optimizer:
73
+ if optimizer in self.__available_optimizers:
74
+ conversation_prompt = getattr(Optimizers, optimizer)(
75
+ conversation_prompt if conversationally else prompt
76
+ )
77
+ else:
78
+ raise exceptions.FailedToGenerateResponseError(
79
+ f"Optimizer is not one of {self.__available_optimizers}"
80
+ )
81
+
82
+ data = {"message": conversation_prompt}
83
+
84
+ def for_stream():
85
+ try:
86
+ with requests.post(self.api_endpoint, headers=self.headers, json=data, stream=True, timeout=self.timeout) as response:
87
+ response.raise_for_status()
88
+ for line in response.iter_lines():
89
+ if line:
90
+ yield line.decode('utf-8')
91
+ self.conversation.update_chat_history(prompt, self.get_message(self.last_response))
92
+
93
+ except requests.exceptions.RequestException as e:
94
+ raise exceptions.ProviderConnectionError(f"Error connecting to Marcus: {str(e)}")
95
+
96
+ def for_non_stream():
97
+ full_response = ""
98
+ for line in for_stream():
99
+ full_response += line
100
+ self.last_response = {"text": full_response}
101
+ return self.last_response
102
+
103
+ return for_stream() if stream else for_non_stream()
104
+
105
+ def chat(
106
+ self,
107
+ prompt: str,
108
+ stream: bool = False,
109
+ optimizer: str = None,
110
+ conversationally: bool = False,
111
+ ) -> str | Generator[str, None, None]:
112
+ """Generates a response from the AskMarcus API."""
113
+
114
+ def for_stream():
115
+ for response_chunk in self.ask(
116
+ prompt, stream=True, optimizer=optimizer, conversationally=conversationally
117
+ ):
118
+ yield response_chunk
119
+
120
+ def for_non_stream():
121
+ response = self.ask(
122
+ prompt, stream=False, optimizer=optimizer, conversationally=conversationally
123
+ )
124
+ return self.get_message(response)
125
+
126
+ return for_stream() if stream else for_non_stream()
127
+
128
+ def get_message(self, response: Dict[str, Any]) -> str:
129
+ """Extracts the message from the API response."""
130
+ assert isinstance(response, dict), "Response should be of dict data-type only"
131
+ return response.get("text", "")
132
+
133
+ if __name__ == '__main__':
134
+ ai = Marcus(timeout=30)
135
+ response = ai.chat("Tell me about India", stream=True)
136
+ for chunk in response:
137
+ print(chunk)
@@ -7,5 +7,5 @@ from .huggingface import *
7
7
  from .artbit import *
8
8
  from .WebSimAI import *
9
9
  from .imgninza import *
10
- from .AIuncensored import *
10
+ from .AIuncensoredimage import *
11
11
  from .talkai import *
@@ -11,7 +11,6 @@ from .Koboldai import KOBOLDAI
11
11
  from .Koboldai import AsyncKOBOLDAI
12
12
  from .Perplexity import *
13
13
  from .Blackboxai import BLACKBOXAI
14
- from .Blackboxai import AsyncBLACKBOXAI
15
14
  from .Phind import PhindSearch
16
15
  from .Phind import Phindv2
17
16
  from .ai4chat import *
@@ -65,6 +64,9 @@ from .geminiprorealtime import *
65
64
  from .NinjaChat import *
66
65
  from .llmchat import *
67
66
  from .talkai import *
67
+ from .askmyai import *
68
+ from .llama3mitril import *
69
+ from .Marcus import *
68
70
  __all__ = [
69
71
  'Farfalle',
70
72
  'LLAMA',
@@ -78,7 +80,6 @@ __all__ = [
78
80
  'AsyncKOBOLDAI',
79
81
  'Perplexity',
80
82
  'BLACKBOXAI',
81
- 'AsyncBLACKBOXAI',
82
83
  'PhindSearch',
83
84
  'Felo',
84
85
  'GEMINI',
@@ -94,6 +95,7 @@ __all__ = [
94
95
  'KOALA',
95
96
  'RUBIKSAI',
96
97
  'Meta',
98
+ 'AskMyAI',
97
99
  'DiscordRocks',
98
100
  'PiAI',
99
101
  'Julius',
@@ -131,6 +133,8 @@ __all__ = [
131
133
  'GeminiPro',
132
134
  'NinjaChat',
133
135
  'LLMChat',
134
- 'Talkai'
136
+ 'Talkai',
137
+ 'Llama3Mitril',
138
+ 'Marcus',
135
139
 
136
140
  ]
@@ -0,0 +1,158 @@
1
+ import requests
2
+ import json
3
+ import re
4
+ from typing import Any, Dict, Optional, Generator
5
+
6
+ from webscout.AIutel import Optimizers
7
+ from webscout.AIutel import Conversation
8
+ from webscout.AIutel import AwesomePrompts
9
+ from webscout.AIbase import Provider
10
+ from webscout import exceptions
11
+
12
+
13
+ class AskMyAI(Provider):
14
+ """
15
+ A class to interact with the askmyai.chat API. Improved to match webscout standards.
16
+ """
17
+
18
+ def __init__(
19
+ self,
20
+ is_conversation: bool = True,
21
+ max_tokens: int = 2048, # Added max_tokens parameter
22
+ timeout: int = 30,
23
+ intro: str = None,
24
+ filepath: str = None,
25
+ update_file: bool = True,
26
+ proxies: dict = {},
27
+ history_offset: int = 10250,
28
+ act: str = None,
29
+ system_prompt: str = "You are a helpful assistant.", # Added system prompt
30
+ ):
31
+ """Initializes the AskMyAI API."""
32
+ self.session = requests.Session()
33
+ self.is_conversation = is_conversation
34
+ self.max_tokens_to_sample = max_tokens
35
+ self.api_endpoint = "https://www.askmyai.chat/api/chat"
36
+ self.timeout = timeout
37
+ self.last_response = {}
38
+ self.system_prompt = system_prompt # Use system prompt
39
+ self.headers = {
40
+ "Content-Type": "application/json",
41
+ "Accept": "*/*",
42
+ "Accept-Encoding": "gzip, deflate, br",
43
+ "Accept-Language": "en-US,en;q=0.9",
44
+ "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"
45
+ }
46
+ self.__available_optimizers = (
47
+ method
48
+ for method in dir(Optimizers)
49
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
50
+ )
51
+ Conversation.intro = (
52
+ AwesomePrompts().get_act(
53
+ act, raise_not_found=True, default=None, case_insensitive=True
54
+ )
55
+ if act
56
+ else intro or Conversation.intro
57
+ )
58
+ self.conversation = Conversation(
59
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
60
+ )
61
+ self.conversation.history_offset = history_offset
62
+ self.session.proxies = proxies
63
+
64
+ def ask(
65
+ self,
66
+ prompt: str,
67
+ stream: bool = False,
68
+ raw: bool = False,
69
+ optimizer: str = None,
70
+ conversationally: bool = False,
71
+ ) -> Dict[str, Any] | Generator[Dict[str, Any], None, None]:
72
+ """Sends a prompt to the askmyai.chat API and returns the response."""
73
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
74
+ if optimizer:
75
+ if optimizer in self.__available_optimizers:
76
+ conversation_prompt = getattr(Optimizers, optimizer)(
77
+ conversation_prompt if conversationally else prompt
78
+ )
79
+ else:
80
+ raise exceptions.FailedToGenerateResponseError(
81
+ f"Optimizer is not one of {self.__available_optimizers}"
82
+ )
83
+
84
+ payload = {
85
+ "messages": [
86
+ {"role": "system", "content": self.system_prompt},
87
+ {"role": "user", "content": conversation_prompt}
88
+ ],
89
+ "data": {"datasource": "thucpn"}
90
+ }
91
+
92
+ def for_stream():
93
+ response = self.session.post(
94
+ self.api_endpoint, json=payload, stream=True, timeout=self.timeout
95
+ )
96
+ if not response.ok:
97
+ raise exceptions.FailedToGenerateResponseError(
98
+ f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
99
+ )
100
+
101
+ streaming_response = ""
102
+ for line in response.iter_lines(decode_unicode=True):
103
+ if line:
104
+ match = re.search(r'0:"(.*?)"', line)
105
+ if match:
106
+ content = match.group(1)
107
+ streaming_response += content
108
+ yield content if raw else {"text": content}
109
+ self.last_response.update({"text": streaming_response})
110
+ self.conversation.update_chat_history(
111
+ prompt, self.get_message(self.last_response)
112
+ )
113
+
114
+ def for_non_stream():
115
+ full_response = ""
116
+ for chunk in for_stream():
117
+ full_response += chunk if raw else chunk['text']
118
+ return {"text": full_response}
119
+
120
+ return for_stream() if stream else for_non_stream()
121
+
122
+ def chat(
123
+ self,
124
+ prompt: str,
125
+ stream: bool = False,
126
+ optimizer: str = None,
127
+ conversationally: bool = False,
128
+ ) -> str | Generator[str, None, None]:
129
+ """Generates a response from the AskMyAI API."""
130
+
131
+ def for_stream():
132
+ for response in self.ask(
133
+ prompt, stream=True, optimizer=optimizer, conversationally=conversationally
134
+ ):
135
+ yield self.get_message(response)
136
+
137
+ def for_non_stream():
138
+ return self.get_message(
139
+ self.ask(
140
+ prompt, stream=False, optimizer=optimizer, conversationally=conversationally
141
+ )
142
+ )
143
+
144
+ return for_stream() if stream else for_non_stream()
145
+
146
+ def get_message(self, response: Dict[str, Any]) -> str:
147
+ """Extracts the message from the API response."""
148
+ assert isinstance(response, dict), "Response should be of dict data-type only"
149
+ return response["text"].replace('\\n', '\n').replace('\\n\\n', '\n\n')
150
+
151
+ if __name__ == "__main__":
152
+ from rich import print
153
+
154
+ ai = AskMyAI(timeout=30)
155
+ response = ai.chat("write a poem about AI", stream=True)
156
+
157
+ for chunk in response:
158
+ print(chunk, end="", flush=True)
@@ -7,7 +7,7 @@ from webscout.AIutel import Optimizers, Conversation, AwesomePrompts
7
7
  from webscout.AIbase import Provider
8
8
  from webscout import exceptions
9
9
  from fake_useragent import UserAgent
10
- from cerebras.cloud.sdk import Cerebras as CerebrasSDK
10
+ from cerebras.cloud.sdk import Cerebras as CerebrasSDK # type: ignore
11
11
 
12
12
 
13
13
  class Cerebras(Provider):