webscout 6.3__py3-none-any.whl → 6.5__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 +191 -176
- webscout/AIbase.py +0 -197
- webscout/AIutel.py +441 -1130
- webscout/DWEBS.py +189 -35
- webscout/{YTdownloader.py → Extra/YTToolkit/YTdownloader.py} +990 -1103
- webscout/Extra/YTToolkit/__init__.py +3 -0
- webscout/{transcriber.py → Extra/YTToolkit/transcriber.py} +479 -551
- webscout/Extra/YTToolkit/ytapi/__init__.py +6 -0
- webscout/Extra/YTToolkit/ytapi/channel.py +307 -0
- webscout/Extra/YTToolkit/ytapi/errors.py +13 -0
- webscout/Extra/YTToolkit/ytapi/extras.py +45 -0
- webscout/Extra/YTToolkit/ytapi/https.py +88 -0
- webscout/Extra/YTToolkit/ytapi/patterns.py +61 -0
- webscout/Extra/YTToolkit/ytapi/playlist.py +59 -0
- webscout/Extra/YTToolkit/ytapi/pool.py +8 -0
- webscout/Extra/YTToolkit/ytapi/query.py +37 -0
- webscout/Extra/YTToolkit/ytapi/stream.py +60 -0
- webscout/Extra/YTToolkit/ytapi/utils.py +62 -0
- webscout/Extra/YTToolkit/ytapi/video.py +102 -0
- webscout/Extra/__init__.py +3 -1
- webscout/Extra/autocoder/__init__.py +9 -0
- webscout/Extra/autocoder/autocoder_utiles.py +121 -0
- webscout/Extra/autocoder/rawdog.py +680 -0
- webscout/Extra/autollama.py +246 -195
- webscout/Extra/gguf.py +81 -56
- webscout/Extra/markdownlite/__init__.py +862 -0
- webscout/Extra/weather_ascii.py +2 -2
- webscout/LLM.py +206 -43
- webscout/Litlogger/__init__.py +681 -0
- webscout/Provider/DARKAI.py +1 -1
- webscout/Provider/EDITEE.py +1 -1
- webscout/Provider/NinjaChat.py +1 -1
- webscout/Provider/PI.py +120 -35
- webscout/Provider/Perplexity.py +590 -598
- webscout/Provider/Reka.py +0 -1
- webscout/Provider/RoboCoders.py +206 -0
- webscout/Provider/TTI/AiForce/__init__.py +22 -0
- webscout/Provider/TTI/AiForce/async_aiforce.py +257 -0
- webscout/Provider/TTI/AiForce/sync_aiforce.py +242 -0
- webscout/Provider/TTI/Nexra/__init__.py +22 -0
- webscout/Provider/TTI/Nexra/async_nexra.py +286 -0
- webscout/Provider/TTI/Nexra/sync_nexra.py +258 -0
- webscout/Provider/TTI/PollinationsAI/__init__.py +23 -0
- webscout/Provider/TTI/PollinationsAI/async_pollinations.py +330 -0
- webscout/Provider/TTI/PollinationsAI/sync_pollinations.py +285 -0
- webscout/Provider/TTI/__init__.py +2 -4
- webscout/Provider/TTI/artbit/__init__.py +22 -0
- webscout/Provider/TTI/artbit/async_artbit.py +184 -0
- webscout/Provider/TTI/artbit/sync_artbit.py +176 -0
- webscout/Provider/TTI/blackbox/__init__.py +4 -0
- webscout/Provider/TTI/blackbox/async_blackbox.py +212 -0
- webscout/Provider/TTI/{blackboximage.py → blackbox/sync_blackbox.py} +199 -153
- webscout/Provider/TTI/deepinfra/__init__.py +4 -0
- webscout/Provider/TTI/deepinfra/async_deepinfra.py +227 -0
- webscout/Provider/TTI/deepinfra/sync_deepinfra.py +199 -0
- webscout/Provider/TTI/huggingface/__init__.py +22 -0
- webscout/Provider/TTI/huggingface/async_huggingface.py +199 -0
- webscout/Provider/TTI/huggingface/sync_huggingface.py +195 -0
- webscout/Provider/TTI/imgninza/__init__.py +4 -0
- webscout/Provider/TTI/imgninza/async_ninza.py +214 -0
- webscout/Provider/TTI/{imgninza.py → imgninza/sync_ninza.py} +209 -136
- webscout/Provider/TTI/talkai/__init__.py +4 -0
- webscout/Provider/TTI/talkai/async_talkai.py +229 -0
- webscout/Provider/TTI/talkai/sync_talkai.py +207 -0
- webscout/Provider/TTS/__init__.py +5 -1
- webscout/Provider/TTS/deepgram.py +183 -0
- webscout/Provider/TTS/elevenlabs.py +137 -0
- webscout/Provider/TTS/gesserit.py +151 -0
- webscout/Provider/TTS/murfai.py +139 -0
- webscout/Provider/TTS/parler.py +134 -107
- webscout/Provider/TTS/streamElements.py +360 -275
- webscout/Provider/TTS/utils.py +280 -0
- webscout/Provider/TTS/voicepod.py +116 -116
- webscout/Provider/__init__.py +8 -1
- webscout/Provider/askmyai.py +2 -2
- webscout/Provider/cerebras.py +227 -219
- webscout/Provider/llama3mitril.py +0 -1
- webscout/Provider/meta.py +794 -779
- webscout/Provider/mhystical.py +176 -0
- webscout/Provider/perplexitylabs.py +265 -0
- webscout/Provider/twitterclone.py +251 -245
- webscout/Provider/typegpt.py +358 -0
- webscout/__init__.py +9 -8
- webscout/__main__.py +5 -5
- webscout/cli.py +252 -280
- webscout/conversation.py +227 -0
- webscout/exceptions.py +161 -29
- webscout/litagent/__init__.py +172 -0
- webscout/litprinter/__init__.py +832 -0
- webscout/optimizers.py +270 -0
- webscout/prompt_manager.py +279 -0
- webscout/scout/__init__.py +11 -0
- webscout/scout/core.py +884 -0
- webscout/scout/element.py +459 -0
- webscout/scout/parsers/__init__.py +69 -0
- webscout/scout/parsers/html5lib_parser.py +172 -0
- webscout/scout/parsers/html_parser.py +236 -0
- webscout/scout/parsers/lxml_parser.py +178 -0
- webscout/scout/utils.py +38 -0
- webscout/swiftcli/__init__.py +810 -0
- webscout/update_checker.py +125 -0
- webscout/version.py +1 -1
- webscout/zeroart/__init__.py +55 -0
- webscout/zeroart/base.py +61 -0
- webscout/zeroart/effects.py +99 -0
- webscout/zeroart/fonts.py +816 -0
- webscout/zerodir/__init__.py +225 -0
- {webscout-6.3.dist-info → webscout-6.5.dist-info}/METADATA +37 -112
- webscout-6.5.dist-info/RECORD +179 -0
- webscout/Agents/Onlinesearcher.py +0 -182
- webscout/Agents/__init__.py +0 -2
- webscout/Agents/functioncall.py +0 -248
- webscout/Bing_search.py +0 -154
- webscout/Provider/TTI/AIuncensoredimage.py +0 -103
- webscout/Provider/TTI/Nexra.py +0 -120
- webscout/Provider/TTI/PollinationsAI.py +0 -138
- webscout/Provider/TTI/WebSimAI.py +0 -142
- webscout/Provider/TTI/aiforce.py +0 -160
- webscout/Provider/TTI/artbit.py +0 -141
- webscout/Provider/TTI/deepinfra.py +0 -148
- webscout/Provider/TTI/huggingface.py +0 -155
- webscout/Provider/TTI/talkai.py +0 -116
- webscout/g4f.py +0 -666
- webscout/models.py +0 -23
- webscout/requestsHTMLfix.py +0 -775
- webscout/webai.py +0 -2590
- webscout-6.3.dist-info/RECORD +0 -124
- {webscout-6.3.dist-info → webscout-6.5.dist-info}/LICENSE.md +0 -0
- {webscout-6.3.dist-info → webscout-6.5.dist-info}/WHEEL +0 -0
- {webscout-6.3.dist-info → webscout-6.5.dist-info}/entry_points.txt +0 -0
- {webscout-6.3.dist-info → webscout-6.5.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import requests
|
|
2
|
+
import json
|
|
3
|
+
from typing import Any, Dict, Optional, Generator, List
|
|
4
|
+
|
|
5
|
+
from webscout.AIutel import Optimizers
|
|
6
|
+
from webscout.AIutel import Conversation
|
|
7
|
+
from webscout.AIutel import AwesomePrompts
|
|
8
|
+
from webscout.AIbase import Provider
|
|
9
|
+
from webscout import exceptions
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Mhystical(Provider):
|
|
13
|
+
"""
|
|
14
|
+
A class to interact with the Mhystical API. Improved to meet webscout provider standards.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
AVAILABLE_MODELS = ["gpt-4", "gpt-3.5-turbo"] # Add available models
|
|
18
|
+
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
is_conversation: bool = True,
|
|
22
|
+
max_tokens: int = 2048,
|
|
23
|
+
timeout: int = 30,
|
|
24
|
+
intro: str = None,
|
|
25
|
+
filepath: str = None,
|
|
26
|
+
update_file: bool = True,
|
|
27
|
+
proxies: dict = {},
|
|
28
|
+
history_offset: int = 10250,
|
|
29
|
+
act: str = None,
|
|
30
|
+
model: str = "gpt-4", # Default model
|
|
31
|
+
system_prompt: str = "You are a helpful AI assistant." # Default system prompt
|
|
32
|
+
):
|
|
33
|
+
"""Initializes the Mhystical API."""
|
|
34
|
+
if model not in self.AVAILABLE_MODELS:
|
|
35
|
+
raise ValueError(f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}")
|
|
36
|
+
|
|
37
|
+
self.session = requests.Session()
|
|
38
|
+
self.is_conversation = is_conversation
|
|
39
|
+
self.max_tokens_to_sample = max_tokens
|
|
40
|
+
self.api_endpoint = "https://api.mhystical.cc/v1/completions"
|
|
41
|
+
self.timeout = timeout
|
|
42
|
+
self.last_response = {}
|
|
43
|
+
self.model = model
|
|
44
|
+
self.system_prompt = system_prompt # Store system prompt
|
|
45
|
+
self.headers = {
|
|
46
|
+
"x-api-key": "mhystical", # Set API key in header (or better, in __init__ from parameter)
|
|
47
|
+
"Content-Type": "application/json",
|
|
48
|
+
"accept": "*/*",
|
|
49
|
+
"user-agent": "Mozilla/5.0"
|
|
50
|
+
}
|
|
51
|
+
self.__available_optimizers = (
|
|
52
|
+
method
|
|
53
|
+
for method in dir(Optimizers)
|
|
54
|
+
if callable(getattr(Optimizers, method)) and not method.startswith("__")
|
|
55
|
+
)
|
|
56
|
+
Conversation.intro = (
|
|
57
|
+
AwesomePrompts().get_act(
|
|
58
|
+
act, raise_not_found=True, default=None, case_insensitive=True
|
|
59
|
+
)
|
|
60
|
+
if act
|
|
61
|
+
else intro or Conversation.intro
|
|
62
|
+
)
|
|
63
|
+
self.conversation = Conversation(
|
|
64
|
+
is_conversation, self.max_tokens_to_sample, filepath, update_file
|
|
65
|
+
)
|
|
66
|
+
self.conversation.history_offset = history_offset
|
|
67
|
+
self.session.proxies = proxies
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def ask(
|
|
71
|
+
self,
|
|
72
|
+
prompt: str,
|
|
73
|
+
stream: bool = False,
|
|
74
|
+
raw: bool = False,
|
|
75
|
+
optimizer: str = None,
|
|
76
|
+
conversationally: bool = False,
|
|
77
|
+
) -> Dict[str, Any] | Generator[Dict[str, Any], None, None]:
|
|
78
|
+
|
|
79
|
+
conversation_prompt = self.conversation.gen_complete_prompt(prompt)
|
|
80
|
+
if optimizer:
|
|
81
|
+
if optimizer in self.__available_optimizers:
|
|
82
|
+
conversation_prompt = getattr(Optimizers, optimizer)(
|
|
83
|
+
conversation_prompt if conversationally else prompt
|
|
84
|
+
)
|
|
85
|
+
else:
|
|
86
|
+
raise exceptions.FailedToGenerateResponseError(
|
|
87
|
+
f"Optimizer is not one of {self.__available_optimizers}"
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
messages = [
|
|
91
|
+
{"role": "system", "content": self.system_prompt}, # Include system prompt
|
|
92
|
+
{"role": "user", "content": conversation_prompt},
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
data = {
|
|
96
|
+
"model": self.model, # Now using self.model
|
|
97
|
+
"messages": messages # Pass messages to API
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
def for_stream():
|
|
101
|
+
try:
|
|
102
|
+
with requests.post(self.api_endpoint, headers=self.headers, json=data, stream=True, timeout=self.timeout) as response:
|
|
103
|
+
response.raise_for_status() # Raise exceptions for HTTP errors
|
|
104
|
+
|
|
105
|
+
# Emulate streaming for this API
|
|
106
|
+
full_response = "" # Accumulate the full response
|
|
107
|
+
for chunk in response.iter_content(decode_unicode=True, chunk_size=self.stream_chunk_size):
|
|
108
|
+
if chunk:
|
|
109
|
+
full_response += chunk
|
|
110
|
+
yield chunk if raw else {"text": chunk}
|
|
111
|
+
|
|
112
|
+
self.last_response.update({"text": full_response})
|
|
113
|
+
self.conversation.update_chat_history(prompt, full_response)
|
|
114
|
+
except requests.exceptions.RequestException as e:
|
|
115
|
+
raise exceptions.ProviderConnectionError(f"Network error: {str(e)}")
|
|
116
|
+
|
|
117
|
+
def for_non_stream():
|
|
118
|
+
try:
|
|
119
|
+
response = self.session.post(self.api_endpoint, headers=self.headers, json=data, timeout=self.timeout)
|
|
120
|
+
response.raise_for_status()
|
|
121
|
+
|
|
122
|
+
full_response = self._parse_response(response.text)
|
|
123
|
+
self.last_response.update({"text": full_response})
|
|
124
|
+
|
|
125
|
+
# Yield the entire response as a single chunk
|
|
126
|
+
yield {"text": full_response}
|
|
127
|
+
|
|
128
|
+
except requests.exceptions.RequestException as e:
|
|
129
|
+
raise exceptions.ProviderConnectionError(f"Network error: {str(e)}")
|
|
130
|
+
|
|
131
|
+
return for_stream() if stream else for_non_stream()
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def chat(
|
|
136
|
+
self,
|
|
137
|
+
prompt: str,
|
|
138
|
+
stream: bool = False,
|
|
139
|
+
optimizer: str = None,
|
|
140
|
+
conversationally: bool = False,
|
|
141
|
+
) -> str | Generator[str, None, None]:
|
|
142
|
+
|
|
143
|
+
def for_stream():
|
|
144
|
+
for response in self.ask(
|
|
145
|
+
prompt, stream=True, optimizer=optimizer, conversationally=conversationally
|
|
146
|
+
):
|
|
147
|
+
yield self.get_message(response)
|
|
148
|
+
|
|
149
|
+
def for_non_stream():
|
|
150
|
+
response = next(self.ask(
|
|
151
|
+
prompt, stream=False, optimizer=optimizer, conversationally=conversationally
|
|
152
|
+
))
|
|
153
|
+
return self.get_message(response)
|
|
154
|
+
return for_stream() if stream else for_non_stream()
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def get_message(self, response: dict) -> str:
|
|
159
|
+
assert isinstance(response, dict), "Response should be of dict data-type only"
|
|
160
|
+
return response["text"]
|
|
161
|
+
|
|
162
|
+
@staticmethod
|
|
163
|
+
def _parse_response(response_text: str) -> str:
|
|
164
|
+
"""Parse and validate API response."""
|
|
165
|
+
try:
|
|
166
|
+
data = json.loads(response_text)
|
|
167
|
+
return data["choices"][0]["message"]["content"].strip()
|
|
168
|
+
except (json.JSONDecodeError, KeyError, IndexError) as e:
|
|
169
|
+
raise exceptions.InvalidResponseError(f"Failed to parse response: {str(e)}")
|
|
170
|
+
|
|
171
|
+
if __name__ == "__main__":
|
|
172
|
+
from rich import print
|
|
173
|
+
ai = Mhystical()
|
|
174
|
+
response = ai.chat(input(">>> "))
|
|
175
|
+
for chunk in response:
|
|
176
|
+
print(chunk, end="", flush=True)
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import random
|
|
3
|
+
import requests
|
|
4
|
+
import websocket
|
|
5
|
+
from typing import Generator, Union, Optional, Dict, Any
|
|
6
|
+
|
|
7
|
+
from webscout.AIutel import Optimizers
|
|
8
|
+
from webscout.AIutel import Conversation
|
|
9
|
+
from webscout.AIutel import AwesomePrompts
|
|
10
|
+
from webscout.AIbase import Provider
|
|
11
|
+
from webscout import exceptions
|
|
12
|
+
|
|
13
|
+
API_URL = "https://www.perplexity.ai/socket.io/"
|
|
14
|
+
WS_URL = "wss://www.perplexity.ai/socket.io/"
|
|
15
|
+
|
|
16
|
+
class PerplexityLabs(Provider):
|
|
17
|
+
"""
|
|
18
|
+
A class to interact with the Perplexity Labs API
|
|
19
|
+
"""
|
|
20
|
+
url = "https://labs.perplexity.ai"
|
|
21
|
+
|
|
22
|
+
# Models with web search capability
|
|
23
|
+
online_models = [
|
|
24
|
+
"llama-3.1-sonar-large-128k-online",
|
|
25
|
+
"llama-3.1-sonar-small-128k-online",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
# Models for chat/instruct without web search
|
|
29
|
+
chat_models = [
|
|
30
|
+
"llama-3.1-sonar-large-128k-chat",
|
|
31
|
+
"llama-3.1-sonar-small-128k-chat",
|
|
32
|
+
"llama-3.1-8b-instruct",
|
|
33
|
+
"llama-3.1-70b-instruct",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
is_conversation: bool = True,
|
|
39
|
+
max_tokens: int = 600,
|
|
40
|
+
timeout: int = 30,
|
|
41
|
+
intro: str = None,
|
|
42
|
+
filepath: str = None,
|
|
43
|
+
update_file: bool = True,
|
|
44
|
+
proxies: dict = {},
|
|
45
|
+
history_offset: int = 10250,
|
|
46
|
+
act: str = None,
|
|
47
|
+
model: str = "llama-3.1-sonar-large-128k-online",
|
|
48
|
+
system_prompt: str = "You are a helpful AI assistant.",
|
|
49
|
+
):
|
|
50
|
+
"""Initializes the PerplexityLabs API client."""
|
|
51
|
+
self.session = requests.Session()
|
|
52
|
+
self.is_conversation = is_conversation
|
|
53
|
+
self.max_tokens_to_sample = max_tokens
|
|
54
|
+
self.timeout = timeout
|
|
55
|
+
self.last_response = {}
|
|
56
|
+
self.system_prompt = system_prompt
|
|
57
|
+
self.headers = {
|
|
58
|
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
|
59
|
+
"Accept": "*/*",
|
|
60
|
+
"Accept-Language": "en-US,en;q=0.9",
|
|
61
|
+
"Accept-Encoding": "gzip, deflate, br",
|
|
62
|
+
"Origin": self.url,
|
|
63
|
+
"Connection": "keep-alive",
|
|
64
|
+
"Referer": f"{self.url}/",
|
|
65
|
+
"Sec-Fetch-Dest": "empty",
|
|
66
|
+
"Sec-Fetch-Mode": "cors",
|
|
67
|
+
"Sec-Fetch-Site": "same-site",
|
|
68
|
+
"Pragma": "no-cache",
|
|
69
|
+
"Cache-Control": "no-cache",
|
|
70
|
+
}
|
|
71
|
+
self.session.headers.update(self.headers)
|
|
72
|
+
self.proxies = proxies
|
|
73
|
+
self.model = model
|
|
74
|
+
self.conversation = Conversation(is_conversation, max_tokens, filepath, update_file)
|
|
75
|
+
self.conversation.history_offset = history_offset
|
|
76
|
+
self.__available_optimizers = ["gpt4", "claude", "gemini", "simple"]
|
|
77
|
+
|
|
78
|
+
try:
|
|
79
|
+
self.session.get(self.url)
|
|
80
|
+
except requests.exceptions.RequestException as e:
|
|
81
|
+
raise exceptions.ProviderConnectionError(f"Failed to initialize session: {e}")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _get_session_id(self) -> str:
|
|
85
|
+
t = format(random.getrandbits(32), "08x")
|
|
86
|
+
try:
|
|
87
|
+
response = self.session.get(
|
|
88
|
+
f"{API_URL}?EIO=4&transport=polling&t={t}",
|
|
89
|
+
proxies=self.proxies
|
|
90
|
+
)
|
|
91
|
+
response.raise_for_status()
|
|
92
|
+
text = response.text
|
|
93
|
+
|
|
94
|
+
if not text.startswith("0"):
|
|
95
|
+
raise exceptions.InvalidResponseError("Invalid response format")
|
|
96
|
+
|
|
97
|
+
return json.loads(text[1:])["sid"]
|
|
98
|
+
except requests.exceptions.RequestException as e:
|
|
99
|
+
raise exceptions.ProviderConnectionError(f"Failed to get session ID: {e}")
|
|
100
|
+
except (json.JSONDecodeError, KeyError) as e:
|
|
101
|
+
raise exceptions.InvalidResponseError(f"Failed to parse session ID: {e}")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _authenticate_session(self, sid: str, t: str) -> None:
|
|
105
|
+
try:
|
|
106
|
+
response = self.session.post(
|
|
107
|
+
f"{API_URL}?EIO=4&transport=polling&t={t}&sid={sid}",
|
|
108
|
+
data='40{"jwt":"anonymous-ask-user"}',
|
|
109
|
+
proxies=self.proxies
|
|
110
|
+
)
|
|
111
|
+
response.raise_for_status()
|
|
112
|
+
if response.text != "OK":
|
|
113
|
+
raise exceptions.AuthenticationError("Authentication failed")
|
|
114
|
+
except requests.exceptions.RequestException as e:
|
|
115
|
+
raise exceptions.ProviderConnectionError(f"Authentication failed: {e}")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _websocket_interaction(
|
|
119
|
+
self,
|
|
120
|
+
sid: str,
|
|
121
|
+
t: str,
|
|
122
|
+
prompt: str,
|
|
123
|
+
model: str
|
|
124
|
+
) -> Generator[str, None, None]:
|
|
125
|
+
ws = websocket.create_connection(
|
|
126
|
+
f"{WS_URL}?EIO=4&transport=websocket&sid={sid}",
|
|
127
|
+
header=[f"{k}: {v}" for k, v in self.headers.items()],
|
|
128
|
+
cookie="; ".join([f"{k}={v}" for k, v in self.session.cookies.items()]),
|
|
129
|
+
proxy=self.proxies.get("http") or self.proxies.get("https") if self.proxies else None,
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
try:
|
|
133
|
+
ws.send("2probe")
|
|
134
|
+
if ws.recv() != "3probe":
|
|
135
|
+
raise exceptions.ProviderConnectionError("WebSocket handshake failed")
|
|
136
|
+
ws.send("5")
|
|
137
|
+
ws.recv()
|
|
138
|
+
ws.recv()
|
|
139
|
+
|
|
140
|
+
message_data = {
|
|
141
|
+
"version": "2.5",
|
|
142
|
+
"source": "default",
|
|
143
|
+
"model": model,
|
|
144
|
+
"messages": [{"role": "user", "content": prompt}]
|
|
145
|
+
}
|
|
146
|
+
ws.send("42" + json.dumps(["perplexity_labs", message_data]))
|
|
147
|
+
|
|
148
|
+
last_message = 0
|
|
149
|
+
while True:
|
|
150
|
+
message = ws.recv()
|
|
151
|
+
if message == "2":
|
|
152
|
+
if last_message == 0:
|
|
153
|
+
raise exceptions.InvalidResponseError("No response received")
|
|
154
|
+
ws.send("3")
|
|
155
|
+
continue
|
|
156
|
+
|
|
157
|
+
try:
|
|
158
|
+
data = json.loads(message[2:])[1]
|
|
159
|
+
new_content = data["output"][last_message:]
|
|
160
|
+
if new_content:
|
|
161
|
+
yield new_content
|
|
162
|
+
last_message = len(data["output"])
|
|
163
|
+
if data.get("final", False):
|
|
164
|
+
break
|
|
165
|
+
except Exception as e:
|
|
166
|
+
raise exceptions.InvalidResponseError(f"Failed to parse message: {e}")
|
|
167
|
+
|
|
168
|
+
finally:
|
|
169
|
+
ws.close()
|
|
170
|
+
|
|
171
|
+
def ask(
|
|
172
|
+
self,
|
|
173
|
+
prompt: str,
|
|
174
|
+
stream: bool = False,
|
|
175
|
+
raw: bool = False,
|
|
176
|
+
optimizer: str = None,
|
|
177
|
+
conversationally: bool = False,
|
|
178
|
+
) -> Union[str, Dict[str, Any]]:
|
|
179
|
+
"""Ask a question and get a response."""
|
|
180
|
+
conversation_prompt = self.conversation.gen_complete_prompt(prompt)
|
|
181
|
+
if optimizer:
|
|
182
|
+
if optimizer in self.__available_optimizers:
|
|
183
|
+
conversation_prompt = getattr(Optimizers, optimizer)(
|
|
184
|
+
conversation_prompt if conversationally else prompt
|
|
185
|
+
)
|
|
186
|
+
else:
|
|
187
|
+
raise exceptions.FailedToGenerateResponseError(
|
|
188
|
+
f"Optimizer is not one of {self.__available_optimizers}"
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
t = format(random.getrandbits(32), "08x")
|
|
192
|
+
sid = self._get_session_id()
|
|
193
|
+
self._authenticate_session(sid, t)
|
|
194
|
+
|
|
195
|
+
def for_stream():
|
|
196
|
+
gen = self._websocket_interaction(sid, t, conversation_prompt, self.model)
|
|
197
|
+
full_response = ""
|
|
198
|
+
for chunk in gen:
|
|
199
|
+
full_response += chunk
|
|
200
|
+
response_dict = dict(text=chunk)
|
|
201
|
+
self.last_response.update(response_dict)
|
|
202
|
+
yield response_dict if not raw else chunk
|
|
203
|
+
self.conversation.update_chat_history(prompt, full_response)
|
|
204
|
+
|
|
205
|
+
def for_non_stream():
|
|
206
|
+
full_response = "".join(self._websocket_interaction(sid, t, conversation_prompt, self.model))
|
|
207
|
+
self.last_response.update({"text": full_response})
|
|
208
|
+
self.conversation.update_chat_history(prompt, full_response)
|
|
209
|
+
return self.last_response
|
|
210
|
+
|
|
211
|
+
return for_stream() if stream else for_non_stream()
|
|
212
|
+
|
|
213
|
+
def chat(
|
|
214
|
+
self,
|
|
215
|
+
prompt: str,
|
|
216
|
+
stream: bool = False,
|
|
217
|
+
optimizer: str = None,
|
|
218
|
+
conversationally: bool = False,
|
|
219
|
+
) -> Union[str, Generator[str, None, None]]:
|
|
220
|
+
"""Generate response
|
|
221
|
+
Args:
|
|
222
|
+
prompt (str): Prompt to be send.
|
|
223
|
+
stream (bool, optional): Flag for streaming response. Defaults to False.
|
|
224
|
+
optimizer (str, optional): Prompt optimizer name. Defaults to None.
|
|
225
|
+
conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
|
|
226
|
+
Returns:
|
|
227
|
+
Union[str, Generator[str, None, None]]: Response generated
|
|
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, Any]) -> 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
|
+
|
|
259
|
+
if __name__ == "__main__":
|
|
260
|
+
from rich import print
|
|
261
|
+
|
|
262
|
+
ai = PerplexityLabs()
|
|
263
|
+
response = ai.chat("Tell me about Abhay Koul (HelpingAI)", stream=True)
|
|
264
|
+
for chunk in response:
|
|
265
|
+
print(chunk, end="", flush=True)
|