webscout 4.4__py3-none-any.whl → 4.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.

@@ -0,0 +1,239 @@
1
+ import requests
2
+ import json
3
+ from typing import Any, Dict, Optional
4
+ from ..AIutel import Optimizers
5
+ from ..AIutel import Conversation
6
+ from ..AIutel import AwesomePrompts, sanitize_stream
7
+ from ..AIbase import Provider
8
+ from webscout import exceptions
9
+
10
+ class KOALA(Provider):
11
+ """
12
+ A class to interact with the Koala.sh API.
13
+ """
14
+
15
+ def __init__(
16
+ self,
17
+ is_conversation: bool = True,
18
+ max_tokens: int = 600,
19
+ timeout: int = 30,
20
+ intro: str = None,
21
+ filepath: str = None,
22
+ update_file: bool = True,
23
+ proxies: dict = {},
24
+ history_offset: int = 10250,
25
+ act: str = None,
26
+ model: str = "gpt-4o-mini",
27
+ web_search: bool = True,
28
+
29
+ ) -> None:
30
+ """
31
+ Initializes the KOALASH API with given parameters.
32
+
33
+ Args:
34
+ is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
35
+ max_tokens (int, optional): Maximum number of tokens to be generated upon completion.
36
+ Defaults to 600.
37
+ timeout (int, optional): Http request timeout. Defaults to 30.
38
+ intro (str, optional): Conversation introductory prompt. Defaults to None.
39
+ filepath (str, optional): Path to file containing conversation history. Defaults to None.
40
+ update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
41
+ proxies (dict, optional): Http request proxies. Defaults to {}.
42
+ history_offset (int, optional): Limit conversation history to this number of last texts.
43
+ Defaults to 10250.
44
+ act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
45
+ model (str, optional): AI model to use. Defaults to "gpt-4o-mini".
46
+ """
47
+ self.session = requests.Session()
48
+ self.is_conversation = is_conversation
49
+ self.max_tokens_to_sample = max_tokens
50
+ self.api_endpoint = "https://koala.sh/api/gpt/"
51
+ self.stream_chunk_size = 64
52
+ self.timeout = timeout
53
+ self.last_response = {}
54
+ self.model = model
55
+ self.headers = {
56
+ "accept": "text/event-stream",
57
+ "accept-encoding": "gzip, deflate, br, zstd",
58
+ "accept-language": "en-US,en;q=0.9,en-IN;q=0.8",
59
+ "content-length": "73",
60
+ "content-type": "application/json",
61
+ "dnt": "1",
62
+ "flag-real-time-data": "true" if web_search else "false",
63
+ "origin": "https://koala.sh",
64
+ "priority": "u=1, i",
65
+ "referer": "https://koala.sh/chat",
66
+ "sec-ch-ua": '"Not)A;Brand";v="99", "Microsoft Edge";v="127", "Chromium";v="127"',
67
+ "sec-ch-ua-mobile": "?0",
68
+ "sec-ch-ua-platform": '"Windows"',
69
+ "sec-fetch-dest": "empty",
70
+ "sec-fetch-mode": "cors",
71
+ "sec-fetch-site": "same-origin",
72
+ "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 Edg/127.0.0.0",
73
+ }
74
+
75
+ self.__available_optimizers = (
76
+ method
77
+ for method in dir(Optimizers)
78
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
79
+ )
80
+ self.session.headers.update(self.headers)
81
+ Conversation.intro = (
82
+ AwesomePrompts().get_act(
83
+ act, raise_not_found=True, default=None, case_insensitive=True
84
+ )
85
+ if act
86
+ else intro or Conversation.intro
87
+ )
88
+ self.conversation = Conversation(
89
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
90
+ )
91
+ self.conversation.history_offset = history_offset
92
+ self.session.proxies = proxies
93
+
94
+ def ask(
95
+ self,
96
+ prompt: str,
97
+ stream: bool = False,
98
+ raw: bool = False,
99
+ optimizer: str = None,
100
+ conversationally: bool = False,
101
+ ) -> Dict[str, Any]:
102
+ """
103
+ Sends a prompt to the Koala.sh API and returns the response.
104
+
105
+ Args:
106
+ prompt: The text prompt to generate text from.
107
+ stream (bool, optional): Whether to stream the response. Defaults to False.
108
+ raw (bool, optional): Whether to return the raw response. Defaults to False.
109
+ optimizer (str, optional): The name of the optimizer to use. Defaults to None.
110
+ conversationally (bool, optional): Whether to chat conversationally. Defaults to False.
111
+
112
+ Returns:
113
+ The response from the API.
114
+ """
115
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
116
+ if optimizer:
117
+ if optimizer in self.__available_optimizers:
118
+ conversation_prompt = getattr(Optimizers, optimizer)(
119
+ conversation_prompt if conversationally else prompt
120
+ )
121
+ else:
122
+ raise Exception(
123
+ f"Optimizer is not one of {self.__available_optimizers}"
124
+ )
125
+
126
+ payload = {
127
+ "input": conversation_prompt,
128
+ "model": self.model
129
+ }
130
+
131
+ def for_stream():
132
+ response = self.session.post(
133
+ self.api_endpoint, json=payload, headers=self.headers, stream=True, timeout=self.timeout
134
+ )
135
+
136
+ if not response.ok:
137
+ raise exceptions.FailedToGenerateResponseError(
138
+ f"Failed to generate response - ({response.status_code}, {response.reason})"
139
+ )
140
+
141
+ streaming_response = ""
142
+ for line in response.iter_lines(decode_unicode=True):
143
+ if line:
144
+ if line.startswith("data:"):
145
+ data = line[len("data:"):].strip()
146
+ if data:
147
+ try:
148
+ event = json.loads(data)
149
+ streaming_response += event.get("choices", [{}])[0].get("delta", {}).get("content", "")
150
+ yield event if raw else dict(text=streaming_response)
151
+ except json.decoder.JSONDecodeError:
152
+ continue
153
+ self.last_response.update(dict(text=streaming_response))
154
+ self.conversation.update_chat_history(
155
+ prompt, self.get_message(self.last_response)
156
+ )
157
+ def for_non_stream():
158
+ response = self.session.post(
159
+ self.api_endpoint, json=payload, headers=self.headers, timeout=self.timeout
160
+ )
161
+
162
+ if not response.ok:
163
+ raise exceptions.FailedToGenerateResponseError(
164
+ f"Failed to generate response - ({response.status_code}, {response.reason})"
165
+ )
166
+
167
+ response_content = response.content.decode('utf-8')
168
+ data_parts = response_content.strip().split('\n\n')
169
+ formatted_response = ''.join([part.replace('data: ', '') for part in data_parts if part.startswith('data: ')])
170
+
171
+ # Remove extra quotes from the formatted response
172
+ formatted_response = formatted_response.replace('""', '')
173
+
174
+ # Split the response into lines and format with new lines before headers
175
+ lines = formatted_response.split('\n')
176
+ formatted_lines = []
177
+ for line in lines:
178
+ if line.startswith('###'):
179
+ formatted_lines.append('\n' + line)
180
+ else:
181
+ formatted_lines.append(line)
182
+
183
+ # Join the formatted lines back into a single string
184
+ final_response = '\n'.join(formatted_lines)
185
+
186
+ # self.last_response.update(dict(text=streaming_response))
187
+ self.conversation.update_chat_history(
188
+ prompt, final_response
189
+ )
190
+ return dict(text=final_response)
191
+
192
+ return for_stream() if stream else for_non_stream()
193
+
194
+ def chat(
195
+ self,
196
+ prompt: str,
197
+ stream: bool = False,
198
+ optimizer: str = None,
199
+ conversationally: bool = False,
200
+ ) -> str:
201
+ """Generate response `str`
202
+ Args:
203
+ prompt (str): Prompt to be send.
204
+ stream (bool, optional): Flag for streaming response. Defaults to False.
205
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
206
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
207
+ Returns:
208
+ str: Response generated
209
+ """
210
+
211
+ def for_stream():
212
+ for response in self.ask(
213
+ prompt, True, optimizer=optimizer, conversationally=conversationally
214
+ ):
215
+ yield self.get_message(response)
216
+
217
+ def for_non_stream():
218
+ return self.get_message(
219
+ self.ask(
220
+ prompt,
221
+ False,
222
+ optimizer=optimizer,
223
+ conversationally=conversationally,
224
+ )
225
+ )
226
+
227
+ return for_stream() if stream else for_non_stream()
228
+
229
+ def get_message(self, response: dict) -> str:
230
+ """Retrieves message only from response
231
+
232
+ Args:
233
+ response (dict): Response generated by `self.ask`
234
+
235
+ Returns:
236
+ str: Message extracted
237
+ """
238
+ assert isinstance(response, dict), "Response should be of dict data-type only"
239
+ return response["text"]
webscout/__init__.py CHANGED
@@ -7,14 +7,14 @@ from .voice import play_audio
7
7
  from .websx_search import WEBSX
8
8
  from .LLM import VLM, LLM
9
9
  from .YTdownloader import *
10
- from .GoogleS import *
10
+
11
11
  import g4f
12
12
  from .YTdownloader import *
13
13
  from .Provider import *
14
14
  from .Extra import gguf
15
15
  from .Extra import autollama
16
16
  from .Extra import weather_ascii, weather
17
-
17
+ from .Agents import *
18
18
  __repo__ = "https://github.com/OE-LUCIFER/Webscout"
19
19
 
20
20
  webai = [
@@ -44,7 +44,9 @@ webai = [
44
44
  "vtlchat",
45
45
  "geminiflash",
46
46
  "geminipro",
47
- "ollama"
47
+ "ollama",
48
+ "andi",
49
+ "llama3"
48
50
  ]
49
51
 
50
52
  gpt4free_providers = [
webscout/version.py CHANGED
@@ -1,2 +1,2 @@
1
- __version__ = "4.3"
1
+ __version__ = "4.6"
2
2
  __prog__ = "webscout"
webscout/voice.py CHANGED
@@ -24,4 +24,11 @@ def play_audio(message: str, voice: str = "Brian") -> typing.Union[str, typing.N
24
24
  result = requests.get(url=url, headers=headers)
25
25
  return result.content
26
26
  except:
27
- return None
27
+ return None
28
+
29
+ if __name__ == "__main__":
30
+ # Example usage of the play_audio function
31
+ message = "Hello, world!"
32
+ voice = "Brian"
33
+ audio_result = play_audio(message, voice)
34
+ print(audio_result)
webscout/webai.py CHANGED
@@ -65,7 +65,7 @@ class this:
65
65
 
66
66
  rich_code_themes = ["monokai", "paraiso-dark", "igor", "vs", "fruity", "xcode"]
67
67
 
68
- default_provider = "phind"
68
+ default_provider = "llama3"
69
69
 
70
70
  getExc = lambda e: e.args[1] if len(e.args) > 1 else str(e)
71
71
 
@@ -518,6 +518,20 @@ class Main(cmd.Cmd):
518
518
  history_offset=history_offset,
519
519
  act=awesome_prompt,
520
520
  )
521
+ elif provider == "llama3":
522
+ from webscout import LLAMA3
523
+ self.bot = LLAMA3(
524
+ is_conversation=disable_conversation,
525
+ max_tokens=max_tokens,
526
+ timeout=timeout,
527
+ intro=intro,
528
+ filepath=filepath,
529
+ update_file=update_file,
530
+ proxies=proxies,
531
+ history_offset=history_offset,
532
+ act=awesome_prompt,
533
+ model=getOr(model, "llama3-8b"),
534
+ )
521
535
  elif provider == "berlin4h":
522
536
  from webscout import Berlin4h
523
537
 
@@ -765,7 +779,20 @@ class Main(cmd.Cmd):
765
779
  model=getOr(model, "Phind Model"),
766
780
  quiet=quiet,
767
781
  )
782
+ elif provider == "andi":
783
+ from webscout import AndiSearch
768
784
 
785
+ self.bot = AndiSearch(
786
+ is_conversation=disable_conversation,
787
+ max_tokens=max_tokens,
788
+ timeout=timeout,
789
+ intro=intro,
790
+ filepath=filepath,
791
+ update_file=update_file,
792
+ proxies=proxies,
793
+ history_offset=history_offset,
794
+ act=awesome_prompt,
795
+ )
769
796
  elif provider == "blackboxai":
770
797
 
771
798
  from webscout import BLACKBOXAI
@@ -142,6 +142,7 @@ class WEBS:
142
142
  "gpt-3.5": "gpt-3.5-turbo-0125",
143
143
  "llama-3-70b": "meta-llama/Llama-3-70b-chat-hf",
144
144
  "mixtral-8x7b": "mistralai/Mixtral-8x7B-Instruct-v0.1",
145
+ "gpt-4o-mini": "gpt-4o-mini",
145
146
  }
146
147
  # vqd
147
148
  if not self._chat_vqd: