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

@@ -1,230 +1,230 @@
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 ..AIutel import Optimizers
23
- from ..AIutel import Conversation
24
- from ..AIutel import AwesomePrompts, sanitize_stream
25
- from ..AIbase import Provider, AsyncProvider
26
- from Helpingai_T2 import Perplexity
27
- from webscout import exceptions
28
- from typing import Any, AsyncGenerator, Dict
29
- import logging
30
- import httpx
31
- #------------------------------------------------------PERPLEXITY--------------------------------------------------------
32
- class PERPLEXITY(Provider):
33
- def __init__(
34
- self,
35
- is_conversation: bool = True,
36
- max_tokens: int = 600,
37
- timeout: int = 30,
38
- intro: str = None,
39
- filepath: str = None,
40
- update_file: bool = True,
41
- proxies: dict = {},
42
- history_offset: int = 10250,
43
- act: str = None,
44
- quiet: bool = False,
45
- ):
46
- """Instantiates PERPLEXITY
47
-
48
- Args:
49
- is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True
50
- max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
51
- timeout (int, optional): Http request timeout. Defaults to 30.
52
- intro (str, optional): Conversation introductory prompt. Defaults to None.
53
- filepath (str, optional): Path to file containing conversation history. Defaults to None.
54
- update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
55
- proxies (dict, optional): Http request proxies. Defaults to {}.
56
- history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
57
- act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
58
- quiet (bool, optional): Ignore web search-results and yield final response only. Defaults to False.
59
- """
60
- self.max_tokens_to_sample = max_tokens
61
- self.is_conversation = is_conversation
62
- self.last_response = {}
63
- self.web_results: dict = {}
64
- self.quiet = quiet
65
-
66
- self.__available_optimizers = (
67
- method
68
- for method in dir(Optimizers)
69
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
70
- )
71
- Conversation.intro = (
72
- AwesomePrompts().get_act(
73
- act, raise_not_found=True, default=None, case_insensitive=True
74
- )
75
- if act
76
- else intro or Conversation.intro
77
- )
78
- self.conversation = Conversation(
79
- is_conversation, self.max_tokens_to_sample, filepath, update_file
80
- )
81
- self.conversation.history_offset = history_offset
82
-
83
- def ask(
84
- self,
85
- prompt: str,
86
- stream: bool = False,
87
- raw: bool = False,
88
- optimizer: str = None,
89
- conversationally: bool = False,
90
- ) -> dict:
91
- """Chat with AI
92
-
93
- Args:
94
- prompt (str): Prompt to be send.
95
- stream (bool, optional): Flag for streaming response. Defaults to False.
96
- raw (bool, optional): Stream back raw response as received. Defaults to False.
97
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
98
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
99
- Returns:
100
- dict : {}
101
- ```json
102
- {
103
- "status": "pending",
104
- "uuid": "3604dfcc-611f-4b7d-989d-edca2a7233c7",
105
- "read_write_token": null,
106
- "frontend_context_uuid": "f6d43119-5231-481d-b692-f52e1f52d2c6",
107
- "final": false,
108
- "backend_uuid": "a6d6ec9e-da69-4841-af74-0de0409267a8",
109
- "media_items": [],
110
- "widget_data": [],
111
- "knowledge_cards": [],
112
- "expect_search_results": "false",
113
- "mode": "concise",
114
- "search_focus": "internet",
115
- "gpt4": false,
116
- "display_model": "turbo",
117
- "attachments": null,
118
- "answer": "",
119
- "web_results": [],
120
- "chunks": [],
121
- "extra_web_results": []
122
- }
123
- ```
124
- """
125
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
126
- if optimizer:
127
- if optimizer in self.__available_optimizers:
128
- conversation_prompt = getattr(Optimizers, optimizer)(
129
- conversation_prompt if conversationally else prompt
130
- )
131
- else:
132
- raise Exception(
133
- f"Optimizer is not one of {self.__available_optimizers}"
134
- )
135
-
136
- def for_stream():
137
- for response in Perplexity().generate_answer(conversation_prompt):
138
- yield json.dumps(response) if raw else response
139
- self.last_response.update(response)
140
-
141
- self.conversation.update_chat_history(
142
- prompt,
143
- self.get_message(self.last_response),
144
- )
145
-
146
- def for_non_stream():
147
- for _ in for_stream():
148
- pass
149
- return self.last_response
150
-
151
- return for_stream() if stream else for_non_stream()
152
-
153
- def chat(
154
- self,
155
- prompt: str,
156
- stream: bool = False,
157
- optimizer: str = None,
158
- conversationally: bool = False,
159
- ) -> str:
160
- """Generate response `str`
161
- Args:
162
- prompt (str): Prompt to be send.
163
- stream (bool, optional): Flag for streaming response. Defaults to False.
164
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
165
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
166
- Returns:
167
- str: Response generated
168
- """
169
-
170
- def for_stream():
171
- for response in self.ask(
172
- prompt, True, optimizer=optimizer, conversationally=conversationally
173
- ):
174
- yield self.get_message(response)
175
-
176
- def for_non_stream():
177
- return self.get_message(
178
- self.ask(
179
- prompt,
180
- False,
181
- optimizer=optimizer,
182
- conversationally=conversationally,
183
- )
184
- )
185
-
186
- return for_stream() if stream else for_non_stream()
187
-
188
- def get_message(self, response: dict) -> str:
189
- """Retrieves message only from response
190
-
191
- Args:
192
- response (dict): Response generated by `self.ask`
193
-
194
- Returns:
195
- str: Message extracted
196
- """
197
- assert isinstance(response, dict), "Response should be of dict data-type only"
198
- text_str: str = response.get("answer", "")
199
-
200
- def update_web_results(web_results: list) -> None:
201
- for index, results in enumerate(web_results, start=1):
202
- self.web_results[str(index) + ". " + results["name"]] = dict(
203
- url=results.get("url"), snippet=results.get("snippet")
204
- )
205
-
206
- if response.get("text"):
207
- # last chunk
208
- target: dict[str, Any] = json.loads(response.get("text"))
209
- text_str = target.get("answer")
210
- web_results: list[dict] = target.get("web_results")
211
- self.web_results.clear()
212
- update_web_results(web_results)
213
-
214
- return (
215
- text_str
216
- if self.quiet or not self.web_results
217
- else text_str + "\n\n# WEB-RESULTS\n\n" + yaml.dump(self.web_results)
218
- )
219
-
220
- else:
221
- if str(response.get("expect_search_results")).lower() == "true":
222
- return (
223
- text_str
224
- if self.quiet
225
- else text_str
226
- + "\n\n# WEB-RESULTS\n\n"
227
- + yaml.dump(response.get("web_results"))
228
- )
229
- else:
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 ..AIutel import Optimizers
23
+ from ..AIutel import Conversation
24
+ from ..AIutel import AwesomePrompts, sanitize_stream
25
+ from ..AIbase import Provider, AsyncProvider
26
+ from Helpingai_T2 import Perplexity
27
+ from webscout import exceptions
28
+ from typing import Any, AsyncGenerator, Dict
29
+ import logging
30
+ import httpx
31
+ #------------------------------------------------------PERPLEXITY--------------------------------------------------------
32
+ class PERPLEXITY(Provider):
33
+ def __init__(
34
+ self,
35
+ is_conversation: bool = True,
36
+ max_tokens: int = 600,
37
+ timeout: int = 30,
38
+ intro: str = None,
39
+ filepath: str = None,
40
+ update_file: bool = True,
41
+ proxies: dict = {},
42
+ history_offset: int = 10250,
43
+ act: str = None,
44
+ quiet: bool = False,
45
+ ):
46
+ """Instantiates PERPLEXITY
47
+
48
+ Args:
49
+ is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True
50
+ max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
51
+ timeout (int, optional): Http request timeout. Defaults to 30.
52
+ intro (str, optional): Conversation introductory prompt. Defaults to None.
53
+ filepath (str, optional): Path to file containing conversation history. Defaults to None.
54
+ update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
55
+ proxies (dict, optional): Http request proxies. Defaults to {}.
56
+ history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
57
+ act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
58
+ quiet (bool, optional): Ignore web search-results and yield final response only. Defaults to False.
59
+ """
60
+ self.max_tokens_to_sample = max_tokens
61
+ self.is_conversation = is_conversation
62
+ self.last_response = {}
63
+ self.web_results: dict = {}
64
+ self.quiet = quiet
65
+
66
+ self.__available_optimizers = (
67
+ method
68
+ for method in dir(Optimizers)
69
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
70
+ )
71
+ Conversation.intro = (
72
+ AwesomePrompts().get_act(
73
+ act, raise_not_found=True, default=None, case_insensitive=True
74
+ )
75
+ if act
76
+ else intro or Conversation.intro
77
+ )
78
+ self.conversation = Conversation(
79
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
80
+ )
81
+ self.conversation.history_offset = history_offset
82
+
83
+ def ask(
84
+ self,
85
+ prompt: str,
86
+ stream: bool = False,
87
+ raw: bool = False,
88
+ optimizer: str = None,
89
+ conversationally: bool = False,
90
+ ) -> dict:
91
+ """Chat with AI
92
+
93
+ Args:
94
+ prompt (str): Prompt to be send.
95
+ stream (bool, optional): Flag for streaming response. Defaults to False.
96
+ raw (bool, optional): Stream back raw response as received. Defaults to False.
97
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
98
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
99
+ Returns:
100
+ dict : {}
101
+ ```json
102
+ {
103
+ "status": "pending",
104
+ "uuid": "3604dfcc-611f-4b7d-989d-edca2a7233c7",
105
+ "read_write_token": null,
106
+ "frontend_context_uuid": "f6d43119-5231-481d-b692-f52e1f52d2c6",
107
+ "final": false,
108
+ "backend_uuid": "a6d6ec9e-da69-4841-af74-0de0409267a8",
109
+ "media_items": [],
110
+ "widget_data": [],
111
+ "knowledge_cards": [],
112
+ "expect_search_results": "false",
113
+ "mode": "concise",
114
+ "search_focus": "internet",
115
+ "gpt4": false,
116
+ "display_model": "turbo",
117
+ "attachments": null,
118
+ "answer": "",
119
+ "web_results": [],
120
+ "chunks": [],
121
+ "extra_web_results": []
122
+ }
123
+ ```
124
+ """
125
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
126
+ if optimizer:
127
+ if optimizer in self.__available_optimizers:
128
+ conversation_prompt = getattr(Optimizers, optimizer)(
129
+ conversation_prompt if conversationally else prompt
130
+ )
131
+ else:
132
+ raise Exception(
133
+ f"Optimizer is not one of {self.__available_optimizers}"
134
+ )
135
+
136
+ def for_stream():
137
+ for response in Perplexity().generate_answer(conversation_prompt):
138
+ yield json.dumps(response) if raw else response
139
+ self.last_response.update(response)
140
+
141
+ self.conversation.update_chat_history(
142
+ prompt,
143
+ self.get_message(self.last_response),
144
+ )
145
+
146
+ def for_non_stream():
147
+ for _ in for_stream():
148
+ pass
149
+ return self.last_response
150
+
151
+ return for_stream() if stream else for_non_stream()
152
+
153
+ def chat(
154
+ self,
155
+ prompt: str,
156
+ stream: bool = False,
157
+ optimizer: str = None,
158
+ conversationally: bool = False,
159
+ ) -> str:
160
+ """Generate response `str`
161
+ Args:
162
+ prompt (str): Prompt to be send.
163
+ stream (bool, optional): Flag for streaming response. Defaults to False.
164
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
165
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
166
+ Returns:
167
+ str: Response generated
168
+ """
169
+
170
+ def for_stream():
171
+ for response in self.ask(
172
+ prompt, True, optimizer=optimizer, conversationally=conversationally
173
+ ):
174
+ yield self.get_message(response)
175
+
176
+ def for_non_stream():
177
+ return self.get_message(
178
+ self.ask(
179
+ prompt,
180
+ False,
181
+ optimizer=optimizer,
182
+ conversationally=conversationally,
183
+ )
184
+ )
185
+
186
+ return for_stream() if stream else for_non_stream()
187
+
188
+ def get_message(self, response: dict) -> str:
189
+ """Retrieves message only from response
190
+
191
+ Args:
192
+ response (dict): Response generated by `self.ask`
193
+
194
+ Returns:
195
+ str: Message extracted
196
+ """
197
+ assert isinstance(response, dict), "Response should be of dict data-type only"
198
+ text_str: str = response.get("answer", "")
199
+
200
+ def update_web_results(web_results: list) -> None:
201
+ for index, results in enumerate(web_results, start=1):
202
+ self.web_results[str(index) + ". " + results["name"]] = dict(
203
+ url=results.get("url"), snippet=results.get("snippet")
204
+ )
205
+
206
+ if response.get("text"):
207
+ # last chunk
208
+ target: dict[str, Any] = json.loads(response.get("text"))
209
+ text_str = target.get("answer")
210
+ web_results: list[dict] = target.get("web_results")
211
+ self.web_results.clear()
212
+ update_web_results(web_results)
213
+
214
+ return (
215
+ text_str
216
+ if self.quiet or not self.web_results
217
+ else text_str + "\n\n# WEB-RESULTS\n\n" + yaml.dump(self.web_results)
218
+ )
219
+
220
+ else:
221
+ if str(response.get("expect_search_results")).lower() == "true":
222
+ return (
223
+ text_str
224
+ if self.quiet
225
+ else text_str
226
+ + "\n\n# WEB-RESULTS\n\n"
227
+ + yaml.dump(response.get("web_results"))
228
+ )
229
+ else:
230
230
  return text_str