webscout 4.8__py3-none-any.whl → 4.9__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,263 @@
1
+ import time
2
+ import uuid
3
+ from selenium import webdriver
4
+ from selenium.webdriver.chrome.options import Options
5
+ from selenium.webdriver.common.by import By
6
+ from selenium.webdriver.support import expected_conditions as EC
7
+ from selenium.webdriver.support.ui import WebDriverWait
8
+ import click
9
+ import requests
10
+ from requests import get
11
+ from uuid import uuid4
12
+ from re import findall
13
+ from requests.exceptions import RequestException
14
+ from curl_cffi.requests import get, RequestsError
15
+ import g4f
16
+ from random import randint
17
+ from PIL import Image
18
+ import io
19
+ import re
20
+ import json
21
+ import yaml
22
+ from webscout.AIutel import Optimizers
23
+ from webscout.AIutel import Conversation
24
+ from webscout.AIutel import AwesomePrompts, sanitize_stream
25
+ from webscout.AIbase import Provider, AsyncProvider
26
+ from webscout import exceptions
27
+ from typing import Any, AsyncGenerator, Dict
28
+ import logging
29
+ import httpx
30
+
31
+ class Julius(Provider):
32
+ AVAILABLE_MODELS = [
33
+ "Llama 3",
34
+ "GPT-4o",
35
+ "GPT-3.5",
36
+ "Command R",
37
+ "Gemini Flash",
38
+ "Gemini 1.5",
39
+ ]
40
+ def __init__(
41
+ self,
42
+ is_conversation: bool = True,
43
+ max_tokens: int = 600,
44
+ timeout: int = 30,
45
+ intro: str = None,
46
+ filepath: str = None,
47
+ update_file: bool = True,
48
+ proxies: dict = {},
49
+ history_offset: int = 10250,
50
+ act: str = None,
51
+ model: str = "Gemini Flash",
52
+ ):
53
+ """Instantiates Julius
54
+
55
+ Args:
56
+ is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
57
+ max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
58
+ timeout (int, optional): Http request timeout. Defaults to 30.
59
+ intro (str, optional): Conversation introductory prompt. Defaults to None.
60
+ filepath (str, optional): Path to file containing conversation history. Defaults to None.
61
+ update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
62
+ proxies (dict, optional): Http request proxies. Defaults to {}.
63
+ history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
64
+ act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
65
+ model (str, optional): Model to use for generating text. Defaults to "Gemini Flash".
66
+ Options: "Llama 3", "GPT-4o", "GPT-3.5", "Command R", "Gemini Flash", "Gemini 1.5".
67
+ """
68
+ if model not in self.AVAILABLE_MODELS:
69
+ raise ValueError(f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}")
70
+
71
+ self.session = requests.Session()
72
+ self.is_conversation = is_conversation
73
+ self.max_tokens_to_sample = max_tokens
74
+ self.chat_endpoint = "https://api.julius.ai/api/chat/message"
75
+ self.stream_chunk_size = 64
76
+ self.timeout = timeout
77
+ self.last_response = {}
78
+ self.model = model
79
+ self.headers = {
80
+ "accept": "*/*",
81
+ "accept-encoding": "gzip, deflate, br, zstd",
82
+ "accept-language": "en-US,en;q=0.9,en-IN;q=0.8",
83
+ "authorization": "Bearer",
84
+ "content-length": "206",
85
+ "content-type": "application/json",
86
+ "conversation-id": str(uuid.uuid4()),
87
+ "dnt": "1",
88
+ "interactive-charts": "true",
89
+ "is-demo": "temp_14aabbb1-95bc-4203-a678-596258d6fdf3",
90
+ "is-native": "false",
91
+ "orient-split": "true",
92
+ "origin": "https://julius.ai",
93
+ "platform": "undefined",
94
+ "priority": "u=1, i",
95
+ "referer": "https://julius.ai/",
96
+ "request-id": str(uuid.uuid4()),
97
+ "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",
98
+ "visitor-id": str(uuid.uuid4())
99
+ }
100
+
101
+ self.__available_optimizers = (
102
+ method
103
+ for method in dir(Optimizers)
104
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
105
+ )
106
+ self.session.headers.update(self.headers)
107
+ Conversation.intro = (
108
+ AwesomePrompts().get_act(
109
+ act, raise_not_found=True, default=None, case_insensitive=True
110
+ )
111
+ if act
112
+ else intro or Conversation.intro
113
+ )
114
+ self.conversation = Conversation(
115
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
116
+ )
117
+ self.conversation.history_offset = history_offset
118
+ self.session.proxies = proxies
119
+
120
+ def ask(
121
+ self,
122
+ prompt: str,
123
+ stream: bool = False,
124
+ raw: bool = False,
125
+ optimizer: str = None,
126
+ conversationally: bool = False,
127
+ ) -> dict:
128
+ """Chat with AI
129
+
130
+ Args:
131
+ prompt (str): Prompt to be send.
132
+ stream (bool, optional): Whether to stream the response. Defaults to False.
133
+ raw (bool, optional): Whether to return the raw response. Defaults to False.
134
+ optimizer (str, optional): The name of the optimizer to use. Defaults to None.
135
+ conversationally (bool, optional): Whether to chat conversationally. Defaults to False.
136
+
137
+ Returns:
138
+ The response from the API.
139
+ """
140
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
141
+ if optimizer:
142
+ if optimizer in self.__available_optimizers:
143
+ conversation_prompt = getattr(Optimizers, optimizer)(
144
+ conversation_prompt if conversationally else prompt
145
+ )
146
+ else:
147
+ raise Exception(
148
+ f"Optimizer is not one of {self.__available_optimizers}"
149
+ )
150
+
151
+ payload = {
152
+ "message": {"content": conversation_prompt, "role": "user"},
153
+ "provider": "default",
154
+ "chat_mode": "auto",
155
+ "client_version": "20240130",
156
+ "theme": "dark",
157
+ "new_images": None,
158
+ "new_attachments": None,
159
+ "dataframe_format": "json",
160
+ "selectedModels": [self.model] # Choose the model here
161
+ }
162
+
163
+ def for_stream():
164
+ response = self.session.post(
165
+ self.chat_endpoint, json=payload, headers=self.headers, stream=True, timeout=self.timeout
166
+ )
167
+
168
+ if not response.ok:
169
+ raise exceptions.FailedToGenerateResponseError(
170
+ f"Failed to generate response - ({response.status_code}, {response.reason})"
171
+ )
172
+ streaming_response = ""
173
+ for line in response.iter_lines(decode_unicode=True):
174
+ if line:
175
+ try:
176
+ json_line = json.loads(line)
177
+ content = json_line['content']
178
+ streaming_response += content
179
+ yield content if raw else dict(text=streaming_response)
180
+ except:
181
+ continue
182
+ self.last_response.update(dict(text=streaming_response))
183
+ self.conversation.update_chat_history(
184
+ prompt, self.get_message(self.last_response)
185
+ )
186
+
187
+ def for_non_stream():
188
+ response = self.session.post(
189
+ self.chat_endpoint, json=payload, headers=self.headers, timeout=self.timeout
190
+ )
191
+
192
+ if not response.ok:
193
+ raise exceptions.FailedToGenerateResponseError(
194
+ f"Failed to generate response - ({response.status_code}, {response.reason})"
195
+ )
196
+ full_content = ""
197
+ for line in response.text.splitlines():
198
+ try:
199
+ data = json.loads(line)
200
+ if "content" in data:
201
+ full_content += data['content']
202
+ except json.JSONDecodeError:
203
+ pass
204
+ self.last_response.update(dict(text=full_content))
205
+ self.conversation.update_chat_history(
206
+ prompt, self.get_message(self.last_response)
207
+ )
208
+ return self.last_response
209
+
210
+ return for_stream() if stream else for_non_stream()
211
+
212
+ def chat(
213
+ self,
214
+ prompt: str,
215
+ stream: bool = False,
216
+ optimizer: str = None,
217
+ conversationally: bool = False,
218
+ ) -> str:
219
+ """Generate response `str`
220
+ Args:
221
+ prompt (str): Prompt to be send.
222
+ stream (bool, optional): Flag for streaming response. Defaults to False.
223
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
224
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
225
+ Returns:
226
+ str: Response generated
227
+ """
228
+
229
+ def for_stream():
230
+ for response in self.ask(
231
+ prompt, True, optimizer=optimizer, conversationally=conversationally
232
+ ):
233
+ yield self.get_message(response)
234
+
235
+ def for_non_stream():
236
+ return self.get_message(
237
+ self.ask(
238
+ prompt,
239
+ False,
240
+ optimizer=optimizer,
241
+ conversationally=conversationally,
242
+ )
243
+ )
244
+
245
+ return for_stream() if stream else for_non_stream()
246
+
247
+ def get_message(self, response: dict) -> str:
248
+ """Retrieves message only from response
249
+
250
+ Args:
251
+ response (dict): Response generated by `self.ask`
252
+
253
+ Returns:
254
+ str: Message extracted
255
+ """
256
+ assert isinstance(response, dict), "Response should be of dict data-type only"
257
+ return response["text"]
258
+ if __name__ == '__main__':
259
+ from rich import print
260
+ ai = Julius()
261
+ response = ai.chat(input(">>> "))
262
+ for chunk in response:
263
+ print(chunk, end="", flush=True)
@@ -0,0 +1,237 @@
1
+ import time
2
+ import uuid
3
+ from selenium import webdriver
4
+ from selenium.webdriver.chrome.options import Options
5
+ from selenium.webdriver.common.by import By
6
+ from selenium.webdriver.support import expected_conditions as EC
7
+ from selenium.webdriver.support.ui import WebDriverWait
8
+ import click
9
+ import requests
10
+ from requests import get
11
+ from uuid import uuid4
12
+ from re import findall
13
+ from requests.exceptions import RequestException
14
+ from curl_cffi.requests import get, RequestsError
15
+ import g4f
16
+ from random import randint
17
+ from PIL import Image
18
+ import io
19
+ import re
20
+ import json
21
+ import yaml
22
+ from webscout.AIutel import Optimizers
23
+ from webscout.AIutel import Conversation
24
+ from webscout.AIutel import AwesomePrompts, sanitize_stream
25
+ from webscout.AIbase import Provider, AsyncProvider
26
+ from webscout import exceptions
27
+ from typing import Any, AsyncGenerator, Dict
28
+ import logging
29
+ import httpx
30
+
31
+ class TurboSeek(Provider):
32
+ """
33
+ This class provides methods for interacting with the TurboSeek API.
34
+ """
35
+ def __init__(
36
+ self,
37
+ is_conversation: bool = True,
38
+ max_tokens: int = 600,
39
+ timeout: int = 30,
40
+ intro: str = None,
41
+ filepath: str = None,
42
+ update_file: bool = True,
43
+ proxies: dict = {},
44
+ history_offset: int = 10250,
45
+ act: str = None,
46
+ ):
47
+ """Instantiates TurboSeek
48
+
49
+ Args:
50
+ is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
51
+ max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
52
+ timeout (int, optional): Http request timeout. Defaults to 30.
53
+ intro (str, optional): Conversation introductory prompt. Defaults to None.
54
+ filepath (str, optional): Path to file containing conversation history. Defaults to None.
55
+ update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
56
+ proxies (dict, optional): Http request proxies. Defaults to {}.
57
+ history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
58
+ act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
59
+ """
60
+ self.session = requests.Session()
61
+ self.is_conversation = is_conversation
62
+ self.max_tokens_to_sample = max_tokens
63
+ self.chat_endpoint = "https://www.turboseek.io/api/getAnswer"
64
+ self.stream_chunk_size = 64
65
+ self.timeout = timeout
66
+ self.last_response = {}
67
+ self.headers = {
68
+ "authority": "www.turboseek.io",
69
+ "method": "POST",
70
+ "path": "/api/getAnswer",
71
+ "scheme": "https",
72
+ "accept": "*/*",
73
+ "accept-encoding": "gzip, deflate, br, zstd",
74
+ "accept-language": "en-US,en;q=0.9,en-IN;q=0.8",
75
+ "content-length": "63",
76
+ "content-type": "application/json",
77
+ "dnt": "1",
78
+ "origin": "https://www.turboseek.io",
79
+ "priority": "u=1, i",
80
+ "referer": "https://www.turboseek.io/?ref=taaft&utm_source=taaft&utm_medium=referral",
81
+ "sec-ch-ua": '"Not)A;Brand";v="99", "Microsoft Edge";v="127", "Chromium";v="127"',
82
+ "sec-ch-ua-mobile": "?0",
83
+ "sec-ch-ua-platform": '"Windows"',
84
+ "sec-fetch-dest": "empty",
85
+ "sec-fetch-mode": "cors",
86
+ "sec-fetch-site": "same-origin",
87
+ "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"
88
+ }
89
+
90
+ self.__available_optimizers = (
91
+ method
92
+ for method in dir(Optimizers)
93
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
94
+ )
95
+ self.session.headers.update(self.headers)
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
+ self.conversation = Conversation(
104
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
105
+ )
106
+ self.conversation.history_offset = history_offset
107
+ self.session.proxies = proxies
108
+
109
+ def ask(
110
+ self,
111
+ prompt: str,
112
+ stream: bool = False,
113
+ raw: bool = False,
114
+ optimizer: str = None,
115
+ conversationally: bool = False,
116
+ ) -> dict:
117
+ """Chat with AI
118
+
119
+ Args:
120
+ prompt (str): Prompt to be send.
121
+ stream (bool, optional): Flag for streaming response. Defaults to False.
122
+ raw (bool, optional): Stream back raw response as received. Defaults to False.
123
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
124
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
125
+ Returns:
126
+ dict : {}
127
+ ```json
128
+ {
129
+ "text" : "How may I assist you today?"
130
+ }
131
+ ```
132
+ """
133
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
134
+ if optimizer:
135
+ if optimizer in self.__available_optimizers:
136
+ conversation_prompt = getattr(Optimizers, optimizer)(
137
+ conversation_prompt if conversationally else prompt
138
+ )
139
+ else:
140
+ raise Exception(
141
+ f"Optimizer is not one of {self.__available_optimizers}"
142
+ )
143
+
144
+ self.session.headers.update(self.headers)
145
+ payload = {
146
+ "question": conversation_prompt,
147
+ "sources": []
148
+ }
149
+
150
+ def for_stream():
151
+ response = self.session.post(
152
+ self.chat_endpoint, json=payload, stream=True, timeout=self.timeout
153
+ )
154
+ if not response.ok:
155
+ raise exceptions.FailedToGenerateResponseError(
156
+ f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
157
+ )
158
+
159
+ streaming_text = ""
160
+ for value in response.iter_lines(
161
+ decode_unicode=True,
162
+ chunk_size=self.stream_chunk_size,
163
+ delimiter="\n",
164
+ ):
165
+ try:
166
+ if bool(value) and value.startswith("data: "):
167
+ data = json.loads(value[6:])
168
+ if "text" in data:
169
+ streaming_text += data["text"]
170
+ resp = dict(text=streaming_text)
171
+ self.last_response.update(resp)
172
+ yield value if raw else resp
173
+ except json.decoder.JSONDecodeError:
174
+ pass
175
+ self.conversation.update_chat_history(
176
+ prompt, self.get_message(self.last_response)
177
+ )
178
+
179
+ def for_non_stream():
180
+ for _ in for_stream():
181
+ pass
182
+ return self.last_response
183
+
184
+ return for_stream() if stream else for_non_stream()
185
+
186
+ def chat(
187
+ self,
188
+ prompt: str,
189
+ stream: bool = False,
190
+ optimizer: str = None,
191
+ conversationally: bool = False,
192
+ ) -> str:
193
+ """Generate response `str`
194
+ Args:
195
+ prompt (str): Prompt to be send.
196
+ stream (bool, optional): Flag for streaming response. Defaults to False.
197
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
198
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
199
+ Returns:
200
+ str: Response generated
201
+ """
202
+
203
+ def for_stream():
204
+ for response in self.ask(
205
+ prompt, True, optimizer=optimizer, conversationally=conversationally
206
+ ):
207
+ yield self.get_message(response)
208
+
209
+ def for_non_stream():
210
+ return self.get_message(
211
+ self.ask(
212
+ prompt,
213
+ False,
214
+ optimizer=optimizer,
215
+ conversationally=conversationally,
216
+ )
217
+ )
218
+
219
+ return for_stream() if stream else for_non_stream()
220
+
221
+ def get_message(self, response: dict) -> str:
222
+ """Retrieves message only from response
223
+
224
+ Args:
225
+ response (dict): Response generated by `self.ask`
226
+
227
+ Returns:
228
+ str: Message extracted
229
+ """
230
+ assert isinstance(response, dict), "Response should be of dict data-type only"
231
+ return response["text"]
232
+ if __name__ == '__main__':
233
+ from rich import print
234
+ ai = TurboSeek()
235
+ response = ai.chat(input(">>> "))
236
+ for chunk in response:
237
+ print(chunk, end="", flush=True)