webscout 8.2.6__py3-none-any.whl → 8.2.8__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 (150) hide show
  1. webscout/AIauto.py +1 -1
  2. webscout/AIutel.py +298 -239
  3. webscout/Extra/Act.md +309 -0
  4. webscout/Extra/GitToolkit/gitapi/README.md +110 -0
  5. webscout/Extra/YTToolkit/README.md +375 -0
  6. webscout/Extra/YTToolkit/ytapi/README.md +44 -0
  7. webscout/Extra/YTToolkit/ytapi/extras.py +92 -19
  8. webscout/Extra/autocoder/autocoder.py +309 -114
  9. webscout/Extra/autocoder/autocoder_utiles.py +15 -15
  10. webscout/Extra/gguf.md +430 -0
  11. webscout/Extra/tempmail/README.md +488 -0
  12. webscout/Extra/weather.md +281 -0
  13. webscout/Litlogger/Readme.md +175 -0
  14. webscout/Provider/AISEARCH/DeepFind.py +41 -37
  15. webscout/Provider/AISEARCH/README.md +279 -0
  16. webscout/Provider/AISEARCH/__init__.py +0 -1
  17. webscout/Provider/AISEARCH/genspark_search.py +228 -86
  18. webscout/Provider/AISEARCH/hika_search.py +11 -11
  19. webscout/Provider/AISEARCH/scira_search.py +324 -322
  20. webscout/Provider/AllenAI.py +7 -14
  21. webscout/Provider/Blackboxai.py +518 -74
  22. webscout/Provider/Cloudflare.py +0 -1
  23. webscout/Provider/Deepinfra.py +23 -21
  24. webscout/Provider/Flowith.py +217 -0
  25. webscout/Provider/FreeGemini.py +250 -0
  26. webscout/Provider/GizAI.py +15 -5
  27. webscout/Provider/Glider.py +11 -8
  28. webscout/Provider/HeckAI.py +80 -52
  29. webscout/Provider/Koboldai.py +7 -4
  30. webscout/Provider/LambdaChat.py +2 -2
  31. webscout/Provider/Marcus.py +10 -18
  32. webscout/Provider/OPENAI/BLACKBOXAI.py +735 -0
  33. webscout/Provider/OPENAI/Cloudflare.py +378 -0
  34. webscout/Provider/OPENAI/FreeGemini.py +282 -0
  35. webscout/Provider/OPENAI/NEMOTRON.py +244 -0
  36. webscout/Provider/OPENAI/README.md +1253 -0
  37. webscout/Provider/OPENAI/__init__.py +8 -0
  38. webscout/Provider/OPENAI/ai4chat.py +293 -286
  39. webscout/Provider/OPENAI/api.py +810 -0
  40. webscout/Provider/OPENAI/base.py +217 -14
  41. webscout/Provider/OPENAI/c4ai.py +373 -367
  42. webscout/Provider/OPENAI/chatgpt.py +7 -0
  43. webscout/Provider/OPENAI/chatgptclone.py +7 -0
  44. webscout/Provider/OPENAI/chatsandbox.py +172 -0
  45. webscout/Provider/OPENAI/deepinfra.py +30 -20
  46. webscout/Provider/OPENAI/e2b.py +6 -0
  47. webscout/Provider/OPENAI/exaai.py +7 -0
  48. webscout/Provider/OPENAI/exachat.py +6 -0
  49. webscout/Provider/OPENAI/flowith.py +162 -0
  50. webscout/Provider/OPENAI/freeaichat.py +359 -352
  51. webscout/Provider/OPENAI/glider.py +323 -316
  52. webscout/Provider/OPENAI/groq.py +361 -354
  53. webscout/Provider/OPENAI/heckai.py +30 -64
  54. webscout/Provider/OPENAI/llmchatco.py +8 -0
  55. webscout/Provider/OPENAI/mcpcore.py +7 -0
  56. webscout/Provider/OPENAI/multichat.py +8 -0
  57. webscout/Provider/OPENAI/netwrck.py +356 -350
  58. webscout/Provider/OPENAI/opkfc.py +8 -0
  59. webscout/Provider/OPENAI/scirachat.py +471 -462
  60. webscout/Provider/OPENAI/sonus.py +9 -0
  61. webscout/Provider/OPENAI/standardinput.py +9 -1
  62. webscout/Provider/OPENAI/textpollinations.py +339 -329
  63. webscout/Provider/OPENAI/toolbaz.py +7 -0
  64. webscout/Provider/OPENAI/typefully.py +355 -0
  65. webscout/Provider/OPENAI/typegpt.py +358 -346
  66. webscout/Provider/OPENAI/uncovrAI.py +7 -0
  67. webscout/Provider/OPENAI/utils.py +103 -7
  68. webscout/Provider/OPENAI/venice.py +12 -0
  69. webscout/Provider/OPENAI/wisecat.py +19 -19
  70. webscout/Provider/OPENAI/writecream.py +7 -0
  71. webscout/Provider/OPENAI/x0gpt.py +7 -0
  72. webscout/Provider/OPENAI/yep.py +50 -21
  73. webscout/Provider/OpenGPT.py +1 -1
  74. webscout/Provider/TTI/AiForce/README.md +159 -0
  75. webscout/Provider/TTI/FreeAIPlayground/README.md +99 -0
  76. webscout/Provider/TTI/ImgSys/README.md +174 -0
  77. webscout/Provider/TTI/MagicStudio/README.md +101 -0
  78. webscout/Provider/TTI/Nexra/README.md +155 -0
  79. webscout/Provider/TTI/PollinationsAI/README.md +146 -0
  80. webscout/Provider/TTI/README.md +128 -0
  81. webscout/Provider/TTI/aiarta/README.md +134 -0
  82. webscout/Provider/TTI/artbit/README.md +100 -0
  83. webscout/Provider/TTI/fastflux/README.md +129 -0
  84. webscout/Provider/TTI/huggingface/README.md +114 -0
  85. webscout/Provider/TTI/piclumen/README.md +161 -0
  86. webscout/Provider/TTI/pixelmuse/README.md +79 -0
  87. webscout/Provider/TTI/talkai/README.md +139 -0
  88. webscout/Provider/TTS/README.md +192 -0
  89. webscout/Provider/TTS/__init__.py +2 -1
  90. webscout/Provider/TTS/speechma.py +500 -100
  91. webscout/Provider/TTS/sthir.py +94 -0
  92. webscout/Provider/TeachAnything.py +3 -7
  93. webscout/Provider/TextPollinationsAI.py +4 -2
  94. webscout/Provider/{aimathgpt.py → UNFINISHED/ChatHub.py} +88 -68
  95. webscout/Provider/UNFINISHED/liner_api_request.py +263 -0
  96. webscout/Provider/UNFINISHED/oivscode.py +351 -0
  97. webscout/Provider/UNFINISHED/test_lmarena.py +119 -0
  98. webscout/Provider/Writecream.py +11 -2
  99. webscout/Provider/__init__.py +8 -14
  100. webscout/Provider/ai4chat.py +4 -58
  101. webscout/Provider/asksteve.py +17 -9
  102. webscout/Provider/cerebras.py +3 -1
  103. webscout/Provider/koala.py +170 -268
  104. webscout/Provider/llmchat.py +3 -0
  105. webscout/Provider/lmarena.py +198 -0
  106. webscout/Provider/meta.py +7 -4
  107. webscout/Provider/samurai.py +223 -0
  108. webscout/Provider/scira_chat.py +4 -2
  109. webscout/Provider/typefully.py +23 -151
  110. webscout/__init__.py +4 -2
  111. webscout/cli.py +3 -28
  112. webscout/conversation.py +35 -35
  113. webscout/litagent/Readme.md +276 -0
  114. webscout/scout/README.md +402 -0
  115. webscout/swiftcli/Readme.md +323 -0
  116. webscout/version.py +1 -1
  117. webscout/webscout_search.py +2 -182
  118. webscout/webscout_search_async.py +1 -179
  119. webscout/zeroart/README.md +89 -0
  120. webscout/zeroart/__init__.py +134 -54
  121. webscout/zeroart/base.py +19 -13
  122. webscout/zeroart/effects.py +101 -99
  123. webscout/zeroart/fonts.py +1239 -816
  124. {webscout-8.2.6.dist-info → webscout-8.2.8.dist-info}/METADATA +116 -74
  125. {webscout-8.2.6.dist-info → webscout-8.2.8.dist-info}/RECORD +130 -103
  126. {webscout-8.2.6.dist-info → webscout-8.2.8.dist-info}/WHEEL +1 -1
  127. webscout-8.2.8.dist-info/entry_points.txt +3 -0
  128. webscout-8.2.8.dist-info/top_level.txt +1 -0
  129. webscout/Provider/AISEARCH/ISou.py +0 -256
  130. webscout/Provider/ElectronHub.py +0 -773
  131. webscout/Provider/Free2GPT.py +0 -241
  132. webscout/Provider/GPTWeb.py +0 -249
  133. webscout/Provider/bagoodex.py +0 -145
  134. webscout/Provider/geminiprorealtime.py +0 -160
  135. webscout/scout/core.py +0 -881
  136. webscout-8.2.6.dist-info/entry_points.txt +0 -3
  137. webscout-8.2.6.dist-info/top_level.txt +0 -2
  138. webstoken/__init__.py +0 -30
  139. webstoken/classifier.py +0 -189
  140. webstoken/keywords.py +0 -216
  141. webstoken/language.py +0 -128
  142. webstoken/ner.py +0 -164
  143. webstoken/normalizer.py +0 -35
  144. webstoken/processor.py +0 -77
  145. webstoken/sentiment.py +0 -206
  146. webstoken/stemmer.py +0 -73
  147. webstoken/tagger.py +0 -60
  148. webstoken/tokenizer.py +0 -158
  149. /webscout/Provider/{Youchat.py → UNFINISHED/Youchat.py} +0 -0
  150. {webscout-8.2.6.dist-info → webscout-8.2.8.dist-info}/licenses/LICENSE.md +0 -0
@@ -1,322 +1,324 @@
1
- import requests
2
- import json
3
- import re
4
- import uuid
5
- import time
6
- from typing import Dict, Optional, Generator, Union, Any
7
-
8
- from webscout.AIbase import AISearch
9
- from webscout import exceptions
10
- from webscout.litagent import LitAgent
11
-
12
-
13
- class Response:
14
- """A wrapper class for SCIRA API responses.
15
-
16
- This class automatically converts response objects to their text representation
17
- when printed or converted to string.
18
-
19
- Attributes:
20
- text (str): The text content of the response
21
-
22
- Example:
23
- >>> response = Response("Hello, world!")
24
- >>> print(response)
25
- Hello, world!
26
- >>> str(response)
27
- 'Hello, world!'
28
- """
29
- def __init__(self, text: str):
30
- self.text = text
31
-
32
- def __str__(self):
33
- return self.text
34
-
35
- def __repr__(self):
36
- return self.text
37
-
38
-
39
- class Scira(AISearch):
40
- """A class to interact with the SCIRA AI search API.
41
-
42
- SCIRA provides a powerful search interface that returns AI-generated responses
43
- based on web content. It supports both streaming and non-streaming responses.
44
-
45
- Basic Usage:
46
- >>> from webscout import Scira
47
- >>> ai = Scira()
48
- >>> # Non-streaming example
49
- >>> response = ai.search("What is Python?")
50
- >>> print(response)
51
- Python is a high-level programming language...
52
-
53
- >>> # Streaming example
54
- >>> for chunk in ai.search("Tell me about AI", stream=True):
55
- ... print(chunk, end="", flush=True)
56
- Artificial Intelligence is...
57
-
58
- >>> # Raw response format
59
- >>> for chunk in ai.search("Hello", stream=True, raw=True):
60
- ... print(chunk)
61
- {'text': 'Hello'}
62
- {'text': ' there!'}
63
-
64
- Args:
65
- timeout (int, optional): Request timeout in seconds. Defaults to 60.
66
- proxies (dict, optional): Proxy configuration for requests. Defaults to None.
67
- model (str, optional): Model to use for the search. Defaults to "scira-default".
68
- group (str, optional): Group parameter. Defaults to "web".
69
- """
70
-
71
- AVAILABLE_MODELS = {
72
- "scira-default": "Grok3-mini", # thinking model
73
- "scira-grok-3": "Grok3",
74
- "scira-anthropic": "Sonnet 3.7 thinking",
75
- "scira-vision" : "Grok2-Vision", # vision model
76
- "scira-4.1-mini": "GPT4.1-mini",
77
- "scira-qwq": "QWQ-32B",
78
- "scira-o4-mini": "o4-mini",
79
- "scira-google": "gemini 2.5 flash"
80
- }
81
- def __init__(
82
- self,
83
- timeout: int = 60,
84
- proxies: Optional[dict] = None,
85
- model: str = "scira-default",
86
- deepsearch: bool = False
87
- ):
88
- """Initialize the SCIRA API client.
89
-
90
- Args:
91
- timeout (int, optional): Request timeout in seconds. Defaults to 60.
92
- proxies (dict, optional): Proxy configuration for requests. Defaults to None.
93
- model (str, optional): Model to use for the search. Defaults to "scira-default" (Grok3).
94
- deepsearch (bool, optional): Whether to use deep search mode. If True, uses "extreme" group for more comprehensive results. If False, uses "web" group for faster results. Defaults to False.
95
-
96
- Example:
97
- >>> ai = Scira(timeout=120) # Longer timeout
98
- >>> ai = Scira(proxies={'http': 'http://proxy.com:8080'}) # With proxy
99
- >>> ai = Scira(model="scira-claude") # Use Claude model
100
- >>> ai = Scira(deepsearch=True) # Use deep search mode
101
- """
102
- # Validate model
103
- if model not in self.AVAILABLE_MODELS:
104
- raise ValueError(
105
- f"Invalid model: {model}. Choose from: {list(self.AVAILABLE_MODELS.keys())}"
106
- )
107
-
108
- self.session = requests.Session()
109
- self.api_endpoint = "https://scira.ai/api/search"
110
- self.timeout = timeout
111
- self.proxies = proxies
112
- self.model = model
113
-
114
- # Set group based on deepsearch parameter
115
- self.group = "extreme" if deepsearch else "web"
116
- self.last_response = {}
117
-
118
- # Set headers
119
- self.headers = {
120
- "Content-Type": "application/json",
121
- "Accept": "*/*",
122
- "User-Agent": LitAgent().random()
123
- }
124
-
125
- self.session.headers.update(self.headers)
126
-
127
- def search(
128
- self,
129
- prompt: str,
130
- stream: bool = False,
131
- raw: bool = False,
132
- ) -> Union[Response, Generator[Union[Dict[str, str], Response], None, None]]:
133
- """Search using the SCIRA API and get AI-generated responses.
134
-
135
- This method sends a search query to SCIRA and returns the AI-generated response.
136
- It supports both streaming and non-streaming modes, as well as raw response format.
137
-
138
- Args:
139
- prompt (str): The search query or prompt to send to the API.
140
- stream (bool, optional): If True, yields response chunks as they arrive.
141
- If False, returns complete response. Defaults to False.
142
- raw (bool, optional): If True, returns raw response dictionaries with 'text' key.
143
- If False, returns Response objects that convert to text automatically.
144
- Defaults to False.
145
-
146
- Returns:
147
- Union[Response, Generator[Union[Dict[str, str], Response], None, None]]:
148
- - If stream=False: Returns complete response
149
- - If stream=True: Yields response chunks as they arrive
150
-
151
- Raises:
152
- exceptions.APIConnectionError: If there's an issue connecting to the API
153
- exceptions.APIResponseError: If the API returns an error response
154
-
155
- Example:
156
- >>> ai = Scira()
157
- >>> # Non-streaming example
158
- >>> response = ai.search("What is Python?")
159
- >>> print(response)
160
- Python is a high-level programming language...
161
-
162
- >>> # Streaming example
163
- >>> for chunk in ai.search("Tell me about AI", stream=True):
164
- ... print(chunk, end="", flush=True)
165
- Artificial Intelligence is...
166
- """
167
- # Create a unique message ID
168
- message_id = str(uuid.uuid4()).replace("-", "")[:16]
169
- self.user_id = str(uuid.uuid4()).replace("-", "")[:16]
170
- # Prepare the payload
171
- payload = {
172
- "id": message_id,
173
- "messages": [
174
- {
175
- "role": "user",
176
- "content": prompt,
177
- "parts": [
178
- {
179
- "type": "text",
180
- "text": prompt
181
- }
182
- ]
183
- }
184
- ],
185
- "model": self.model,
186
- "group": self.group,
187
- "user_id": self.user_id,
188
- "timezone": "Asia/Calcutta"
189
- }
190
-
191
- try:
192
- # Send the request
193
- response = self.session.post(
194
- self.api_endpoint,
195
- headers=self.headers,
196
- data=json.dumps(payload),
197
- stream=True,
198
- timeout=self.timeout,
199
- proxies=self.proxies
200
- )
201
-
202
- # Check for successful response
203
- if response.status_code != 200:
204
- raise exceptions.APIResponseError(
205
- f"API returned error status: {response.status_code}"
206
- )
207
-
208
- # Store the last response
209
- self.last_response = {"status_code": response.status_code}
210
-
211
- # Handle streaming response
212
- if stream:
213
- return self._handle_streaming_response(response, raw)
214
-
215
- # Handle non-streaming response
216
- return self._handle_non_streaming_response(response, raw)
217
-
218
- except requests.RequestException as e:
219
- raise exceptions.APIConnectionError(f"Error connecting to API: {str(e)}")
220
-
221
- def _handle_streaming_response(
222
- self,
223
- response: requests.Response,
224
- raw: bool
225
- ) -> Generator[Union[Dict[str, str], Response], None, None]:
226
- """Handle streaming response from the API.
227
-
228
- Args:
229
- response (requests.Response): The streaming response from the API
230
- raw (bool): Whether to return raw response dictionaries
231
-
232
- Yields:
233
- Union[Dict[str, str], Response]: Response chunks as they arrive
234
- """
235
- for line in response.iter_lines():
236
- if line:
237
- try:
238
- # Decode the line
239
- decoded_line = line.decode("utf-8")
240
-
241
- # Check if this is a line starting with "0:" (content)
242
- if re.match(r'^0:', decoded_line):
243
- # Extract the content after "0:"
244
- content = re.sub(r'^0:', '', decoded_line)
245
- # Remove surrounding quotes if present
246
- content = re.sub(r'^"(.*)"$', r'\1', content)
247
- # Replace escaped newlines with actual newlines
248
- content = content.replace('\\n', '\n')
249
-
250
- if raw:
251
- yield {"text": content}
252
- else:
253
- yield Response(content)
254
- except Exception:
255
- # Skip lines that can't be processed
256
- pass
257
-
258
- def _handle_non_streaming_response(
259
- self,
260
- response: requests.Response,
261
- raw: bool
262
- ) -> Union[Dict[str, str], Response]:
263
- """Handle non-streaming response from the API.
264
-
265
- Args:
266
- response (requests.Response): The response from the API
267
- raw (bool): Whether to return raw response dictionary
268
-
269
- Returns:
270
- Union[Dict[str, str], Response]: Complete response
271
- """
272
- full_text = ""
273
-
274
- for line in response.iter_lines():
275
- if line:
276
- try:
277
- # Decode the line
278
- decoded_line = line.decode("utf-8")
279
-
280
- # Check if this is a line starting with "0:" (content)
281
- if re.match(r'^0:', decoded_line):
282
- # Extract the content after "0:"
283
- content = re.sub(r'^0:', '', decoded_line)
284
- # Remove surrounding quotes if present
285
- content = re.sub(r'^"(.*)"$', r'\1', content)
286
- # Replace escaped newlines with actual newlines
287
- content = content.replace('\\n', '\n')
288
- full_text += content
289
- except Exception:
290
- # Skip lines that can't be processed
291
- pass
292
-
293
- if raw:
294
- return {"text": full_text}
295
- else:
296
- return Response(full_text)
297
-
298
- @staticmethod
299
- def clean_content(text: str) -> str:
300
- """Clean the response content by removing unnecessary formatting.
301
-
302
- Args:
303
- text (str): The text to clean
304
-
305
- Returns:
306
- str: The cleaned text
307
- """
308
- # Remove any extra whitespace
309
- cleaned_text = re.sub(r'\s+', ' ', text)
310
- # Remove any trailing whitespace
311
- cleaned_text = cleaned_text.strip()
312
-
313
- return cleaned_text
314
-
315
-
316
- if __name__ == "__main__":
317
- from rich import print
318
- ai = Scira()
319
- user_query = input(">>> ")
320
- response = ai.search(user_query, stream=True, raw=False)
321
- for chunk in response:
322
- print(chunk, end="", flush=True)
1
+ import requests
2
+ import json
3
+ import re
4
+ import uuid
5
+ import time
6
+ from typing import Dict, Optional, Generator, Union, Any
7
+
8
+ from webscout.AIbase import AISearch
9
+ from webscout import exceptions
10
+ from webscout.litagent import LitAgent
11
+
12
+
13
+ class Response:
14
+ """A wrapper class for SCIRA API responses.
15
+
16
+ This class automatically converts response objects to their text representation
17
+ when printed or converted to string.
18
+
19
+ Attributes:
20
+ text (str): The text content of the response
21
+
22
+ Example:
23
+ >>> response = Response("Hello, world!")
24
+ >>> print(response)
25
+ Hello, world!
26
+ >>> str(response)
27
+ 'Hello, world!'
28
+ """
29
+ def __init__(self, text: str):
30
+ self.text = text
31
+
32
+ def __str__(self):
33
+ return self.text
34
+
35
+ def __repr__(self):
36
+ return self.text
37
+
38
+
39
+ class Scira(AISearch):
40
+ """A class to interact with the SCIRA AI search API.
41
+
42
+ SCIRA provides a powerful search interface that returns AI-generated responses
43
+ based on web content. It supports both streaming and non-streaming responses.
44
+
45
+ Basic Usage:
46
+ >>> from webscout import Scira
47
+ >>> ai = Scira()
48
+ >>> # Non-streaming example
49
+ >>> response = ai.search("What is Python?")
50
+ >>> print(response)
51
+ Python is a high-level programming language...
52
+
53
+ >>> # Streaming example
54
+ >>> for chunk in ai.search("Tell me about AI", stream=True):
55
+ ... print(chunk, end="", flush=True)
56
+ Artificial Intelligence is...
57
+
58
+ >>> # Raw response format
59
+ >>> for chunk in ai.search("Hello", stream=True, raw=True):
60
+ ... print(chunk)
61
+ {'text': 'Hello'}
62
+ {'text': ' there!'}
63
+
64
+ Args:
65
+ timeout (int, optional): Request timeout in seconds. Defaults to 60.
66
+ proxies (dict, optional): Proxy configuration for requests. Defaults to None.
67
+ model (str, optional): Model to use for the search. Defaults to "scira-default".
68
+ group (str, optional): Group parameter. Defaults to "web".
69
+ """
70
+
71
+ AVAILABLE_MODELS = {
72
+ "scira-default": "Grok3-mini", # thinking model
73
+ "scira-grok-3": "Grok3",
74
+ "scira-anthropic": "Sonnet 3.7 thinking",
75
+ "scira-vision" : "Grok2-Vision", # vision model
76
+ "scira-4o": "GPT4o",
77
+ "scira-qwq": "QWQ-32B",
78
+ "scira-o4-mini": "o4-mini",
79
+ "scira-google": "gemini 2.5 flash",
80
+ "scira-google-pro": "gemini 2.5 pro",
81
+ "scira-llama-4": "llama 4 Maverick",
82
+ }
83
+ def __init__(
84
+ self,
85
+ timeout: int = 60,
86
+ proxies: Optional[dict] = None,
87
+ model: str = "scira-default",
88
+ deepsearch: bool = False
89
+ ):
90
+ """Initialize the SCIRA API client.
91
+
92
+ Args:
93
+ timeout (int, optional): Request timeout in seconds. Defaults to 60.
94
+ proxies (dict, optional): Proxy configuration for requests. Defaults to None.
95
+ model (str, optional): Model to use for the search. Defaults to "scira-default" (Grok3).
96
+ deepsearch (bool, optional): Whether to use deep search mode. If True, uses "extreme" group for more comprehensive results. If False, uses "web" group for faster results. Defaults to False.
97
+
98
+ Example:
99
+ >>> ai = Scira(timeout=120) # Longer timeout
100
+ >>> ai = Scira(proxies={'http': 'http://proxy.com:8080'}) # With proxy
101
+ >>> ai = Scira(model="scira-claude") # Use Claude model
102
+ >>> ai = Scira(deepsearch=True) # Use deep search mode
103
+ """
104
+ # Validate model
105
+ if model not in self.AVAILABLE_MODELS:
106
+ raise ValueError(
107
+ f"Invalid model: {model}. Choose from: {list(self.AVAILABLE_MODELS.keys())}"
108
+ )
109
+
110
+ self.session = requests.Session()
111
+ self.api_endpoint = "https://scira.ai/api/search"
112
+ self.timeout = timeout
113
+ self.proxies = proxies
114
+ self.model = model
115
+
116
+ # Set group based on deepsearch parameter
117
+ self.group = "extreme" if deepsearch else "web"
118
+ self.last_response = {}
119
+
120
+ # Set headers
121
+ self.headers = {
122
+ "Content-Type": "application/json",
123
+ "Accept": "*/*",
124
+ "User-Agent": LitAgent().random()
125
+ }
126
+
127
+ self.session.headers.update(self.headers)
128
+
129
+ def search(
130
+ self,
131
+ prompt: str,
132
+ stream: bool = False,
133
+ raw: bool = False,
134
+ ) -> Union[Response, Generator[Union[Dict[str, str], Response], None, None]]:
135
+ """Search using the SCIRA API and get AI-generated responses.
136
+
137
+ This method sends a search query to SCIRA and returns the AI-generated response.
138
+ It supports both streaming and non-streaming modes, as well as raw response format.
139
+
140
+ Args:
141
+ prompt (str): The search query or prompt to send to the API.
142
+ stream (bool, optional): If True, yields response chunks as they arrive.
143
+ If False, returns complete response. Defaults to False.
144
+ raw (bool, optional): If True, returns raw response dictionaries with 'text' key.
145
+ If False, returns Response objects that convert to text automatically.
146
+ Defaults to False.
147
+
148
+ Returns:
149
+ Union[Response, Generator[Union[Dict[str, str], Response], None, None]]:
150
+ - If stream=False: Returns complete response
151
+ - If stream=True: Yields response chunks as they arrive
152
+
153
+ Raises:
154
+ exceptions.APIConnectionError: If there's an issue connecting to the API
155
+ exceptions.APIResponseError: If the API returns an error response
156
+
157
+ Example:
158
+ >>> ai = Scira()
159
+ >>> # Non-streaming example
160
+ >>> response = ai.search("What is Python?")
161
+ >>> print(response)
162
+ Python is a high-level programming language...
163
+
164
+ >>> # Streaming example
165
+ >>> for chunk in ai.search("Tell me about AI", stream=True):
166
+ ... print(chunk, end="", flush=True)
167
+ Artificial Intelligence is...
168
+ """
169
+ # Create a unique message ID
170
+ message_id = str(uuid.uuid4()).replace("-", "")[:16]
171
+ self.user_id = str(uuid.uuid4()).replace("-", "")[:16]
172
+ # Prepare the payload
173
+ payload = {
174
+ "id": message_id,
175
+ "messages": [
176
+ {
177
+ "role": "user",
178
+ "content": prompt,
179
+ "parts": [
180
+ {
181
+ "type": "text",
182
+ "text": prompt
183
+ }
184
+ ]
185
+ }
186
+ ],
187
+ "model": self.model,
188
+ "group": self.group,
189
+ "user_id": self.user_id,
190
+ "timezone": "Asia/Calcutta"
191
+ }
192
+
193
+ try:
194
+ # Send the request
195
+ response = self.session.post(
196
+ self.api_endpoint,
197
+ headers=self.headers,
198
+ data=json.dumps(payload),
199
+ stream=True,
200
+ timeout=self.timeout,
201
+ proxies=self.proxies
202
+ )
203
+
204
+ # Check for successful response
205
+ if response.status_code != 200:
206
+ raise exceptions.APIResponseError(
207
+ f"API returned error status: {response.status_code}"
208
+ )
209
+
210
+ # Store the last response
211
+ self.last_response = {"status_code": response.status_code}
212
+
213
+ # Handle streaming response
214
+ if stream:
215
+ return self._handle_streaming_response(response, raw)
216
+
217
+ # Handle non-streaming response
218
+ return self._handle_non_streaming_response(response, raw)
219
+
220
+ except requests.RequestException as e:
221
+ raise exceptions.APIConnectionError(f"Error connecting to API: {str(e)}")
222
+
223
+ def _handle_streaming_response(
224
+ self,
225
+ response: requests.Response,
226
+ raw: bool
227
+ ) -> Generator[Union[Dict[str, str], Response], None, None]:
228
+ """Handle streaming response from the API.
229
+
230
+ Args:
231
+ response (requests.Response): The streaming response from the API
232
+ raw (bool): Whether to return raw response dictionaries
233
+
234
+ Yields:
235
+ Union[Dict[str, str], Response]: Response chunks as they arrive
236
+ """
237
+ for line in response.iter_lines():
238
+ if line:
239
+ try:
240
+ # Decode the line
241
+ decoded_line = line.decode("utf-8")
242
+
243
+ # Check if this is a line starting with "0:" (content)
244
+ if re.match(r'^0:', decoded_line):
245
+ # Extract the content after "0:"
246
+ content = re.sub(r'^0:', '', decoded_line)
247
+ # Remove surrounding quotes if present
248
+ content = re.sub(r'^"(.*)"$', r'\1', content)
249
+ # Replace escaped newlines with actual newlines
250
+ content = content.replace('\\n', '\n')
251
+
252
+ if raw:
253
+ yield {"text": content}
254
+ else:
255
+ yield Response(content)
256
+ except Exception:
257
+ # Skip lines that can't be processed
258
+ pass
259
+
260
+ def _handle_non_streaming_response(
261
+ self,
262
+ response: requests.Response,
263
+ raw: bool
264
+ ) -> Union[Dict[str, str], Response]:
265
+ """Handle non-streaming response from the API.
266
+
267
+ Args:
268
+ response (requests.Response): The response from the API
269
+ raw (bool): Whether to return raw response dictionary
270
+
271
+ Returns:
272
+ Union[Dict[str, str], Response]: Complete response
273
+ """
274
+ full_text = ""
275
+
276
+ for line in response.iter_lines():
277
+ if line:
278
+ try:
279
+ # Decode the line
280
+ decoded_line = line.decode("utf-8")
281
+
282
+ # Check if this is a line starting with "0:" (content)
283
+ if re.match(r'^0:', decoded_line):
284
+ # Extract the content after "0:"
285
+ content = re.sub(r'^0:', '', decoded_line)
286
+ # Remove surrounding quotes if present
287
+ content = re.sub(r'^"(.*)"$', r'\1', content)
288
+ # Replace escaped newlines with actual newlines
289
+ content = content.replace('\\n', '\n')
290
+ full_text += content
291
+ except Exception:
292
+ # Skip lines that can't be processed
293
+ pass
294
+
295
+ if raw:
296
+ return {"text": full_text}
297
+ else:
298
+ return Response(full_text)
299
+
300
+ @staticmethod
301
+ def clean_content(text: str) -> str:
302
+ """Clean the response content by removing unnecessary formatting.
303
+
304
+ Args:
305
+ text (str): The text to clean
306
+
307
+ Returns:
308
+ str: The cleaned text
309
+ """
310
+ # Remove any extra whitespace
311
+ cleaned_text = re.sub(r'\s+', ' ', text)
312
+ # Remove any trailing whitespace
313
+ cleaned_text = cleaned_text.strip()
314
+
315
+ return cleaned_text
316
+
317
+
318
+ if __name__ == "__main__":
319
+ from rich import print
320
+ ai = Scira(deepsearch=False)
321
+ user_query = input(">>> ")
322
+ response = ai.search(user_query, stream=True, raw=False)
323
+ for chunk in response:
324
+ print(chunk, end="", flush=True)