webscout 6.0__py3-none-any.whl → 6.2b0__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 (60) hide show
  1. webscout/AIauto.py +77 -259
  2. webscout/Agents/Onlinesearcher.py +22 -10
  3. webscout/Agents/functioncall.py +2 -2
  4. webscout/Bard.py +21 -21
  5. webscout/Extra/autollama.py +37 -20
  6. webscout/Local/__init__.py +6 -7
  7. webscout/Local/formats.py +404 -194
  8. webscout/Local/model.py +1074 -477
  9. webscout/Local/samplers.py +108 -144
  10. webscout/Local/thread.py +251 -410
  11. webscout/Local/ui.py +401 -0
  12. webscout/Local/utils.py +338 -136
  13. webscout/Provider/Amigo.py +51 -38
  14. webscout/Provider/Deepseek.py +7 -6
  15. webscout/Provider/EDITEE.py +2 -2
  16. webscout/Provider/GPTWeb.py +1 -1
  17. webscout/Provider/NinjaChat.py +200 -0
  18. webscout/Provider/OLLAMA.py +1 -1
  19. webscout/Provider/Perplexity.py +1 -1
  20. webscout/Provider/Reka.py +12 -5
  21. webscout/Provider/TTI/AIuncensored.py +103 -0
  22. webscout/Provider/TTI/Nexra.py +3 -3
  23. webscout/Provider/TTI/__init__.py +3 -2
  24. webscout/Provider/TTI/aiforce.py +2 -2
  25. webscout/Provider/TTI/imgninza.py +136 -0
  26. webscout/Provider/TeachAnything.py +0 -3
  27. webscout/Provider/Youchat.py +1 -1
  28. webscout/Provider/__init__.py +12 -11
  29. webscout/Provider/{ChatHub.py → aimathgpt.py} +72 -88
  30. webscout/Provider/cerebras.py +125 -118
  31. webscout/Provider/cleeai.py +1 -1
  32. webscout/Provider/felo_search.py +1 -1
  33. webscout/Provider/gaurish.py +207 -0
  34. webscout/Provider/geminiprorealtime.py +160 -0
  35. webscout/Provider/genspark.py +1 -1
  36. webscout/Provider/julius.py +8 -3
  37. webscout/Provider/learnfastai.py +1 -1
  38. webscout/Provider/promptrefine.py +3 -1
  39. webscout/Provider/turboseek.py +3 -8
  40. webscout/Provider/tutorai.py +1 -1
  41. webscout/__init__.py +2 -43
  42. webscout/exceptions.py +5 -1
  43. webscout/tempid.py +4 -73
  44. webscout/utils.py +3 -0
  45. webscout/version.py +1 -1
  46. webscout/webai.py +1 -1
  47. webscout/webscout_search.py +154 -123
  48. {webscout-6.0.dist-info → webscout-6.2b0.dist-info}/METADATA +156 -236
  49. {webscout-6.0.dist-info → webscout-6.2b0.dist-info}/RECORD +53 -54
  50. webscout/Local/rawdog.py +0 -946
  51. webscout/Provider/BasedGPT.py +0 -214
  52. webscout/Provider/TTI/amigo.py +0 -148
  53. webscout/Provider/aigames.py +0 -213
  54. webscout/Provider/bixin.py +0 -264
  55. webscout/Provider/xdash.py +0 -182
  56. webscout/websx_search.py +0 -19
  57. {webscout-6.0.dist-info → webscout-6.2b0.dist-info}/LICENSE.md +0 -0
  58. {webscout-6.0.dist-info → webscout-6.2b0.dist-info}/WHEEL +0 -0
  59. {webscout-6.0.dist-info → webscout-6.2b0.dist-info}/entry_points.txt +0 -0
  60. {webscout-6.0.dist-info → webscout-6.2b0.dist-info}/top_level.txt +0 -0
webscout/Local/utils.py CHANGED
@@ -1,86 +1,296 @@
1
- from ._version import __version__, __llama_cpp_version__
2
-
1
+ import os
3
2
  import sys
3
+ import struct
4
+ from enum import IntEnum
5
+ from io import BufferedReader
6
+ from typing import Dict, Iterable, TextIO, Optional, Union, Tuple, Generator, Any
7
+
8
+ from huggingface_hub import hf_hub_download
4
9
  import numpy as np
5
10
 
6
- from typing import Any, Iterable, TextIO
7
- from time import strftime
8
- from enum import IntEnum
9
- from struct import unpack
10
- from colorama import Fore
11
- from huggingface_hub import hf_hub_url, cached_download
12
-
13
- # color codes used in Thread.interact()
14
- RESET_ALL = Fore.RESET
15
- USER_STYLE = RESET_ALL + Fore.GREEN
16
- BOT_STYLE = RESET_ALL + Fore.CYAN
17
- DIM_STYLE = RESET_ALL + Fore.LIGHTBLACK_EX
18
- SPECIAL_STYLE = RESET_ALL + Fore.YELLOW
19
-
20
- # for typing of softmax parameter `z`
11
+ from ._version import __version__, __llama_cpp_version__
12
+
13
+
14
+ # Color codes for Thread.interact()
15
+ RESET_ALL = "\x1b[39m"
16
+ USER_STYLE = "\x1b[39m\x1b[32m"
17
+ BOT_STYLE = "\x1b[39m\x1b[36m"
18
+ DIM_STYLE = "\x1b[39m\x1b[90m"
19
+ SPECIAL_STYLE = "\x1b[39m\x1b[33m"
20
+ ERROR_STYLE = "\x1b[39m\x1b[91m"
21
+
22
+ NoneType: type = type(None)
23
+
24
+ class TypeAssertionError(Exception):
25
+ """Raised when a type assertion fails."""
26
+ pass
27
+
21
28
  class _ArrayLike(Iterable):
29
+ """Represents any object that can be treated as a NumPy array."""
22
30
  pass
23
31
 
24
- # for typing of Model.stream_print() parameter `file`
25
32
  class _SupportsWriteAndFlush(TextIO):
33
+ """Represents a file-like object supporting write and flush operations."""
26
34
  pass
27
35
 
28
- def download_model(repo_id: str, filename: str, token: str, cache_dir: str = ".cache") -> str:
36
+ class UnreachableException(Exception):
37
+ """Raised when code reaches a theoretically unreachable state."""
38
+
39
+ def __init__(self):
40
+ super().__init__(
41
+ "Unreachable code reached. Please report this issue at: "
42
+ "https://github.com/ddh0/easy-llama/issues/new/choose"
43
+ )
44
+
45
+ def download_model(
46
+ repo_id: str,
47
+ filename: str,
48
+ token: Optional[str] = None,
49
+ cache_dir: str = ".cache",
50
+ revision: str = "main"
51
+ ) -> str:
52
+ """
53
+ Downloads a model file from the Hugging Face Hub.
54
+
55
+ Args:
56
+ repo_id (str): Hugging Face repository ID (e.g., 'facebook/bart-large-cnn')
57
+ filename (str): Name of the file to download (e.g., 'model.bin', 'tokenizer.json')
58
+ token (str, optional): Hugging Face API token for private repos. Defaults to None.
59
+ cache_dir (str, optional): Local directory for storing downloaded files.
60
+ Defaults to ".cache".
61
+ revision (str, optional): The specific model version to use. Defaults to "main".
62
+
63
+ Returns:
64
+ str: Path to the downloaded file.
65
+
66
+ Raises:
67
+ ValueError: If the repository or file is not found
68
+ Exception: For other download-related errors
29
69
  """
30
- Downloads a GGUF model file from Hugging Face Hub.
31
-
32
- repo_id: The Hugging Face repository ID (e.g., 'facebook/bart-large-cnn').
33
- filename: The name of the GGUF file within the repository (e.g., 'model.gguf').
34
- token: The Hugging Face token for authentication.
35
- cache_dir: The directory where the downloaded file should be stored.
36
-
37
- Returns: The path to the downloaded file.
70
+ try:
71
+ # Create cache directory if it doesn't exist
72
+ os.makedirs(cache_dir, exist_ok=True)
73
+
74
+ # Download the file
75
+ downloaded_path = hf_hub_download(
76
+ repo_id=repo_id,
77
+ filename=filename,
78
+ token=token,
79
+ cache_dir=cache_dir,
80
+ revision=revision,
81
+ resume_download=True, # Resume interrupted downloads
82
+ force_download=False # Use cached version if available
83
+ )
84
+
85
+ return downloaded_path
86
+
87
+ except Exception as e:
88
+ raise Exception(f"Error downloading model from {repo_id}: {str(e)}")
89
+
90
+ def softmax(z: _ArrayLike, T: Optional[float] = None, dtype: Optional[np.dtype] = None) -> np.ndarray:
38
91
  """
39
- url = hf_hub_url(repo_id, filename)
40
- filepath = cached_download(url, cache_dir=cache_dir, force_filename=filename, use_auth_token=token)
41
- return filepath
92
+ Computes the softmax of an array-like input.
42
93
 
43
- class GGUFReader:
94
+ Args:
95
+ z (_ArrayLike): Input array.
96
+ T (Optional[float], optional): Temperature parameter (scales input before softmax).
97
+ Defaults to None.
98
+ dtype (Optional[np.dtype], optional): Data type for calculations. Defaults to None
99
+ (highest precision available).
100
+
101
+ Returns:
102
+ np.ndarray: Softmax output.
44
103
  """
45
- Peek at file header for GGUF metadata
104
+ if dtype is None:
105
+ _dtype = next(
106
+ (getattr(np, f'float{bits}') for bits in [128, 96, 80, 64, 32, 16]
107
+ if hasattr(np, f'float{bits}')),
108
+ float # Default to Python float if no NumPy float types are available
109
+ )
110
+ else:
111
+ assert_type(
112
+ dtype,
113
+ type,
114
+ 'dtype',
115
+ 'softmax',
116
+ 'dtype should be a floating type, such as `np.float32`'
117
+ )
118
+ _dtype = dtype
119
+
120
+ _z = np.asarray(z, dtype=_dtype)
121
+ if T is None or T == 1.0:
122
+ exp_z = np.exp(_z - np.max(_z), dtype=_dtype)
123
+ return exp_z / np.sum(exp_z, axis=0, dtype=_dtype)
124
+
125
+ assert_type(T, float, "temperature value 'T'", 'softmax')
126
+
127
+ if T == 0.0:
128
+ result = np.zeros_like(_z, dtype=_dtype)
129
+ result[np.argmax(_z)] = 1.0
130
+ return result
131
+
132
+ exp_z = np.exp(np.divide(_z, T, dtype=_dtype), dtype=_dtype)
133
+ return exp_z / np.sum(exp_z, axis=0, dtype=_dtype)
134
+
135
+ def cls() -> None:
136
+ """Clears the terminal screen."""
137
+ os.system('cls' if os.name == 'nt' else 'clear')
138
+ if os.name != 'nt':
139
+ print("\033c\033[3J", end="", flush=True)
140
+
141
+ def truncate(text: str, max_length: int = 72) -> str:
142
+ """Truncates a string to a given length and adds ellipsis if truncated."""
143
+ return text if len(text) <= max_length else f"{text[:max_length - 3]}..."
144
+
145
+ def print_version_info(file: _SupportsWriteAndFlush) -> None:
146
+ """Prints easy-llama and llama_cpp package versions."""
147
+ print(f"webscout.Local package version: {__version__}", file=file)
148
+ print(f"llama_cpp package version: {__llama_cpp_version__}", file=file)
149
+
150
+ def print_verbose(text: str) -> None:
151
+ """Prints verbose messages to stderr."""
152
+ print("webscout.Local:", text, file=sys.stderr, flush=True)
153
+
154
+ def print_info(text: str) -> None:
155
+ """Prints informational messages to stderr."""
156
+ print("webscout.Local: info:", text, file=sys.stderr, flush=True)
157
+
158
+ def print_warning(text: str) -> None:
159
+ """Prints warning messages to stderr."""
160
+ print("webscout.Local: WARNING:", text, file=sys.stderr, flush=True)
161
+
162
+ def assert_type(
163
+ obj: object,
164
+ expected_type: Union[type, Tuple[type, ...]],
165
+ obj_name: str,
166
+ code_location: str,
167
+ hint: Optional[str] = None
168
+ ) -> None:
169
+ """
170
+ Asserts that an object is of an expected type.
171
+
172
+ Args:
173
+ obj (object): The object to check.
174
+ expected_type (Union[type, Tuple[type, ...]]): The expected type(s).
175
+ obj_name (str): Name of the object in the code.
176
+ code_location (str): Location of the assertion in the code.
177
+ hint (Optional[str], optional): Additional hint for the error message.
178
+ Defaults to None.
179
+
180
+ Raises:
181
+ TypeAssertionError: If the object is not of the expected type.
182
+ """
183
+ if isinstance(obj, expected_type):
184
+ return
185
+
186
+ if isinstance(expected_type, tuple):
187
+ expected_types_str = ", ".join(t.__name__ for t in expected_type)
188
+ error_msg = (
189
+ f"{code_location}: {obj_name} should be one of "
190
+ f"{expected_types_str}, not {type(obj).__name__}"
191
+ )
192
+ else:
193
+ error_msg = (
194
+ f"{code_location}: {obj_name} should be an instance of "
195
+ f"{expected_type.__name__}, not {type(obj).__name__}"
196
+ )
46
197
 
47
- Raise ValueError if file is not GGUF or is outdated
198
+ if hint:
199
+ error_msg += f" ({hint})"
48
200
 
49
- Credit to oobabooga for the parts of the code in this class
201
+ raise TypeAssertionError(error_msg)
50
202
 
51
- Format spec: https://github.com/philpax/ggml/blob/gguf-spec/docs/gguf.md
203
+ class InferenceLock:
52
204
  """
205
+ Context manager to prevent concurrent model inferences.
53
206
 
54
- class GGUFValueType(IntEnum):
55
- UINT8 = 0
56
- INT8 = 1
57
- UINT16 = 2
58
- INT16 = 3
59
- UINT32 = 4
60
- INT32 = 5
61
- FLOAT32 = 6
62
- BOOL = 7
63
- STRING = 8
64
- ARRAY = 9
65
- UINT64 = 10
66
- INT64 = 11
67
- FLOAT64 = 12
68
-
69
- _simple_value_packing = {
70
- GGUFValueType.UINT8: "<B",
71
- GGUFValueType.INT8: "<b",
72
- GGUFValueType.UINT16: "<H",
73
- GGUFValueType.INT16: "<h",
74
- GGUFValueType.UINT32: "<I",
75
- GGUFValueType.INT32: "<i",
76
- GGUFValueType.FLOAT32: "<f",
77
- GGUFValueType.UINT64: "<Q",
78
- GGUFValueType.INT64: "<q",
79
- GGUFValueType.FLOAT64: "<d",
207
+ This is primarily useful in asynchronous or multi-threaded contexts where
208
+ concurrent calls to the model can lead to issues.
209
+ """
210
+
211
+ class LockFailure(Exception):
212
+ """Raised when acquiring or releasing the lock fails."""
213
+ pass
214
+
215
+ def __init__(self):
216
+ """Initializes the InferenceLock."""
217
+ self.locked = False
218
+
219
+ def __enter__(self):
220
+ """Acquires the lock when entering the context."""
221
+ return self.acquire()
222
+
223
+ def __exit__(self, *exc_info):
224
+ """Releases the lock when exiting the context."""
225
+ self.release()
226
+
227
+ async def __aenter__(self):
228
+ """Acquires the lock asynchronously."""
229
+ return self.__enter__()
230
+
231
+ async def __aexit__(self, *exc_info):
232
+ """Releases the lock asynchronously."""
233
+ self.__exit__()
234
+
235
+ def acquire(self):
236
+ """Acquires the lock."""
237
+ if self.locked:
238
+ raise self.LockFailure("InferenceLock is already locked.")
239
+ self.locked = True
240
+ return self
241
+
242
+ def release(self):
243
+ """Releases the lock."""
244
+ if not self.locked:
245
+ raise self.LockFailure("InferenceLock is not acquired.")
246
+ self.locked = False
247
+
248
+
249
+ class GGUFValueType(IntEnum):
250
+ """
251
+ Represents data types supported by the GGUF format.
252
+
253
+ This enum should be kept consistent with the GGUF specification.
254
+ """
255
+ UINT8 = 0
256
+ INT8 = 1
257
+ UINT16 = 2
258
+ INT16 = 3
259
+ UINT32 = 4
260
+ INT32 = 5
261
+ FLOAT32 = 6
262
+ BOOL = 7
263
+ STRING = 8
264
+ ARRAY = 9
265
+ UINT64 = 10
266
+ INT64 = 11
267
+ FLOAT64 = 12
268
+
269
+
270
+ class QuickGGUFReader:
271
+ """
272
+ Provides methods for quickly reading metadata from GGUF files.
273
+
274
+ Supports GGUF versions 2 and 3. Assumes little or big endian
275
+ architecture.
276
+ """
277
+
278
+ SUPPORTED_GGUF_VERSIONS = [2, 3]
279
+ VALUE_PACKING = {
280
+ GGUFValueType.UINT8: "=B",
281
+ GGUFValueType.INT8: "=b",
282
+ GGUFValueType.UINT16: "=H",
283
+ GGUFValueType.INT16: "=h",
284
+ GGUFValueType.UINT32: "=I",
285
+ GGUFValueType.INT32: "=i",
286
+ GGUFValueType.FLOAT32: "=f",
287
+ GGUFValueType.UINT64: "=Q",
288
+ GGUFValueType.INT64: "=q",
289
+ GGUFValueType.FLOAT64: "=d",
80
290
  GGUFValueType.BOOL: "?",
81
291
  }
82
292
 
83
- value_type_info = {
293
+ VALUE_LENGTHS = {
84
294
  GGUFValueType.UINT8: 1,
85
295
  GGUFValueType.INT8: 1,
86
296
  GGUFValueType.UINT16: 2,
@@ -94,93 +304,85 @@ class GGUFReader:
94
304
  GGUFValueType.BOOL: 1,
95
305
  }
96
306
 
97
- def get_single(self, value_type, file) -> Any:
98
- if value_type == GGUFReader.GGUFValueType.STRING:
99
- value_length = unpack("<Q", file.read(8))[0]
100
- value = file.read(value_length)
101
- value = value.decode("utf-8")
102
- else:
103
- type_str = GGUFReader._simple_value_packing.get(value_type)
104
- bytes_length = GGUFReader.value_type_info.get(value_type)
105
- value = unpack(type_str, file.read(bytes_length))[0]
307
+ @staticmethod
308
+ def unpack(value_type: GGUFValueType, file: BufferedReader) -> Any:
309
+ """Unpacks a single value from the file based on its type."""
310
+ return struct.unpack(
311
+ QuickGGUFReader.VALUE_PACKING.get(value_type),
312
+ file.read(QuickGGUFReader.VALUE_LENGTHS.get(value_type))
313
+ )[0]
106
314
 
107
- return value
315
+ @staticmethod
316
+ def get_single(
317
+ value_type: GGUFValueType,
318
+ file: BufferedReader
319
+ ) -> Union[str, int, float, bool]:
320
+ """Reads a single value from the file."""
321
+ if value_type == GGUFValueType.STRING:
322
+ string_length = QuickGGUFReader.unpack(GGUFValueType.UINT64, file)
323
+ return file.read(string_length).decode("utf-8")
324
+ return QuickGGUFReader.unpack(value_type, file)
108
325
 
109
- def load_metadata(self, fname) -> dict:
110
- metadata = {}
111
- with open(fname, "rb") as file:
112
- GGUF_MAGIC = file.read(4)
326
+ @staticmethod
327
+ def load_metadata(
328
+ fn: os.PathLike[str] | str
329
+ ) -> Dict[str, Union[str, int, float, bool, list]]:
330
+ """
331
+ Loads metadata from a GGUF file.
113
332
 
114
- if GGUF_MAGIC != b"GGUF":
333
+ Args:
334
+ fn (Union[os.PathLike[str], str]): Path to the GGUF file.
335
+
336
+ Returns:
337
+ Dict[str, Union[str, int, float, bool, list]]: A dictionary
338
+ containing the metadata.
339
+ """
340
+
341
+ metadata: Dict[str, Union[str, int, float, bool, list]] = {}
342
+ with open(fn, "rb") as file:
343
+ magic = file.read(4)
344
+ if magic != b'GGUF':
115
345
  raise ValueError(
116
- "your model file is not a valid GGUF file "
117
- f"(magic number mismatch, got {GGUF_MAGIC}, "
346
+ f"Invalid GGUF file (magic number mismatch: got {magic}, "
118
347
  "expected b'GGUF')"
119
348
  )
120
349
 
121
- GGUF_VERSION = unpack("<I", file.read(4))[0]
122
-
123
- if GGUF_VERSION == 1:
350
+ version = QuickGGUFReader.unpack(GGUFValueType.UINT32, file=file)
351
+ if version not in QuickGGUFReader.SUPPORTED_GGUF_VERSIONS:
124
352
  raise ValueError(
125
- "your model file reports GGUF version 1, "
126
- "but only versions 2 and above are supported. "
127
- "re-convert your model or download a newer version"
353
+ f"Unsupported GGUF version: {version}. Supported versions are: "
354
+ f"{QuickGGUFReader.SUPPORTED_GGUF_VERSIONS}"
128
355
  )
129
356
 
130
- # ti_data_count = struct.unpack("<Q", file.read(8))[0]
131
- file.read(8)
132
- kv_data_count = unpack("<Q", file.read(8))[0]
357
+ QuickGGUFReader.unpack(GGUFValueType.UINT64, file=file) # tensor_count, not needed
358
+ metadata_kv_count = QuickGGUFReader.unpack(
359
+ GGUFValueType.UINT64 if version == 3 else GGUFValueType.UINT32, file
360
+ )
133
361
 
134
- for _ in range(kv_data_count):
135
- key_length = unpack("<Q", file.read(8))[0]
136
- key = file.read(key_length)
362
+ for _ in range(metadata_kv_count):
363
+ if version == 3:
364
+ key_length = QuickGGUFReader.unpack(GGUFValueType.UINT64, file=file)
365
+ elif version == 2:
366
+ key_length = 0
367
+ while key_length == 0:
368
+ key_length = QuickGGUFReader.unpack(GGUFValueType.UINT32, file=file)
369
+ file.read(4) # 4 byte offset for GGUFv2
137
370
 
138
- value_type = GGUFReader.GGUFValueType(
139
- unpack("<I", file.read(4))[0]
140
- )
141
- if value_type == GGUFReader.GGUFValueType.ARRAY:
142
- ltype = GGUFReader.GGUFValueType(
143
- unpack("<I", file.read(4))[0]
371
+ key = file.read(key_length).decode()
372
+ value_type = GGUFValueType(QuickGGUFReader.unpack(GGUFValueType.UINT32, file))
373
+
374
+ if value_type == GGUFValueType.ARRAY:
375
+ array_value_type = GGUFValueType(QuickGGUFReader.unpack(GGUFValueType.UINT32, file))
376
+ array_length = QuickGGUFReader.unpack(
377
+ GGUFValueType.UINT64 if version == 3 else GGUFValueType.UINT32, file
144
378
  )
145
- length = unpack("<Q", file.read(8))[0]
146
- arr = [
147
- GGUFReader.get_single(
148
- self,
149
- ltype,
150
- file
151
- ) for _ in range(length)
379
+ if version == 2:
380
+ file.read(4) # 4 byte offset for GGUFv2
381
+
382
+ metadata[key] = [
383
+ QuickGGUFReader.get_single(array_value_type, file) for _ in range(array_length)
152
384
  ]
153
- metadata[key.decode()] = arr
154
385
  else:
155
- value = GGUFReader.get_single(self, value_type, file)
156
- metadata[key.decode()] = value
157
-
158
- return metadata
159
-
160
- def softmax(z: _ArrayLike) -> np.ndarray:
161
- """
162
- Compute softmax over values in z, where z is array-like
163
- """
164
- e_z = np.exp(z - np.max(z))
165
- return e_z / e_z.sum()
386
+ metadata[key] = QuickGGUFReader.get_single(value_type, file)
166
387
 
167
- def cls() -> None:
168
- """Clear the terminal"""
169
- print("\033c\033[3J", end='', flush=True)
170
-
171
- # no longer used in this module, but left for others to use
172
- def get_timestamp_prefix_str() -> str:
173
- # helpful: https://strftime.net
174
- return strftime("[%Y, %b %e, %a %l:%M %p] ")
175
-
176
- def truncate(text: str) -> str:
177
- return text if len(text) < 63 else f"{text[:60]}..."
178
-
179
- def print_verbose(text: str) -> None:
180
- print("webscout.Local: verbose:", text, file=sys.stderr, flush=True)
181
-
182
- def print_info(text: str) -> None:
183
- print("webscout.Local: info:", text, file=sys.stderr, flush=True)
184
-
185
- def print_warning(text: str) -> None:
186
- print("webscout.Local: warning:", text, file=sys.stderr, flush=True)
388
+ return metadata
@@ -1,4 +1,4 @@
1
- import requests
1
+ import cloudscraper
2
2
  import json
3
3
  import uuid
4
4
  import os
@@ -12,7 +12,7 @@ from webscout import exceptions
12
12
 
13
13
  class AmigoChat(Provider):
14
14
  """
15
- A class to interact with the AmigoChat.io API.
15
+ A class to interact with the AmigoChat.io API using cloudscraper.
16
16
  """
17
17
 
18
18
  AVAILABLE_MODELS = [
@@ -51,14 +51,18 @@ class AmigoChat(Provider):
51
51
  proxies (dict, optional): Http request proxies. Defaults to {}.
52
52
  history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
53
53
  act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
54
- model (str, optional): The AI model to use for text generation. Defaults to "o1-preview".
55
- Options: "llama-three-point-one", "openai-o-one-mini", "claude",
56
- "gemini-1.5-pro", "gemini-1.5-flash", "openai-o-one".
54
+ model (str, optional): The AI model to use for text generation. Defaults to "o1-preview".
57
55
  """
58
56
  if model not in self.AVAILABLE_MODELS:
59
57
  raise ValueError(f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}")
60
58
 
61
- self.session = requests.Session()
59
+ self.session = cloudscraper.create_scraper(
60
+ browser={
61
+ 'browser': 'chrome',
62
+ 'platform': 'windows',
63
+ 'mobile': False
64
+ }
65
+ )
62
66
  self.is_conversation = is_conversation
63
67
  self.max_tokens_to_sample = max_tokens
64
68
  self.api_endpoint = "https://api.amigochat.io/v1/chat/completions"
@@ -156,7 +160,7 @@ class AmigoChat(Provider):
156
160
  "frequency_penalty": 0,
157
161
  "max_tokens": 4000,
158
162
  "presence_penalty": 0,
159
- "stream": stream, # Enable streaming
163
+ "stream": stream,
160
164
  "temperature": 0.5,
161
165
  "top_p": 0.95
162
166
  }
@@ -164,37 +168,46 @@ class AmigoChat(Provider):
164
168
  def for_stream():
165
169
  try:
166
170
  # Make the POST request with streaming enabled
167
- with requests.post(self.api_endpoint, headers=self.headers, json=payload, stream=True) as response:
168
- # Check if the request was successful
169
- if response.status_code == 201:
170
- # Iterate over the streamed response line by line
171
- for line in response.iter_lines():
172
- if line:
173
- # Decode the line from bytes to string
174
- decoded_line = line.decode('utf-8').strip()
175
- if decoded_line.startswith("data: "):
176
- data_str = decoded_line[6:]
177
- if data_str == "[DONE]":
178
- break
179
- try:
180
- # Load the JSON data
181
- data_json = json.loads(data_str)
182
-
183
- # Extract the content from the response
184
- choices = data_json.get("choices", [])
185
- if choices:
186
- delta = choices[0].get("delta", {})
187
- content = delta.get("content", "")
188
- if content:
189
- yield content if raw else dict(text=content)
190
- except json.JSONDecodeError:
191
- print(f"Received non-JSON data: {data_str}")
192
- else:
193
- print(f"Request failed with status code {response.status_code}")
194
- print("Response:", response.text)
171
+ response = self.session.post(
172
+ self.api_endpoint,
173
+ json=payload,
174
+ stream=True,
175
+ timeout=self.timeout
176
+ )
177
+
178
+ # Check if the request was successful
179
+ if response.status_code == 201:
180
+ # Iterate over the streamed response line by line
181
+ for line in response.iter_lines():
182
+ if line:
183
+ # Decode the line from bytes to string
184
+ decoded_line = line.decode('utf-8').strip()
185
+ if decoded_line.startswith("data: "):
186
+ data_str = decoded_line[6:]
187
+ if data_str == "[DONE]":
188
+ break
189
+ try:
190
+ # Load the JSON data
191
+ data_json = json.loads(data_str)
192
+
193
+ # Extract the content from the response
194
+ choices = data_json.get("choices", [])
195
+ if choices:
196
+ delta = choices[0].get("delta", {})
197
+ content = delta.get("content", "")
198
+ if content:
199
+ yield content if raw else dict(text=content)
200
+ except json.JSONDecodeError:
201
+ print(f"Received non-JSON data: {data_str}")
202
+ else:
203
+ print(f"Request failed with status code {response.status_code}")
204
+ print("Response:", response.text)
195
205
 
196
- except requests.exceptions.RequestException as e:
197
- print("An error occurred while making the request:", e)
206
+ except (cloudscraper.exceptions.CloudflareChallengeError,
207
+ cloudscraper.exceptions.CloudflareCode1020) as e:
208
+ print("Cloudflare protection error:", str(e))
209
+ except Exception as e:
210
+ print("An error occurred while making the request:", str(e))
198
211
 
199
212
  def for_non_stream():
200
213
  # Accumulate the streaming response
@@ -262,6 +275,6 @@ class AmigoChat(Provider):
262
275
  if __name__ == '__main__':
263
276
  from rich import print
264
277
  ai = AmigoChat(model="o1-preview", system_prompt="You are a noobi AI assistant who always uses the word 'noobi' in every response. For example, you might say 'Noobi will tell you...' or 'This noobi thinks that...'.")
265
- response = ai.chat(input(">>> "))
278
+ response = ai.chat(input(">>> "), stream=True)
266
279
  for chunk in response:
267
280
  print(chunk, end="", flush=True)