webscout 7.4__py3-none-any.whl → 7.6__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 (137) hide show
  1. webscout/AIauto.py +5 -53
  2. webscout/AIutel.py +8 -318
  3. webscout/DWEBS.py +460 -489
  4. webscout/Extra/YTToolkit/YTdownloader.py +14 -53
  5. webscout/Extra/YTToolkit/transcriber.py +12 -13
  6. webscout/Extra/YTToolkit/ytapi/video.py +0 -1
  7. webscout/Extra/__init__.py +0 -1
  8. webscout/Extra/autocoder/autocoder_utiles.py +0 -4
  9. webscout/Extra/autocoder/rawdog.py +13 -41
  10. webscout/Extra/gguf.py +652 -428
  11. webscout/Extra/weather.py +178 -156
  12. webscout/Extra/weather_ascii.py +70 -17
  13. webscout/Litlogger/core/logger.py +1 -2
  14. webscout/Litlogger/handlers/file.py +1 -1
  15. webscout/Litlogger/styles/formats.py +0 -2
  16. webscout/Litlogger/utils/detectors.py +0 -1
  17. webscout/Provider/AISEARCH/DeepFind.py +0 -1
  18. webscout/Provider/AISEARCH/ISou.py +1 -1
  19. webscout/Provider/AISEARCH/felo_search.py +0 -1
  20. webscout/Provider/AllenAI.py +24 -9
  21. webscout/Provider/C4ai.py +432 -0
  22. webscout/Provider/ChatGPTGratis.py +24 -56
  23. webscout/Provider/Cloudflare.py +18 -21
  24. webscout/Provider/DeepSeek.py +27 -48
  25. webscout/Provider/Deepinfra.py +129 -53
  26. webscout/Provider/Gemini.py +1 -1
  27. webscout/Provider/GithubChat.py +362 -0
  28. webscout/Provider/Glider.py +25 -8
  29. webscout/Provider/HF_space/qwen_qwen2.py +2 -2
  30. webscout/Provider/HeckAI.py +38 -5
  31. webscout/Provider/HuggingFaceChat.py +462 -0
  32. webscout/Provider/Jadve.py +20 -5
  33. webscout/Provider/Marcus.py +7 -50
  34. webscout/Provider/Netwrck.py +43 -67
  35. webscout/Provider/PI.py +4 -2
  36. webscout/Provider/Perplexitylabs.py +26 -6
  37. webscout/Provider/Phind.py +29 -3
  38. webscout/Provider/PizzaGPT.py +10 -51
  39. webscout/Provider/TTI/AiForce/async_aiforce.py +4 -37
  40. webscout/Provider/TTI/AiForce/sync_aiforce.py +41 -38
  41. webscout/Provider/TTI/FreeAIPlayground/__init__.py +9 -9
  42. webscout/Provider/TTI/FreeAIPlayground/async_freeaiplayground.py +206 -206
  43. webscout/Provider/TTI/FreeAIPlayground/sync_freeaiplayground.py +192 -192
  44. webscout/Provider/TTI/MagicStudio/__init__.py +2 -0
  45. webscout/Provider/TTI/MagicStudio/async_magicstudio.py +111 -0
  46. webscout/Provider/TTI/MagicStudio/sync_magicstudio.py +109 -0
  47. webscout/Provider/TTI/PollinationsAI/async_pollinations.py +5 -24
  48. webscout/Provider/TTI/PollinationsAI/sync_pollinations.py +2 -22
  49. webscout/Provider/TTI/__init__.py +2 -3
  50. webscout/Provider/TTI/aiarta/__init__.py +2 -0
  51. webscout/Provider/TTI/aiarta/async_aiarta.py +482 -0
  52. webscout/Provider/TTI/aiarta/sync_aiarta.py +440 -0
  53. webscout/Provider/TTI/fastflux/__init__.py +22 -0
  54. webscout/Provider/TTI/fastflux/async_fastflux.py +257 -0
  55. webscout/Provider/TTI/fastflux/sync_fastflux.py +247 -0
  56. webscout/Provider/TTS/__init__.py +2 -2
  57. webscout/Provider/TTS/deepgram.py +12 -39
  58. webscout/Provider/TTS/elevenlabs.py +14 -40
  59. webscout/Provider/TTS/gesserit.py +11 -35
  60. webscout/Provider/TTS/murfai.py +13 -39
  61. webscout/Provider/TTS/parler.py +17 -40
  62. webscout/Provider/TTS/speechma.py +180 -0
  63. webscout/Provider/TTS/streamElements.py +17 -44
  64. webscout/Provider/TextPollinationsAI.py +39 -59
  65. webscout/Provider/Venice.py +217 -200
  66. webscout/Provider/WiseCat.py +27 -5
  67. webscout/Provider/Youchat.py +63 -36
  68. webscout/Provider/__init__.py +13 -8
  69. webscout/Provider/akashgpt.py +28 -10
  70. webscout/Provider/copilot.py +416 -0
  71. webscout/Provider/flowith.py +196 -0
  72. webscout/Provider/freeaichat.py +32 -45
  73. webscout/Provider/granite.py +17 -53
  74. webscout/Provider/koala.py +20 -5
  75. webscout/Provider/llamatutor.py +7 -47
  76. webscout/Provider/llmchat.py +36 -53
  77. webscout/Provider/multichat.py +92 -98
  78. webscout/Provider/talkai.py +1 -0
  79. webscout/Provider/turboseek.py +3 -0
  80. webscout/Provider/tutorai.py +2 -0
  81. webscout/Provider/typegpt.py +154 -64
  82. webscout/Provider/x0gpt.py +3 -1
  83. webscout/Provider/yep.py +102 -20
  84. webscout/__init__.py +3 -0
  85. webscout/cli.py +4 -40
  86. webscout/conversation.py +1 -10
  87. webscout/exceptions.py +19 -9
  88. webscout/litagent/__init__.py +2 -2
  89. webscout/litagent/agent.py +351 -20
  90. webscout/litagent/constants.py +34 -5
  91. webscout/litprinter/__init__.py +0 -3
  92. webscout/models.py +181 -0
  93. webscout/optimizers.py +1 -1
  94. webscout/prompt_manager.py +2 -8
  95. webscout/scout/core/scout.py +1 -4
  96. webscout/scout/core/search_result.py +1 -1
  97. webscout/scout/core/text_utils.py +1 -1
  98. webscout/scout/core.py +2 -5
  99. webscout/scout/element.py +1 -1
  100. webscout/scout/parsers/html_parser.py +1 -1
  101. webscout/scout/utils.py +0 -1
  102. webscout/swiftcli/__init__.py +1 -3
  103. webscout/tempid.py +1 -1
  104. webscout/update_checker.py +55 -95
  105. webscout/version.py +1 -1
  106. webscout/webscout_search_async.py +1 -2
  107. webscout/yep_search.py +297 -297
  108. webscout-7.6.dist-info/LICENSE.md +146 -0
  109. {webscout-7.4.dist-info → webscout-7.6.dist-info}/METADATA +104 -514
  110. {webscout-7.4.dist-info → webscout-7.6.dist-info}/RECORD +113 -120
  111. webscout/Extra/autollama.py +0 -231
  112. webscout/Local/__init__.py +0 -10
  113. webscout/Local/_version.py +0 -3
  114. webscout/Local/formats.py +0 -747
  115. webscout/Local/model.py +0 -1368
  116. webscout/Local/samplers.py +0 -125
  117. webscout/Local/thread.py +0 -539
  118. webscout/Local/ui.py +0 -401
  119. webscout/Local/utils.py +0 -388
  120. webscout/Provider/Amigo.py +0 -274
  121. webscout/Provider/Bing.py +0 -243
  122. webscout/Provider/DiscordRocks.py +0 -253
  123. webscout/Provider/TTI/blackbox/__init__.py +0 -4
  124. webscout/Provider/TTI/blackbox/async_blackbox.py +0 -212
  125. webscout/Provider/TTI/blackbox/sync_blackbox.py +0 -199
  126. webscout/Provider/TTI/deepinfra/__init__.py +0 -4
  127. webscout/Provider/TTI/deepinfra/async_deepinfra.py +0 -227
  128. webscout/Provider/TTI/deepinfra/sync_deepinfra.py +0 -199
  129. webscout/Provider/TTI/imgninza/__init__.py +0 -4
  130. webscout/Provider/TTI/imgninza/async_ninza.py +0 -214
  131. webscout/Provider/TTI/imgninza/sync_ninza.py +0 -209
  132. webscout/Provider/TTS/voicepod.py +0 -117
  133. webscout/Provider/dgaf.py +0 -214
  134. webscout-7.4.dist-info/LICENSE.md +0 -211
  135. {webscout-7.4.dist-info → webscout-7.6.dist-info}/WHEEL +0 -0
  136. {webscout-7.4.dist-info → webscout-7.6.dist-info}/entry_points.txt +0 -0
  137. {webscout-7.4.dist-info → webscout-7.6.dist-info}/top_level.txt +0 -0
webscout/Provider/Bing.py DELETED
@@ -1,243 +0,0 @@
1
- from typing import Any, Dict
2
- import requests
3
- import json
4
- import re
5
- from webscout.AIutel import Optimizers
6
- from webscout.AIutel import Conversation
7
- from webscout.AIutel import AwesomePrompts, sanitize_stream
8
- from webscout.AIbase import Provider
9
- from webscout import exceptions
10
-
11
-
12
- class Bing(Provider):
13
- """
14
- A class to interact with the Nexra Bing Chat API.
15
- """
16
-
17
- AVAILABLE_CONVERSATION_STYLES = [
18
- "Balanced",
19
- "Creative",
20
- "Precise",
21
- ]
22
-
23
- def __init__(
24
- self,
25
- is_conversation: bool = True,
26
- max_tokens: int = 600,
27
- timeout: int = 30,
28
- intro: str = None,
29
- filepath: str = None,
30
- update_file: bool = True,
31
- proxies: dict = {},
32
- history_offset: int = 10250,
33
- act: str = None,
34
- system_prompt: str = "You are a helpful AI assistant.",
35
- conversation_style: str = "Balanced",
36
- ):
37
- """
38
- Initializes the Nexra Bing Chat API with given parameters.
39
- """
40
- if conversation_style not in self.AVAILABLE_CONVERSATION_STYLES:
41
- raise ValueError(
42
- f"Invalid conversation_style: {conversation_style}. Choose from: {self.AVAILABLE_CONVERSATION_STYLES}"
43
- )
44
-
45
- self.session = requests.Session()
46
- self.is_conversation = is_conversation
47
- self.max_tokens_to_sample = max_tokens
48
- self.api_endpoint = "https://nexra.aryahcr.cc/api/chat/complements"
49
- self.stream_chunk_size = 1024
50
-
51
- self.timeout = timeout
52
- self.last_response = {}
53
- self.system_prompt = system_prompt
54
- self.conversation_style = conversation_style
55
- self.headers = {"Content-Type": "application/json"}
56
-
57
- self.__available_optimizers = (
58
- method
59
- for method in dir(Optimizers)
60
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
61
- )
62
- self.session.headers.update(self.headers)
63
- Conversation.intro = (
64
- AwesomePrompts().get_act(
65
- act, raise_not_found=True, default=None, case_insensitive=True
66
- )
67
- if act
68
- else intro or Conversation.intro
69
- )
70
- self.conversation = Conversation(
71
- is_conversation, self.max_tokens_to_sample, filepath, update_file
72
- )
73
- self.conversation.history_offset = history_offset
74
- self.session.proxies = proxies
75
-
76
- def ask(
77
- self,
78
- prompt: str,
79
- stream: bool = False,
80
- raw: bool = False,
81
- optimizer: str = None,
82
- conversationally: bool = False,
83
- ) -> Dict[str, Any]:
84
- """Chat with AI"""
85
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
86
- if optimizer:
87
- if optimizer in self.__available_optimizers:
88
- conversation_prompt = getattr(Optimizers, optimizer)(
89
- conversation_prompt if conversationally else prompt
90
- )
91
- else:
92
- raise Exception(
93
- f"Optimizer is not one of {self.__available_optimizers}"
94
- )
95
-
96
- messages = [
97
- {"role": "system", "content": self.system_prompt},
98
- {"role": "user", "content": conversation_prompt},
99
- ]
100
-
101
- data = {
102
- "messages": messages,
103
- "conversation_style": self.conversation_style,
104
- "markdown": False,
105
- "stream": stream,
106
- "model": "Bing",
107
- }
108
-
109
- def for_stream():
110
- try:
111
- response = self.session.post(
112
- self.api_endpoint, json=data, stream=True, timeout=self.timeout
113
- )
114
- response.raise_for_status()
115
-
116
- full_response = ""
117
- tmp = None
118
- for chunk in response.iter_content(chunk_size=self.stream_chunk_size):
119
- if chunk:
120
- chk = chunk.decode()
121
- chk = chk.split(" ")
122
-
123
- for data in chk:
124
- result = None
125
-
126
- try:
127
- convert = json.loads(data)
128
- result = data
129
- tmp = None
130
- except Exception as e:
131
- if tmp is None:
132
- tmp = data
133
- else:
134
- try:
135
- convert = json.loads(tmp)
136
- result = tmp
137
- tmp = None
138
- except Exception as e:
139
- tmp = tmp + data
140
- try:
141
- convert = json.loads(tmp)
142
- result = tmp
143
- tmp = None
144
- except Exception as e:
145
- tmp = tmp
146
-
147
- if result is not None:
148
- if "code" not in result and "status" not in result:
149
- full_response += result
150
-
151
- yield result if raw else dict(text=full_response)
152
- else:
153
- raise exceptions.FailedToGenerateResponseError(result)
154
- self.last_response.update(dict(text=full_response))
155
- self.conversation.update_chat_history(
156
- prompt, self.get_message(self.last_response)
157
- )
158
- except requests.exceptions.RequestException as e:
159
- raise exceptions.FailedToGenerateResponseError(
160
- f"An error occurred: {e}"
161
- )
162
-
163
- def for_non_stream():
164
- try:
165
- response = self.session.post(
166
- self.api_endpoint,
167
- headers=self.headers,
168
- json=data,
169
- timeout=self.timeout,
170
- )
171
- response.raise_for_status()
172
-
173
- # Remove any leading non-printable characters
174
- clean_text = response.text.lstrip()
175
-
176
- # Attempt to parse the response as JSON
177
- resp = json.loads(clean_text)
178
-
179
- if "message" in resp:
180
- self.last_response.update(dict(text=resp["message"]))
181
- self.conversation.update_chat_history(
182
- prompt, self.get_message(self.last_response)
183
- )
184
- return self.last_response
185
- else:
186
- raise exceptions.FailedToGenerateResponseError(
187
- f"Unexpected response format: {clean_text}"
188
- )
189
-
190
- except json.JSONDecodeError as e:
191
- # Handle JSON decoding error, print raw response for debugging
192
- print(f"Error decoding JSON. Raw response: {response.text}")
193
- raise exceptions.FailedToGenerateResponseError(
194
- f"Failed to decode JSON response - {response.text}"
195
- ) from e
196
- except requests.exceptions.RequestException as e:
197
- raise exceptions.FailedToGenerateResponseError(
198
- f"An error occurred: {e}"
199
- )
200
-
201
- return for_stream() if stream else for_non_stream()
202
-
203
- def chat(
204
- self,
205
- prompt: str,
206
- stream: bool = False,
207
- optimizer: str = None,
208
- conversationally: bool = False,
209
- ) -> str:
210
- """Generate response `str`"""
211
-
212
- def for_stream():
213
- for response in self.ask(
214
- prompt, True, optimizer=optimizer, conversationally=conversationally
215
- ):
216
- yield self.get_message(response)
217
-
218
- def for_non_stream():
219
- return self.get_message(
220
- self.ask(
221
- prompt,
222
- False,
223
- optimizer=optimizer,
224
- conversationally=conversationally,
225
- )
226
- )
227
-
228
- return for_stream() if stream else for_non_stream()
229
-
230
- def get_message(self, response: dict) -> str:
231
- """Retrieves message only from response"""
232
- assert isinstance(
233
- response, dict
234
- ), "Response should be of dict data-type only"
235
- text = re.sub(r"<sup>.*?</sup>", "", response["text"])
236
- return text
237
-
238
- if __name__ == "__main__":
239
- from rich import print
240
- ai = Bing()
241
- response = ai.chat(input(">>> "))
242
- for chunk in response:
243
- print(chunk, end="", flush=True)
@@ -1,253 +0,0 @@
1
- from typing import Any, Dict
2
- import requests
3
- import json
4
-
5
- from webscout.AIutel import Optimizers
6
- from webscout.AIutel import Conversation
7
- from webscout.AIutel import AwesomePrompts
8
- from webscout.AIbase import Provider
9
- from webscout import exceptions
10
-
11
- class DiscordRocks(Provider):
12
- """
13
- A class to interact with the Airforce API.
14
- """
15
-
16
- AVAILABLE_MODELS = [
17
- 'claude-3-haiku-20240307', 'claude-3-sonnet-20240229', 'claude-3-5-sonnet-20240620',
18
- 'claude-3-opus-20240229', 'chatgpt-4o-latest', 'gpt-4', 'gpt-4-0613', 'gpt-4-turbo',
19
- 'gpt-4o-mini-2024-07-18', 'gpt-4o-mini', 'gpt-3.5-turbo', 'gpt-3.5-turbo-0125',
20
- 'gpt-3.5-turbo-1106', 'gpt-3.5-turbo-16k', 'gpt-3.5-turbo-0613', 'gpt-3.5-turbo-16k-0613',
21
- 'gpt-4o', 'llama-3-70b-chat', 'llama-3-70b-chat-turbo', 'llama-3-8b-chat',
22
- 'llama-3-8b-chat-turbo', 'llama-3-70b-chat-lite', 'llama-3-8b-chat-lite',
23
- 'llama-2-13b-chat', 'llama-3.1-405b-turbo', 'llama-3.1-70b-turbo', 'llama-3.1-8b-turbo',
24
- 'LlamaGuard-2-8b', 'Llama-Guard-7b', 'Meta-Llama-Guard-3-8B', 'Mixtral-8x7B-v0.1',
25
- 'Mixtral-8x7B-Instruct-v0.1', 'Mixtral-8x22B-Instruct-v0.1', 'Mistral-7B-Instruct-v0.1',
26
- 'Mistral-7B-Instruct-v0.2', 'Mistral-7B-Instruct-v0.3', 'Qwen1.5-72B-Chat',
27
- 'Qwen1.5-110B-Chat', 'Qwen2-72B-Instruct', 'gemma-2b-it', 'dbrx-instruct',
28
- 'deepseek-coder-33b-instruct', 'deepseek-llm-67b-chat', 'Nous-Hermes-2-Mixtral-8x7B-DPO',
29
- 'Nous-Hermes-2-Yi-34B', 'WizardLM-2-8x22B', 'CodeLlama-7b-Python',
30
- 'snowflake-arctic-instruct', 'SOLAR-10.7B-Instruct-v1.0', 'StripedHyena-Nous-7B',
31
- 'CodeLlama-13b-Instruct', 'MythoMax-L2-13b', 'gemma-2-9b-it', 'gemma-2-27b-it',
32
- 'gemini-1.5-flash', 'gemini-1.5-pro', 'sparkdesk', 'cosmosrp'
33
- ]
34
-
35
- def __init__(
36
- self,
37
- is_conversation: bool = True,
38
- max_tokens: int = 600,
39
- timeout: int = 30,
40
- intro: str = None,
41
- filepath: str = None,
42
- update_file: bool = True,
43
- proxies: dict = {},
44
- history_offset: int = 10250,
45
- act: str = None,
46
- system_prompt: str = "You are a helpful AI assistant.",
47
- model: str = "chatgpt-4o-latest",
48
- temperature: float = 1,
49
- top_p: float = 1,
50
- ):
51
- """
52
- Initializes the Airforce API with given parameters.
53
-
54
- Args:
55
- is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
56
- max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
57
- timeout (int, optional): Http request timeout. Defaults to 30.
58
- intro (str, optional): Conversation introductory prompt. Defaults to None.
59
- filepath (str, optional): Path to file containing conversation history. Defaults to None.
60
- update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
61
- proxies (dict, optional): Http request proxies. Defaults to {}.
62
- history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
63
- act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
64
- system_prompt (str, optional): System prompt for Airforce. Defaults to "You are a helpful AI assistant.".
65
- model (str, optional): AI model to use. Defaults to "chatgpt-4o-latest".
66
- temperature (float, optional): Temperature parameter for the model. Defaults to 1.
67
- top_p (float, optional): Top_p parameter for the model. Defaults to 1.
68
- """
69
- if model not in self.AVAILABLE_MODELS:
70
- raise ValueError(f'Error: Invalid model. Please choose from {self.AVAILABLE_MODELS}')
71
-
72
- self.session = requests.Session()
73
- self.is_conversation = is_conversation
74
- self.max_tokens_to_sample = max_tokens
75
- self.api_endpoint = "https://api.airforce/chat/completions"
76
- self.stream_chunk_size = 1024
77
- self.timeout = timeout
78
- self.last_response = {}
79
- self.system_prompt = system_prompt
80
- self.model = model
81
- self.temperature = temperature
82
- self.top_p = top_p
83
- self.headers = {
84
- 'accept': '*/*',
85
- 'accept-encoding': 'gzip, deflate, br, zstd',
86
- 'accept-language': 'en-US,en;q=0.9,en-IN;q=0.8',
87
- 'authorization': 'Bearer missing api key',
88
- 'content-type': 'application/json',
89
- 'dnt': '1',
90
- 'origin': 'https://llmplayground.net',
91
- 'referer': 'https://llmplayground.net/',
92
- 'sec-ch-ua': '"Chromium";v="128", "Not;A=Brand";v="24", "Microsoft Edge";v="128"',
93
- 'sec-ch-ua-mobile': '?0',
94
- 'sec-ch-ua-platform': '"Windows"',
95
- 'sec-fetch-dest': 'empty',
96
- 'sec-fetch-mode': 'cors',
97
- 'sec-fetch-site': 'cross-site',
98
- 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0'
99
- }
100
-
101
- self.__available_optimizers = (
102
- method
103
- for method in dir(Optimizers)
104
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
105
- )
106
- self.session.headers.update(self.headers)
107
- Conversation.intro = (
108
- AwesomePrompts().get_act(
109
- act, raise_not_found=True, default=None, case_insensitive=True
110
- )
111
- if act
112
- else intro or Conversation.intro
113
- )
114
- self.conversation = Conversation(
115
- is_conversation, self.max_tokens_to_sample, filepath, update_file
116
- )
117
- self.conversation.history_offset = history_offset
118
- self.session.proxies = proxies
119
-
120
- def ask(
121
- self,
122
- prompt: str,
123
- stream: bool = False,
124
- raw: bool = False,
125
- optimizer: str = None,
126
- conversationally: bool = False,
127
- ) -> Dict[str, Any]:
128
- """Chat with AI"""
129
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
130
- if optimizer:
131
- if optimizer in self.__available_optimizers:
132
- conversation_prompt = getattr(Optimizers, optimizer)(
133
- conversation_prompt if conversationally else prompt
134
- )
135
- else:
136
- raise Exception(
137
- f"Optimizer is not one of {self.__available_optimizers}"
138
- )
139
-
140
- # Define the payload
141
- payload = {
142
- 'messages': [{'role': 'user', 'content': conversation_prompt}],
143
- 'model': self.model,
144
- 'max_tokens': self.max_tokens_to_sample,
145
- 'temperature': self.temperature,
146
- 'top_p': self.top_p,
147
- 'stream': stream
148
- }
149
-
150
- def for_stream():
151
- try:
152
- # Send the POST request
153
- response = self.session.post(self.api_endpoint, headers=self.headers, json=payload, stream=True)
154
-
155
- # Check if the request was successful
156
- response.raise_for_status()
157
-
158
- full_content = ''
159
- for line in response.iter_lines():
160
- if line:
161
- decoded_line = line.decode('utf-8')
162
- if decoded_line.startswith('data:'):
163
- if decoded_line.strip() == 'data: [DONE]':
164
- break
165
- try:
166
- json_data = json.loads(decoded_line[5:])
167
- content = json_data['choices'][0]['delta'].get('content', '')
168
- if content:
169
- full_content += content
170
- yield content if raw else dict(text=content)
171
- except json.JSONDecodeError:
172
- print(f'Error decoding JSON: {decoded_line}')
173
- except KeyError:
174
- print(f'Unexpected JSON structure: {json_data}')
175
- self.last_response.update(dict(text=full_content))
176
- self.conversation.update_chat_history(
177
- prompt, self.get_message(self.last_response)
178
- )
179
- except requests.exceptions.RequestException as e:
180
- raise exceptions.FailedToGenerateResponseError(f'An error occurred: {e}')
181
-
182
- def for_non_stream():
183
- try:
184
- # Send the POST request
185
- response = self.session.post(self.api_endpoint, headers=self.headers, json=payload)
186
-
187
- # Check if the request was successful
188
- response.raise_for_status()
189
-
190
- resp = response.json()
191
- self.last_response.update(dict(text=resp.get("choices", [{}])[0].get('message', {}).get('content', '')))
192
- self.conversation.update_chat_history(
193
- prompt, self.get_message(self.last_response)
194
- )
195
- return self.last_response
196
- except requests.exceptions.RequestException as e:
197
- raise exceptions.FailedToGenerateResponseError(f'An error occurred: {e}')
198
-
199
- return for_stream() if stream else for_non_stream()
200
-
201
- def chat(
202
- self,
203
- prompt: str,
204
- stream: bool = False,
205
- optimizer: str = None,
206
- conversationally: bool = False,
207
- ) -> str:
208
- """Generate response `str`
209
- Args:
210
- prompt (str): Prompt to be send.
211
- stream (bool, optional): Flag for streaming response. Defaults to False.
212
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
213
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
214
- Returns:
215
- str: Response generated
216
- """
217
-
218
- def for_stream():
219
- for response in self.ask(
220
- prompt, True, optimizer=optimizer, conversationally=conversationally
221
- ):
222
- yield self.get_message(response)
223
-
224
- def for_non_stream():
225
- return self.get_message(
226
- self.ask(
227
- prompt,
228
- False,
229
- optimizer=optimizer,
230
- conversationally=conversationally,
231
- )
232
- )
233
-
234
- return for_stream() if stream else for_non_stream()
235
-
236
- def get_message(self, response: dict) -> str:
237
- """Retrieves message only from response
238
-
239
- Args:
240
- response (dict): Response generated by `self.ask`
241
-
242
- Returns:
243
- str: Message extracted
244
- """
245
- assert isinstance(response, dict), "Response should be of dict data-type only"
246
- return response["text"]
247
-
248
- if __name__ == '__main__':
249
- from rich import print
250
- ai = DiscordRocks(timeout=5000)
251
- response = ai.chat("write a poem about AI", stream=True)
252
- for chunk in response:
253
- print(chunk, end="", flush=True)
@@ -1,4 +0,0 @@
1
- from .sync_blackbox import BlackboxAIImager
2
- from .async_blackbox import AsyncBlackboxAIImager
3
-
4
- __all__ = ["BlackboxAIImager", "AsyncBlackboxAIImager"]