webscout 6.2b0__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()
@@ -183,7 +183,7 @@ class LLAMA3(Provider):
183
183
 
184
184
  if __name__ == "__main__":
185
185
  from rich import print
186
- ai = LLAMA3(api_key='7979b01c-c5ea-40df-9198-f45733fa2208')
186
+ ai = LLAMA3(api_key='')
187
187
  response = ai.chat(input(">>> "))
188
188
  for chunks in response:
189
189
  print(chunks, end="", flush=True)
@@ -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,4 +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
+ from .talkai import *
@@ -0,0 +1,116 @@
1
+ import uuid
2
+ import requests
3
+ import json
4
+ import os
5
+ from typing import Any, Dict, List, Optional
6
+
7
+ from webscout.AIbase import ImageProvider
8
+ from webscout import exceptions
9
+
10
+
11
+ class TalkaiImager(ImageProvider):
12
+ """
13
+ Image provider for Talkai.info.
14
+ """
15
+
16
+ def __init__(self, timeout: int = 60, proxies: dict = {}):
17
+ """Initializes the TalkaiImager class.
18
+
19
+ Args:
20
+ timeout (int, optional): HTTP request timeout in seconds. Defaults to 60.
21
+ proxies (dict, optional): HTTP request proxies. Defaults to {}.
22
+ """
23
+ self.api_endpoint = "https://talkai.info/chat/send/"
24
+ self.headers = {
25
+ 'accept': 'application/json',
26
+ 'accept-language': 'en-US,en;q=0.9',
27
+ 'content-type': 'application/json',
28
+ 'origin': 'https://talkai.info',
29
+ 'referer': 'https://talkai.info/image/',
30
+ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
31
+ }
32
+ self.session = requests.Session()
33
+ self.session.headers.update(self.headers)
34
+ self.session.proxies.update(proxies)
35
+ self.timeout = timeout
36
+ self.prompt: str = "AI-generated image - webscout"
37
+ self.image_extension: str = "png"
38
+
39
+ def generate(self, prompt: str, amount: int = 1) -> List[str]:
40
+ """Generates image URLs from a prompt."""
41
+ assert bool(prompt), "Prompt cannot be empty."
42
+ assert isinstance(amount, int) and amount > 0, "Amount must be a positive integer."
43
+
44
+ self.prompt = prompt
45
+ image_urls = []
46
+
47
+ try:
48
+ with self.session.post(self.api_endpoint, json=self._create_payload(prompt), timeout=self.timeout) as response:
49
+ response.raise_for_status()
50
+ data = response.json()
51
+
52
+ if 'data' in data and len(data['data']) > 0 and 'url' in data['data'][0]:
53
+ image_urls.append(data['data'][0]['url'])
54
+ else:
55
+ raise exceptions.InvalidResponseError("No image URL found in API response.")
56
+
57
+ except requests.exceptions.RequestException as e:
58
+ raise exceptions.APIConnectionError(f"Error making API request: {e}") from e
59
+ except json.JSONDecodeError as e:
60
+ raise exceptions.InvalidResponseError(f"Invalid JSON response: {e}") from e
61
+ except Exception as e:
62
+ raise exceptions.FailedToGenerateResponseError(f"An unexpected error occurred: {e}") from e
63
+
64
+ return image_urls
65
+
66
+ def _create_payload(self, prompt: str) -> Dict[str, Any]:
67
+ return {
68
+ "type": "image",
69
+ "messagesHistory": [
70
+ {
71
+ "id": str(uuid.uuid4()),
72
+ "from": "you",
73
+ "content": prompt
74
+ }
75
+ ],
76
+ "settings": {
77
+ "model": "gpt-4o-mini" # Or another suitable model if available
78
+ }
79
+ }
80
+
81
+
82
+ def save(
83
+ self,
84
+ response: List[str],
85
+ name: str = None,
86
+ dir: str = os.getcwd(),
87
+ filenames_prefix: str = "",
88
+ ) -> List[str]:
89
+ assert isinstance(response, list), f"Response should be a list, not {type(response)}"
90
+ name = self.prompt if name is None else name
91
+
92
+ filenames = []
93
+ for i, url in enumerate(response):
94
+ try:
95
+ with self.session.get(url, stream=True, timeout=self.timeout) as r:
96
+ r.raise_for_status()
97
+ filename = f"{filenames_prefix}{name}_{i}.{self.image_extension}"
98
+ filepath = os.path.join(dir, filename)
99
+ with open(filepath, 'wb') as f:
100
+ for chunk in r.iter_content(chunk_size=8192):
101
+ f.write(chunk)
102
+ filenames.append(filename)
103
+ except requests.exceptions.RequestException as e:
104
+ print(f"Error downloading image from {url}: {e}")
105
+ filenames.append(None) # Indicate failure to download
106
+
107
+ return filenames
108
+
109
+
110
+ if __name__ == "__main__":
111
+ bot = TalkaiImager()
112
+ try:
113
+ resp = bot.generate("A shiny red sports car speeding down a scenic mountain road", 1)
114
+ print(bot.save(resp))
115
+ except Exception as e:
116
+ print(f"An error occurred: {e}")
@@ -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 *
@@ -63,6 +62,11 @@ from .aimathgpt import *
63
62
  from .gaurish import *
64
63
  from .geminiprorealtime import *
65
64
  from .NinjaChat import *
65
+ from .llmchat import *
66
+ from .talkai import *
67
+ from .askmyai import *
68
+ from .llama3mitril import *
69
+ from .Marcus import *
66
70
  __all__ = [
67
71
  'Farfalle',
68
72
  'LLAMA',
@@ -76,7 +80,6 @@ __all__ = [
76
80
  'AsyncKOBOLDAI',
77
81
  'Perplexity',
78
82
  'BLACKBOXAI',
79
- 'AsyncBLACKBOXAI',
80
83
  'PhindSearch',
81
84
  'Felo',
82
85
  'GEMINI',
@@ -92,6 +95,7 @@ __all__ = [
92
95
  'KOALA',
93
96
  'RUBIKSAI',
94
97
  'Meta',
98
+ 'AskMyAI',
95
99
  'DiscordRocks',
96
100
  'PiAI',
97
101
  'Julius',
@@ -128,6 +132,9 @@ __all__ = [
128
132
  'GaurishCerebras',
129
133
  'GeminiPro',
130
134
  'NinjaChat',
131
-
135
+ 'LLMChat',
136
+ 'Talkai',
137
+ 'Llama3Mitril',
138
+ 'Marcus',
132
139
 
133
140
  ]