webscout 2.8__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.

webscout/Provider/Reka.py CHANGED
@@ -1,226 +1,226 @@
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
- #-----------------------------------------------REKA-----------------------------------------------
32
- class REKA(Provider):
33
- def __init__(
34
- self,
35
- api_key: str,
36
- is_conversation: bool = True,
37
- max_tokens: int = 600,
38
- timeout: int = 30,
39
- intro: str = None,
40
- filepath: str = None,
41
- update_file: bool = True,
42
- proxies: dict = {},
43
- history_offset: int = 10250,
44
- act: str = None,
45
- model: str = "reka-core",
46
- system_prompt: str = "Be Helpful and Friendly. Keep your response straightforward, short and concise",
47
- use_search_engine: bool = False,
48
- use_code_interpreter: bool = False,
49
- ):
50
- """Instantiates REKA
51
-
52
- Args:
53
- is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True
54
- max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
55
- timeout (int, optional): Http request timeout. Defaults to 30.
56
- intro (str, optional): Conversation introductory prompt. Defaults to None.
57
- filepath (str, optional): Path to file containing conversation history. Defaults to None.
58
- update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
59
- proxies (dict, optional): Http request proxies. Defaults to {}.
60
- history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
61
- act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
62
- model (str, optional): REKA model name. Defaults to "reka-core".
63
- system_prompt (str, optional): System prompt for REKA. Defaults to "Be Helpful and Friendly. Keep your response straightforward, short and concise".
64
- use_search_engine (bool, optional): Whether to use the search engine. Defaults to False.
65
- use_code_interpreter (bool, optional): Whether to use the code interpreter. Defaults to False.
66
- """
67
- self.session = requests.Session()
68
- self.is_conversation = is_conversation
69
- self.max_tokens_to_sample = max_tokens
70
- self.api_endpoint = "https://chat.reka.ai/api/chat"
71
- self.stream_chunk_size = 64
72
- self.timeout = timeout
73
- self.last_response = {}
74
- self.model = model
75
- self.system_prompt = system_prompt
76
- self.use_search_engine = use_search_engine
77
- self.use_code_interpreter = use_code_interpreter
78
- self.access_token = api_key
79
- self.headers = {
80
- "Authorization": f"Bearer {self.access_token}",
81
- }
82
-
83
- self.__available_optimizers = (
84
- method
85
- for method in dir(Optimizers)
86
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
87
- )
88
- self.session.headers.update(self.headers)
89
- Conversation.intro = (
90
- AwesomePrompts().get_act(
91
- act, raise_not_found=True, default=None, case_insensitive=True
92
- )
93
- if act
94
- else intro or Conversation.intro
95
- )
96
- self.conversation = Conversation(
97
- is_conversation, self.max_tokens_to_sample, filepath, update_file
98
- )
99
- self.conversation.history_offset = history_offset
100
- self.session.proxies = proxies
101
-
102
- def ask(
103
- self,
104
- prompt: str,
105
- stream: bool = False,
106
- raw: bool = False,
107
- optimizer: str = None,
108
- conversationally: bool = False,
109
- ) -> dict:
110
- """Chat with AI
111
-
112
- Args:
113
- prompt (str): Prompt to be send.
114
- stream (bool, optional): Flag for streaming response. Defaults to False.
115
- raw (bool, optional): Stream back raw response as received. Defaults to False.
116
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
117
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
118
- Returns:
119
- dict : {}
120
- ```json
121
- {
122
- "text" : "How may I assist you today?"
123
- }
124
- ```
125
- """
126
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
127
- if optimizer:
128
- if optimizer in self.__available_optimizers:
129
- conversation_prompt = getattr(Optimizers, optimizer)(
130
- conversation_prompt if conversationally else prompt
131
- )
132
- else:
133
- raise Exception(
134
- f"Optimizer is not one of {self.__available_optimizers}"
135
- )
136
-
137
- self.session.headers.update(self.headers)
138
- payload = {
139
-
140
- "conversation_history": [
141
- {"type": "human", "text": f"## SYSTEM PROMPT: {self.system_prompt}\n\n## QUERY: {conversation_prompt}"},
142
- ],
143
-
144
- "stream": stream,
145
- "use_search_engine": self.use_search_engine,
146
- "use_code_interpreter": self.use_code_interpreter,
147
- "model_name": self.model,
148
- # "model_name": "reka-flash",
149
- # "model_name": "reka-edge",
150
- }
151
-
152
- def for_stream():
153
- response = self.session.post(self.api_endpoint, json=payload, stream=True, timeout=self.timeout)
154
- if not response.ok:
155
- raise Exception(
156
- f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
157
- )
158
-
159
- for value in response.iter_lines(
160
- decode_unicode=True,
161
- chunk_size=self.stream_chunk_size,
162
- ):
163
- try:
164
- resp = json.loads(value)
165
- self.last_response.update(resp)
166
- yield value if raw else resp
167
- except json.decoder.JSONDecodeError:
168
- pass
169
- self.conversation.update_chat_history(
170
- prompt, self.get_message(self.last_response)
171
- )
172
-
173
- def for_non_stream():
174
- # let's make use of stream
175
- for _ in for_stream():
176
- pass
177
- return self.last_response
178
-
179
- return for_stream() if stream else for_non_stream()
180
-
181
- def chat(
182
- self,
183
- prompt: str,
184
- stream: bool = False,
185
- optimizer: str = None,
186
- conversationally: bool = False,
187
- ) -> str:
188
- """Generate response `str`
189
- Args:
190
- prompt (str): Prompt to be send.
191
- stream (bool, optional): Flag for streaming response. Defaults to False.
192
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
193
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
194
- Returns:
195
- str: Response generated
196
- """
197
-
198
- def for_stream():
199
- for response in self.ask(
200
- prompt, True, optimizer=optimizer, conversationally=conversationally
201
- ):
202
- yield self.get_message(response)
203
-
204
- def for_non_stream():
205
- return self.get_message(
206
- self.ask(
207
- prompt,
208
- False,
209
- optimizer=optimizer,
210
- conversationally=conversationally,
211
- )
212
- )
213
-
214
- return for_stream() if stream else for_non_stream()
215
-
216
- def get_message(self, response: dict) -> str:
217
- """Retrieves message only from response
218
-
219
- Args:
220
- response (dict): Response generated by `self.ask`
221
-
222
- Returns:
223
- str: Message extracted
224
- """
225
- 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
29
+ import logging
30
+ import httpx
31
+ #-----------------------------------------------REKA-----------------------------------------------
32
+ class REKA(Provider):
33
+ def __init__(
34
+ self,
35
+ api_key: str,
36
+ is_conversation: bool = True,
37
+ max_tokens: int = 600,
38
+ timeout: int = 30,
39
+ intro: str = None,
40
+ filepath: str = None,
41
+ update_file: bool = True,
42
+ proxies: dict = {},
43
+ history_offset: int = 10250,
44
+ act: str = None,
45
+ model: str = "reka-core",
46
+ system_prompt: str = "Be Helpful and Friendly. Keep your response straightforward, short and concise",
47
+ use_search_engine: bool = False,
48
+ use_code_interpreter: bool = False,
49
+ ):
50
+ """Instantiates REKA
51
+
52
+ Args:
53
+ is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True
54
+ max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
55
+ timeout (int, optional): Http request timeout. Defaults to 30.
56
+ intro (str, optional): Conversation introductory prompt. Defaults to None.
57
+ filepath (str, optional): Path to file containing conversation history. Defaults to None.
58
+ update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
59
+ proxies (dict, optional): Http request proxies. Defaults to {}.
60
+ history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
61
+ act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
62
+ model (str, optional): REKA model name. Defaults to "reka-core".
63
+ system_prompt (str, optional): System prompt for REKA. Defaults to "Be Helpful and Friendly. Keep your response straightforward, short and concise".
64
+ use_search_engine (bool, optional): Whether to use the search engine. Defaults to False.
65
+ use_code_interpreter (bool, optional): Whether to use the code interpreter. Defaults to False.
66
+ """
67
+ self.session = requests.Session()
68
+ self.is_conversation = is_conversation
69
+ self.max_tokens_to_sample = max_tokens
70
+ self.api_endpoint = "https://chat.reka.ai/api/chat"
71
+ self.stream_chunk_size = 64
72
+ self.timeout = timeout
73
+ self.last_response = {}
74
+ self.model = model
75
+ self.system_prompt = system_prompt
76
+ self.use_search_engine = use_search_engine
77
+ self.use_code_interpreter = use_code_interpreter
78
+ self.access_token = api_key
79
+ self.headers = {
80
+ "Authorization": f"Bearer {self.access_token}",
81
+ }
82
+
83
+ self.__available_optimizers = (
84
+ method
85
+ for method in dir(Optimizers)
86
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
87
+ )
88
+ self.session.headers.update(self.headers)
89
+ Conversation.intro = (
90
+ AwesomePrompts().get_act(
91
+ act, raise_not_found=True, default=None, case_insensitive=True
92
+ )
93
+ if act
94
+ else intro or Conversation.intro
95
+ )
96
+ self.conversation = Conversation(
97
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
98
+ )
99
+ self.conversation.history_offset = history_offset
100
+ self.session.proxies = proxies
101
+
102
+ def ask(
103
+ self,
104
+ prompt: str,
105
+ stream: bool = False,
106
+ raw: bool = False,
107
+ optimizer: str = None,
108
+ conversationally: bool = False,
109
+ ) -> dict:
110
+ """Chat with AI
111
+
112
+ Args:
113
+ prompt (str): Prompt to be send.
114
+ stream (bool, optional): Flag for streaming response. Defaults to False.
115
+ raw (bool, optional): Stream back raw response as received. Defaults to False.
116
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
117
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
118
+ Returns:
119
+ dict : {}
120
+ ```json
121
+ {
122
+ "text" : "How may I assist you today?"
123
+ }
124
+ ```
125
+ """
126
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
127
+ if optimizer:
128
+ if optimizer in self.__available_optimizers:
129
+ conversation_prompt = getattr(Optimizers, optimizer)(
130
+ conversation_prompt if conversationally else prompt
131
+ )
132
+ else:
133
+ raise Exception(
134
+ f"Optimizer is not one of {self.__available_optimizers}"
135
+ )
136
+
137
+ self.session.headers.update(self.headers)
138
+ payload = {
139
+
140
+ "conversation_history": [
141
+ {"type": "human", "text": f"## SYSTEM PROMPT: {self.system_prompt}\n\n## QUERY: {conversation_prompt}"},
142
+ ],
143
+
144
+ "stream": stream,
145
+ "use_search_engine": self.use_search_engine,
146
+ "use_code_interpreter": self.use_code_interpreter,
147
+ "model_name": self.model,
148
+ # "model_name": "reka-flash",
149
+ # "model_name": "reka-edge",
150
+ }
151
+
152
+ def for_stream():
153
+ response = self.session.post(self.api_endpoint, json=payload, stream=True, timeout=self.timeout)
154
+ if not response.ok:
155
+ raise Exception(
156
+ f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
157
+ )
158
+
159
+ for value in response.iter_lines(
160
+ decode_unicode=True,
161
+ chunk_size=self.stream_chunk_size,
162
+ ):
163
+ try:
164
+ resp = json.loads(value)
165
+ self.last_response.update(resp)
166
+ yield value if raw else resp
167
+ except json.decoder.JSONDecodeError:
168
+ pass
169
+ self.conversation.update_chat_history(
170
+ prompt, self.get_message(self.last_response)
171
+ )
172
+
173
+ def for_non_stream():
174
+ # let's make use of stream
175
+ for _ in for_stream():
176
+ pass
177
+ return self.last_response
178
+
179
+ return for_stream() if stream else for_non_stream()
180
+
181
+ def chat(
182
+ self,
183
+ prompt: str,
184
+ stream: bool = False,
185
+ optimizer: str = None,
186
+ conversationally: bool = False,
187
+ ) -> str:
188
+ """Generate response `str`
189
+ Args:
190
+ prompt (str): Prompt to be send.
191
+ stream (bool, optional): Flag for streaming response. Defaults to False.
192
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
193
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
194
+ Returns:
195
+ str: Response generated
196
+ """
197
+
198
+ def for_stream():
199
+ for response in self.ask(
200
+ prompt, True, optimizer=optimizer, conversationally=conversationally
201
+ ):
202
+ yield self.get_message(response)
203
+
204
+ def for_non_stream():
205
+ return self.get_message(
206
+ self.ask(
207
+ prompt,
208
+ False,
209
+ optimizer=optimizer,
210
+ conversationally=conversationally,
211
+ )
212
+ )
213
+
214
+ return for_stream() if stream else for_non_stream()
215
+
216
+ def get_message(self, response: dict) -> str:
217
+ """Retrieves message only from response
218
+
219
+ Args:
220
+ response (dict): Response generated by `self.ask`
221
+
222
+ Returns:
223
+ str: Message extracted
224
+ """
225
+ assert isinstance(response, dict), "Response should be of dict data-type only"
226
226
  return response.get("text")