webscout 6.2b0__py3-none-any.whl → 6.4__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.

Files changed (97) hide show
  1. webscout/AIauto.py +191 -176
  2. webscout/AIbase.py +112 -239
  3. webscout/AIutel.py +488 -1130
  4. webscout/Agents/functioncall.py +248 -198
  5. webscout/Bing_search.py +250 -153
  6. webscout/DWEBS.py +454 -178
  7. webscout/Extra/__init__.py +2 -1
  8. webscout/Extra/autocoder/__init__.py +9 -0
  9. webscout/Extra/autocoder/autocoder_utiles.py +121 -0
  10. webscout/Extra/autocoder/rawdog.py +681 -0
  11. webscout/Extra/autollama.py +246 -195
  12. webscout/Extra/gguf.py +441 -226
  13. webscout/Extra/weather.py +172 -67
  14. webscout/LLM.py +442 -100
  15. webscout/Litlogger/__init__.py +681 -0
  16. webscout/Local/formats.py +4 -2
  17. webscout/Provider/Amigo.py +19 -10
  18. webscout/Provider/Andi.py +0 -33
  19. webscout/Provider/Blackboxai.py +4 -204
  20. webscout/Provider/DARKAI.py +1 -1
  21. webscout/Provider/EDITEE.py +1 -1
  22. webscout/Provider/Llama3.py +1 -1
  23. webscout/Provider/Marcus.py +137 -0
  24. webscout/Provider/NinjaChat.py +1 -1
  25. webscout/Provider/PI.py +221 -207
  26. webscout/Provider/Perplexity.py +598 -598
  27. webscout/Provider/RoboCoders.py +206 -0
  28. webscout/Provider/TTI/AiForce/__init__.py +22 -0
  29. webscout/Provider/TTI/AiForce/async_aiforce.py +257 -0
  30. webscout/Provider/TTI/AiForce/sync_aiforce.py +242 -0
  31. webscout/Provider/TTI/Nexra/__init__.py +22 -0
  32. webscout/Provider/TTI/Nexra/async_nexra.py +286 -0
  33. webscout/Provider/TTI/Nexra/sync_nexra.py +258 -0
  34. webscout/Provider/TTI/PollinationsAI/__init__.py +23 -0
  35. webscout/Provider/TTI/PollinationsAI/async_pollinations.py +330 -0
  36. webscout/Provider/TTI/PollinationsAI/sync_pollinations.py +285 -0
  37. webscout/Provider/TTI/__init__.py +3 -4
  38. webscout/Provider/TTI/artbit/__init__.py +22 -0
  39. webscout/Provider/TTI/artbit/async_artbit.py +184 -0
  40. webscout/Provider/TTI/artbit/sync_artbit.py +176 -0
  41. webscout/Provider/TTI/blackbox/__init__.py +4 -0
  42. webscout/Provider/TTI/blackbox/async_blackbox.py +212 -0
  43. webscout/Provider/TTI/{blackboximage.py → blackbox/sync_blackbox.py} +199 -153
  44. webscout/Provider/TTI/deepinfra/__init__.py +4 -0
  45. webscout/Provider/TTI/deepinfra/async_deepinfra.py +227 -0
  46. webscout/Provider/TTI/deepinfra/sync_deepinfra.py +199 -0
  47. webscout/Provider/TTI/huggingface/__init__.py +22 -0
  48. webscout/Provider/TTI/huggingface/async_huggingface.py +199 -0
  49. webscout/Provider/TTI/huggingface/sync_huggingface.py +195 -0
  50. webscout/Provider/TTI/imgninza/__init__.py +4 -0
  51. webscout/Provider/TTI/imgninza/async_ninza.py +214 -0
  52. webscout/Provider/TTI/{imgninza.py → imgninza/sync_ninza.py} +209 -136
  53. webscout/Provider/TTI/talkai/__init__.py +4 -0
  54. webscout/Provider/TTI/talkai/async_talkai.py +229 -0
  55. webscout/Provider/TTI/talkai/sync_talkai.py +207 -0
  56. webscout/Provider/__init__.py +146 -132
  57. webscout/Provider/askmyai.py +158 -0
  58. webscout/Provider/cerebras.py +227 -206
  59. webscout/Provider/geminiapi.py +208 -198
  60. webscout/Provider/llama3mitril.py +180 -0
  61. webscout/Provider/llmchat.py +203 -0
  62. webscout/Provider/mhystical.py +176 -0
  63. webscout/Provider/perplexitylabs.py +265 -0
  64. webscout/Provider/talkai.py +196 -0
  65. webscout/Provider/twitterclone.py +251 -244
  66. webscout/Provider/typegpt.py +359 -0
  67. webscout/__init__.py +28 -23
  68. webscout/__main__.py +5 -5
  69. webscout/cli.py +327 -347
  70. webscout/conversation.py +227 -0
  71. webscout/exceptions.py +161 -29
  72. webscout/litagent/__init__.py +172 -0
  73. webscout/litprinter/__init__.py +831 -0
  74. webscout/optimizers.py +270 -0
  75. webscout/prompt_manager.py +279 -0
  76. webscout/swiftcli/__init__.py +810 -0
  77. webscout/transcriber.py +479 -551
  78. webscout/update_checker.py +125 -0
  79. webscout/version.py +1 -1
  80. webscout-6.4.dist-info/LICENSE.md +211 -0
  81. {webscout-6.2b0.dist-info → webscout-6.4.dist-info}/METADATA +34 -55
  82. webscout-6.4.dist-info/RECORD +154 -0
  83. webscout/Provider/TTI/AIuncensored.py +0 -103
  84. webscout/Provider/TTI/Nexra.py +0 -120
  85. webscout/Provider/TTI/PollinationsAI.py +0 -138
  86. webscout/Provider/TTI/WebSimAI.py +0 -142
  87. webscout/Provider/TTI/aiforce.py +0 -160
  88. webscout/Provider/TTI/artbit.py +0 -141
  89. webscout/Provider/TTI/deepinfra.py +0 -148
  90. webscout/Provider/TTI/huggingface.py +0 -155
  91. webscout/models.py +0 -23
  92. webscout-6.2b0.dist-info/LICENSE.md +0 -50
  93. webscout-6.2b0.dist-info/RECORD +0 -118
  94. /webscout/{g4f.py → gpt4free.py} +0 -0
  95. {webscout-6.2b0.dist-info → webscout-6.4.dist-info}/WHEEL +0 -0
  96. {webscout-6.2b0.dist-info → webscout-6.4.dist-info}/entry_points.txt +0 -0
  97. {webscout-6.2b0.dist-info → webscout-6.4.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,203 @@
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
+ class LLMChat(Provider):
12
+ """
13
+ A class to interact with the LLMChat API.
14
+ """
15
+
16
+ AVAILABLE_MODELS = [
17
+ "@cf/meta/llama-3.1-70b-instruct",
18
+ "@cf/meta/llama-3.1-8b-instruct",
19
+ "@cf/meta/llama-3.2-3b-instruct",
20
+ "@cf/meta/llama-3.2-1b-instruct"
21
+ ]
22
+
23
+ def __init__(
24
+ self,
25
+ is_conversation: bool = True,
26
+ max_tokens: int = 2048,
27
+ timeout: int = 30,
28
+ intro: str = None,
29
+ filepath: str = None,
30
+ update_file: bool = True,
31
+ proxies: dict = {},
32
+ history_offset: int = 10250,
33
+ act: str = None,
34
+ model: str = "@cf/meta/llama-3.1-70b-instruct", # Default model
35
+ system_prompt: str = "You are a helpful assistant.",
36
+ ):
37
+ """
38
+ Initializes the LLMChat API with given parameters.
39
+ """
40
+ if model not in self.AVAILABLE_MODELS:
41
+ raise ValueError(f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}")
42
+
43
+ self.session = requests.Session()
44
+ self.is_conversation = is_conversation
45
+ self.max_tokens_to_sample = max_tokens
46
+ self.api_endpoint = "https://llmchat.in/inference/stream"
47
+ self.timeout = timeout
48
+ self.last_response = {}
49
+ self.model = model
50
+ self.system_prompt = system_prompt
51
+ self.headers = {
52
+ "Content-Type": "application/json",
53
+ "Accept": "*/*",
54
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0",
55
+ "Origin": "https://llmchat.in",
56
+ "Referer": "https://llmchat.in/"
57
+ }
58
+ self.__available_optimizers = (
59
+ method
60
+ for method in dir(Optimizers)
61
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
62
+ )
63
+ Conversation.intro = (
64
+ AwesomePrompts().get_act(
65
+ act, raise_not_found=True, default=None, case_insensitive=True
66
+ )
67
+ if act
68
+ else intro or Conversation.intro
69
+ )
70
+ self.conversation = Conversation(
71
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
72
+ )
73
+ self.conversation.history_offset = history_offset
74
+ self.session.proxies = proxies
75
+
76
+ def ask(
77
+ self,
78
+ prompt: str,
79
+ stream: bool = False,
80
+ raw: bool = False,
81
+ optimizer: str = None,
82
+ conversationally: bool = False,
83
+ ) -> Dict[str, Any]:
84
+ """Chat with LLMChat
85
+
86
+ Args:
87
+ prompt (str): Prompt to be sent.
88
+ stream (bool, optional): Flag for streaming response. Defaults to False.
89
+ raw (bool, optional): Stream back raw response as received. Defaults to False.
90
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
91
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
92
+ Returns:
93
+ dict: Response dictionary.
94
+ """
95
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
96
+ if optimizer:
97
+ if optimizer in self.__available_optimizers:
98
+ conversation_prompt = getattr(Optimizers, optimizer)(
99
+ conversation_prompt if conversationally else prompt
100
+ )
101
+ else:
102
+ raise exceptions.FailedToGenerateResponseError(
103
+ f"Optimizer is not one of {self.__available_optimizers}"
104
+ )
105
+
106
+ url = f"{self.api_endpoint}?model={self.model}"
107
+ payload = {
108
+ "messages": [
109
+ {"role": "system", "content": self.system_prompt},
110
+ {"role": "user", "content": conversation_prompt}
111
+ ],
112
+ "max_tokens": self.max_tokens_to_sample,
113
+ "stream": stream
114
+ }
115
+
116
+ def for_stream():
117
+ try:
118
+ with requests.post(url, json=payload, headers=self.headers, stream=True, timeout=self.timeout) as response:
119
+ response.raise_for_status()
120
+ full_response = ""
121
+ for line in response.iter_lines():
122
+ if line:
123
+ line = line.decode('utf-8')
124
+ if line.startswith('data: '):
125
+ try:
126
+ data = json.loads(line[6:])
127
+ if data.get('response'):
128
+ response_text = data['response']
129
+ full_response += response_text
130
+ yield response_text if raw else dict(text=response_text)
131
+ except json.JSONDecodeError:
132
+ if line.strip() != 'data: [DONE]':
133
+ print(f"Failed to parse line: {line}")
134
+ continue
135
+ self.last_response.update(dict(text=full_response))
136
+ self.conversation.update_chat_history(
137
+ prompt, self.get_message(self.last_response)
138
+ )
139
+ except requests.exceptions.RequestException as e:
140
+ raise exceptions.FailedToGenerateResponseError(f"Request failed: {e}")
141
+
142
+ def for_non_stream():
143
+ full_response = ""
144
+ for line in for_stream():
145
+ full_response += line['text'] if not raw else line
146
+ return dict(text=full_response)
147
+
148
+ return for_stream() if stream else for_non_stream()
149
+
150
+ def chat(
151
+ self,
152
+ prompt: str,
153
+ stream: bool = False,
154
+ optimizer: str = None,
155
+ conversationally: bool = False,
156
+ ) -> str | Generator[str, None, None]:
157
+ """Generate response `str`
158
+ Args:
159
+ prompt (str): Prompt to be send.
160
+ stream (bool, optional): Flag for streaming response. Defaults to False.
161
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
162
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
163
+ Returns:
164
+ str: Response generated
165
+ """
166
+
167
+ def for_stream():
168
+ for response in self.ask(
169
+ prompt, True, optimizer=optimizer, conversationally=conversationally
170
+ ):
171
+ yield self.get_message(response)
172
+
173
+ def for_non_stream():
174
+ return self.get_message(
175
+ self.ask(
176
+ prompt,
177
+ False,
178
+ optimizer=optimizer,
179
+ conversationally=conversationally,
180
+ )
181
+ )
182
+
183
+ return for_stream() if stream else for_non_stream()
184
+
185
+ def get_message(self, response: Dict[str, Any]) -> str:
186
+ """Retrieves message only from response.
187
+
188
+ Args:
189
+ response (dict): Response generated by `self.ask`
190
+
191
+ Returns:
192
+ str: Message extracted.
193
+ """
194
+ assert isinstance(response, dict), "Response should be of dict data-type only"
195
+ return response["text"]
196
+
197
+
198
+ if __name__ == "__main__":
199
+ from rich import print
200
+ ai = LLMChat(model='@cf/meta/llama-3.1-70b-instruct')
201
+ response = ai.chat("What's the meaning of life?", stream=True)
202
+ for chunk in response:
203
+ print(chunk, end="", flush=True)
@@ -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)