webscout 8.3.6__py3-none-any.whl → 8.3.7__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 (130) hide show
  1. webscout/AIutel.py +2 -0
  2. webscout/Provider/AISEARCH/__init__.py +18 -11
  3. webscout/Provider/AISEARCH/scira_search.py +3 -1
  4. webscout/Provider/Aitopia.py +2 -3
  5. webscout/Provider/Andi.py +3 -3
  6. webscout/Provider/ChatGPTClone.py +1 -1
  7. webscout/Provider/ChatSandbox.py +1 -0
  8. webscout/Provider/Cloudflare.py +1 -1
  9. webscout/Provider/Cohere.py +1 -0
  10. webscout/Provider/Deepinfra.py +7 -10
  11. webscout/Provider/ExaAI.py +1 -1
  12. webscout/Provider/ExaChat.py +1 -80
  13. webscout/Provider/Flowith.py +1 -1
  14. webscout/Provider/Gemini.py +7 -5
  15. webscout/Provider/GeminiProxy.py +1 -0
  16. webscout/Provider/GithubChat.py +3 -1
  17. webscout/Provider/Groq.py +1 -1
  18. webscout/Provider/HeckAI.py +8 -4
  19. webscout/Provider/Jadve.py +23 -38
  20. webscout/Provider/K2Think.py +308 -0
  21. webscout/Provider/Koboldai.py +8 -186
  22. webscout/Provider/LambdaChat.py +2 -4
  23. webscout/Provider/Nemotron.py +3 -4
  24. webscout/Provider/Netwrck.py +3 -2
  25. webscout/Provider/OLLAMA.py +1 -0
  26. webscout/Provider/OPENAI/Cloudflare.py +6 -7
  27. webscout/Provider/OPENAI/FalconH1.py +2 -7
  28. webscout/Provider/OPENAI/FreeGemini.py +6 -8
  29. webscout/Provider/OPENAI/{monochat.py → K2Think.py} +180 -77
  30. webscout/Provider/OPENAI/NEMOTRON.py +3 -6
  31. webscout/Provider/OPENAI/PI.py +5 -4
  32. webscout/Provider/OPENAI/Qwen3.py +2 -3
  33. webscout/Provider/OPENAI/TogetherAI.py +2 -2
  34. webscout/Provider/OPENAI/TwoAI.py +3 -4
  35. webscout/Provider/OPENAI/__init__.py +17 -58
  36. webscout/Provider/OPENAI/ai4chat.py +313 -303
  37. webscout/Provider/OPENAI/base.py +9 -29
  38. webscout/Provider/OPENAI/chatgpt.py +7 -2
  39. webscout/Provider/OPENAI/chatgptclone.py +4 -7
  40. webscout/Provider/OPENAI/chatsandbox.py +84 -59
  41. webscout/Provider/OPENAI/deepinfra.py +6 -6
  42. webscout/Provider/OPENAI/heckai.py +4 -1
  43. webscout/Provider/OPENAI/netwrck.py +1 -0
  44. webscout/Provider/OPENAI/scirachat.py +6 -0
  45. webscout/Provider/OPENAI/textpollinations.py +3 -11
  46. webscout/Provider/OPENAI/toolbaz.py +14 -11
  47. webscout/Provider/OpenGPT.py +1 -1
  48. webscout/Provider/Openai.py +150 -402
  49. webscout/Provider/PI.py +1 -0
  50. webscout/Provider/Perplexitylabs.py +1 -2
  51. webscout/Provider/QwenLM.py +107 -89
  52. webscout/Provider/STT/__init__.py +17 -2
  53. webscout/Provider/{Llama3.py → Sambanova.py} +9 -10
  54. webscout/Provider/StandardInput.py +1 -1
  55. webscout/Provider/TTI/__init__.py +18 -12
  56. webscout/Provider/TTS/__init__.py +18 -10
  57. webscout/Provider/TeachAnything.py +1 -0
  58. webscout/Provider/TextPollinationsAI.py +5 -12
  59. webscout/Provider/TogetherAI.py +86 -87
  60. webscout/Provider/TwoAI.py +53 -309
  61. webscout/Provider/TypliAI.py +2 -1
  62. webscout/Provider/{GizAI.py → UNFINISHED/GizAI.py} +1 -1
  63. webscout/Provider/Venice.py +2 -1
  64. webscout/Provider/VercelAI.py +1 -0
  65. webscout/Provider/WiseCat.py +2 -1
  66. webscout/Provider/WrDoChat.py +2 -1
  67. webscout/Provider/__init__.py +18 -86
  68. webscout/Provider/ai4chat.py +1 -1
  69. webscout/Provider/akashgpt.py +7 -10
  70. webscout/Provider/cerebras.py +115 -9
  71. webscout/Provider/chatglm.py +170 -83
  72. webscout/Provider/cleeai.py +1 -2
  73. webscout/Provider/deepseek_assistant.py +1 -1
  74. webscout/Provider/elmo.py +1 -1
  75. webscout/Provider/geminiapi.py +1 -1
  76. webscout/Provider/granite.py +1 -1
  77. webscout/Provider/hermes.py +1 -3
  78. webscout/Provider/julius.py +1 -0
  79. webscout/Provider/learnfastai.py +1 -1
  80. webscout/Provider/llama3mitril.py +1 -1
  81. webscout/Provider/llmchat.py +1 -1
  82. webscout/Provider/llmchatco.py +1 -1
  83. webscout/Provider/meta.py +3 -3
  84. webscout/Provider/oivscode.py +2 -2
  85. webscout/Provider/scira_chat.py +51 -124
  86. webscout/Provider/searchchat.py +1 -0
  87. webscout/Provider/sonus.py +1 -1
  88. webscout/Provider/toolbaz.py +15 -12
  89. webscout/Provider/turboseek.py +31 -22
  90. webscout/Provider/typefully.py +2 -1
  91. webscout/Provider/x0gpt.py +1 -0
  92. webscout/Provider/yep.py +2 -1
  93. webscout/tempid.py +6 -0
  94. webscout/version.py +1 -1
  95. {webscout-8.3.6.dist-info → webscout-8.3.7.dist-info}/METADATA +2 -1
  96. {webscout-8.3.6.dist-info → webscout-8.3.7.dist-info}/RECORD +103 -129
  97. webscout/Provider/AllenAI.py +0 -440
  98. webscout/Provider/Blackboxai.py +0 -793
  99. webscout/Provider/FreeGemini.py +0 -250
  100. webscout/Provider/GptOss.py +0 -207
  101. webscout/Provider/Hunyuan.py +0 -283
  102. webscout/Provider/Kimi.py +0 -445
  103. webscout/Provider/MCPCore.py +0 -322
  104. webscout/Provider/MiniMax.py +0 -207
  105. webscout/Provider/OPENAI/BLACKBOXAI.py +0 -1045
  106. webscout/Provider/OPENAI/MiniMax.py +0 -298
  107. webscout/Provider/OPENAI/autoproxy.py +0 -1067
  108. webscout/Provider/OPENAI/copilot.py +0 -321
  109. webscout/Provider/OPENAI/gptoss.py +0 -288
  110. webscout/Provider/OPENAI/kimi.py +0 -469
  111. webscout/Provider/OPENAI/mcpcore.py +0 -431
  112. webscout/Provider/OPENAI/multichat.py +0 -378
  113. webscout/Provider/Reka.py +0 -214
  114. webscout/Provider/UNFINISHED/fetch_together_models.py +0 -90
  115. webscout/Provider/asksteve.py +0 -220
  116. webscout/Provider/copilot.py +0 -441
  117. webscout/Provider/freeaichat.py +0 -294
  118. webscout/Provider/koala.py +0 -182
  119. webscout/Provider/lmarena.py +0 -198
  120. webscout/Provider/monochat.py +0 -275
  121. webscout/Provider/multichat.py +0 -375
  122. webscout/Provider/scnet.py +0 -244
  123. webscout/Provider/talkai.py +0 -194
  124. /webscout/Provider/{Marcus.py → UNFINISHED/Marcus.py} +0 -0
  125. /webscout/Provider/{Qodo.py → UNFINISHED/Qodo.py} +0 -0
  126. /webscout/Provider/{XenAI.py → UNFINISHED/XenAI.py} +0 -0
  127. {webscout-8.3.6.dist-info → webscout-8.3.7.dist-info}/WHEEL +0 -0
  128. {webscout-8.3.6.dist-info → webscout-8.3.7.dist-info}/entry_points.txt +0 -0
  129. {webscout-8.3.6.dist-info → webscout-8.3.7.dist-info}/licenses/LICENSE.md +0 -0
  130. {webscout-8.3.6.dist-info → webscout-8.3.7.dist-info}/top_level.txt +0 -0
@@ -1,15 +1,22 @@
1
1
  import json
2
- from ..AIutel import Optimizers
3
- from ..AIutel import Conversation
4
- from ..AIutel import AwesomePrompts, sanitize_stream
5
- from ..AIbase import Provider, AsyncProvider
2
+ import os
3
+ from typing import Any, Dict, Optional, Generator, Union, List
6
4
 
5
+ from curl_cffi.requests import Session
6
+ from curl_cffi import CurlError
7
+
8
+ from webscout.AIutel import Optimizers
9
+ from webscout.AIutel import Conversation
10
+ from webscout.AIutel import AwesomePrompts, sanitize_stream
11
+ from webscout.AIbase import Provider
7
12
  from webscout import exceptions
8
- from typing import Any, AsyncGenerator, Dict, List, Optional, Union
9
- import requests
10
- import httpx
11
- #----------------------------------------------------------OpenAI-----------------------------------
13
+ from webscout.litagent import LitAgent
14
+
12
15
  class OPENAI(Provider):
16
+ """
17
+ A class to interact with the OpenAI API with LitAgent user-agent.
18
+ """
19
+ required_auth = True
13
20
  def __init__(
14
21
  self,
15
22
  api_key: str,
@@ -28,49 +35,46 @@ class OPENAI(Provider):
28
35
  history_offset: int = 10250,
29
36
  act: str = None,
30
37
  base_url: str = "https://api.openai.com/v1/chat/completions",
38
+ system_prompt: str = "You are a helpful assistant.",
39
+ browser: str = "chrome"
31
40
  ):
32
- """Instantiates OPENAI
41
+ """Initializes the OpenAI API client."""
42
+ self.url = base_url
33
43
 
34
- Args:
35
- api_key (key): OpenAI's API key.
36
- is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
37
- max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
38
- temperature (float, optional): Charge of the generated text's randomness. Defaults to 1.
39
- presence_penalty (int, optional): Chances of topic being repeated. Defaults to 0.
40
- frequency_penalty (int, optional): Chances of word being repeated. Defaults to 0.
41
- top_p (float, optional): Sampling threshold during inference time. Defaults to 0.999.
42
- model (str, optional): LLM model name. Defaults to "gpt-3.5-turbo".
43
- timeout (int, optional): Http request timeout. Defaults to 30.
44
- intro (str, optional): Conversation introductory prompt. Defaults to None.
45
- filepath (str, optional): Path to file containing conversation history. Defaults to None.
46
- update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
47
- proxies (dict, optional): Http request proxies. Defaults to {}.
48
- history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
49
- act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
50
- """
44
+ # Initialize LitAgent
45
+ self.agent = LitAgent()
46
+ self.fingerprint = self.agent.generate_fingerprint(browser)
47
+ self.api_key = api_key
48
+ # Use the fingerprint for headers
49
+ self.headers = {
50
+ "Accept": self.fingerprint["accept"],
51
+ "Accept-Language": self.fingerprint["accept_language"],
52
+ "User-Agent": self.fingerprint.get("user_agent", ""),
53
+ }
54
+ if self.api_key:
55
+ self.headers["Authorization"] = f"Bearer {self.api_key}"
56
+
57
+ # Initialize curl_cffi Session
58
+ self.session = Session()
59
+ # Update curl_cffi session headers and proxies
60
+ self.session.headers.update(self.headers)
61
+ self.session.proxies = proxies # Assign proxies directly
62
+ self.system_prompt = system_prompt
51
63
  self.is_conversation = is_conversation
52
64
  self.max_tokens_to_sample = max_tokens
53
- self.api_key = api_key
65
+ self.timeout = timeout
66
+ self.last_response = {}
54
67
  self.model = model
55
68
  self.temperature = temperature
56
69
  self.presence_penalty = presence_penalty
57
70
  self.frequency_penalty = frequency_penalty
58
71
  self.top_p = top_p
59
- self.chat_endpoint = base_url
60
- self.stream_chunk_size = 64
61
- self.timeout = timeout
62
- self.last_response = {}
63
- self.headers = {
64
- "Content-Type": "application/json",
65
- "Authorization": f"Bearer {self.api_key}",
66
- }
67
- self.session = requests.session()
72
+
68
73
  self.__available_optimizers = (
69
74
  method
70
75
  for method in dir(Optimizers)
71
76
  if callable(getattr(Optimizers, method)) and not method.startswith("__")
72
77
  )
73
- self.session.headers.update(self.headers)
74
78
  Conversation.intro = (
75
79
  AwesomePrompts().get_act(
76
80
  act, raise_not_found=True, default=None, case_insensitive=True
@@ -78,11 +82,32 @@ class OPENAI(Provider):
78
82
  if act
79
83
  else intro or Conversation.intro
80
84
  )
85
+
81
86
  self.conversation = Conversation(
82
87
  is_conversation, self.max_tokens_to_sample, filepath, update_file
83
88
  )
84
89
  self.conversation.history_offset = history_offset
85
- self.session.proxies = proxies
90
+
91
+ def refresh_identity(self, browser: str = None):
92
+ """
93
+ Refreshes the browser identity fingerprint.
94
+
95
+ Args:
96
+ browser: Specific browser to use for the new fingerprint
97
+ """
98
+ browser = browser or self.fingerprint.get("browser_type", "chrome")
99
+ self.fingerprint = self.agent.generate_fingerprint(browser)
100
+
101
+ # Update headers with new fingerprint (only relevant ones)
102
+ self.headers.update({
103
+ "Accept": self.fingerprint["accept"],
104
+ "Accept-Language": self.fingerprint["accept_language"],
105
+ })
106
+
107
+ # Update session headers
108
+ self.session.headers.update(self.headers)
109
+
110
+ return self.fingerprint
86
111
 
87
112
  def ask(
88
113
  self,
@@ -91,41 +116,7 @@ class OPENAI(Provider):
91
116
  raw: bool = False,
92
117
  optimizer: str = None,
93
118
  conversationally: bool = False,
94
- ) -> dict:
95
- """Chat with AI
96
-
97
- Args:
98
- prompt (str): Prompt to be send.
99
- stream (bool, optional): Flag for streaming response. Defaults to False.
100
- raw (bool, optional): Stream back raw response as received. Defaults to False.
101
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
102
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
103
- Returns:
104
- dict : {}
105
- ```json
106
- {
107
- "id": "chatcmpl-TaREJpBZsRVQFRFic1wIA7Q7XfnaD",
108
- "object": "chat.completion",
109
- "created": 1704623244,
110
- "model": "gpt-3.5-turbo",
111
- "usage": {
112
- "prompt_tokens": 0,
113
- "completion_tokens": 0,
114
- "total_tokens": 0
115
- },
116
- "choices": [
117
- {
118
- "message": {
119
- "role": "assistant",
120
- "content": "Hello! How can I assist you today?"
121
- },
122
- "finish_reason": "stop",
123
- "index": 0
124
- }
125
- ]
126
- }
127
- ```
128
- """
119
+ ) -> Union[Dict[str, Any], Generator]:
129
120
  conversation_prompt = self.conversation.gen_complete_prompt(prompt)
130
121
  if optimizer:
131
122
  if optimizer in self.__available_optimizers:
@@ -133,364 +124,121 @@ class OPENAI(Provider):
133
124
  conversation_prompt if conversationally else prompt
134
125
  )
135
126
  else:
136
- raise exceptions.FailedToGenerateResponseError(
137
- f"Optimizer is not one of {self.__available_optimizers}"
138
- )
139
- self.session.headers.update(self.headers)
127
+ raise exceptions.FailedToGenerateResponseError(f"Optimizer is not one of {self.__available_optimizers}")
128
+
129
+ # Payload construction
140
130
  payload = {
141
- "frequency_penalty": self.frequency_penalty,
142
- "messages": [{"content": conversation_prompt, "role": "user"}],
143
131
  "model": self.model,
144
- "presence_penalty": self.presence_penalty,
132
+ "messages": [
133
+ {"role": "system", "content": self.system_prompt},
134
+ {"role": "user", "content": conversation_prompt},
135
+ ],
145
136
  "stream": stream,
146
137
  "temperature": self.temperature,
147
138
  "top_p": self.top_p,
139
+ "presence_penalty": self.presence_penalty,
140
+ "frequency_penalty": self.frequency_penalty,
148
141
  }
149
142
 
150
143
  def for_stream():
151
- response = self.session.post(
152
- self.chat_endpoint, json=payload, stream=True, timeout=self.timeout
153
- )
154
- if not response.ok:
155
- raise exceptions.FailedToGenerateResponseError(
156
- f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
144
+ streaming_text = ""
145
+ try:
146
+ # Use curl_cffi session post with impersonate
147
+ response = self.session.post(
148
+ self.url,
149
+ data=json.dumps(payload),
150
+ stream=True,
151
+ timeout=self.timeout,
152
+ impersonate="chrome110"
157
153
  )
158
-
159
- message_load = ""
160
- for value in response.iter_lines(
161
- decode_unicode=True,
162
- delimiter="" if raw else "data:",
163
- chunk_size=self.stream_chunk_size,
164
- ):
165
- try:
166
- resp = json.loads(value)
167
- incomplete_message = self.get_message(resp)
168
- if incomplete_message:
169
- message_load += incomplete_message
170
- resp["choices"][0]["delta"]["content"] = message_load
171
- self.last_response.update(resp)
172
- yield value if raw else resp
173
- elif raw:
174
- yield value
175
- except json.decoder.JSONDecodeError:
176
- pass
177
- self.conversation.update_chat_history(
178
- prompt, self.get_message(self.last_response)
179
- )
180
-
181
- def for_non_stream():
182
- response = self.session.post(
183
- self.chat_endpoint, json=payload, stream=False, timeout=self.timeout
184
- )
185
- if (
186
- not response.ok
187
- or not response.headers.get("Content-Type", "") == "application/json"
188
- ):
189
- raise exceptions.FailedToGenerateResponseError(
190
- f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
154
+ response.raise_for_status()
155
+
156
+ # Use sanitize_stream
157
+ processed_stream = sanitize_stream(
158
+ data=response.iter_content(chunk_size=None),
159
+ intro_value="data:",
160
+ to_json=True,
161
+ skip_markers=["[DONE]"],
162
+ content_extractor=lambda chunk: chunk.get("choices", [{}])[0].get("delta", {}).get("content") if isinstance(chunk, dict) else None,
163
+ yield_raw_on_error=False
191
164
  )
192
- resp = response.json()
193
- self.last_response.update(resp)
194
- self.conversation.update_chat_history(
195
- prompt, self.get_message(self.last_response)
196
- )
197
- return resp
198
-
199
- return for_stream() if stream else for_non_stream()
200
-
201
- def chat(
202
- self,
203
- prompt: str,
204
- stream: bool = False,
205
- optimizer: str = None,
206
- conversationally: bool = False,
207
- ) -> str:
208
- """Generate response `str`
209
- Args:
210
- prompt (str): Prompt to be send.
211
- stream (bool, optional): Flag for streaming response. Defaults to False.
212
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
213
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
214
- Returns:
215
- str: Response generated
216
- """
217
165
 
218
- def for_stream():
219
- for response in self.ask(
220
- prompt, True, optimizer=optimizer, conversationally=conversationally
221
- ):
222
- yield self.get_message(response)
166
+ for content_chunk in processed_stream:
167
+ if content_chunk and isinstance(content_chunk, str):
168
+ streaming_text += content_chunk
169
+ resp = dict(text=content_chunk)
170
+ yield resp if not raw else content_chunk
171
+
172
+ except CurlError as e:
173
+ raise exceptions.FailedToGenerateResponseError(f"Request failed (CurlError): {str(e)}") from e
174
+ except Exception as e:
175
+ raise exceptions.FailedToGenerateResponseError(f"Request failed ({type(e).__name__}): {str(e)}") from e
176
+ finally:
177
+ if streaming_text:
178
+ self.last_response = {"text": streaming_text}
179
+ self.conversation.update_chat_history(prompt, streaming_text)
223
180
 
224
181
  def for_non_stream():
225
- return self.get_message(
226
- self.ask(
227
- prompt,
228
- False,
229
- optimizer=optimizer,
230
- conversationally=conversationally,
182
+ try:
183
+ # Use curl_cffi session post with impersonate for non-streaming
184
+ response = self.session.post(
185
+ self.url,
186
+ data=json.dumps(payload),
187
+ timeout=self.timeout,
188
+ impersonate="chrome110"
231
189
  )
232
- )
233
-
234
- return for_stream() if stream else for_non_stream()
235
-
236
- def get_message(self, response: dict) -> str:
237
- """Retrieves message only from response
238
-
239
- Args:
240
- response (dict): Response generated by `self.ask`
241
-
242
- Returns:
243
- str: Message extracted
244
- """
245
- assert isinstance(response, dict), "Response should be of dict data-type only"
246
- try:
247
- if response["choices"][0].get("delta"):
248
- return response["choices"][0]["delta"]["content"]
249
- return response["choices"][0]["message"]["content"]
250
- except KeyError:
251
- return ""
252
- class AsyncOPENAI(AsyncProvider):
253
- def __init__(
254
- self,
255
- api_key: str,
256
- is_conversation: bool = True,
257
- max_tokens: int = 600,
258
- temperature: float = 1,
259
- presence_penalty: int = 0,
260
- frequency_penalty: int = 0,
261
- top_p: float = 1,
262
- model: str = "gpt-3.5-turbo",
263
- timeout: int = 30,
264
- intro: str = None,
265
- filepath: str = None,
266
- update_file: bool = True,
267
- proxies: dict = {},
268
- history_offset: int = 10250,
269
- act: str = None,
270
- ):
271
- """Instantiates OPENAI
272
-
273
- Args:
274
- api_key (key): OpenAI's API key.
275
- is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
276
- max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
277
- temperature (float, optional): Charge of the generated text's randomness. Defaults to 1.
278
- presence_penalty (int, optional): Chances of topic being repeated. Defaults to 0.
279
- frequency_penalty (int, optional): Chances of word being repeated. Defaults to 0.
280
- top_p (float, optional): Sampling threshold during inference time. Defaults to 0.999.
281
- model (str, optional): LLM model name. Defaults to "gpt-3.5-turbo".
282
- timeout (int, optional): Http request timeout. Defaults to 30.
283
- intro (str, optional): Conversation introductory prompt. Defaults to None.
284
- filepath (str, optional): Path to file containing conversation history. Defaults to None.
285
- update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
286
- proxies (dict, optional): Http request proxies. Defaults to {}.
287
- history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
288
- act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
289
- """
290
- self.is_conversation = is_conversation
291
- self.max_tokens_to_sample = max_tokens
292
- self.api_key = api_key
293
- self.model = model
294
- self.temperature = temperature
295
- self.presence_penalty = presence_penalty
296
- self.frequency_penalty = frequency_penalty
297
- self.top_p = top_p
298
- self.chat_endpoint = "https://api.openai.com/v1/chat/completions"
299
- self.stream_chunk_size = 64
300
- self.timeout = timeout
301
- self.last_response = {}
302
- self.headers = {
303
- "Content-Type": "application/json",
304
- "Authorization": f"Bearer {self.api_key}",
305
- }
306
-
307
- self.__available_optimizers = (
308
- method
309
- for method in dir(Optimizers)
310
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
311
- )
312
- Conversation.intro = (
313
- AwesomePrompts().get_act(
314
- act, raise_not_found=True, default=None, case_insensitive=True
315
- )
316
- if act
317
- else intro or Conversation.intro
318
- )
319
- self.conversation = Conversation(
320
- is_conversation, self.max_tokens_to_sample, filepath, update_file
321
- )
322
- self.conversation.history_offset = history_offset
323
- self.session = httpx.AsyncClient(
324
- headers=self.headers,
325
- proxies=proxies,
326
- )
190
+ response.raise_for_status()
327
191
 
328
- async def ask(
329
- self,
330
- prompt: str,
331
- stream: bool = False,
332
- raw: bool = False,
333
- optimizer: str = None,
334
- conversationally: bool = False,
335
- tools: Optional[List[Dict[str, Any]]] = None,
336
- ) -> Union[dict, AsyncGenerator]:
337
- """Chat with AI asynchronously.
192
+ response_text = response.text
338
193
 
339
- Args:
340
- prompt (str): Prompt to be send.
341
- stream (bool, optional): Flag for streaming response. Defaults to False.
342
- raw (bool, optional): Stream back raw response as received. Defaults to False.
343
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
344
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
345
- tools (Optional[List[Dict[str, Any]]], optional): List of tools to be used. Defaults to None.
346
- Returns:
347
- dict|AsyncGenerator : ai content.
348
- ```json
349
- {
350
- "id": "chatcmpl-TaREJpBZsRVQFRFic1wIA7Q7XfnaD",
351
- "object": "chat.completion",
352
- "created": 1704623244,
353
- "model": "gpt-3.5-turbo",
354
- "usage": {
355
- "prompt_tokens": 0,
356
- "completion_tokens": 0,
357
- "total_tokens": 0
358
- },
359
- "choices": [
360
- {
361
- "message": {
362
- "role": "assistant",
363
- "content": "Hello! How can I assist you today?"
364
- },
365
- "finish_reason": "stop",
366
- "index": 0
367
- }
368
- ]
369
- }
370
- ```
371
- """
372
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
373
- if optimizer:
374
- if optimizer in self.__available_optimizers:
375
- conversation_prompt = getattr(Optimizers, optimizer)(
376
- conversation_prompt if conversationally else prompt
377
- )
378
- else:
379
- raise Exception(
380
- f"Optimizer is not one of {self.__available_optimizers}"
194
+ # Use sanitize_stream to parse the non-streaming JSON response
195
+ processed_stream = sanitize_stream(
196
+ data=response_text,
197
+ to_json=True,
198
+ intro_value=None,
199
+ content_extractor=lambda chunk: chunk.get("choices", [{}])[0].get("message", {}).get("content") if isinstance(chunk, dict) else None,
200
+ yield_raw_on_error=False
381
201
  )
382
- payload = {
383
- "frequency_penalty": self.frequency_penalty,
384
- "messages": [{"content": conversation_prompt, "role": "user"}],
385
- "model": self.model,
386
- "presence_penalty": self.presence_penalty,
387
- "stream": stream,
388
- "temperature": self.temperature,
389
- "top_p": self.top_p,
390
- }
391
-
392
- async def for_stream():
393
- async with self.session.stream(
394
- "POST", self.chat_endpoint, json=payload, timeout=self.timeout
395
- ) as response:
396
- if not response.is_success:
397
- raise Exception(
398
- f"Failed to generate response - ({response.status_code}, {response.reason_phrase})"
399
- )
400
-
401
- message_load = ""
402
- async for value in response.aiter_lines():
403
- try:
202
+ # Extract the single result
203
+ content = next(processed_stream, None)
204
+ content = content if isinstance(content, str) else ""
404
205
 
405
- resp = sanitize_stream(value)
406
- incomplete_message = await self.get_message(resp)
407
- if incomplete_message:
408
- message_load += incomplete_message
409
- resp["choices"][0]["delta"]["content"] = message_load
410
- self.last_response.update(resp)
411
- yield value if raw else resp
412
- elif raw:
413
- yield value
414
- except json.decoder.JSONDecodeError:
415
- pass
416
- self.conversation.update_chat_history(
417
- prompt, await self.get_message(self.last_response)
418
- )
206
+ self.last_response = {"text": content}
207
+ self.conversation.update_chat_history(prompt, content)
208
+ return self.last_response if not raw else content
419
209
 
420
- async def for_non_stream():
421
- response = httpx.post(
422
- self.chat_endpoint,
423
- json=payload,
424
- timeout=self.timeout,
425
- headers=self.headers,
426
- )
427
- if (
428
- not response.is_success
429
- or not response.headers.get("Content-Type", "") == "application/json"
430
- ):
431
- raise Exception(
432
- f"Failed to generate response - ({response.status_code}, {response.reason_phrase})"
433
- )
434
- resp = response.json()
435
- self.last_response.update(resp)
436
- self.conversation.update_chat_history(
437
- prompt, await self.get_message(self.last_response)
438
- )
439
- return resp
210
+ except CurlError as e:
211
+ raise exceptions.FailedToGenerateResponseError(f"Request failed (CurlError): {e}") from e
212
+ except Exception as e:
213
+ err_text = getattr(e, 'response', None) and getattr(e.response, 'text', '')
214
+ raise exceptions.FailedToGenerateResponseError(f"Request failed ({type(e).__name__}): {e} - {err_text}") from e
440
215
 
441
- return for_stream() if stream else await for_non_stream()
216
+ return for_stream() if stream else for_non_stream()
442
217
 
443
- async def chat(
218
+ def chat(
444
219
  self,
445
220
  prompt: str,
446
221
  stream: bool = False,
447
222
  optimizer: str = None,
448
223
  conversationally: bool = False,
449
- tools: Optional[List[Dict[str, Any]]] = None,
450
- ) -> Union[str, AsyncGenerator]:
451
- """Generate response `str` asynchronously.
452
- Args:
453
- prompt (str): Prompt to be send.
454
- stream (bool, optional): Flag for streaming response. Defaults to False.
455
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
456
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
457
- tools (Optional[List[Dict[str, Any]]], optional): List of tools to be used. Defaults to None.
458
- Returns:
459
- str|AsyncGenerator: Response generated
460
- """
461
-
462
- async def for_stream():
463
- async_ask = await self.ask(
464
- prompt, True, optimizer=optimizer, conversationally=conversationally
224
+ ) -> Union[str, Generator[str, None, None]]:
225
+ def for_stream_chat():
226
+ gen = self.ask(
227
+ prompt, stream=True, raw=False,
228
+ optimizer=optimizer, conversationally=conversationally
465
229
  )
466
- async for response in async_ask:
467
- yield await self.get_message(response)
230
+ for response_dict in gen:
231
+ yield self.get_message(response_dict)
468
232
 
469
- async def for_non_stream():
470
- return await self.get_message(
471
- await self.ask(
472
- prompt,
473
- False,
474
- optimizer=optimizer,
475
- conversationally=conversationally,
476
- )
233
+ def for_non_stream_chat():
234
+ response_data = self.ask(
235
+ prompt, stream=False, raw=False,
236
+ optimizer=optimizer, conversationally=conversationally
477
237
  )
238
+ return self.get_message(response_data)
478
239
 
479
- return for_stream() if stream else await for_non_stream()
240
+ return for_stream_chat() if stream else for_non_stream_chat()
480
241
 
481
- async def get_message(self, response: dict) -> str:
482
- """Retrieves message only from response asynchronously.
483
-
484
- Args:
485
- response (dict): Response generated by `self.ask`
486
-
487
- Returns:
488
- str: Message extracted
489
- """
242
+ def get_message(self, response: dict) -> str:
490
243
  assert isinstance(response, dict), "Response should be of dict data-type only"
491
- try:
492
- if response["choices"][0].get("delta"):
493
- return response["choices"][0]["delta"]["content"]
494
- return response["choices"][0]["message"]["content"]
495
- except KeyError:
496
- return ""
244
+ return response["text"]
webscout/Provider/PI.py CHANGED
@@ -21,6 +21,7 @@ class PiAI(Provider):
21
21
  AVAILABLE_VOICES (Dict[str, int]): Available voice options for audio responses
22
22
  AVAILABLE_MODELS (List[str]): Available model options for the API
23
23
  """
24
+ required_auth = False
24
25
  AVAILABLE_MODELS = ["inflection_3_pi"]
25
26
  AVAILABLE_VOICES: Dict[str, int] = {
26
27
  "voice1": 1,
@@ -17,9 +17,8 @@ class PerplexityLabs(Provider):
17
17
  """
18
18
  A client for interacting with the Perplexity AI Labs API.
19
19
  """
20
-
20
+ required_auth = False
21
21
  AVAILABLE_MODELS = [
22
- "r1-1776",
23
22
  "sonar-pro",
24
23
  "sonar",
25
24
  "sonar-reasoning-pro",