webscout 8.3__py3-none-any.whl → 8.3.2__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/AIauto.py +4 -4
- webscout/AIbase.py +61 -1
- webscout/AIutel.py +46 -53
- webscout/Bing_search.py +418 -0
- webscout/Extra/YTToolkit/ytapi/patterns.py +45 -45
- webscout/Extra/YTToolkit/ytapi/stream.py +1 -1
- webscout/Extra/YTToolkit/ytapi/video.py +10 -10
- webscout/Extra/autocoder/autocoder_utiles.py +1 -1
- webscout/Extra/gguf.py +706 -177
- webscout/Litlogger/formats.py +9 -0
- webscout/Litlogger/handlers.py +18 -0
- webscout/Litlogger/logger.py +43 -1
- webscout/Provider/AISEARCH/genspark_search.py +7 -7
- webscout/Provider/AISEARCH/scira_search.py +3 -2
- webscout/Provider/GeminiProxy.py +140 -0
- webscout/Provider/LambdaChat.py +7 -1
- webscout/Provider/MCPCore.py +78 -75
- webscout/Provider/OPENAI/BLACKBOXAI.py +1046 -1017
- webscout/Provider/OPENAI/GeminiProxy.py +328 -0
- webscout/Provider/OPENAI/Qwen3.py +303 -303
- webscout/Provider/OPENAI/README.md +5 -0
- webscout/Provider/OPENAI/README_AUTOPROXY.md +238 -0
- webscout/Provider/OPENAI/TogetherAI.py +355 -0
- webscout/Provider/OPENAI/__init__.py +16 -1
- webscout/Provider/OPENAI/autoproxy.py +332 -0
- webscout/Provider/OPENAI/base.py +101 -14
- webscout/Provider/OPENAI/chatgpt.py +15 -2
- webscout/Provider/OPENAI/chatgptclone.py +14 -3
- webscout/Provider/OPENAI/deepinfra.py +339 -328
- webscout/Provider/OPENAI/e2b.py +295 -74
- webscout/Provider/OPENAI/mcpcore.py +109 -70
- webscout/Provider/OPENAI/opkfc.py +18 -6
- webscout/Provider/OPENAI/scirachat.py +59 -50
- webscout/Provider/OPENAI/toolbaz.py +2 -10
- webscout/Provider/OPENAI/writecream.py +166 -166
- webscout/Provider/OPENAI/x0gpt.py +367 -367
- webscout/Provider/OPENAI/xenai.py +514 -0
- webscout/Provider/OPENAI/yep.py +389 -383
- webscout/Provider/STT/__init__.py +3 -0
- webscout/Provider/STT/base.py +281 -0
- webscout/Provider/STT/elevenlabs.py +265 -0
- webscout/Provider/TTI/__init__.py +4 -1
- webscout/Provider/TTI/aiarta.py +399 -365
- webscout/Provider/TTI/base.py +74 -2
- webscout/Provider/TTI/bing.py +231 -0
- webscout/Provider/TTI/fastflux.py +63 -30
- webscout/Provider/TTI/gpt1image.py +149 -0
- webscout/Provider/TTI/imagen.py +196 -0
- webscout/Provider/TTI/magicstudio.py +60 -29
- webscout/Provider/TTI/piclumen.py +43 -32
- webscout/Provider/TTI/pixelmuse.py +232 -225
- webscout/Provider/TTI/pollinations.py +43 -32
- webscout/Provider/TTI/together.py +287 -0
- webscout/Provider/TTI/utils.py +2 -1
- webscout/Provider/TTS/README.md +1 -0
- webscout/Provider/TTS/__init__.py +2 -1
- webscout/Provider/TTS/freetts.py +140 -0
- webscout/Provider/TTS/speechma.py +45 -39
- webscout/Provider/TogetherAI.py +366 -0
- webscout/Provider/UNFINISHED/ChutesAI.py +314 -0
- webscout/Provider/UNFINISHED/fetch_together_models.py +95 -0
- webscout/Provider/XenAI.py +324 -0
- webscout/Provider/__init__.py +8 -0
- webscout/Provider/deepseek_assistant.py +378 -0
- webscout/Provider/scira_chat.py +3 -2
- webscout/Provider/toolbaz.py +0 -1
- webscout/auth/__init__.py +44 -0
- webscout/auth/api_key_manager.py +189 -0
- webscout/auth/auth_system.py +100 -0
- webscout/auth/config.py +76 -0
- webscout/auth/database.py +400 -0
- webscout/auth/exceptions.py +67 -0
- webscout/auth/middleware.py +248 -0
- webscout/auth/models.py +130 -0
- webscout/auth/providers.py +257 -0
- webscout/auth/rate_limiter.py +254 -0
- webscout/auth/request_models.py +127 -0
- webscout/auth/request_processing.py +226 -0
- webscout/auth/routes.py +526 -0
- webscout/auth/schemas.py +103 -0
- webscout/auth/server.py +312 -0
- webscout/auth/static/favicon.svg +11 -0
- webscout/auth/swagger_ui.py +203 -0
- webscout/auth/templates/components/authentication.html +237 -0
- webscout/auth/templates/components/base.html +103 -0
- webscout/auth/templates/components/endpoints.html +750 -0
- webscout/auth/templates/components/examples.html +491 -0
- webscout/auth/templates/components/footer.html +75 -0
- webscout/auth/templates/components/header.html +27 -0
- webscout/auth/templates/components/models.html +286 -0
- webscout/auth/templates/components/navigation.html +70 -0
- webscout/auth/templates/static/api.js +455 -0
- webscout/auth/templates/static/icons.js +168 -0
- webscout/auth/templates/static/main.js +784 -0
- webscout/auth/templates/static/particles.js +201 -0
- webscout/auth/templates/static/styles.css +3353 -0
- webscout/auth/templates/static/ui.js +374 -0
- webscout/auth/templates/swagger_ui.html +170 -0
- webscout/client.py +49 -3
- webscout/litagent/Readme.md +12 -3
- webscout/litagent/agent.py +99 -62
- webscout/scout/core/scout.py +104 -26
- webscout/scout/element.py +139 -18
- webscout/swiftcli/core/cli.py +14 -3
- webscout/swiftcli/decorators/output.py +59 -9
- webscout/update_checker.py +31 -49
- webscout/version.py +1 -1
- webscout/webscout_search.py +4 -12
- webscout/webscout_search_async.py +3 -10
- webscout/yep_search.py +2 -11
- {webscout-8.3.dist-info → webscout-8.3.2.dist-info}/METADATA +41 -11
- {webscout-8.3.dist-info → webscout-8.3.2.dist-info}/RECORD +116 -68
- {webscout-8.3.dist-info → webscout-8.3.2.dist-info}/entry_points.txt +1 -1
- webscout/Provider/HF_space/__init__.py +0 -0
- webscout/Provider/HF_space/qwen_qwen2.py +0 -206
- webscout/Provider/OPENAI/api.py +0 -1035
- webscout/Provider/TTI/artbit.py +0 -0
- {webscout-8.3.dist-info → webscout-8.3.2.dist-info}/WHEEL +0 -0
- {webscout-8.3.dist-info → webscout-8.3.2.dist-info}/licenses/LICENSE.md +0 -0
- {webscout-8.3.dist-info → webscout-8.3.2.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
from curl_cffi.requests import Session
|
|
2
|
+
from curl_cffi import CurlError
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
from typing import Any, Dict, Optional, Generator, Union, List
|
|
6
|
+
|
|
7
|
+
from webscout.AIutel import Optimizers
|
|
8
|
+
from webscout.AIutel import Conversation
|
|
9
|
+
from webscout.AIutel import AwesomePrompts, sanitize_stream
|
|
10
|
+
from webscout.AIbase import Provider
|
|
11
|
+
from webscout import exceptions
|
|
12
|
+
from webscout.litagent import LitAgent
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class DeepSeekAssistant(Provider):
|
|
16
|
+
"""
|
|
17
|
+
A class to interact with the DeepSeek Assistant API.
|
|
18
|
+
|
|
19
|
+
This provider interfaces with the deepseek-assistant.com API to provide
|
|
20
|
+
AI chat completions using the V3 model.
|
|
21
|
+
|
|
22
|
+
Attributes:
|
|
23
|
+
AVAILABLE_MODELS (list): List of available models for the provider.
|
|
24
|
+
|
|
25
|
+
Examples:
|
|
26
|
+
>>> from webscout.Provider.deepseek_assistant import DeepSeekAssistant
|
|
27
|
+
>>> ai = DeepSeekAssistant()
|
|
28
|
+
>>> response = ai.chat("What's the weather today?")
|
|
29
|
+
>>> print(response)
|
|
30
|
+
'I can help you with weather information...'
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
AVAILABLE_MODELS = ["V3 model", "R1 model"]
|
|
34
|
+
|
|
35
|
+
@staticmethod
|
|
36
|
+
def _deepseek_assistant_extractor(chunk: Union[str, Dict[str, Any]]) -> Optional[str]:
|
|
37
|
+
"""Extracts content from DeepSeek Assistant stream JSON objects."""
|
|
38
|
+
if isinstance(chunk, dict):
|
|
39
|
+
return chunk.get("choices", [{}])[0].get("delta", {}).get("content")
|
|
40
|
+
return None
|
|
41
|
+
|
|
42
|
+
def __init__(
|
|
43
|
+
self,
|
|
44
|
+
is_conversation: bool = True,
|
|
45
|
+
max_tokens: int = 2049,
|
|
46
|
+
timeout: int = 30,
|
|
47
|
+
intro: str = None,
|
|
48
|
+
filepath: str = None,
|
|
49
|
+
update_file: bool = True,
|
|
50
|
+
proxies: dict = {},
|
|
51
|
+
history_offset: int = 10250,
|
|
52
|
+
act: str = None,
|
|
53
|
+
model: str = "V3 model",
|
|
54
|
+
system_prompt: str = "You are a helpful assistant.",
|
|
55
|
+
browser: str = "chrome"
|
|
56
|
+
):
|
|
57
|
+
"""
|
|
58
|
+
Initializes the DeepSeek Assistant API client.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
is_conversation (bool): Whether the provider is in conversation mode.
|
|
62
|
+
max_tokens (int): Maximum number of tokens to sample.
|
|
63
|
+
timeout (int): Timeout for API requests.
|
|
64
|
+
intro (str): Introduction message for the conversation.
|
|
65
|
+
filepath (str): Filepath for storing conversation history.
|
|
66
|
+
update_file (bool): Whether to update the conversation history file.
|
|
67
|
+
proxies (dict): Proxies for the API requests.
|
|
68
|
+
history_offset (int): Offset for conversation history.
|
|
69
|
+
act (str): Act for the conversation.
|
|
70
|
+
model (str): The model to use for completions.
|
|
71
|
+
system_prompt (str): The system prompt to define the assistant's role.
|
|
72
|
+
browser (str): Browser type for fingerprinting.
|
|
73
|
+
|
|
74
|
+
Examples:
|
|
75
|
+
>>> ai = DeepSeekAssistant(model="V3 model")
|
|
76
|
+
>>> print(ai.model)
|
|
77
|
+
'V3 model'
|
|
78
|
+
"""
|
|
79
|
+
if model not in self.AVAILABLE_MODELS:
|
|
80
|
+
raise ValueError(f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}")
|
|
81
|
+
|
|
82
|
+
self.url = "https://deepseek-assistant.com/api/search-stream-deep-chat-testing.php"
|
|
83
|
+
|
|
84
|
+
# Initialize LitAgent for user agent generation
|
|
85
|
+
self.agent = LitAgent()
|
|
86
|
+
self.fingerprint = self.agent.generate_fingerprint(browser)
|
|
87
|
+
|
|
88
|
+
# Headers based on the JavaScript code
|
|
89
|
+
self.headers = {
|
|
90
|
+
"accept": "*/*",
|
|
91
|
+
"accept-language": "id-ID,id;q=0.9",
|
|
92
|
+
"cache-control": "no-cache",
|
|
93
|
+
"content-type": "application/json",
|
|
94
|
+
"cookie": "click_id=OS3Hz0E1yKfu4YnZNwedESMEdKEgMTzL; organic_user_deepseek_assistant_ch=%7B%22pixel%22%3A%22OS3Hz0E1yKfu4YnZNwedESMEdKEgMTzL%22%2C%22cc%22%3A%22ID%22%2C%22channel%22%3A%22organic_flag%22%7D",
|
|
95
|
+
"origin": "https://deepseek-assistant.com",
|
|
96
|
+
**self.fingerprint
|
|
97
|
+
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
# Initialize curl_cffi Session
|
|
101
|
+
self.session = Session()
|
|
102
|
+
self.session.headers.update(self.headers)
|
|
103
|
+
self.session.proxies = proxies
|
|
104
|
+
|
|
105
|
+
self.system_prompt = system_prompt
|
|
106
|
+
self.is_conversation = is_conversation
|
|
107
|
+
self.max_tokens_to_sample = max_tokens
|
|
108
|
+
self.timeout = timeout
|
|
109
|
+
self.last_response = {}
|
|
110
|
+
self.model = model
|
|
111
|
+
|
|
112
|
+
self.__available_optimizers = (
|
|
113
|
+
method
|
|
114
|
+
for method in dir(Optimizers)
|
|
115
|
+
if callable(getattr(Optimizers, method)) and not method.startswith("__")
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
Conversation.intro = (
|
|
119
|
+
AwesomePrompts().get_act(
|
|
120
|
+
act, raise_not_found=True, default=None, case_insensitive=True
|
|
121
|
+
)
|
|
122
|
+
if act
|
|
123
|
+
else intro or Conversation.intro
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
self.conversation = Conversation(
|
|
127
|
+
is_conversation, self.max_tokens_to_sample, filepath, update_file
|
|
128
|
+
)
|
|
129
|
+
self.conversation.history_offset = history_offset
|
|
130
|
+
|
|
131
|
+
def refresh_identity(self, browser: str = None):
|
|
132
|
+
"""
|
|
133
|
+
Refreshes the browser identity fingerprint.
|
|
134
|
+
|
|
135
|
+
Args:
|
|
136
|
+
browser: Specific browser to use for the new fingerprint
|
|
137
|
+
"""
|
|
138
|
+
browser = browser or self.fingerprint.get("browser_type", "chrome")
|
|
139
|
+
self.fingerprint = self.agent.generate_fingerprint(browser)
|
|
140
|
+
|
|
141
|
+
# Update user-agent header with new fingerprint
|
|
142
|
+
self.headers.update({
|
|
143
|
+
"user-agent": self.fingerprint.get("user_agent", self.headers["user-agent"])
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
# Update session headers
|
|
147
|
+
self.session.headers.update(self.headers)
|
|
148
|
+
|
|
149
|
+
return self.fingerprint
|
|
150
|
+
|
|
151
|
+
def _parse_chat_response(self, input_text: str) -> str:
|
|
152
|
+
"""
|
|
153
|
+
Parses the chat response from the API, similar to the JavaScript parseChatResponse method.
|
|
154
|
+
|
|
155
|
+
Args:
|
|
156
|
+
input_text (str): The raw response text from the API
|
|
157
|
+
|
|
158
|
+
Returns:
|
|
159
|
+
str: The parsed content from the response
|
|
160
|
+
"""
|
|
161
|
+
lines = input_text.strip().split("\n")
|
|
162
|
+
result = ""
|
|
163
|
+
|
|
164
|
+
for line in lines:
|
|
165
|
+
trimmed_line = line.strip()
|
|
166
|
+
if trimmed_line.startswith("data: {") and trimmed_line.endswith("}"):
|
|
167
|
+
try:
|
|
168
|
+
# Extract JSON from the line
|
|
169
|
+
json_start = trimmed_line.find("{")
|
|
170
|
+
if json_start != -1:
|
|
171
|
+
json_str = trimmed_line[json_start:]
|
|
172
|
+
parsed_data = json.loads(json_str)
|
|
173
|
+
|
|
174
|
+
# Extract content from the parsed data
|
|
175
|
+
content = parsed_data.get("choices", [{}])[0].get("delta", {}).get("content")
|
|
176
|
+
if content is not None:
|
|
177
|
+
result += content
|
|
178
|
+
except (json.JSONDecodeError, KeyError, IndexError):
|
|
179
|
+
# Skip malformed JSON or missing keys
|
|
180
|
+
continue
|
|
181
|
+
|
|
182
|
+
return result.strip()
|
|
183
|
+
|
|
184
|
+
def ask(
|
|
185
|
+
self,
|
|
186
|
+
prompt: str,
|
|
187
|
+
stream: bool = False,
|
|
188
|
+
raw: bool = False,
|
|
189
|
+
optimizer: str = None,
|
|
190
|
+
conversationally: bool = False,
|
|
191
|
+
) -> Union[Dict[str, Any], Generator]:
|
|
192
|
+
"""
|
|
193
|
+
Sends a prompt to the DeepSeek Assistant API and returns the response.
|
|
194
|
+
|
|
195
|
+
Args:
|
|
196
|
+
prompt (str): The prompt to send to the API.
|
|
197
|
+
stream (bool): Whether to stream the response.
|
|
198
|
+
raw (bool): Whether to return the raw response.
|
|
199
|
+
optimizer (str): Optimizer to use for the prompt.
|
|
200
|
+
conversationally (bool): Whether to generate the prompt conversationally.
|
|
201
|
+
|
|
202
|
+
Returns:
|
|
203
|
+
Union[Dict[str, Any], Generator]: The API response.
|
|
204
|
+
|
|
205
|
+
Examples:
|
|
206
|
+
>>> ai = DeepSeekAssistant()
|
|
207
|
+
>>> response = ai.ask("Tell me a joke!")
|
|
208
|
+
>>> print(response)
|
|
209
|
+
{'text': 'Why did the scarecrow win an award? Because he was outstanding in his field!'}
|
|
210
|
+
"""
|
|
211
|
+
conversation_prompt = self.conversation.gen_complete_prompt(prompt)
|
|
212
|
+
if optimizer:
|
|
213
|
+
if optimizer in self.__available_optimizers:
|
|
214
|
+
conversation_prompt = getattr(Optimizers, optimizer)(
|
|
215
|
+
conversation_prompt if conversationally else prompt
|
|
216
|
+
)
|
|
217
|
+
else:
|
|
218
|
+
raise Exception(f"Optimizer is not one of {self.__available_optimizers}")
|
|
219
|
+
|
|
220
|
+
payload = {
|
|
221
|
+
"model": self.model,
|
|
222
|
+
"messages": [
|
|
223
|
+
{"role": "system", "content": self.system_prompt}, # Add system role
|
|
224
|
+
{"role": "user", "content": conversation_prompt}
|
|
225
|
+
]
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
def for_stream():
|
|
229
|
+
streaming_text = ""
|
|
230
|
+
try:
|
|
231
|
+
response = self.session.post(
|
|
232
|
+
self.url,
|
|
233
|
+
data=json.dumps(payload),
|
|
234
|
+
stream=True,
|
|
235
|
+
timeout=self.timeout,
|
|
236
|
+
impersonate="chrome110"
|
|
237
|
+
)
|
|
238
|
+
response.raise_for_status()
|
|
239
|
+
|
|
240
|
+
# Use sanitize_stream to process the response
|
|
241
|
+
processed_stream = sanitize_stream(
|
|
242
|
+
data=response.iter_content(chunk_size=None),
|
|
243
|
+
intro_value="data:",
|
|
244
|
+
to_json=True,
|
|
245
|
+
skip_markers=["[DONE]"],
|
|
246
|
+
content_extractor=self._deepseek_assistant_extractor,
|
|
247
|
+
yield_raw_on_error=False
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
for content_chunk in processed_stream:
|
|
251
|
+
if content_chunk and isinstance(content_chunk, str):
|
|
252
|
+
streaming_text += content_chunk
|
|
253
|
+
resp = dict(text=content_chunk)
|
|
254
|
+
yield resp if not raw else content_chunk
|
|
255
|
+
|
|
256
|
+
except CurlError as e:
|
|
257
|
+
raise exceptions.FailedToGenerateResponseError(f"Request failed (CurlError): {str(e)}") from e
|
|
258
|
+
except Exception as e:
|
|
259
|
+
raise exceptions.FailedToGenerateResponseError(f"Request failed ({type(e).__name__}): {str(e)}") from e
|
|
260
|
+
finally:
|
|
261
|
+
# Update history after stream finishes or fails
|
|
262
|
+
if streaming_text:
|
|
263
|
+
self.last_response = {"text": streaming_text}
|
|
264
|
+
self.conversation.update_chat_history(prompt, streaming_text)
|
|
265
|
+
|
|
266
|
+
def for_non_stream():
|
|
267
|
+
try:
|
|
268
|
+
response = self.session.post(
|
|
269
|
+
self.url,
|
|
270
|
+
data=json.dumps(payload),
|
|
271
|
+
timeout=self.timeout,
|
|
272
|
+
impersonate="chrome110"
|
|
273
|
+
)
|
|
274
|
+
response.raise_for_status()
|
|
275
|
+
|
|
276
|
+
# Parse the response using the custom parser
|
|
277
|
+
content = self._parse_chat_response(response.text)
|
|
278
|
+
|
|
279
|
+
self.last_response = {"text": content}
|
|
280
|
+
self.conversation.update_chat_history(prompt, content)
|
|
281
|
+
return self.last_response if not raw else content
|
|
282
|
+
|
|
283
|
+
except CurlError as e:
|
|
284
|
+
raise exceptions.FailedToGenerateResponseError(f"Request failed (CurlError): {e}") from e
|
|
285
|
+
except Exception as e:
|
|
286
|
+
err_text = getattr(e, 'response', None) and getattr(e.response, 'text', '')
|
|
287
|
+
raise exceptions.FailedToGenerateResponseError(f"Request failed ({type(e).__name__}): {e} - {err_text}") from e
|
|
288
|
+
|
|
289
|
+
return for_stream() if stream else for_non_stream()
|
|
290
|
+
|
|
291
|
+
def chat(
|
|
292
|
+
self,
|
|
293
|
+
prompt: str,
|
|
294
|
+
stream: bool = False,
|
|
295
|
+
optimizer: str = None,
|
|
296
|
+
conversationally: bool = False,
|
|
297
|
+
) -> Union[str, Generator[str, None, None]]:
|
|
298
|
+
"""
|
|
299
|
+
Initiates a chat with the DeepSeek Assistant API using the provided prompt.
|
|
300
|
+
|
|
301
|
+
Args:
|
|
302
|
+
prompt (str): The prompt to send to the API.
|
|
303
|
+
stream (bool): Whether to stream the response.
|
|
304
|
+
optimizer (str): Optimizer to use for the prompt.
|
|
305
|
+
conversationally (bool): Whether to generate the prompt conversationally.
|
|
306
|
+
|
|
307
|
+
Returns:
|
|
308
|
+
Union[str, Generator[str, None, None]]: The chat response.
|
|
309
|
+
|
|
310
|
+
Examples:
|
|
311
|
+
>>> ai = DeepSeekAssistant()
|
|
312
|
+
>>> response = ai.chat("Tell me a joke")
|
|
313
|
+
>>> print(response)
|
|
314
|
+
'Why did the scarecrow win an award? Because he was outstanding in his field!'
|
|
315
|
+
"""
|
|
316
|
+
def for_stream_chat():
|
|
317
|
+
gen = self.ask(
|
|
318
|
+
prompt, stream=True, raw=False,
|
|
319
|
+
optimizer=optimizer, conversationally=conversationally
|
|
320
|
+
)
|
|
321
|
+
for response_dict in gen:
|
|
322
|
+
yield self.get_message(response_dict)
|
|
323
|
+
|
|
324
|
+
def for_non_stream_chat():
|
|
325
|
+
response_data = self.ask(
|
|
326
|
+
prompt, stream=False, raw=False,
|
|
327
|
+
optimizer=optimizer, conversationally=conversationally
|
|
328
|
+
)
|
|
329
|
+
return self.get_message(response_data)
|
|
330
|
+
|
|
331
|
+
return for_stream_chat() if stream else for_non_stream_chat()
|
|
332
|
+
|
|
333
|
+
def get_message(self, response: dict) -> str:
|
|
334
|
+
"""
|
|
335
|
+
Extracts the message content from the API response.
|
|
336
|
+
|
|
337
|
+
Args:
|
|
338
|
+
response (dict): The API response.
|
|
339
|
+
|
|
340
|
+
Returns:
|
|
341
|
+
str: The message content.
|
|
342
|
+
|
|
343
|
+
Examples:
|
|
344
|
+
>>> ai = DeepSeekAssistant()
|
|
345
|
+
>>> response = ai.ask("Tell me a joke!")
|
|
346
|
+
>>> message = ai.get_message(response)
|
|
347
|
+
>>> print(message)
|
|
348
|
+
'Why did the scarecrow win an award? Because he was outstanding in his field!'
|
|
349
|
+
"""
|
|
350
|
+
assert isinstance(response, dict), "Response should be of dict data-type only"
|
|
351
|
+
return response["text"]
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
if __name__ == "__main__":
|
|
355
|
+
# Test the provider
|
|
356
|
+
print("-" * 80)
|
|
357
|
+
print(f"{'Model':<50} {'Status':<10} {'Response'}")
|
|
358
|
+
print("-" * 80)
|
|
359
|
+
|
|
360
|
+
for model in DeepSeekAssistant.AVAILABLE_MODELS:
|
|
361
|
+
try:
|
|
362
|
+
test_ai = DeepSeekAssistant(model=model, timeout=60)
|
|
363
|
+
response = test_ai.chat("Say 'Hello' in one word", stream=True)
|
|
364
|
+
response_text = ""
|
|
365
|
+
for chunk in response:
|
|
366
|
+
response_text += chunk
|
|
367
|
+
|
|
368
|
+
if response_text and len(response_text.strip()) > 0:
|
|
369
|
+
status = "✓"
|
|
370
|
+
# Clean and truncate response
|
|
371
|
+
clean_text = response_text.strip().encode('utf-8', errors='ignore').decode('utf-8')
|
|
372
|
+
display_text = clean_text[:50] + "..." if len(clean_text) > 50 else clean_text
|
|
373
|
+
else:
|
|
374
|
+
status = "✗"
|
|
375
|
+
display_text = "Empty or invalid response"
|
|
376
|
+
print(f"\r{model:<50} {status:<10} {display_text}")
|
|
377
|
+
except Exception as e:
|
|
378
|
+
print(f"\r{model:<50} {'✗':<10} {str(e)}")
|
webscout/Provider/scira_chat.py
CHANGED
|
@@ -20,12 +20,13 @@ class SciraAI(Provider):
|
|
|
20
20
|
AVAILABLE_MODELS = {
|
|
21
21
|
"scira-default": "Grok3-mini", # thinking model
|
|
22
22
|
"scira-grok-3": "Grok3",
|
|
23
|
-
"scira-anthropic": "
|
|
23
|
+
"scira-anthropic": "Claude 4 Sonnet",
|
|
24
|
+
"scira-anthropic-thinking": "Claude 4 Sonnet Thinking", # thinking model
|
|
24
25
|
"scira-vision" : "Grok2-Vision", # vision model
|
|
25
26
|
"scira-4o": "GPT4o",
|
|
26
27
|
"scira-qwq": "QWQ-32B",
|
|
27
28
|
"scira-o4-mini": "o4-mini",
|
|
28
|
-
"scira-google": "gemini 2.5 flash",
|
|
29
|
+
"scira-google": "gemini 2.5 flash Thinking", # thinking model
|
|
29
30
|
"scira-google-pro": "gemini 2.5 pro",
|
|
30
31
|
"scira-llama-4": "llama 4 Maverick",
|
|
31
32
|
}
|
webscout/Provider/toolbaz.py
CHANGED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# webscout/auth/__init__.py
|
|
2
|
+
|
|
3
|
+
from .models import User, APIKey
|
|
4
|
+
from .database import DatabaseManager
|
|
5
|
+
from .api_key_manager import APIKeyManager
|
|
6
|
+
from .rate_limiter import RateLimiter
|
|
7
|
+
from .middleware import AuthMiddleware
|
|
8
|
+
from .schemas import (
|
|
9
|
+
APIKeyCreateRequest,
|
|
10
|
+
APIKeyCreateResponse,
|
|
11
|
+
APIKeyValidationResponse,
|
|
12
|
+
UserCreateRequest,
|
|
13
|
+
UserResponse,
|
|
14
|
+
HealthCheckResponse
|
|
15
|
+
)
|
|
16
|
+
from .server import create_app, run_api, start_server
|
|
17
|
+
from .routes import Api
|
|
18
|
+
from .config import ServerConfig, AppConfig
|
|
19
|
+
from .exceptions import APIError
|
|
20
|
+
from .providers import initialize_provider_map, initialize_tti_provider_map
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"User",
|
|
24
|
+
"APIKey",
|
|
25
|
+
"DatabaseManager",
|
|
26
|
+
"APIKeyManager",
|
|
27
|
+
"RateLimiter",
|
|
28
|
+
"AuthMiddleware",
|
|
29
|
+
"APIKeyCreateRequest",
|
|
30
|
+
"APIKeyCreateResponse",
|
|
31
|
+
"APIKeyValidationResponse",
|
|
32
|
+
"UserCreateRequest",
|
|
33
|
+
"UserResponse",
|
|
34
|
+
"HealthCheckResponse",
|
|
35
|
+
"create_app",
|
|
36
|
+
"run_api",
|
|
37
|
+
"start_server",
|
|
38
|
+
"Api",
|
|
39
|
+
"ServerConfig",
|
|
40
|
+
"AppConfig",
|
|
41
|
+
"APIError",
|
|
42
|
+
"initialize_provider_map",
|
|
43
|
+
"initialize_tti_provider_map"
|
|
44
|
+
]
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
# webscout/auth/api_key_manager.py
|
|
2
|
+
|
|
3
|
+
import secrets
|
|
4
|
+
import string
|
|
5
|
+
from datetime import datetime, timezone, timedelta
|
|
6
|
+
from typing import Optional, Tuple
|
|
7
|
+
import hashlib
|
|
8
|
+
import logging
|
|
9
|
+
|
|
10
|
+
from .models import User, APIKey
|
|
11
|
+
from .database import DatabaseManager
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class APIKeyManager:
|
|
17
|
+
"""Manages API key generation, validation, and lifecycle."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, database_manager: DatabaseManager):
|
|
20
|
+
self.db = database_manager
|
|
21
|
+
self.key_prefix = "ws_" # webscout prefix
|
|
22
|
+
self.key_length = 32 # Length of the random part
|
|
23
|
+
|
|
24
|
+
def generate_api_key(self) -> str:
|
|
25
|
+
"""Generate a secure API key."""
|
|
26
|
+
# Generate random string
|
|
27
|
+
alphabet = string.ascii_letters + string.digits
|
|
28
|
+
random_part = ''.join(secrets.choice(alphabet) for _ in range(self.key_length))
|
|
29
|
+
|
|
30
|
+
# Add prefix
|
|
31
|
+
api_key = f"{self.key_prefix}{random_part}"
|
|
32
|
+
|
|
33
|
+
return api_key
|
|
34
|
+
|
|
35
|
+
def hash_api_key(self, api_key: str) -> str:
|
|
36
|
+
"""Hash an API key for secure storage (optional, for extra security)."""
|
|
37
|
+
return hashlib.sha256(api_key.encode()).hexdigest()
|
|
38
|
+
|
|
39
|
+
async def create_api_key(
|
|
40
|
+
self,
|
|
41
|
+
username: str,
|
|
42
|
+
telegram_id: str,
|
|
43
|
+
name: Optional[str] = None,
|
|
44
|
+
rate_limit: int = 10,
|
|
45
|
+
expires_in_days: Optional[int] = None
|
|
46
|
+
) -> Tuple[APIKey, User]:
|
|
47
|
+
"""Create a new API key and associated user if needed. Only one API key per user allowed."""
|
|
48
|
+
|
|
49
|
+
# Check if user already exists by telegram_id
|
|
50
|
+
user = await self.db.get_user_by_telegram_id(telegram_id)
|
|
51
|
+
|
|
52
|
+
if user:
|
|
53
|
+
# Check if user already has an API key
|
|
54
|
+
existing_keys = await self.db.get_api_keys_by_user(user.id)
|
|
55
|
+
active_keys = [key for key in existing_keys if key.is_active and not key.is_expired()]
|
|
56
|
+
|
|
57
|
+
if active_keys:
|
|
58
|
+
raise ValueError(f"User with Telegram ID {telegram_id} already has an active API key. Only one API key per user is allowed.")
|
|
59
|
+
else:
|
|
60
|
+
# Check if username is already taken
|
|
61
|
+
existing_user = await self.db.get_user_by_username(username)
|
|
62
|
+
if existing_user:
|
|
63
|
+
raise ValueError(f"Username '{username}' is already taken")
|
|
64
|
+
|
|
65
|
+
# Create new user
|
|
66
|
+
user = User(
|
|
67
|
+
username=username,
|
|
68
|
+
telegram_id=telegram_id,
|
|
69
|
+
created_at=datetime.now(timezone.utc),
|
|
70
|
+
updated_at=datetime.now(timezone.utc)
|
|
71
|
+
)
|
|
72
|
+
try:
|
|
73
|
+
user = await self.db.create_user(user)
|
|
74
|
+
logger.info(f"Created new user: {user.username} (Telegram ID: {telegram_id})")
|
|
75
|
+
except ValueError as e:
|
|
76
|
+
# User might already exist, try to get it
|
|
77
|
+
if "already exists" in str(e):
|
|
78
|
+
user = await self.db.get_user_by_telegram_id(telegram_id)
|
|
79
|
+
if not user:
|
|
80
|
+
raise e
|
|
81
|
+
else:
|
|
82
|
+
raise e
|
|
83
|
+
|
|
84
|
+
# Generate API key
|
|
85
|
+
api_key_value = self.generate_api_key()
|
|
86
|
+
|
|
87
|
+
# Calculate expiration
|
|
88
|
+
expires_at = None
|
|
89
|
+
if expires_in_days:
|
|
90
|
+
expires_at = datetime.now(timezone.utc) + timedelta(days=expires_in_days)
|
|
91
|
+
|
|
92
|
+
# Create API key object
|
|
93
|
+
api_key = APIKey(
|
|
94
|
+
key=api_key_value,
|
|
95
|
+
user_id=user.id,
|
|
96
|
+
name=name,
|
|
97
|
+
created_at=datetime.now(timezone.utc),
|
|
98
|
+
expires_at=expires_at,
|
|
99
|
+
rate_limit=rate_limit,
|
|
100
|
+
is_active=True
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
# Store in database
|
|
104
|
+
try:
|
|
105
|
+
api_key = await self.db.create_api_key(api_key)
|
|
106
|
+
logger.info(f"Created API key for user {user.username}: {api_key.id}")
|
|
107
|
+
return api_key, user
|
|
108
|
+
except ValueError as e:
|
|
109
|
+
# Key collision (very unlikely), try again
|
|
110
|
+
if "already exists" in str(e):
|
|
111
|
+
logger.warning("API key collision detected, regenerating...")
|
|
112
|
+
return await self.create_api_key(username, telegram_id, name, rate_limit, expires_in_days)
|
|
113
|
+
raise e
|
|
114
|
+
|
|
115
|
+
async def validate_api_key(self, api_key: str) -> Tuple[bool, Optional[APIKey], Optional[str]]:
|
|
116
|
+
"""
|
|
117
|
+
Validate an API key.
|
|
118
|
+
|
|
119
|
+
Returns:
|
|
120
|
+
Tuple of (is_valid, api_key_object, error_message)
|
|
121
|
+
"""
|
|
122
|
+
if not api_key:
|
|
123
|
+
return False, None, "API key is required"
|
|
124
|
+
|
|
125
|
+
if not api_key.startswith(self.key_prefix):
|
|
126
|
+
return False, None, "Invalid API key format"
|
|
127
|
+
|
|
128
|
+
try:
|
|
129
|
+
# Get API key from database
|
|
130
|
+
key_obj = await self.db.get_api_key(api_key)
|
|
131
|
+
|
|
132
|
+
if not key_obj:
|
|
133
|
+
return False, None, "API key not found"
|
|
134
|
+
|
|
135
|
+
if not key_obj.is_active:
|
|
136
|
+
return False, None, "API key is inactive"
|
|
137
|
+
|
|
138
|
+
if key_obj.is_expired():
|
|
139
|
+
return False, None, "API key has expired"
|
|
140
|
+
|
|
141
|
+
# Update last used timestamp
|
|
142
|
+
key_obj.last_used_at = datetime.now(timezone.utc)
|
|
143
|
+
key_obj.usage_count += 1
|
|
144
|
+
|
|
145
|
+
try:
|
|
146
|
+
await self.db.update_api_key(key_obj)
|
|
147
|
+
except Exception as e:
|
|
148
|
+
logger.warning(f"Failed to update API key usage: {e}")
|
|
149
|
+
|
|
150
|
+
return True, key_obj, None
|
|
151
|
+
|
|
152
|
+
except Exception as e:
|
|
153
|
+
logger.error(f"Error validating API key: {e}")
|
|
154
|
+
return False, None, "Internal error during validation"
|
|
155
|
+
|
|
156
|
+
async def revoke_api_key(self, api_key: str) -> bool:
|
|
157
|
+
"""Revoke an API key by marking it as inactive."""
|
|
158
|
+
try:
|
|
159
|
+
key_obj = await self.db.get_api_key(api_key)
|
|
160
|
+
|
|
161
|
+
if not key_obj:
|
|
162
|
+
return False
|
|
163
|
+
|
|
164
|
+
key_obj.is_active = False
|
|
165
|
+
key_obj.updated_at = datetime.now(timezone.utc)
|
|
166
|
+
|
|
167
|
+
await self.db.update_api_key(key_obj)
|
|
168
|
+
logger.info(f"Revoked API key: {key_obj.id}")
|
|
169
|
+
return True
|
|
170
|
+
|
|
171
|
+
except Exception as e:
|
|
172
|
+
logger.error(f"Error revoking API key: {e}")
|
|
173
|
+
return False
|
|
174
|
+
|
|
175
|
+
async def get_user_api_keys(self, user_id: str) -> list[APIKey]:
|
|
176
|
+
"""Get all API keys for a user."""
|
|
177
|
+
try:
|
|
178
|
+
return await self.db.get_api_keys_by_user(user_id)
|
|
179
|
+
except Exception as e:
|
|
180
|
+
logger.error(f"Error getting user API keys: {e}")
|
|
181
|
+
return []
|
|
182
|
+
|
|
183
|
+
async def cleanup_expired_keys(self) -> int:
|
|
184
|
+
"""Clean up expired API keys (mark as inactive)."""
|
|
185
|
+
# This would require a method to get all API keys, which we haven't implemented
|
|
186
|
+
# For now, we'll just return 0
|
|
187
|
+
# In a production system, you'd want to implement this properly
|
|
188
|
+
logger.info("Cleanup expired keys called (not implemented)")
|
|
189
|
+
return 0
|