webscout 3.4__py3-none-any.whl → 3.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.
@@ -1,266 +1,266 @@
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, Optional
29
- import logging
30
- import httpx
31
- import os
32
- from dotenv import load_dotenv; load_dotenv()
33
-
34
- #-----------------------------------------------DeepSeek--------------------------------------------
35
- class DeepSeek(Provider):
36
- def __init__(
37
- self,
38
- api_key: str,
39
- is_conversation: bool = True,
40
- max_tokens: int = 600,
41
- timeout: int = 30,
42
- intro: str = None,
43
- filepath: str = None,
44
- update_file: bool = True,
45
- proxies: dict = {},
46
- history_offset: int = 10250,
47
- act: str = None,
48
- model: str = 'deepseek_chat',
49
- temperature: float = 1.0,
50
- ):
51
- """Initializes DeepSeek
52
-
53
- Args:
54
- api_key (str): DeepSeek API key.
55
- is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
56
- max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
57
- timeout (int, optional): Http request timeout. Defaults to 30.
58
- intro (str, optional): Conversation introductory prompt. Defaults to None.
59
- filepath (str, optional): Path to file containing conversation history. Defaults to None.
60
- update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
61
- proxies (dict, optional): Http request proxies. Defaults to {}.
62
- history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
63
- act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
64
- model_type (str, optional): DeepSeek model type. Defaults to 'deepseek_chat'.
65
- temperature (float, optional): Creativity level of the response. Defaults to 1.0.
66
- """
67
- self.api_token = api_key
68
- self.auth_headers = {
69
- 'Authorization': f'Bearer {self.api_token}'
70
- }
71
- self.api_base_url = 'https://chat.deepseek.com/api/v0/chat'
72
- self.api_session = requests.Session()
73
- self.api_session.headers.update(self.auth_headers)
74
-
75
- self.is_conversation = is_conversation
76
- self.max_tokens_to_sample = max_tokens
77
- self.timeout = timeout
78
- self.last_response = {}
79
- self.model_type = model
80
- self.temperature = temperature
81
- self.__available_optimizers = (
82
- method
83
- for method in dir(Optimizers)
84
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
85
- )
86
- Conversation.intro = (
87
- AwesomePrompts().get_act(
88
- act, raise_not_found=True, default=None, case_insensitive=True
89
- )
90
- if act
91
- else intro or Conversation.intro
92
- )
93
- self.conversation = Conversation(
94
- is_conversation, self.max_tokens_to_sample, filepath, update_file
95
- )
96
- self.conversation.history_offset = history_offset
97
- # self.session.proxies = proxies
98
-
99
- def clear_chat(self) -> None:
100
- """
101
- Clears the chat context by making a POST request to the clear_context endpoint.
102
- """
103
- clear_payload = {"model_class": "deepseek_chat", "append_welcome_message": False}
104
- clear_response = self.api_session.post(f'{self.api_base_url}/clear_context', json=clear_payload)
105
- clear_response.raise_for_status() # Raises an HTTPError if the HTTP request returned an unsuccessful status code
106
-
107
- def generate(self, user_message: str, response_temperature: float = 1.0, model_type: Optional[str] = "deepseek_chat", verbose: bool = False) -> str:
108
- """
109
- Generates a response from the DeepSeek API based on the provided message.
110
-
111
- Args:
112
- user_message (str): The message to send to the chat API.
113
- response_temperature (float, optional): The creativity level of the response. Defaults to 1.0.
114
- model_type (str, optional): The model class to be used for the chat session.
115
- verbose (bool, optional): Whether to print the response content. Defaults to False.
116
-
117
- Returns:
118
- str: The concatenated response content received from the API.
119
-
120
- Available models:
121
- - deepseek_chat
122
- - deepseek_code
123
- """
124
- request_payload = {
125
- "message": user_message,
126
- "stream": True,
127
- "model_preference": None,
128
- "model_class": model_type,
129
- "temperature": response_temperature
130
- }
131
- api_response = self.api_session.post(f'{self.api_base_url}/completions', json=request_payload, stream=True)
132
- api_response.raise_for_status()
133
-
134
- combined_response = ""
135
- for response_line in api_response.iter_lines(decode_unicode=True, chunk_size=1):
136
- if response_line:
137
- cleaned_line = re.sub("data:", "", response_line)
138
- response_json = json.loads(cleaned_line)
139
- response_content = response_json['choices'][0]['delta']['content']
140
- if response_content and not re.match(r'^\s{5,}$', response_content):
141
- if verbose: print(response_content, end="", flush=True)
142
- combined_response += response_content
143
-
144
- return combined_response
145
-
146
- def ask(
147
- self,
148
- prompt: str,
149
- stream: bool = False,
150
- raw: bool = False,
151
- optimizer: str = None,
152
- conversationally: bool = False,
153
- ) -> dict:
154
- """Chat with AI
155
-
156
- Args:
157
- prompt (str): Prompt to be send.
158
- stream (bool, optional): Flag for streaming response. Defaults to False.
159
- raw (bool, optional): Stream back raw response as received. Defaults to False.
160
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
161
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
162
- Returns:
163
- dict : {}
164
- ```json
165
- {
166
- "id": "chatcmpl-TaREJpBZsRVQFRFic1wIA7Q7XfnaD",
167
- "object": "chat.completion",
168
- "created": 1704623244,
169
- "model": "gpt-3.5-turbo",
170
- "usage": {
171
- "prompt_tokens": 0,
172
- "completion_tokens": 0,
173
- "total_tokens": 0
174
- },
175
- "choices": [
176
- {
177
- "message": {
178
- "role": "assistant",
179
- "content": "Hello! How can I assist you today?"
180
- },
181
- "finish_reason": "stop",
182
- "index": 0
183
- }
184
- ]
185
- }
186
- ```
187
- """
188
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
189
- if optimizer:
190
- if optimizer in self.__available_optimizers:
191
- conversation_prompt = getattr(Optimizers, optimizer)(
192
- conversation_prompt if conversationally else prompt
193
- )
194
- else:
195
- raise Exception(
196
- f"Optimizer is not one of {self.__available_optimizers}"
197
- )
198
-
199
- def for_stream():
200
- response = self.generate(
201
- user_message=conversation_prompt,
202
- response_temperature=self.temperature,
203
- model_type=self.model_type,
204
- verbose=False,
205
- )
206
- # print(response)
207
- self.last_response.update(dict(text=response))
208
- self.conversation.update_chat_history(
209
- prompt, self.get_message(self.last_response)
210
- )
211
- yield dict(text=response) if raw else dict(text=response)
212
-
213
- def for_non_stream():
214
- # let's make use of stream
215
- for _ in for_stream():
216
- pass
217
- return self.last_response
218
-
219
- return for_stream() if stream else for_non_stream()
220
-
221
- def chat(
222
- self,
223
- prompt: str,
224
- stream: bool = False,
225
- optimizer: str = None,
226
- conversationally: bool = False,
227
- ) -> str:
228
- """Generate response `str`
229
- Args:
230
- prompt (str): Prompt to be send.
231
- stream (bool, optional): Flag for streaming response. Defaults to False.
232
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
233
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
234
- Returns:
235
- str: Response generated
236
- """
237
-
238
- def for_stream():
239
- for response in self.ask(
240
- prompt, True, optimizer=optimizer, conversationally=conversationally
241
- ):
242
- yield self.get_message(response)
243
-
244
- def for_non_stream():
245
- return self.get_message(
246
- self.ask(
247
- prompt,
248
- False,
249
- optimizer=optimizer,
250
- conversationally=conversationally,
251
- )
252
- )
253
-
254
- return for_stream() if stream else for_non_stream()
255
-
256
- def get_message(self, response: dict) -> str:
257
- """Retrieves message only from response
258
-
259
- Args:
260
- response (dict): Response generated by `self.ask`
261
-
262
- Returns:
263
- str: Message extracted
264
- """
265
- assert isinstance(response, dict), "Response should be of dict data-type only"
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, Optional
29
+ import logging
30
+ import httpx
31
+ import os
32
+ from dotenv import load_dotenv; load_dotenv()
33
+
34
+ #-----------------------------------------------DeepSeek--------------------------------------------
35
+ class DeepSeek(Provider):
36
+ def __init__(
37
+ self,
38
+ api_key: str,
39
+ is_conversation: bool = True,
40
+ max_tokens: int = 600,
41
+ timeout: int = 30,
42
+ intro: str = None,
43
+ filepath: str = None,
44
+ update_file: bool = True,
45
+ proxies: dict = {},
46
+ history_offset: int = 10250,
47
+ act: str = None,
48
+ model: str = 'deepseek_chat',
49
+ temperature: float = 1.0,
50
+ ):
51
+ """Initializes DeepSeek
52
+
53
+ Args:
54
+ api_key (str): DeepSeek API key.
55
+ is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
56
+ max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
57
+ timeout (int, optional): Http request timeout. Defaults to 30.
58
+ intro (str, optional): Conversation introductory prompt. Defaults to None.
59
+ filepath (str, optional): Path to file containing conversation history. Defaults to None.
60
+ update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
61
+ proxies (dict, optional): Http request proxies. Defaults to {}.
62
+ history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
63
+ act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
64
+ model_type (str, optional): DeepSeek model type. Defaults to 'deepseek_chat'.
65
+ temperature (float, optional): Creativity level of the response. Defaults to 1.0.
66
+ """
67
+ self.api_token = api_key
68
+ self.auth_headers = {
69
+ 'Authorization': f'Bearer {self.api_token}'
70
+ }
71
+ self.api_base_url = 'https://chat.deepseek.com/api/v0/chat'
72
+ self.api_session = requests.Session()
73
+ self.api_session.headers.update(self.auth_headers)
74
+
75
+ self.is_conversation = is_conversation
76
+ self.max_tokens_to_sample = max_tokens
77
+ self.timeout = timeout
78
+ self.last_response = {}
79
+ self.model_type = model
80
+ self.temperature = temperature
81
+ self.__available_optimizers = (
82
+ method
83
+ for method in dir(Optimizers)
84
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
85
+ )
86
+ Conversation.intro = (
87
+ AwesomePrompts().get_act(
88
+ act, raise_not_found=True, default=None, case_insensitive=True
89
+ )
90
+ if act
91
+ else intro or Conversation.intro
92
+ )
93
+ self.conversation = Conversation(
94
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
95
+ )
96
+ self.conversation.history_offset = history_offset
97
+ # self.session.proxies = proxies
98
+
99
+ def clear_chat(self) -> None:
100
+ """
101
+ Clears the chat context by making a POST request to the clear_context endpoint.
102
+ """
103
+ clear_payload = {"model_class": "deepseek_chat", "append_welcome_message": False}
104
+ clear_response = self.api_session.post(f'{self.api_base_url}/clear_context', json=clear_payload)
105
+ clear_response.raise_for_status() # Raises an HTTPError if the HTTP request returned an unsuccessful status code
106
+
107
+ def generate(self, user_message: str, response_temperature: float = 1.0, model_type: Optional[str] = "deepseek_chat", verbose: bool = False) -> str:
108
+ """
109
+ Generates a response from the DeepSeek API based on the provided message.
110
+
111
+ Args:
112
+ user_message (str): The message to send to the chat API.
113
+ response_temperature (float, optional): The creativity level of the response. Defaults to 1.0.
114
+ model_type (str, optional): The model class to be used for the chat session.
115
+ verbose (bool, optional): Whether to print the response content. Defaults to False.
116
+
117
+ Returns:
118
+ str: The concatenated response content received from the API.
119
+
120
+ Available models:
121
+ - deepseek_chat
122
+ - deepseek_code
123
+ """
124
+ request_payload = {
125
+ "message": user_message,
126
+ "stream": True,
127
+ "model_preference": None,
128
+ "model_class": model_type,
129
+ "temperature": response_temperature
130
+ }
131
+ api_response = self.api_session.post(f'{self.api_base_url}/completions', json=request_payload, stream=True)
132
+ api_response.raise_for_status()
133
+
134
+ combined_response = ""
135
+ for response_line in api_response.iter_lines(decode_unicode=True, chunk_size=1):
136
+ if response_line:
137
+ cleaned_line = re.sub("data:", "", response_line)
138
+ response_json = json.loads(cleaned_line)
139
+ response_content = response_json['choices'][0]['delta']['content']
140
+ if response_content and not re.match(r'^\s{5,}$', response_content):
141
+ if verbose: print(response_content, end="", flush=True)
142
+ combined_response += response_content
143
+
144
+ return combined_response
145
+
146
+ def ask(
147
+ self,
148
+ prompt: str,
149
+ stream: bool = False,
150
+ raw: bool = False,
151
+ optimizer: str = None,
152
+ conversationally: bool = False,
153
+ ) -> dict:
154
+ """Chat with AI
155
+
156
+ Args:
157
+ prompt (str): Prompt to be send.
158
+ stream (bool, optional): Flag for streaming response. Defaults to False.
159
+ raw (bool, optional): Stream back raw response as received. Defaults to False.
160
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
161
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
162
+ Returns:
163
+ dict : {}
164
+ ```json
165
+ {
166
+ "id": "chatcmpl-TaREJpBZsRVQFRFic1wIA7Q7XfnaD",
167
+ "object": "chat.completion",
168
+ "created": 1704623244,
169
+ "model": "gpt-3.5-turbo",
170
+ "usage": {
171
+ "prompt_tokens": 0,
172
+ "completion_tokens": 0,
173
+ "total_tokens": 0
174
+ },
175
+ "choices": [
176
+ {
177
+ "message": {
178
+ "role": "assistant",
179
+ "content": "Hello! How can I assist you today?"
180
+ },
181
+ "finish_reason": "stop",
182
+ "index": 0
183
+ }
184
+ ]
185
+ }
186
+ ```
187
+ """
188
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
189
+ if optimizer:
190
+ if optimizer in self.__available_optimizers:
191
+ conversation_prompt = getattr(Optimizers, optimizer)(
192
+ conversation_prompt if conversationally else prompt
193
+ )
194
+ else:
195
+ raise Exception(
196
+ f"Optimizer is not one of {self.__available_optimizers}"
197
+ )
198
+
199
+ def for_stream():
200
+ response = self.generate(
201
+ user_message=conversation_prompt,
202
+ response_temperature=self.temperature,
203
+ model_type=self.model_type,
204
+ verbose=False,
205
+ )
206
+ # print(response)
207
+ self.last_response.update(dict(text=response))
208
+ self.conversation.update_chat_history(
209
+ prompt, self.get_message(self.last_response)
210
+ )
211
+ yield dict(text=response) if raw else dict(text=response)
212
+
213
+ def for_non_stream():
214
+ # let's make use of stream
215
+ for _ in for_stream():
216
+ pass
217
+ return self.last_response
218
+
219
+ return for_stream() if stream else for_non_stream()
220
+
221
+ def chat(
222
+ self,
223
+ prompt: str,
224
+ stream: bool = False,
225
+ optimizer: str = None,
226
+ conversationally: bool = False,
227
+ ) -> str:
228
+ """Generate response `str`
229
+ Args:
230
+ prompt (str): Prompt to be send.
231
+ stream (bool, optional): Flag for streaming response. Defaults to False.
232
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
233
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
234
+ Returns:
235
+ str: Response generated
236
+ """
237
+
238
+ def for_stream():
239
+ for response in self.ask(
240
+ prompt, True, optimizer=optimizer, conversationally=conversationally
241
+ ):
242
+ yield self.get_message(response)
243
+
244
+ def for_non_stream():
245
+ return self.get_message(
246
+ self.ask(
247
+ prompt,
248
+ False,
249
+ optimizer=optimizer,
250
+ conversationally=conversationally,
251
+ )
252
+ )
253
+
254
+ return for_stream() if stream else for_non_stream()
255
+
256
+ def get_message(self, response: dict) -> str:
257
+ """Retrieves message only from response
258
+
259
+ Args:
260
+ response (dict): Response generated by `self.ask`
261
+
262
+ Returns:
263
+ str: Message extracted
264
+ """
265
+ assert isinstance(response, dict), "Response should be of dict data-type only"
266
266
  return response["text"]