webscout 7.3__py3-none-any.whl → 7.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 (62) hide show
  1. webscout/Provider/AISEARCH/__init__.py +4 -3
  2. webscout/Provider/AISEARCH/genspark_search.py +208 -0
  3. webscout/Provider/AllenAI.py +282 -0
  4. webscout/Provider/C4ai.py +414 -0
  5. webscout/Provider/Cloudflare.py +18 -21
  6. webscout/Provider/DeepSeek.py +3 -32
  7. webscout/Provider/Deepinfra.py +52 -44
  8. webscout/Provider/ElectronHub.py +634 -0
  9. webscout/Provider/GithubChat.py +362 -0
  10. webscout/Provider/Glider.py +7 -41
  11. webscout/Provider/HeckAI.py +217 -0
  12. webscout/Provider/HuggingFaceChat.py +462 -0
  13. webscout/Provider/Jadve.py +49 -63
  14. webscout/Provider/Marcus.py +7 -50
  15. webscout/Provider/Netwrck.py +6 -53
  16. webscout/Provider/PI.py +106 -93
  17. webscout/Provider/Perplexitylabs.py +395 -0
  18. webscout/Provider/Phind.py +29 -3
  19. webscout/Provider/QwenLM.py +7 -61
  20. webscout/Provider/TTI/__init__.py +1 -0
  21. webscout/Provider/TTI/aiarta/__init__.py +2 -0
  22. webscout/Provider/TTI/aiarta/async_aiarta.py +482 -0
  23. webscout/Provider/TTI/aiarta/sync_aiarta.py +409 -0
  24. webscout/Provider/TTI/piclumen/__init__.py +23 -0
  25. webscout/Provider/TTI/piclumen/async_piclumen.py +268 -0
  26. webscout/Provider/TTI/piclumen/sync_piclumen.py +233 -0
  27. webscout/Provider/TextPollinationsAI.py +3 -2
  28. webscout/Provider/TwoAI.py +200 -0
  29. webscout/Provider/Venice.py +200 -0
  30. webscout/Provider/WiseCat.py +1 -18
  31. webscout/Provider/Youchat.py +1 -1
  32. webscout/Provider/__init__.py +25 -2
  33. webscout/Provider/akashgpt.py +315 -0
  34. webscout/Provider/chatglm.py +5 -5
  35. webscout/Provider/copilot.py +416 -0
  36. webscout/Provider/flowith.py +181 -0
  37. webscout/Provider/freeaichat.py +251 -221
  38. webscout/Provider/granite.py +17 -53
  39. webscout/Provider/koala.py +9 -1
  40. webscout/Provider/llamatutor.py +6 -46
  41. webscout/Provider/llmchat.py +7 -46
  42. webscout/Provider/multichat.py +29 -91
  43. webscout/Provider/yep.py +4 -24
  44. webscout/exceptions.py +19 -9
  45. webscout/update_checker.py +55 -93
  46. webscout/version.py +1 -1
  47. webscout-7.5.dist-info/LICENSE.md +146 -0
  48. {webscout-7.3.dist-info → webscout-7.5.dist-info}/METADATA +46 -172
  49. {webscout-7.3.dist-info → webscout-7.5.dist-info}/RECORD +52 -42
  50. webscout/Local/__init__.py +0 -10
  51. webscout/Local/_version.py +0 -3
  52. webscout/Local/formats.py +0 -747
  53. webscout/Local/model.py +0 -1368
  54. webscout/Local/samplers.py +0 -125
  55. webscout/Local/thread.py +0 -539
  56. webscout/Local/ui.py +0 -401
  57. webscout/Local/utils.py +0 -388
  58. webscout/Provider/dgaf.py +0 -214
  59. webscout-7.3.dist-info/LICENSE.md +0 -211
  60. {webscout-7.3.dist-info → webscout-7.5.dist-info}/WHEEL +0 -0
  61. {webscout-7.3.dist-info → webscout-7.5.dist-info}/entry_points.txt +0 -0
  62. {webscout-7.3.dist-info → webscout-7.5.dist-info}/top_level.txt +0 -0
webscout/Local/utils.py DELETED
@@ -1,388 +0,0 @@
1
- import os
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
9
- import numpy as np
10
-
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
-
28
- class _ArrayLike(Iterable):
29
- """Represents any object that can be treated as a NumPy array."""
30
- pass
31
-
32
- class _SupportsWriteAndFlush(TextIO):
33
- """Represents a file-like object supporting write and flush operations."""
34
- pass
35
-
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
69
- """
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:
91
- """
92
- Computes the softmax of an array-like input.
93
-
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.
103
- """
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
- )
197
-
198
- if hint:
199
- error_msg += f" ({hint})"
200
-
201
- raise TypeAssertionError(error_msg)
202
-
203
- class InferenceLock:
204
- """
205
- Context manager to prevent concurrent model inferences.
206
-
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",
290
- GGUFValueType.BOOL: "?",
291
- }
292
-
293
- VALUE_LENGTHS = {
294
- GGUFValueType.UINT8: 1,
295
- GGUFValueType.INT8: 1,
296
- GGUFValueType.UINT16: 2,
297
- GGUFValueType.INT16: 2,
298
- GGUFValueType.UINT32: 4,
299
- GGUFValueType.INT32: 4,
300
- GGUFValueType.FLOAT32: 4,
301
- GGUFValueType.UINT64: 8,
302
- GGUFValueType.INT64: 8,
303
- GGUFValueType.FLOAT64: 8,
304
- GGUFValueType.BOOL: 1,
305
- }
306
-
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]
314
-
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)
325
-
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.
332
-
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':
345
- raise ValueError(
346
- f"Invalid GGUF file (magic number mismatch: got {magic}, "
347
- "expected b'GGUF')"
348
- )
349
-
350
- version = QuickGGUFReader.unpack(GGUFValueType.UINT32, file=file)
351
- if version not in QuickGGUFReader.SUPPORTED_GGUF_VERSIONS:
352
- raise ValueError(
353
- f"Unsupported GGUF version: {version}. Supported versions are: "
354
- f"{QuickGGUFReader.SUPPORTED_GGUF_VERSIONS}"
355
- )
356
-
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
- )
361
-
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
370
-
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
378
- )
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)
384
- ]
385
- else:
386
- metadata[key] = QuickGGUFReader.get_single(value_type, file)
387
-
388
- return metadata
webscout/Provider/dgaf.py DELETED
@@ -1,214 +0,0 @@
1
- import requests
2
- import re
3
- import json
4
- from typing import Any, Dict, Generator, Optional
5
-
6
- from webscout.AIutel import Optimizers
7
- from webscout.AIutel import Conversation
8
- from webscout.AIutel import AwesomePrompts
9
- from webscout.AIbase import Provider
10
- from webscout import exceptions
11
- from webscout import LitAgent
12
- from webscout.Litlogger import Logger, LogFormat
13
-
14
- class DGAFAI(Provider):
15
- """
16
- A class to interact with the DGAF.ai API with logging capabilities.
17
- """
18
-
19
- def __init__(
20
- self,
21
- is_conversation: bool = True,
22
- max_tokens: int = 600,
23
- timeout: int = 30,
24
- intro: str = None,
25
- filepath: str = None,
26
- update_file: bool = True,
27
- proxies: dict = {},
28
- history_offset: int = 10250,
29
- act: str = None,
30
- system_prompt: str = "You are a helpful AI assistant.",
31
- logging: bool = False
32
- ):
33
- """Initializes the DGAFAI API client with logging support."""
34
- self.session = requests.Session()
35
- self.is_conversation = is_conversation
36
- self.max_tokens_to_sample = max_tokens
37
- self.api_endpoint = "https://www.dgaf.ai/api/chat"
38
- self.stream_chunk_size = 64
39
- self.timeout = timeout
40
- self.last_response = {}
41
- self.system_prompt = system_prompt
42
-
43
- self.headers = {
44
- "accept": "*/*",
45
- "accept-encoding": "gzip, deflate, br, zstd",
46
- "accept-language": "en-US,en;q=0.9,en-IN;q=0.8",
47
- "content-type": "application/json",
48
- "cookie": "_ga=GA1.1.1717609725.1738729535; _ga_52CD0XKYNM=GS1.1.1738729535.1.0.1738729546.0.0.0",
49
- "dnt": "1",
50
- "origin": "https://www.dgaf.ai",
51
- "referer": "https://www.dgaf.ai/?via=topaitools",
52
- "sec-ch-ua": '"Not A(Brand";v="8", "Chromium";v="132", "Microsoft Edge";v="132"',
53
- "sec-ch-ua-mobile": "?0",
54
- "sec-ch-ua-platform": '"Windows"',
55
- "sec-fetch-dest": "empty",
56
- "sec-fetch-mode": "cors",
57
- "sec-fetch-site": "same-origin",
58
- "user-agent": LitAgent().random(),
59
- }
60
- self.session.headers.update(self.headers)
61
- self.session.proxies = proxies
62
-
63
- self.__available_optimizers = (
64
- method for method in dir(Optimizers)
65
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
66
- )
67
- Conversation.intro = (
68
- AwesomePrompts().get_act(
69
- act, raise_not_found=True, default=None, case_insensitive=True
70
- )
71
- if act
72
- else intro or Conversation.intro
73
- )
74
- self.conversation = Conversation(
75
- is_conversation, self.max_tokens_to_sample, filepath, update_file
76
- )
77
- self.conversation.history_offset = history_offset
78
-
79
- # Initialize logger if enabled
80
- self.logger = Logger(
81
- name="DGAFAI",
82
- format=LogFormat.MODERN_EMOJI,
83
- ) if logging else None
84
-
85
- if self.logger:
86
- self.logger.info("DGAFAI initialized successfully")
87
-
88
- def ask(
89
- self,
90
- prompt: str,
91
- stream: bool = False,
92
- raw: bool = False,
93
- optimizer: str = None,
94
- conversationally: bool = False,
95
- ) -> Dict[str, Any] | Generator[str, None, None]:
96
- """Chat with AI.
97
-
98
- Args:
99
- prompt (str): Prompt to be sent.
100
- stream (bool, optional): Flag for streaming response. Defaults to False.
101
- raw (bool, optional): Return raw streaming response as received. Defaults to False.
102
- optimizer (str, optional): Prompt optimizer name. Defaults to None.
103
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
104
- Returns:
105
- Union[Dict, Generator[Dict, None, None]]: Generated response.
106
- """
107
- if self.logger:
108
- self.logger.debug(f"Processing ask call with prompt: {prompt[:50]}...")
109
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
110
- if optimizer:
111
- if optimizer in self.__available_optimizers:
112
- conversation_prompt = getattr(Optimizers, optimizer)(
113
- conversation_prompt if conversationally else prompt
114
- )
115
- if self.logger:
116
- self.logger.debug(f"Applied optimizer: {optimizer}")
117
- else:
118
- if self.logger:
119
- self.logger.error(f"Invalid optimizer requested: {optimizer}")
120
- raise Exception(
121
- f"Optimizer is not one of {list(self.__available_optimizers)}"
122
- )
123
-
124
- payload = {
125
- "messages": [
126
- {"role": "system", "content": self.system_prompt},
127
- {"role": "user", "content": conversation_prompt}
128
- ]
129
- }
130
-
131
- def for_stream():
132
- if self.logger:
133
- self.logger.debug("Sending streaming request to DGAF.ai API...")
134
- try:
135
- with self.session.post(self.api_endpoint, headers=self.headers, json=payload, stream=True, timeout=self.timeout) as response:
136
- response.raise_for_status() # Check for HTTP errors
137
- if self.logger:
138
- self.logger.debug(response.text)
139
- streaming_text = ""
140
- for line in response.iter_lines(decode_unicode=True):
141
- if line:
142
- match = re.search(r'0:"(.*?)"', line)
143
- if match:
144
- content = match.group(1)
145
- if content:
146
- streaming_text += content
147
- # if self.logger:
148
- # self.logger.debug(f"Received content: {content[:30]}...")
149
- yield content if raw else dict(text=content)
150
- self.last_response.update(dict(text=streaming_text))
151
- self.conversation.update_chat_history(
152
- prompt, self.get_message(self.last_response)
153
- )
154
- if self.logger:
155
- self.logger.info("Streaming response completed successfully")
156
- except requests.exceptions.RequestException as e:
157
- if self.logger:
158
- self.logger.error(f"Request error: {e}")
159
- raise exceptions.ProviderConnectionError(f"Request failed: {e}")
160
-
161
- def for_non_stream():
162
- full_response = ""
163
- for chunk in for_stream():
164
- full_response += chunk if raw else chunk['text']
165
- return {"text": full_response}
166
-
167
- return for_stream() if stream else for_non_stream()
168
-
169
- def chat(
170
- self,
171
- prompt: str,
172
- stream: bool = False,
173
- optimizer: str = None,
174
- conversationally: bool = False,
175
- ) -> str | Generator[str, None, None]:
176
- """Generate chat response as a string.
177
-
178
- Args:
179
- prompt (str): Prompt to be sent.
180
- stream (bool, optional): Flag for streaming response. Defaults to False.
181
- optimizer (str, optional): Prompt optimizer name. Defaults to None.
182
- conversationally (bool, optional): Use conversational mode when using optimizer. Defaults to False.
183
- Returns:
184
- str or Generator[str, None, None]: Generated response.
185
- """
186
- if self.logger:
187
- self.logger.debug(f"Chat method invoked with prompt: {prompt[:50]}...")
188
- def for_stream():
189
- for response in self.ask(prompt, True, optimizer=optimizer, conversationally=conversationally):
190
- yield self.get_message(response)
191
- def for_non_stream():
192
- return self.get_message(
193
- self.ask(prompt, False, optimizer=optimizer, conversationally=conversationally)
194
- )
195
- return for_stream() if stream else for_non_stream()
196
-
197
- def get_message(self, response: dict) -> str:
198
- """Retrieves message only from response.
199
-
200
- Args:
201
- response (dict): Response from the ask method.
202
- Returns:
203
- str: Extracted message.
204
- """
205
- assert isinstance(response, dict), "Response should be of dict data-type only"
206
- return response["text"].replace('\\n', '\n').replace('\\n\\n', '\n\n')
207
-
208
-
209
- if __name__ == "__main__":
210
- from rich import print
211
- ai = DGAFAI(logging=False)
212
- response = ai.chat("write a poem about AI", stream=True)
213
- for chunk in response:
214
- print(chunk, end="", flush=True)