webscout 8.2.3__py3-none-any.whl → 8.2.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.

Files changed (122) hide show
  1. webscout/AIutel.py +226 -14
  2. webscout/Bard.py +579 -206
  3. webscout/DWEBS.py +78 -35
  4. webscout/Extra/gguf.py +2 -0
  5. webscout/Extra/tempmail/base.py +1 -1
  6. webscout/Provider/AISEARCH/hika_search.py +4 -0
  7. webscout/Provider/AISEARCH/scira_search.py +2 -5
  8. webscout/Provider/Aitopia.py +75 -51
  9. webscout/Provider/AllenAI.py +181 -147
  10. webscout/Provider/ChatGPTClone.py +97 -86
  11. webscout/Provider/ChatSandbox.py +342 -0
  12. webscout/Provider/Cloudflare.py +79 -32
  13. webscout/Provider/Deepinfra.py +135 -94
  14. webscout/Provider/ElectronHub.py +103 -39
  15. webscout/Provider/ExaChat.py +36 -20
  16. webscout/Provider/GPTWeb.py +103 -47
  17. webscout/Provider/GithubChat.py +52 -49
  18. webscout/Provider/GizAI.py +283 -0
  19. webscout/Provider/Glider.py +39 -28
  20. webscout/Provider/Groq.py +222 -91
  21. webscout/Provider/HeckAI.py +93 -69
  22. webscout/Provider/HuggingFaceChat.py +113 -106
  23. webscout/Provider/Hunyuan.py +94 -83
  24. webscout/Provider/Jadve.py +104 -79
  25. webscout/Provider/LambdaChat.py +142 -123
  26. webscout/Provider/Llama3.py +94 -39
  27. webscout/Provider/MCPCore.py +315 -0
  28. webscout/Provider/Marcus.py +95 -37
  29. webscout/Provider/Netwrck.py +94 -52
  30. webscout/Provider/OPENAI/__init__.py +4 -1
  31. webscout/Provider/OPENAI/ai4chat.py +286 -0
  32. webscout/Provider/OPENAI/chatgptclone.py +35 -14
  33. webscout/Provider/OPENAI/deepinfra.py +37 -0
  34. webscout/Provider/OPENAI/exachat.py +4 -0
  35. webscout/Provider/OPENAI/groq.py +354 -0
  36. webscout/Provider/OPENAI/heckai.py +6 -2
  37. webscout/Provider/OPENAI/mcpcore.py +376 -0
  38. webscout/Provider/OPENAI/multichat.py +368 -0
  39. webscout/Provider/OPENAI/netwrck.py +3 -1
  40. webscout/Provider/OPENAI/scirachat.py +2 -4
  41. webscout/Provider/OPENAI/textpollinations.py +20 -22
  42. webscout/Provider/OPENAI/toolbaz.py +1 -0
  43. webscout/Provider/OpenGPT.py +48 -38
  44. webscout/Provider/PI.py +178 -93
  45. webscout/Provider/PizzaGPT.py +66 -36
  46. webscout/Provider/StandardInput.py +42 -30
  47. webscout/Provider/TeachAnything.py +95 -52
  48. webscout/Provider/TextPollinationsAI.py +138 -78
  49. webscout/Provider/TwoAI.py +162 -81
  50. webscout/Provider/TypliAI.py +305 -0
  51. webscout/Provider/Venice.py +97 -58
  52. webscout/Provider/VercelAI.py +33 -14
  53. webscout/Provider/WiseCat.py +65 -28
  54. webscout/Provider/Writecream.py +37 -11
  55. webscout/Provider/WritingMate.py +135 -63
  56. webscout/Provider/__init__.py +9 -27
  57. webscout/Provider/ai4chat.py +6 -7
  58. webscout/Provider/asksteve.py +53 -44
  59. webscout/Provider/cerebras.py +77 -31
  60. webscout/Provider/chatglm.py +47 -37
  61. webscout/Provider/copilot.py +0 -3
  62. webscout/Provider/elmo.py +109 -60
  63. webscout/Provider/granite.py +102 -54
  64. webscout/Provider/hermes.py +95 -48
  65. webscout/Provider/koala.py +1 -1
  66. webscout/Provider/learnfastai.py +113 -54
  67. webscout/Provider/llama3mitril.py +86 -51
  68. webscout/Provider/llmchat.py +88 -46
  69. webscout/Provider/llmchatco.py +110 -115
  70. webscout/Provider/meta.py +41 -37
  71. webscout/Provider/multichat.py +67 -28
  72. webscout/Provider/scira_chat.py +49 -30
  73. webscout/Provider/scnet.py +106 -53
  74. webscout/Provider/searchchat.py +87 -88
  75. webscout/Provider/sonus.py +113 -63
  76. webscout/Provider/toolbaz.py +115 -82
  77. webscout/Provider/turboseek.py +90 -43
  78. webscout/Provider/tutorai.py +82 -64
  79. webscout/Provider/typefully.py +85 -35
  80. webscout/Provider/typegpt.py +118 -61
  81. webscout/Provider/uncovr.py +132 -76
  82. webscout/Provider/x0gpt.py +69 -26
  83. webscout/Provider/yep.py +79 -66
  84. webscout/cli.py +256 -0
  85. webscout/conversation.py +34 -22
  86. webscout/exceptions.py +23 -0
  87. webscout/prompt_manager.py +56 -42
  88. webscout/version.py +1 -1
  89. webscout/webscout_search.py +65 -47
  90. webscout/webscout_search_async.py +81 -126
  91. webscout/yep_search.py +93 -43
  92. {webscout-8.2.3.dist-info → webscout-8.2.5.dist-info}/METADATA +183 -50
  93. {webscout-8.2.3.dist-info → webscout-8.2.5.dist-info}/RECORD +97 -113
  94. {webscout-8.2.3.dist-info → webscout-8.2.5.dist-info}/WHEEL +1 -1
  95. webscout-8.2.5.dist-info/entry_points.txt +3 -0
  96. {webscout-8.2.3.dist-info → webscout-8.2.5.dist-info}/top_level.txt +0 -1
  97. inferno/__init__.py +0 -6
  98. inferno/__main__.py +0 -9
  99. inferno/cli.py +0 -6
  100. webscout/Local/__init__.py +0 -12
  101. webscout/Local/__main__.py +0 -9
  102. webscout/Local/api.py +0 -576
  103. webscout/Local/cli.py +0 -516
  104. webscout/Local/config.py +0 -75
  105. webscout/Local/llm.py +0 -287
  106. webscout/Local/model_manager.py +0 -253
  107. webscout/Local/server.py +0 -721
  108. webscout/Local/utils.py +0 -93
  109. webscout/Provider/C4ai.py +0 -432
  110. webscout/Provider/ChatGPTES.py +0 -237
  111. webscout/Provider/Chatify.py +0 -175
  112. webscout/Provider/DeepSeek.py +0 -196
  113. webscout/Provider/Llama.py +0 -200
  114. webscout/Provider/Phind.py +0 -535
  115. webscout/Provider/WebSim.py +0 -228
  116. webscout/Provider/askmyai.py +0 -158
  117. webscout/Provider/gaurish.py +0 -244
  118. webscout/Provider/labyrinth.py +0 -340
  119. webscout/Provider/lepton.py +0 -194
  120. webscout/Provider/llamatutor.py +0 -192
  121. webscout-8.2.3.dist-info/entry_points.txt +0 -5
  122. {webscout-8.2.3.dist-info → webscout-8.2.5.dist-info/licenses}/LICENSE.md +0 -0
@@ -1,11 +1,13 @@
1
- import requests
1
+ from curl_cffi import CurlError
2
+ from curl_cffi.requests import Session # Import Session
2
3
  import json
3
- from typing import Generator, Dict, Any, List, Union
4
+ from typing import Generator, Dict, Any, List, Optional, Union
4
5
  from uuid import uuid4
6
+ import random
5
7
 
6
8
  from webscout.AIutel import Optimizers
7
9
  from webscout.AIutel import Conversation
8
- from webscout.AIutel import AwesomePrompts, sanitize_stream
10
+ from webscout.AIutel import AwesomePrompts, sanitize_stream # Import sanitize_stream
9
11
  from webscout.AIbase import Provider
10
12
  from webscout import exceptions
11
13
  from webscout.litagent import LitAgent
@@ -17,6 +19,7 @@ class Venice(Provider):
17
19
 
18
20
  AVAILABLE_MODELS = [
19
21
  "mistral-31-24b",
22
+ "dolphin-3.0-mistral-24b",
20
23
  "llama-3.2-3b-akash",
21
24
  "qwen2dot5-coder-32b",
22
25
  "deepseek-coder-v2-lite",
@@ -28,23 +31,26 @@ class Venice(Provider):
28
31
  is_conversation: bool = True,
29
32
  max_tokens: int = 2000,
30
33
  timeout: int = 30,
31
- temperature: float = 0.8,
32
- top_p: float = 0.9,
34
+ temperature: float = 0.8, # Keep temperature, user might want to adjust
35
+ top_p: float = 0.9, # Keep top_p
33
36
  intro: str = None,
34
37
  filepath: str = None,
35
38
  update_file: bool = True,
36
39
  proxies: dict = {},
37
40
  history_offset: int = 10250,
38
41
  act: str = None,
39
- model: str = "llama-3.3-70b",
40
- system_prompt: str = "You are a helpful AI assistant."
42
+ model: str = "mistral-31-24b",
43
+ # System prompt is empty in the example, but keep it configurable
44
+ system_prompt: str = ""
41
45
  ):
42
46
  """Initialize Venice AI client"""
43
47
  if model not in self.AVAILABLE_MODELS:
44
48
  raise ValueError(f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}")
45
49
 
46
- self.api_endpoint = "https://venice.ai/api/inference/chat"
47
- self.session = requests.Session()
50
+ # Update API endpoint
51
+ self.api_endpoint = "https://outerface.venice.ai/api/inference/chat"
52
+ # Initialize curl_cffi Session
53
+ self.session = Session()
48
54
  self.is_conversation = is_conversation
49
55
  self.max_tokens_to_sample = max_tokens
50
56
  self.temperature = temperature
@@ -54,22 +60,29 @@ class Venice(Provider):
54
60
  self.system_prompt = system_prompt
55
61
  self.last_response = {}
56
62
 
57
- # Headers for the request
63
+ # Update Headers based on successful request
58
64
  self.headers = {
59
- "User-Agent": LitAgent().random(),
65
+ "User-Agent": LitAgent().random(), # Keep using LitAgent
60
66
  "accept": "*/*",
61
- "accept-language": "en-US,en;q=0.9",
67
+ "accept-language": "en-US,en;q=0.9", # Keep existing
62
68
  "content-type": "application/json",
63
69
  "origin": "https://venice.ai",
64
- "referer": "https://venice.ai/chat/",
65
- "sec-ch-ua": '"Google Chrome";v="133", "Chromium";v="133", "Not?A_Brand";v="24"',
70
+ "referer": "https://venice.ai/", # Update referer
71
+ # Update sec-ch-ua to match example
72
+ "sec-ch-ua": '"Microsoft Edge";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
66
73
  "sec-ch-ua-mobile": "?0",
67
74
  "sec-ch-ua-platform": '"Windows"',
68
75
  "sec-fetch-dest": "empty",
69
76
  "sec-fetch-mode": "cors",
70
- "sec-fetch-site": "same-origin"
77
+ # Update sec-fetch-site to match example
78
+ "sec-fetch-site": "same-site",
79
+ # Add missing headers from example
80
+ "priority": "u=1, i",
81
+ "sec-gpc": "1",
82
+ "x-venice-version": "interface@20250424.065523+50bac27" # Add version header
71
83
  }
72
-
84
+
85
+ # Update curl_cffi session headers and proxies
73
86
  self.session.headers.update(self.headers)
74
87
  self.session.proxies.update(proxies)
75
88
 
@@ -91,6 +104,14 @@ class Venice(Provider):
91
104
  )
92
105
  self.conversation.history_offset = history_offset
93
106
 
107
+ @staticmethod
108
+ def _venice_extractor(chunk: Union[str, Dict[str, Any]]) -> Optional[str]:
109
+ """Extracts content from Venice stream JSON objects."""
110
+ if isinstance(chunk, dict) and chunk.get("kind") == "content":
111
+ return chunk.get("content")
112
+ return None
113
+
114
+
94
115
  def ask(
95
116
  self,
96
117
  prompt: str,
@@ -108,64 +129,81 @@ class Venice(Provider):
108
129
  else:
109
130
  raise Exception(f"Optimizer is not one of {self.__available_optimizers}")
110
131
 
111
- # Payload construction
132
+ # Update Payload construction based on successful request
112
133
  payload = {
113
- "requestId": str(uuid4())[:7],
134
+ "requestId": str(uuid4())[:7], # Keep generating request ID
114
135
  "modelId": self.model,
115
136
  "prompt": [{"content": conversation_prompt, "role": "user"}],
116
- "systemPrompt": self.system_prompt,
137
+ "systemPrompt": self.system_prompt, # Use configured system prompt
117
138
  "conversationType": "text",
118
- "temperature": self.temperature,
119
- "webEnabled": True,
120
- "topP": self.top_p,
121
- "includeVeniceSystemPrompt": False,
122
- "isCharacter": False,
123
- "clientProcessingTime": 2000
139
+ "temperature": self.temperature, # Use configured temperature
140
+ "webEnabled": True, # Keep webEnabled
141
+ "topP": self.top_p, # Use configured topP
142
+ "includeVeniceSystemPrompt": True, # Set to True as per example
143
+ "isCharacter": False, # Keep as False
144
+ # Add missing fields from example payload
145
+ "userId": "user_anon_" + str(random.randint(1000000000, 9999999999)), # Generate anon user ID
146
+ "isDefault": True,
147
+ "textToSpeech": {"voiceId": "af_sky", "speed": 1},
148
+ "clientProcessingTime": random.randint(10, 50) # Randomize slightly
124
149
  }
125
150
 
126
151
  def for_stream():
127
152
  try:
128
- with self.session.post(
153
+ # Use curl_cffi session post
154
+ response = self.session.post(
129
155
  self.api_endpoint,
130
156
  json=payload,
131
157
  stream=True,
132
- timeout=self.timeout
133
- ) as response:
134
- if response.status_code != 200:
135
- raise exceptions.FailedToGenerateResponseError(
136
- f"Request failed with status code {response.status_code}"
137
- )
158
+ timeout=self.timeout,
159
+ impersonate="edge101" # Match impersonation closer to headers
160
+ )
161
+ # Check response status after the call
162
+ if response.status_code != 200:
163
+ # Include response text in error
164
+ raise exceptions.FailedToGenerateResponseError(
165
+ f"Request failed with status code {response.status_code} - {response.text}"
166
+ )
138
167
 
139
- streaming_text = ""
140
- for line in response.iter_lines():
141
- if not line:
142
- continue
143
-
144
- try:
145
- # Decode bytes to string
146
- line_data = line.decode('utf-8').strip()
147
- if '"kind":"content"' in line_data:
148
- data = json.loads(line_data)
149
- if 'content' in data:
150
- content = data['content']
151
- streaming_text += content
152
- resp = dict(text=content)
153
- yield resp if raw else resp
154
- except json.JSONDecodeError:
155
- continue
156
- except UnicodeDecodeError:
157
- continue
158
-
159
- self.conversation.update_chat_history(prompt, streaming_text)
168
+ streaming_text = ""
169
+ # Use sanitize_stream with the custom extractor
170
+ processed_stream = sanitize_stream(
171
+ data=response.iter_content(chunk_size=None), # Pass byte iterator
172
+ intro_value=None, # No simple prefix
173
+ to_json=True, # Each line is JSON
174
+ content_extractor=self._venice_extractor, # Use the specific extractor
175
+ yield_raw_on_error=False # Skip non-JSON lines or lines where extractor fails
176
+ )
177
+
178
+ for content_chunk in processed_stream:
179
+ # content_chunk is the string extracted by _venice_extractor
180
+ if content_chunk and isinstance(content_chunk, str):
181
+ streaming_text += content_chunk
182
+ yield content_chunk if raw else dict(text=content_chunk)
183
+
184
+ # Update history and last response after stream finishes
185
+ self.conversation.update_chat_history(prompt, streaming_text)
186
+ self.last_response = {"text": streaming_text}
160
187
 
161
- except requests.RequestException as e:
162
- raise exceptions.FailedToGenerateResponseError(f"Request failed: {str(e)}")
188
+ except CurlError as e:
189
+ raise exceptions.FailedToGenerateResponseError(f"Request failed (CurlError): {e}")
190
+ # Catch requests.exceptions.RequestException if needed, but CurlError is primary for curl_cffi
191
+ except Exception as e:
192
+ raise exceptions.FailedToGenerateResponseError(f"An unexpected error occurred ({type(e).__name__}): {e}")
163
193
 
164
194
  def for_non_stream():
165
195
  full_text = ""
166
- for chunk in for_stream():
167
- full_text += chunk["text"]
168
- return {"text": full_text}
196
+ # Iterate through the generator provided by for_stream
197
+ for chunk_data in for_stream():
198
+ # Check if chunk_data is a dict (not raw) and has 'text'
199
+ if isinstance(chunk_data, dict) and "text" in chunk_data:
200
+ full_text += chunk_data["text"]
201
+ # If raw=True, chunk_data is the string content itself
202
+ elif isinstance(chunk_data, str):
203
+ full_text += chunk_data
204
+ # Update last_response after aggregation
205
+ self.last_response = {"text": full_text}
206
+ return self.last_response
169
207
 
170
208
  return for_stream() if stream else for_non_stream()
171
209
 
@@ -190,6 +228,7 @@ class Venice(Provider):
190
228
  return response["text"]
191
229
 
192
230
  if __name__ == "__main__":
231
+ # Ensure curl_cffi is installed
193
232
  print("-" * 80)
194
233
  print(f"{'Model':<50} {'Status':<10} {'Response'}")
195
234
  print("-" * 80)
@@ -1,13 +1,13 @@
1
1
  import re
2
2
  import time
3
- import requests
3
+ from curl_cffi import requests
4
4
  import json
5
5
  from typing import Union, Any, Dict, Generator, Optional
6
6
  import uuid
7
7
 
8
8
  from webscout.AIutel import Optimizers
9
9
  from webscout.AIutel import Conversation
10
- from webscout.AIutel import AwesomePrompts
10
+ from webscout.AIutel import AwesomePrompts, sanitize_stream # Import sanitize_stream
11
11
  from webscout.AIbase import Provider
12
12
  from webscout import exceptions
13
13
  from webscout.litagent import LitAgent
@@ -111,6 +111,17 @@ class VercelAI(Provider):
111
111
  )
112
112
  self.conversation.history_offset = history_offset
113
113
 
114
+ @staticmethod
115
+ def _vercelai_extractor(chunk: Union[str, Dict[str, Any]]) -> Optional[str]:
116
+ """Extracts content from the VercelAI stream format '0:"..."'."""
117
+ if isinstance(chunk, str):
118
+ match = re.search(r'0:"(.*?)"(?=,|$)', chunk) # Look for 0:"...", possibly followed by comma or end of string
119
+ if match:
120
+ # Decode potential unicode escapes like \u00e9 and handle escaped quotes/backslashes
121
+ content = match.group(1).encode().decode('unicode_escape')
122
+ return content.replace('\\\\', '\\').replace('\\"', '"')
123
+ return None
124
+
114
125
  def ask(
115
126
  self,
116
127
  prompt: str,
@@ -153,15 +164,21 @@ class VercelAI(Provider):
153
164
  error_msg = f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
154
165
  raise exceptions.FailedToGenerateResponseError(error_msg)
155
166
 
156
- streaming_response = ""
157
- for line in response.iter_lines(decode_unicode=True):
158
- if line:
159
- match = re.search(r'0:"(.*?)"', line)
160
- if match:
161
- content = match.group(1)
162
- streaming_response += content
163
- yield content if raw else dict(text=content)
164
- self.last_response.update(dict(text=streaming_response))
167
+ streaming_text = ""
168
+ # Use sanitize_stream with the custom extractor
169
+ processed_stream = sanitize_stream(
170
+ data=response.iter_content(chunk_size=None), # Pass byte iterator
171
+ intro_value=None, # No simple prefix
172
+ to_json=False, # Content is not JSON
173
+ content_extractor=self._vercelai_extractor # Use the specific extractor
174
+ )
175
+
176
+ for content_chunk in processed_stream:
177
+ if content_chunk and isinstance(content_chunk, str):
178
+ streaming_text += content_chunk
179
+ yield content_chunk if raw else dict(text=content_chunk)
180
+
181
+ self.last_response.update(dict(text=streaming_text))
165
182
  self.conversation.update_chat_history(
166
183
  prompt, self.get_message(self.last_response)
167
184
  )
@@ -201,8 +218,10 @@ class VercelAI(Provider):
201
218
 
202
219
  def get_message(self, response: dict) -> str:
203
220
  """Retrieves message only from response"""
204
- assert isinstance(response, dict), "Response should be of dict data-type only"
205
- return response["text"].replace('\\n', '\n').replace('\\n\\n', '\n\n')
221
+ assert isinstance(response, dict), "Response should be of dict data-type only"
222
+ # Formatting is handled by the extractor now
223
+ text = response.get("text", "")
224
+ return text.replace('\\n', '\n').replace('\\n\\n', '\n\n') # Keep newline replacement if needed
206
225
 
207
226
  if __name__ == "__main__":
208
227
  print("-" * 80)
@@ -231,4 +250,4 @@ if __name__ == "__main__":
231
250
  display_text = "Empty or invalid response"
232
251
  print(f"\r{model:<50} {status:<10} {display_text}")
233
252
  except Exception as e:
234
- print(f"\r{model:<50} {'✗':<10} {str(e)}")
253
+ print(f"\r{model:<50} {'✗':<10} {str(e)}")
@@ -1,11 +1,12 @@
1
1
  import re
2
- import requests
3
2
  import json
4
3
  from typing import Union, Any, Dict, Generator, Optional
4
+ from curl_cffi import CurlError
5
+ from curl_cffi.requests import Session
5
6
 
6
7
  from webscout.AIutel import Optimizers
7
8
  from webscout.AIutel import Conversation
8
- from webscout.AIutel import AwesomePrompts
9
+ from webscout.AIutel import AwesomePrompts, sanitize_stream # Import sanitize_stream
9
10
  from webscout.AIbase import Provider
10
11
  from webscout import exceptions
11
12
  from webscout.litagent import LitAgent
@@ -18,12 +19,11 @@ class WiseCat(Provider):
18
19
 
19
20
  AVAILABLE_MODELS = [
20
21
  "chat-model-small",
21
- "chat-model-large",
22
+ # "chat-model-large", # >>> NOT WORKING <<<
22
23
  "chat-model-reasoning",
23
24
  ]
24
25
 
25
- def __init__(
26
- self,
26
+ def __init__(self,
27
27
  is_conversation: bool = True,
28
28
  max_tokens: int = 600,
29
29
  timeout: int = 30,
@@ -41,17 +41,21 @@ class WiseCat(Provider):
41
41
  if model not in self.AVAILABLE_MODELS:
42
42
  raise ValueError(f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}")
43
43
 
44
- self.session = requests.Session()
44
+ # Initialize curl_cffi Session
45
+ self.session = Session()
45
46
  self.is_conversation = is_conversation
46
47
  self.max_tokens_to_sample = max_tokens
47
48
  self.api_endpoint = "https://wise-cat-groq.vercel.app/api/chat"
48
- self.stream_chunk_size = 64
49
+ # stream_chunk_size is not directly applicable to curl_cffi iter_lines
50
+ # self.stream_chunk_size = 64
49
51
  self.timeout = timeout
50
52
  self.last_response = {}
51
53
  self.model = model
52
54
  self.system_prompt = system_prompt
53
55
  self.litagent = LitAgent()
54
- self.headers = self.litagent.generate_fingerprint()
56
+ # Generate headers using LitAgent, but apply them to the curl_cffi session
57
+ self.headers = self.litagent.generate_fingerprint()
58
+ # Update curl_cffi session headers and proxies
55
59
  self.session.headers.update(self.headers)
56
60
  self.session.proxies = proxies
57
61
 
@@ -72,6 +76,17 @@ class WiseCat(Provider):
72
76
  )
73
77
  self.conversation.history_offset = history_offset
74
78
 
79
+ @staticmethod
80
+ def _wisecat_extractor(chunk: Union[str, Dict[str, Any]]) -> Optional[str]:
81
+ """Extracts content from the WiseCat stream format '0:"..."'."""
82
+ if isinstance(chunk, str):
83
+ match = re.search(r'0:"(.*?)"', chunk)
84
+ if match:
85
+ # Decode potential unicode escapes like \u00e9
86
+ content = match.group(1).encode().decode('unicode_escape')
87
+ return content.replace('\\\\', '\\').replace('\\"', '"') # Handle escaped backslashes and quotes
88
+ return None
89
+
75
90
  def ask(
76
91
  self,
77
92
  prompt: str,
@@ -108,27 +123,46 @@ class WiseCat(Provider):
108
123
  }
109
124
 
110
125
  def for_stream():
111
- response = self.session.post(
112
- self.api_endpoint, headers=self.headers, json=payload, stream=True, timeout=self.timeout
113
- )
114
- if not response.ok:
115
- error_msg = f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
116
- raise exceptions.FailedToGenerateResponseError(error_msg)
117
-
118
- streaming_response = ""
119
- for line in response.iter_lines(decode_unicode=True):
120
- if line:
121
- match = re.search(r'0:"(.*?)"', line)
122
- if match:
123
- content = match.group(1)
124
- streaming_response += content
125
- yield content if raw else dict(text=content)
126
- self.last_response.update(dict(text=streaming_response))
127
- self.conversation.update_chat_history(
128
- prompt, self.get_message(self.last_response)
129
- )
126
+ try: # Add try block for CurlError
127
+ # Use curl_cffi session post with impersonate
128
+ response = self.session.post(
129
+ self.api_endpoint,
130
+ headers=self.headers,
131
+ json=payload,
132
+ stream=True,
133
+ timeout=self.timeout,
134
+ impersonate="chrome120" # Add impersonate
135
+ )
136
+ if not response.ok:
137
+ error_msg = f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
138
+ raise exceptions.FailedToGenerateResponseError(error_msg)
139
+
140
+ streaming_text = ""
141
+ # Use sanitize_stream with the custom extractor
142
+ processed_stream = sanitize_stream(
143
+ data=response.iter_content(chunk_size=None), # Pass byte iterator
144
+ intro_value=None, # No simple prefix to remove here
145
+ to_json=False, # Content is not JSON
146
+ content_extractor=self._wisecat_extractor # Use the specific extractor
147
+ )
148
+
149
+ for content_chunk in processed_stream:
150
+ if content_chunk and isinstance(content_chunk, str):
151
+ streaming_text += content_chunk
152
+ yield content_chunk if raw else dict(text=content_chunk)
153
+
154
+ self.last_response.update(dict(text=streaming_text)) # Use streaming_text here
155
+ self.conversation.update_chat_history(
156
+ prompt, self.get_message(self.last_response)
157
+ )
158
+ except CurlError as e: # Catch CurlError
159
+ raise exceptions.FailedToGenerateResponseError(f"Request failed (CurlError): {e}")
160
+ except Exception as e: # Catch other potential exceptions
161
+ raise exceptions.FailedToGenerateResponseError(f"An unexpected error occurred ({type(e).__name__}): {e}")
162
+
130
163
 
131
164
  def for_non_stream():
165
+ # This function implicitly uses the updated for_stream
132
166
  for _ in for_stream():
133
167
  pass
134
168
  return self.last_response
@@ -164,9 +198,12 @@ class WiseCat(Provider):
164
198
  def get_message(self, response: dict) -> str:
165
199
  """Retrieves message only from response"""
166
200
  assert isinstance(response, dict), "Response should be of dict data-type only"
167
- return response["text"].replace('\\n', '\n').replace('\\n\\n', '\n\n')
201
+ # Formatting (like unicode escapes) is handled by the extractor now.
202
+ # Keep newline replacement if needed for display.
203
+ return response.get("text", "").replace('\\n', '\n').replace('\\n\\n', '\n\n')
168
204
 
169
205
  if __name__ == "__main__":
206
+ # Ensure curl_cffi is installed
170
207
  print("-" * 80)
171
208
  print(f"{'Model':<50} {'Status':<10} {'Response'}")
172
209
  print("-" * 80)
@@ -1,10 +1,11 @@
1
- import requests
1
+ from curl_cffi import CurlError
2
+ from curl_cffi.requests import Session # Keep Session import
2
3
  import json
3
4
  from typing import Any, Dict, Optional, Generator, Union
4
5
 
5
6
  from webscout.AIutel import Optimizers
6
7
  from webscout.AIutel import Conversation
7
- from webscout.AIutel import AwesomePrompts
8
+ from webscout.AIutel import AwesomePrompts, sanitize_stream # Import sanitize_stream
8
9
  from webscout.AIbase import Provider
9
10
  from webscout import exceptions
10
11
  from webscout.litagent import LitAgent
@@ -29,7 +30,6 @@ class Writecream(Provider):
29
30
  act: str = None,
30
31
  system_prompt: str = "You are a helpful and informative AI assistant.",
31
32
  base_url: str = "https://8pe3nv3qha.execute-api.us-east-1.amazonaws.com/default/llm_chat",
32
- user_agent: str = "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Mobile Safari/537.36",
33
33
  referer: str = "https://www.writecream.com/chatgpt-chat/",
34
34
  link: str = "writecream.com",
35
35
  model: str = "writecream-gpt"
@@ -40,7 +40,8 @@ class Writecream(Provider):
40
40
  if model not in self.AVAILABLE_MODELS:
41
41
  raise ValueError(f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}")
42
42
 
43
- self.session = requests.Session()
43
+ # Initialize curl_cffi Session
44
+ self.session = Session()
44
45
  self.is_conversation = is_conversation
45
46
  self.max_tokens_to_sample = max_tokens
46
47
  self.base_url = base_url
@@ -48,13 +49,16 @@ class Writecream(Provider):
48
49
  self.last_response = {}
49
50
  self.system_prompt = system_prompt
50
51
  self.model = model
51
- self.user_agent = user_agent
52
+ # Initialize LitAgent
53
+ self.agent = LitAgent()
52
54
  self.referer = referer
53
55
  self.link = link
54
56
 
55
57
  self.headers = {
56
- "User-Agent": self.user_agent,
58
+ # Use LitAgent for User-Agent
59
+ "User-Agent": self.agent.random(),
57
60
  "Referer": self.referer
61
+ # Add other headers if needed by curl_cffi impersonation or API
58
62
  }
59
63
 
60
64
  self.__available_optimizers = (
@@ -63,6 +67,7 @@ class Writecream(Provider):
63
67
  if callable(getattr(Optimizers, method)) and not method.startswith("__")
64
68
  )
65
69
 
70
+ # Update curl_cffi session headers and proxies
66
71
  self.session.headers.update(self.headers)
67
72
  self.session.proxies.update(proxies)
68
73
 
@@ -123,20 +128,40 @@ class Writecream(Provider):
123
128
 
124
129
  def for_non_stream():
125
130
  try:
126
- response = self.session.get(self.base_url, params=params, timeout=self.timeout)
131
+ # Use curl_cffi session.get with impersonate
132
+ response = self.session.get(
133
+ self.base_url,
134
+ params=params,
135
+ timeout=self.timeout,
136
+ impersonate="chrome120" # Add impersonate
137
+ )
127
138
  response.raise_for_status()
128
- data = response.json()
139
+ response_text = response.text # Get the raw text
140
+
141
+ # Use sanitize_stream to process the non-streaming text
142
+ # It will try to parse the whole text as JSON because to_json=True
143
+ processed_stream = sanitize_stream(
144
+ data=response_text,
145
+ to_json=True, # Attempt to parse the whole response text as JSON
146
+ intro_value=None, # No prefix expected on the full response
147
+ content_extractor=lambda chunk: chunk.get("response", chunk.get("response_content", "")) if isinstance(chunk, dict) else None
148
+ )
129
149
 
130
- # Extract the response content
131
- response_content = data.get("response", data.get("response_content", ""))
150
+ # Extract the single result from the generator
151
+ response_content = ""
152
+ for content in processed_stream:
153
+ response_content = content if isinstance(content, str) else ""
132
154
 
133
155
  # Update conversation history
134
156
  self.last_response = {"text": response_content}
135
157
  self.conversation.update_chat_history(prompt, response_content)
136
158
 
137
159
  return {"text": response_content}
160
+ except CurlError as e: # Catch CurlError
161
+ raise exceptions.FailedToGenerateResponseError(f"Request failed (CurlError): {e}")
138
162
  except Exception as e:
139
- raise exceptions.FailedToGenerateResponseError(f"Failed to get response from the chat API: {e}")
163
+ # Include original exception type
164
+ raise exceptions.FailedToGenerateResponseError(f"Failed to get response ({type(e).__name__}): {e}")
140
165
 
141
166
  # Currently, Writecream API doesn't support streaming, so we always return non-streaming response
142
167
  return for_non_stream()
@@ -188,6 +213,7 @@ class Writecream(Provider):
188
213
 
189
214
 
190
215
  if __name__ == "__main__":
216
+ # Ensure curl_cffi is installed
191
217
  print("-" * 80)
192
218
  print(f"{'Model':<30} {'Status':<10} {'Response'}")
193
219
  print("-" * 80)