webscout 8.2.6__py3-none-any.whl → 8.2.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of webscout might be problematic. Click here for more details.

Files changed (292) hide show
  1. webscout/AIutel.py +97 -87
  2. webscout/version.py +1 -1
  3. {webscout-8.2.6.dist-info → webscout-8.2.7.dist-info}/METADATA +2 -15
  4. webscout-8.2.7.dist-info/RECORD +26 -0
  5. {webscout-8.2.6.dist-info → webscout-8.2.7.dist-info}/WHEEL +1 -1
  6. webscout-8.2.7.dist-info/entry_points.txt +3 -0
  7. webscout-8.2.7.dist-info/top_level.txt +1 -0
  8. webscout/Extra/GitToolkit/__init__.py +0 -10
  9. webscout/Extra/GitToolkit/gitapi/__init__.py +0 -12
  10. webscout/Extra/GitToolkit/gitapi/repository.py +0 -195
  11. webscout/Extra/GitToolkit/gitapi/user.py +0 -96
  12. webscout/Extra/GitToolkit/gitapi/utils.py +0 -62
  13. webscout/Extra/YTToolkit/YTdownloader.py +0 -957
  14. webscout/Extra/YTToolkit/__init__.py +0 -3
  15. webscout/Extra/YTToolkit/transcriber.py +0 -476
  16. webscout/Extra/YTToolkit/ytapi/__init__.py +0 -6
  17. webscout/Extra/YTToolkit/ytapi/channel.py +0 -307
  18. webscout/Extra/YTToolkit/ytapi/errors.py +0 -13
  19. webscout/Extra/YTToolkit/ytapi/extras.py +0 -45
  20. webscout/Extra/YTToolkit/ytapi/https.py +0 -88
  21. webscout/Extra/YTToolkit/ytapi/patterns.py +0 -61
  22. webscout/Extra/YTToolkit/ytapi/playlist.py +0 -59
  23. webscout/Extra/YTToolkit/ytapi/pool.py +0 -8
  24. webscout/Extra/YTToolkit/ytapi/query.py +0 -40
  25. webscout/Extra/YTToolkit/ytapi/stream.py +0 -63
  26. webscout/Extra/YTToolkit/ytapi/utils.py +0 -62
  27. webscout/Extra/YTToolkit/ytapi/video.py +0 -232
  28. webscout/Extra/__init__.py +0 -7
  29. webscout/Extra/autocoder/__init__.py +0 -9
  30. webscout/Extra/autocoder/autocoder.py +0 -910
  31. webscout/Extra/autocoder/autocoder_utiles.py +0 -332
  32. webscout/Extra/gguf.py +0 -684
  33. webscout/Extra/tempmail/__init__.py +0 -28
  34. webscout/Extra/tempmail/async_utils.py +0 -141
  35. webscout/Extra/tempmail/base.py +0 -161
  36. webscout/Extra/tempmail/cli.py +0 -187
  37. webscout/Extra/tempmail/emailnator.py +0 -84
  38. webscout/Extra/tempmail/mail_tm.py +0 -361
  39. webscout/Extra/tempmail/temp_mail_io.py +0 -292
  40. webscout/Extra/weather.py +0 -194
  41. webscout/Extra/weather_ascii.py +0 -76
  42. webscout/Litlogger/__init__.py +0 -67
  43. webscout/Litlogger/core/__init__.py +0 -6
  44. webscout/Litlogger/core/level.py +0 -23
  45. webscout/Litlogger/core/logger.py +0 -165
  46. webscout/Litlogger/handlers/__init__.py +0 -12
  47. webscout/Litlogger/handlers/console.py +0 -33
  48. webscout/Litlogger/handlers/file.py +0 -143
  49. webscout/Litlogger/handlers/network.py +0 -173
  50. webscout/Litlogger/styles/__init__.py +0 -7
  51. webscout/Litlogger/styles/colors.py +0 -249
  52. webscout/Litlogger/styles/formats.py +0 -458
  53. webscout/Litlogger/styles/text.py +0 -87
  54. webscout/Litlogger/utils/__init__.py +0 -6
  55. webscout/Litlogger/utils/detectors.py +0 -153
  56. webscout/Litlogger/utils/formatters.py +0 -200
  57. webscout/Provider/AI21.py +0 -177
  58. webscout/Provider/AISEARCH/DeepFind.py +0 -250
  59. webscout/Provider/AISEARCH/ISou.py +0 -256
  60. webscout/Provider/AISEARCH/Perplexity.py +0 -359
  61. webscout/Provider/AISEARCH/__init__.py +0 -10
  62. webscout/Provider/AISEARCH/felo_search.py +0 -228
  63. webscout/Provider/AISEARCH/genspark_search.py +0 -208
  64. webscout/Provider/AISEARCH/hika_search.py +0 -198
  65. webscout/Provider/AISEARCH/iask_search.py +0 -436
  66. webscout/Provider/AISEARCH/monica_search.py +0 -246
  67. webscout/Provider/AISEARCH/scira_search.py +0 -322
  68. webscout/Provider/AISEARCH/webpilotai_search.py +0 -281
  69. webscout/Provider/Aitopia.py +0 -316
  70. webscout/Provider/AllenAI.py +0 -447
  71. webscout/Provider/Andi.py +0 -228
  72. webscout/Provider/Blackboxai.py +0 -229
  73. webscout/Provider/ChatGPTClone.py +0 -237
  74. webscout/Provider/ChatGPTGratis.py +0 -194
  75. webscout/Provider/ChatSandbox.py +0 -342
  76. webscout/Provider/Cloudflare.py +0 -325
  77. webscout/Provider/Cohere.py +0 -208
  78. webscout/Provider/Deepinfra.py +0 -338
  79. webscout/Provider/ElectronHub.py +0 -773
  80. webscout/Provider/ExaAI.py +0 -261
  81. webscout/Provider/ExaChat.py +0 -358
  82. webscout/Provider/Free2GPT.py +0 -241
  83. webscout/Provider/GPTWeb.py +0 -249
  84. webscout/Provider/Gemini.py +0 -169
  85. webscout/Provider/GithubChat.py +0 -370
  86. webscout/Provider/GizAI.py +0 -285
  87. webscout/Provider/Glider.py +0 -222
  88. webscout/Provider/Groq.py +0 -801
  89. webscout/Provider/HF_space/__init__.py +0 -0
  90. webscout/Provider/HF_space/qwen_qwen2.py +0 -206
  91. webscout/Provider/HeckAI.py +0 -257
  92. webscout/Provider/HuggingFaceChat.py +0 -469
  93. webscout/Provider/Hunyuan.py +0 -283
  94. webscout/Provider/Jadve.py +0 -291
  95. webscout/Provider/Koboldai.py +0 -381
  96. webscout/Provider/LambdaChat.py +0 -411
  97. webscout/Provider/Llama3.py +0 -259
  98. webscout/Provider/MCPCore.py +0 -315
  99. webscout/Provider/Marcus.py +0 -206
  100. webscout/Provider/Nemotron.py +0 -218
  101. webscout/Provider/Netwrck.py +0 -270
  102. webscout/Provider/OLLAMA.py +0 -396
  103. webscout/Provider/OPENAI/__init__.py +0 -28
  104. webscout/Provider/OPENAI/ai4chat.py +0 -286
  105. webscout/Provider/OPENAI/base.py +0 -46
  106. webscout/Provider/OPENAI/c4ai.py +0 -367
  107. webscout/Provider/OPENAI/chatgpt.py +0 -549
  108. webscout/Provider/OPENAI/chatgptclone.py +0 -481
  109. webscout/Provider/OPENAI/deepinfra.py +0 -309
  110. webscout/Provider/OPENAI/e2b.py +0 -1350
  111. webscout/Provider/OPENAI/exaai.py +0 -404
  112. webscout/Provider/OPENAI/exachat.py +0 -437
  113. webscout/Provider/OPENAI/freeaichat.py +0 -352
  114. webscout/Provider/OPENAI/glider.py +0 -316
  115. webscout/Provider/OPENAI/groq.py +0 -354
  116. webscout/Provider/OPENAI/heckai.py +0 -341
  117. webscout/Provider/OPENAI/llmchatco.py +0 -327
  118. webscout/Provider/OPENAI/mcpcore.py +0 -376
  119. webscout/Provider/OPENAI/multichat.py +0 -368
  120. webscout/Provider/OPENAI/netwrck.py +0 -350
  121. webscout/Provider/OPENAI/opkfc.py +0 -488
  122. webscout/Provider/OPENAI/scirachat.py +0 -462
  123. webscout/Provider/OPENAI/sonus.py +0 -294
  124. webscout/Provider/OPENAI/standardinput.py +0 -425
  125. webscout/Provider/OPENAI/textpollinations.py +0 -329
  126. webscout/Provider/OPENAI/toolbaz.py +0 -406
  127. webscout/Provider/OPENAI/typegpt.py +0 -346
  128. webscout/Provider/OPENAI/uncovrAI.py +0 -455
  129. webscout/Provider/OPENAI/utils.py +0 -211
  130. webscout/Provider/OPENAI/venice.py +0 -413
  131. webscout/Provider/OPENAI/wisecat.py +0 -381
  132. webscout/Provider/OPENAI/writecream.py +0 -156
  133. webscout/Provider/OPENAI/x0gpt.py +0 -371
  134. webscout/Provider/OPENAI/yep.py +0 -327
  135. webscout/Provider/OpenGPT.py +0 -209
  136. webscout/Provider/Openai.py +0 -496
  137. webscout/Provider/PI.py +0 -429
  138. webscout/Provider/Perplexitylabs.py +0 -415
  139. webscout/Provider/QwenLM.py +0 -254
  140. webscout/Provider/Reka.py +0 -214
  141. webscout/Provider/StandardInput.py +0 -290
  142. webscout/Provider/TTI/AiForce/__init__.py +0 -22
  143. webscout/Provider/TTI/AiForce/async_aiforce.py +0 -224
  144. webscout/Provider/TTI/AiForce/sync_aiforce.py +0 -245
  145. webscout/Provider/TTI/FreeAIPlayground/__init__.py +0 -9
  146. webscout/Provider/TTI/FreeAIPlayground/async_freeaiplayground.py +0 -181
  147. webscout/Provider/TTI/FreeAIPlayground/sync_freeaiplayground.py +0 -180
  148. webscout/Provider/TTI/ImgSys/__init__.py +0 -23
  149. webscout/Provider/TTI/ImgSys/async_imgsys.py +0 -202
  150. webscout/Provider/TTI/ImgSys/sync_imgsys.py +0 -195
  151. webscout/Provider/TTI/MagicStudio/__init__.py +0 -2
  152. webscout/Provider/TTI/MagicStudio/async_magicstudio.py +0 -111
  153. webscout/Provider/TTI/MagicStudio/sync_magicstudio.py +0 -109
  154. webscout/Provider/TTI/Nexra/__init__.py +0 -22
  155. webscout/Provider/TTI/Nexra/async_nexra.py +0 -286
  156. webscout/Provider/TTI/Nexra/sync_nexra.py +0 -258
  157. webscout/Provider/TTI/PollinationsAI/__init__.py +0 -23
  158. webscout/Provider/TTI/PollinationsAI/async_pollinations.py +0 -311
  159. webscout/Provider/TTI/PollinationsAI/sync_pollinations.py +0 -265
  160. webscout/Provider/TTI/__init__.py +0 -12
  161. webscout/Provider/TTI/aiarta/__init__.py +0 -2
  162. webscout/Provider/TTI/aiarta/async_aiarta.py +0 -482
  163. webscout/Provider/TTI/aiarta/sync_aiarta.py +0 -440
  164. webscout/Provider/TTI/artbit/__init__.py +0 -22
  165. webscout/Provider/TTI/artbit/async_artbit.py +0 -155
  166. webscout/Provider/TTI/artbit/sync_artbit.py +0 -148
  167. webscout/Provider/TTI/fastflux/__init__.py +0 -22
  168. webscout/Provider/TTI/fastflux/async_fastflux.py +0 -261
  169. webscout/Provider/TTI/fastflux/sync_fastflux.py +0 -252
  170. webscout/Provider/TTI/huggingface/__init__.py +0 -22
  171. webscout/Provider/TTI/huggingface/async_huggingface.py +0 -199
  172. webscout/Provider/TTI/huggingface/sync_huggingface.py +0 -195
  173. webscout/Provider/TTI/piclumen/__init__.py +0 -23
  174. webscout/Provider/TTI/piclumen/async_piclumen.py +0 -268
  175. webscout/Provider/TTI/piclumen/sync_piclumen.py +0 -233
  176. webscout/Provider/TTI/pixelmuse/__init__.py +0 -4
  177. webscout/Provider/TTI/pixelmuse/async_pixelmuse.py +0 -249
  178. webscout/Provider/TTI/pixelmuse/sync_pixelmuse.py +0 -182
  179. webscout/Provider/TTI/talkai/__init__.py +0 -4
  180. webscout/Provider/TTI/talkai/async_talkai.py +0 -229
  181. webscout/Provider/TTI/talkai/sync_talkai.py +0 -207
  182. webscout/Provider/TTS/__init__.py +0 -8
  183. webscout/Provider/TTS/base.py +0 -159
  184. webscout/Provider/TTS/deepgram.py +0 -156
  185. webscout/Provider/TTS/elevenlabs.py +0 -111
  186. webscout/Provider/TTS/gesserit.py +0 -128
  187. webscout/Provider/TTS/murfai.py +0 -113
  188. webscout/Provider/TTS/parler.py +0 -111
  189. webscout/Provider/TTS/speechma.py +0 -180
  190. webscout/Provider/TTS/streamElements.py +0 -333
  191. webscout/Provider/TTS/utils.py +0 -280
  192. webscout/Provider/TeachAnything.py +0 -233
  193. webscout/Provider/TextPollinationsAI.py +0 -306
  194. webscout/Provider/TwoAI.py +0 -280
  195. webscout/Provider/TypliAI.py +0 -305
  196. webscout/Provider/Venice.py +0 -258
  197. webscout/Provider/VercelAI.py +0 -253
  198. webscout/Provider/WiseCat.py +0 -233
  199. webscout/Provider/WrDoChat.py +0 -370
  200. webscout/Provider/Writecream.py +0 -237
  201. webscout/Provider/WritingMate.py +0 -269
  202. webscout/Provider/Youchat.py +0 -330
  203. webscout/Provider/__init__.py +0 -178
  204. webscout/Provider/ai4chat.py +0 -203
  205. webscout/Provider/aimathgpt.py +0 -189
  206. webscout/Provider/akashgpt.py +0 -335
  207. webscout/Provider/asksteve.py +0 -212
  208. webscout/Provider/bagoodex.py +0 -145
  209. webscout/Provider/cerebras.py +0 -288
  210. webscout/Provider/chatglm.py +0 -215
  211. webscout/Provider/cleeai.py +0 -213
  212. webscout/Provider/copilot.py +0 -425
  213. webscout/Provider/elmo.py +0 -283
  214. webscout/Provider/freeaichat.py +0 -285
  215. webscout/Provider/geminiapi.py +0 -208
  216. webscout/Provider/geminiprorealtime.py +0 -160
  217. webscout/Provider/granite.py +0 -235
  218. webscout/Provider/hermes.py +0 -266
  219. webscout/Provider/julius.py +0 -223
  220. webscout/Provider/koala.py +0 -268
  221. webscout/Provider/learnfastai.py +0 -325
  222. webscout/Provider/llama3mitril.py +0 -215
  223. webscout/Provider/llmchat.py +0 -255
  224. webscout/Provider/llmchatco.py +0 -306
  225. webscout/Provider/meta.py +0 -798
  226. webscout/Provider/multichat.py +0 -364
  227. webscout/Provider/scira_chat.py +0 -297
  228. webscout/Provider/scnet.py +0 -243
  229. webscout/Provider/searchchat.py +0 -292
  230. webscout/Provider/sonus.py +0 -258
  231. webscout/Provider/talkai.py +0 -194
  232. webscout/Provider/toolbaz.py +0 -353
  233. webscout/Provider/turboseek.py +0 -266
  234. webscout/Provider/typefully.py +0 -330
  235. webscout/Provider/typegpt.py +0 -289
  236. webscout/Provider/uncovr.py +0 -368
  237. webscout/Provider/x0gpt.py +0 -299
  238. webscout/Provider/yep.py +0 -389
  239. webscout/litagent/__init__.py +0 -29
  240. webscout/litagent/agent.py +0 -455
  241. webscout/litagent/constants.py +0 -60
  242. webscout/litprinter/__init__.py +0 -59
  243. webscout/scout/__init__.py +0 -8
  244. webscout/scout/core/__init__.py +0 -7
  245. webscout/scout/core/crawler.py +0 -140
  246. webscout/scout/core/scout.py +0 -568
  247. webscout/scout/core/search_result.py +0 -96
  248. webscout/scout/core/text_analyzer.py +0 -63
  249. webscout/scout/core/text_utils.py +0 -277
  250. webscout/scout/core/web_analyzer.py +0 -52
  251. webscout/scout/core.py +0 -881
  252. webscout/scout/element.py +0 -460
  253. webscout/scout/parsers/__init__.py +0 -69
  254. webscout/scout/parsers/html5lib_parser.py +0 -172
  255. webscout/scout/parsers/html_parser.py +0 -236
  256. webscout/scout/parsers/lxml_parser.py +0 -178
  257. webscout/scout/utils.py +0 -37
  258. webscout/swiftcli/__init__.py +0 -95
  259. webscout/swiftcli/core/__init__.py +0 -7
  260. webscout/swiftcli/core/cli.py +0 -297
  261. webscout/swiftcli/core/context.py +0 -104
  262. webscout/swiftcli/core/group.py +0 -241
  263. webscout/swiftcli/decorators/__init__.py +0 -28
  264. webscout/swiftcli/decorators/command.py +0 -221
  265. webscout/swiftcli/decorators/options.py +0 -220
  266. webscout/swiftcli/decorators/output.py +0 -252
  267. webscout/swiftcli/exceptions.py +0 -21
  268. webscout/swiftcli/plugins/__init__.py +0 -9
  269. webscout/swiftcli/plugins/base.py +0 -135
  270. webscout/swiftcli/plugins/manager.py +0 -262
  271. webscout/swiftcli/utils/__init__.py +0 -59
  272. webscout/swiftcli/utils/formatting.py +0 -252
  273. webscout/swiftcli/utils/parsing.py +0 -267
  274. webscout/zeroart/__init__.py +0 -55
  275. webscout/zeroart/base.py +0 -60
  276. webscout/zeroart/effects.py +0 -99
  277. webscout/zeroart/fonts.py +0 -816
  278. webscout-8.2.6.dist-info/RECORD +0 -307
  279. webscout-8.2.6.dist-info/entry_points.txt +0 -3
  280. webscout-8.2.6.dist-info/top_level.txt +0 -2
  281. webstoken/__init__.py +0 -30
  282. webstoken/classifier.py +0 -189
  283. webstoken/keywords.py +0 -216
  284. webstoken/language.py +0 -128
  285. webstoken/ner.py +0 -164
  286. webstoken/normalizer.py +0 -35
  287. webstoken/processor.py +0 -77
  288. webstoken/sentiment.py +0 -206
  289. webstoken/stemmer.py +0 -73
  290. webstoken/tagger.py +0 -60
  291. webstoken/tokenizer.py +0 -158
  292. {webscout-8.2.6.dist-info → webscout-8.2.7.dist-info}/licenses/LICENSE.md +0 -0
@@ -1,288 +0,0 @@
1
-
2
- import re
3
- import curl_cffi
4
- from curl_cffi.requests import Session
5
- import json
6
- import os
7
- from typing import Any, Dict, Optional, Generator, List, Union
8
- from webscout.AIutel import Optimizers, Conversation, AwesomePrompts, sanitize_stream # Import sanitize_stream
9
- from webscout.AIbase import Provider
10
- from webscout import exceptions
11
- from webscout.litagent import LitAgent as UserAgent
12
-
13
- class Cerebras(Provider):
14
- """
15
- A class to interact with the Cerebras API using a cookie for authentication.
16
- """
17
-
18
- AVAILABLE_MODELS = [
19
- "llama3.1-8b",
20
- "llama-3.3-70b",
21
- "deepseek-r1-distill-llama-70b",
22
- "llama-4-scout-17b-16e-instruct"
23
-
24
- ]
25
-
26
- def __init__(
27
- self,
28
- is_conversation: bool = True,
29
- max_tokens: int = 2049,
30
- timeout: int = 30,
31
- intro: str = None,
32
- filepath: str = None,
33
- update_file: bool = True,
34
- proxies: dict = {},
35
- history_offset: int = 10250,
36
- act: str = None,
37
- cookie_path: str = "cookie.json",
38
- model: str = "llama3.1-8b",
39
- system_prompt: str = "You are a helpful assistant.",
40
- ):
41
- # Validate model choice
42
- if model not in self.AVAILABLE_MODELS:
43
- raise ValueError(
44
- f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}"
45
- )
46
-
47
- # Initialize basic settings first
48
- self.timeout = timeout
49
- self.model = model
50
- self.system_prompt = system_prompt
51
- self.is_conversation = is_conversation
52
- self.max_tokens_to_sample = max_tokens
53
- self.last_response = {}
54
-
55
- self.session = Session() # Initialize curl_cffi session
56
-
57
- # Get API key first
58
- try:
59
- self.api_key = self.get_demo_api_key(cookie_path)
60
- except Exception as e:
61
- raise exceptions.APIConnectionError(f"Failed to initialize Cerebras client: {e}")
62
-
63
- # Initialize optimizers
64
- self.__available_optimizers = (
65
- method
66
- for method in dir(Optimizers)
67
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
68
- )
69
-
70
- # Initialize conversation settings
71
- Conversation.intro = (
72
- AwesomePrompts().get_act(
73
- act, raise_not_found=True, default=None, case_insensitive=True
74
- )
75
- if act
76
- else None
77
- )
78
- self.conversation = Conversation(
79
- is_conversation, self.max_tokens_to_sample, filepath, update_file
80
- )
81
- self.conversation.history_offset = history_offset
82
-
83
- # Apply proxies to the session
84
- self.session.proxies = proxies
85
-
86
- # Rest of the class implementation remains the same...
87
- @staticmethod
88
- def extract_query(text: str) -> str:
89
- """Extracts the first code block from the given text."""
90
- pattern = r"```(.*?)```"
91
- matches = re.findall(pattern, text, re.DOTALL)
92
- return matches[0].strip() if matches else text.strip()
93
-
94
- @staticmethod
95
- def refiner(text: str) -> str:
96
- """Refines the input text by removing surrounding quotes."""
97
- return text.strip('"')
98
-
99
- @staticmethod
100
- def _cerebras_extractor(chunk: Union[str, Dict[str, Any]]) -> Optional[str]:
101
- """Extracts content from Cerebras stream JSON objects."""
102
- if isinstance(chunk, dict):
103
- return chunk.get("choices", [{}])[0].get("delta", {}).get("content")
104
- return None
105
-
106
- def get_demo_api_key(self, cookie_path: str) -> str: # Keep this using requests or switch to curl_cffi
107
- """Retrieves the demo API key using the provided cookie."""
108
- try:
109
- with open(cookie_path, "r") as file:
110
- cookies = {item["name"]: item["value"] for item in json.load(file)}
111
- except FileNotFoundError:
112
- raise FileNotFoundError(f"Cookie file not found at path: {cookie_path}")
113
- except json.JSONDecodeError:
114
- raise json.JSONDecodeError("Invalid JSON format in the cookie file.", "", 0)
115
-
116
- headers = {
117
- "Accept": "*/*",
118
- "Accept-Language": "en-US,en;q=0.9",
119
- "Content-Type": "application/json",
120
- "Origin": "https://inference.cerebras.ai",
121
- "Referer": "https://inference.cerebras.ai/",
122
- "user-agent": UserAgent().random(),
123
- }
124
-
125
- json_data = {
126
- "operationName": "GetMyDemoApiKey",
127
- "variables": {},
128
- "query": "query GetMyDemoApiKey {\n GetMyDemoApiKey\n}",
129
- }
130
-
131
- try:
132
- # Use the initialized curl_cffi session
133
- response = self.session.post(
134
- "https://inference.cerebras.ai/api/graphql",
135
- cookies=cookies,
136
- headers=headers,
137
- json=json_data,
138
- timeout=self.timeout,
139
- impersonate="chrome120" # Add impersonate
140
- )
141
- response.raise_for_status()
142
- api_key = response.json().get("data", {}).get("GetMyDemoApiKey")
143
- return api_key
144
- except curl_cffi.CurlError as e:
145
- raise exceptions.APIConnectionError(f"Failed to retrieve API key: {e}")
146
- except KeyError:
147
- raise exceptions.InvalidResponseError("API key not found in response.")
148
-
149
- def _make_request(self, messages: List[Dict], stream: bool = False) -> Union[Dict, Generator]:
150
- """Make a request to the Cerebras API."""
151
- headers = {
152
- "Authorization": f"Bearer {self.api_key}",
153
- "Content-Type": "application/json",
154
- "User-Agent": UserAgent().random(),
155
- }
156
-
157
- payload = {
158
- "model": self.model,
159
- "messages": messages,
160
- "stream": stream
161
- }
162
-
163
- try:
164
- # Use the initialized curl_cffi session
165
- response = self.session.post(
166
- "https://api.cerebras.ai/v1/chat/completions",
167
- headers=headers,
168
- json=payload,
169
- stream=stream,
170
- timeout=self.timeout,
171
- impersonate="chrome120" # Add impersonate
172
- )
173
- response.raise_for_status()
174
-
175
- if stream:
176
- def generate_stream():
177
- # Use sanitize_stream
178
- processed_stream = sanitize_stream(
179
- data=response.iter_content(chunk_size=None), # Pass byte iterator
180
- intro_value="data:",
181
- to_json=True, # Stream sends JSON
182
- content_extractor=self._cerebras_extractor, # Use the specific extractor
183
- yield_raw_on_error=False # Skip non-JSON lines or lines where extractor fails
184
- )
185
- for content_chunk in processed_stream:
186
- if content_chunk and isinstance(content_chunk, str):
187
- yield content_chunk # Yield the extracted text chunk
188
-
189
- return generate_stream()
190
- else:
191
- response_json = response.json()
192
- # Extract content for non-streaming response
193
- content = response_json.get("choices", [{}])[0].get("message", {}).get("content")
194
- return content if content else "" # Return empty string if not found
195
-
196
- except curl_cffi.CurlError as e:
197
- raise exceptions.APIConnectionError(f"Request failed (CurlError): {e}") from e
198
- except Exception as e: # Catch other potential errors
199
- raise exceptions.APIConnectionError(f"Request failed: {e}")
200
-
201
- def ask(
202
- self,
203
- prompt: str,
204
- stream: bool = False,
205
- raw: bool = False, # Add raw parameter for consistency
206
- optimizer: str = None,
207
- conversationally: bool = False,
208
- ) -> Union[Dict, Generator]:
209
- """Send a prompt to the model and get a response."""
210
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
211
- if optimizer:
212
- if optimizer in self.__available_optimizers:
213
- conversation_prompt = getattr(Optimizers, optimizer)(
214
- conversation_prompt if conversationally else prompt
215
- )
216
- else:
217
- raise Exception(f"Optimizer is not one of {self.__available_optimizers}")
218
-
219
- messages = [
220
- {"role": "system", "content": self.system_prompt},
221
- {"role": "user", "content": conversation_prompt}
222
- ]
223
-
224
- try:
225
- response = self._make_request(messages, stream)
226
-
227
- if stream:
228
- # Wrap the generator to yield dicts or raw strings
229
- def stream_wrapper():
230
- full_text = ""
231
- for chunk in response:
232
- full_text += chunk
233
- yield chunk if raw else {"text": chunk}
234
- # Update history after stream finishes
235
- self.last_response = {"text": full_text}
236
- self.conversation.update_chat_history(prompt, full_text)
237
- return stream_wrapper()
238
- else:
239
- # Non-streaming response is already the full text string
240
- self.last_response = {"text": response}
241
- self.conversation.update_chat_history(prompt, response)
242
- return self.last_response if not raw else response # Return dict or raw string
243
-
244
- except Exception as e:
245
- raise exceptions.FailedToGenerateResponseError(f"Error during request: {e}")
246
-
247
- def chat(
248
- self,
249
- prompt: str,
250
- stream: bool = False,
251
- optimizer: str = None,
252
- conversationally: bool = False,
253
- ) -> Union[str, Generator]:
254
- """Chat with the model."""
255
- # Ask returns a generator for stream=True, dict/str for stream=False
256
- response_gen_or_dict = self.ask(prompt, stream, raw=False, optimizer=optimizer, conversationally=conversationally)
257
-
258
- if stream:
259
- # Wrap the generator from ask() to get message text
260
- def stream_wrapper():
261
- for chunk_dict in response_gen_or_dict:
262
- yield self.get_message(chunk_dict)
263
- return stream_wrapper()
264
- else:
265
- # Non-streaming response is already a dict
266
- return self.get_message(response_gen_or_dict)
267
-
268
- def get_message(self, response: str) -> str:
269
- """Retrieves message from response."""
270
- # Updated to handle dict input from ask()
271
- assert isinstance(response, dict), "Response should be of dict data-type only for get_message"
272
- return response.get("text", "")
273
-
274
-
275
- if __name__ == "__main__":
276
- from rich import print
277
-
278
- # Example usage
279
- cerebras = Cerebras(
280
- cookie_path=r'cookies.json',
281
- model='llama3.1-8b',
282
- system_prompt="You are a helpful AI assistant."
283
- )
284
-
285
- # Test with streaming
286
- response = cerebras.chat("Hello!", stream=True)
287
- for chunk in response:
288
- print(chunk, end="", flush=True)
@@ -1,215 +0,0 @@
1
- from curl_cffi import CurlError
2
- from curl_cffi.requests import Session
3
- import json
4
- from typing import Any, Dict, Optional, Generator, List, Union
5
- import uuid
6
-
7
- from webscout.AIutel import Optimizers
8
- from webscout.AIutel import Conversation
9
- from webscout.AIutel import AwesomePrompts, sanitize_stream # Import sanitize_stream
10
- from webscout.AIbase import Provider
11
- from webscout import exceptions
12
- from webscout.litagent import LitAgent
13
-
14
- class ChatGLM(Provider):
15
- """
16
- A class to interact with the ChatGLM API.
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
- plus_model: bool = True,
31
- ):
32
- """Initializes the ChatGLM API client."""
33
- self.session = Session() # Use curl_cffi Session
34
- self.is_conversation = is_conversation
35
- self.max_tokens_to_sample = max_tokens
36
- self.api_endpoint = "https://chatglm.cn/chatglm/mainchat-api/guest/stream"
37
- self.stream_chunk_size = 64
38
- self.timeout = timeout
39
- self.last_response = {}
40
- self.plus_model = plus_model
41
- self.headers = {
42
- 'Accept-Language': 'en-US,en;q=0.9',
43
- 'App-Name': 'chatglm',
44
- 'Authorization': 'undefined',
45
- 'Content-Type': 'application/json',
46
- 'Origin': 'https://chatglm.cn',
47
- 'User-Agent': LitAgent().random(),
48
- 'X-App-Platform': 'pc',
49
- 'X-App-Version': '0.0.1',
50
- 'X-Device-Id': '', #Will be generated each time
51
- 'Accept': 'text/event-stream',
52
- }
53
- self.__available_optimizers = (
54
- method
55
- for method in dir(Optimizers)
56
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
57
- )
58
- self.session.headers.update(self.headers)
59
- Conversation.intro = ( # type: ignore
60
- AwesomePrompts().get_act(
61
- act, raise_not_found=True, default=None, case_insensitive=True
62
- )
63
- if act
64
- else intro or Conversation.intro
65
- )
66
- self.conversation = Conversation(
67
- is_conversation, self.max_tokens_to_sample, filepath, update_file
68
- )
69
- self.conversation.history_offset = history_offset
70
- self.session.proxies = proxies # Assign proxies directly
71
-
72
- @staticmethod
73
- def _chatglm_extractor(chunk: Union[str, Dict[str, Any]]) -> Optional[str]:
74
- """Extracts content from ChatGLM stream JSON objects."""
75
- if isinstance(chunk, dict):
76
- parts = chunk.get('parts', [])
77
- if parts and isinstance(parts[0].get('content'), list) and parts[0]['content']:
78
- return parts[0]['content'][0].get('text')
79
- return None
80
-
81
- def ask(
82
- self,
83
- prompt: str,
84
- stream: bool = False,
85
- raw: bool = False,
86
- optimizer: str = None,
87
- conversationally: bool = False,
88
- ) -> Union[Dict[str, Any], Generator[Any, None, None]]:
89
- """Chat with AI
90
- Args:
91
- prompt (str): Prompt to be sent.
92
- stream (bool, optional): Flag for streaming response. Defaults to False.
93
- raw (bool, optional): Stream back raw response as received. Defaults to False.
94
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
95
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
96
- Returns:
97
- Union[Dict, Generator[Dict, None, None]]: Response generated
98
- """
99
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
100
- if optimizer:
101
- if optimizer in self.__available_optimizers:
102
- conversation_prompt = getattr(Optimizers, optimizer)(
103
- conversation_prompt if conversationally else prompt
104
- )
105
- else:
106
- raise exceptions.FailedToGenerateResponseError(
107
- f"Optimizer is not one of {self.__available_optimizers}"
108
- )
109
- device_id = str(uuid.uuid4()).replace('-', '')
110
- self.session.headers.update({'X-Device-Id': device_id})
111
- payload = {
112
- "assistant_id": "65940acff94777010aa6b796",
113
- "conversation_id": "",
114
- "meta_data": {
115
- "if_plus_model": self.plus_model,
116
- "is_test": False,
117
- "input_question_type": "xxxx",
118
- "channel": "",
119
- "draft_id": "",
120
- "quote_log_id": "",
121
- "platform": "pc",
122
- },
123
- "messages": [
124
- {
125
- "role": "user",
126
- "content": [{"type": "text", "text": conversation_prompt}],
127
- }
128
- ],
129
- }
130
-
131
- def for_stream():
132
- streaming_text = "" # Initialize outside try block
133
- last_processed_content = "" # Track the last processed content
134
- try:
135
- response = self.session.post(
136
- self.api_endpoint, json=payload, stream=True, timeout=self.timeout,
137
- impersonate="chrome120" # Add impersonate
138
- )
139
- response.raise_for_status()
140
-
141
- # Use sanitize_stream
142
- processed_stream = sanitize_stream(
143
- data=response.iter_content(chunk_size=None), # Pass byte iterator
144
- intro_value="data:",
145
- to_json=True, # Stream sends JSON
146
- content_extractor=self._chatglm_extractor, # Use the specific extractor
147
- yield_raw_on_error=False # Skip non-JSON lines or lines where extractor fails
148
- )
149
-
150
- for current_full_text in processed_stream:
151
- # current_full_text is the full text extracted by _chatglm_extractor
152
- if current_full_text and isinstance(current_full_text, str):
153
- new_text = current_full_text[len(last_processed_content):]
154
- if new_text: # Check for new content
155
- streaming_text += new_text
156
- last_processed_content = current_full_text # Update tracker
157
- yield new_text if raw else dict(text=new_text)
158
-
159
- except CurlError as e:
160
- raise exceptions.ProviderConnectionError(f"Request failed (CurlError): {e}") from e
161
- except Exception as e:
162
- raise exceptions.FailedToGenerateResponseError(f"An unexpected error occurred ({type(e).__name__}): {e}") from e
163
- finally:
164
- # Update history after stream finishes or fails
165
- if streaming_text:
166
- self.last_response.update(dict(text=streaming_text))
167
- self.conversation.update_chat_history(
168
- prompt, self.get_message(self.last_response)
169
- )
170
-
171
- def for_non_stream():
172
- for _ in for_stream():
173
- pass
174
- return self.last_response
175
- return for_stream() if stream else for_non_stream()
176
-
177
- def chat(
178
- self,
179
- prompt: str,
180
- stream: bool = False,
181
- optimizer: str = None,
182
- conversationally: bool = False,
183
- ) -> Union[str, Generator[str, None, None]]:
184
- """Generate response `str`"""
185
-
186
- def for_stream():
187
- for response in self.ask(
188
- prompt, True, optimizer=optimizer, conversationally=conversationally
189
- ):
190
- yield self.get_message(response)
191
-
192
- def for_non_stream():
193
- return self.get_message(
194
- self.ask(
195
- prompt,
196
- False,
197
- optimizer=optimizer,
198
- conversationally=conversationally,
199
- )
200
- )
201
-
202
- return for_stream() if stream else for_non_stream()
203
-
204
- def get_message(self, response: dict) -> str:
205
- """Retrieves message only from response"""
206
- assert isinstance(response, dict), "Response should be of dict data-type only"
207
- return response["text"]
208
-
209
-
210
- if __name__ == "__main__":
211
- from rich import print
212
- ai = ChatGLM()
213
- response = ai.chat(input(">>> "), stream=True)
214
- for chunk in response:
215
- print(chunk, end="", flush=True)