webscout 2.9__py3-none-any.whl → 3.0__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.

@@ -1,440 +1,440 @@
1
- import time
2
- import uuid
3
- from selenium import webdriver
4
- from selenium.webdriver.chrome.options import Options
5
- from selenium.webdriver.common.by import By
6
- from selenium.webdriver.support import expected_conditions as EC
7
- from selenium.webdriver.support.ui import WebDriverWait
8
- import click
9
- import requests
10
- from requests import get
11
- from uuid import uuid4
12
- from re import findall
13
- from requests.exceptions import RequestException
14
- from curl_cffi.requests import get, RequestsError
15
- import g4f
16
- from random import randint
17
- from PIL import Image
18
- import io
19
- import re
20
- import json
21
- import yaml
22
- from ..AIutel import Optimizers
23
- from ..AIutel import Conversation
24
- from ..AIutel import AwesomePrompts, sanitize_stream
25
- from ..AIbase import Provider, AsyncProvider
26
- from Helpingai_T2 import Perplexity
27
- from webscout import exceptions
28
- from typing import Any, AsyncGenerator, Dict
29
- import logging
30
- import httpx
31
-
32
- #------------------------------------------------------BLACKBOXAI--------------------------------------------------------
33
- class BLACKBOXAI:
34
- def __init__(
35
- self,
36
- is_conversation: bool = True,
37
- max_tokens: int = 8000,
38
- timeout: int = 30,
39
- intro: str = None,
40
- filepath: str = None,
41
- update_file: bool = True,
42
- proxies: dict = {},
43
- history_offset: int = 10250,
44
- act: str = None,
45
- model: str = None,
46
- ):
47
- """Instantiates BLACKBOXAI
48
-
49
- Args:
50
- is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True
51
- max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
52
- timeout (int, optional): Http request timeout. Defaults to 30.
53
- intro (str, optional): Conversation introductory prompt. Defaults to None.
54
- filepath (str, optional): Path to file containing conversation history. Defaults to None.
55
- update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
56
- proxies (dict, optional): Http request proxies. Defaults to {}.
57
- history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
58
- act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
59
- model (str, optional): Model name. Defaults to "Phind Model".
60
- """
61
- self.session = requests.Session()
62
- self.max_tokens_to_sample = max_tokens
63
- self.is_conversation = is_conversation
64
- self.chat_endpoint = "https://www.blackbox.ai/api/chat"
65
- self.stream_chunk_size = 64
66
- self.timeout = timeout
67
- self.last_response = {}
68
- self.model = model
69
- self.previewToken: str = None
70
- self.userId: str = ""
71
- self.codeModelMode: bool = True
72
- self.id: str = ""
73
- self.agentMode: dict = {}
74
- self.trendingAgentMode: dict = {}
75
- self.isMicMode: bool = False
76
-
77
- self.headers = {
78
- "Content-Type": "application/json",
79
- "User-Agent": "",
80
- "Accept": "*/*",
81
- "Accept-Encoding": "Identity",
82
- }
83
-
84
- self.__available_optimizers = (
85
- method
86
- for method in dir(Optimizers)
87
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
88
- )
89
- self.session.headers.update(self.headers)
90
- Conversation.intro = (
91
- AwesomePrompts().get_act(
92
- act, raise_not_found=True, default=None, case_insensitive=True
93
- )
94
- if act
95
- else intro or Conversation.intro
96
- )
97
- self.conversation = Conversation(
98
- is_conversation, self.max_tokens_to_sample, filepath, update_file
99
- )
100
- self.conversation.history_offset = history_offset
101
- self.session.proxies = proxies
102
-
103
- def ask(
104
- self,
105
- prompt: str,
106
- stream: bool = False,
107
- raw: bool = False,
108
- optimizer: str = None,
109
- conversationally: bool = False,
110
- ) -> dict:
111
- """Chat with AI
112
-
113
- Args:
114
- prompt (str): Prompt to be send.
115
- stream (bool, optional): Flag for streaming response. Defaults to False.
116
- raw (bool, optional): Stream back raw response as received. Defaults to False.
117
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
118
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
119
- Returns:
120
- dict : {}
121
- ```json
122
- {
123
- "text" : "print('How may I help you today?')"
124
- }
125
- ```
126
- """
127
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
128
- if optimizer:
129
- if optimizer in self.__available_optimizers:
130
- conversation_prompt = getattr(Optimizers, optimizer)(
131
- conversation_prompt if conversationally else prompt
132
- )
133
- else:
134
- raise Exception(
135
- f"Optimizer is not one of {self.__available_optimizers}"
136
- )
137
-
138
- self.session.headers.update(self.headers)
139
- payload = {
140
- "messages": [
141
- # json.loads(prev_messages),
142
- {"content": conversation_prompt, "role": "user"}
143
- ],
144
- "id": self.id,
145
- "previewToken": self.previewToken,
146
- "userId": self.userId,
147
- "codeModelMode": self.codeModelMode,
148
- "agentMode": self.agentMode,
149
- "trendingAgentMode": self.trendingAgentMode,
150
- "isMicMode": self.isMicMode,
151
- }
152
-
153
- def for_stream():
154
- response = self.session.post(
155
- self.chat_endpoint, json=payload, stream=True, timeout=self.timeout
156
- )
157
- if (
158
- not response.ok
159
- or not response.headers.get("Content-Type")
160
- == "text/plain; charset=utf-8"
161
- ):
162
- raise Exception(
163
- f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
164
- )
165
- streaming_text = ""
166
- for value in response.iter_lines(
167
- decode_unicode=True,
168
- chunk_size=self.stream_chunk_size,
169
- delimiter="\n",
170
- ):
171
- try:
172
- if bool(value):
173
- streaming_text += value + ("\n" if stream else "")
174
-
175
- resp = dict(text=streaming_text)
176
- self.last_response.update(resp)
177
- yield value if raw else resp
178
- except json.decoder.JSONDecodeError:
179
- pass
180
- self.conversation.update_chat_history(
181
- prompt, self.get_message(self.last_response)
182
- )
183
-
184
- def for_non_stream():
185
- for _ in for_stream():
186
- pass
187
- return self.last_response
188
-
189
- return for_stream() if stream else for_non_stream()
190
-
191
- def chat(
192
- self,
193
- prompt: str,
194
- stream: bool = False,
195
- optimizer: str = None,
196
- conversationally: bool = False,
197
- ) -> str:
198
- """Generate response `str`
199
- Args:
200
- prompt (str): Prompt to be send.
201
- stream (bool, optional): Flag for streaming response. Defaults to False.
202
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
203
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
204
- Returns:
205
- str: Response generated
206
- """
207
-
208
- def for_stream():
209
- for response in self.ask(
210
- prompt, True, optimizer=optimizer, conversationally=conversationally
211
- ):
212
- yield self.get_message(response)
213
-
214
- def for_non_stream():
215
- return self.get_message(
216
- self.ask(
217
- prompt,
218
- False,
219
- optimizer=optimizer,
220
- conversationally=conversationally,
221
- )
222
- )
223
-
224
- return for_stream() if stream else for_non_stream()
225
-
226
- def get_message(self, response: dict) -> str:
227
- """Retrieves message only from response
228
-
229
- Args:
230
- response (dict): Response generated by `self.ask`
231
-
232
- Returns:
233
- str: Message extracted
234
- """
235
- assert isinstance(response, dict), "Response should be of dict data-type only"
236
- return response["text"]
237
- @staticmethod
238
- def chat_cli(prompt):
239
- """Sends a request to the BLACKBOXAI API and processes the response."""
240
- blackbox_ai = BLACKBOXAI() # Initialize a BLACKBOXAI instance
241
- response = blackbox_ai.ask(prompt) # Perform a chat with the given prompt
242
- processed_response = blackbox_ai.get_message(response) # Process the response
243
- print(processed_response)
244
- class AsyncBLACKBOXAI(AsyncProvider):
245
- def __init__(
246
- self,
247
- is_conversation: bool = True,
248
- max_tokens: int = 600,
249
- timeout: int = 30,
250
- intro: str = None,
251
- filepath: str = None,
252
- update_file: bool = True,
253
- proxies: dict = {},
254
- history_offset: int = 10250,
255
- act: str = None,
256
- model: str = None,
257
- ):
258
- """Instantiates BLACKBOXAI
259
-
260
- Args:
261
- is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True
262
- max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
263
- timeout (int, optional): Http request timeout. Defaults to 30.
264
- intro (str, optional): Conversation introductory prompt. Defaults to None.
265
- filepath (str, optional): Path to file containing conversation history. Defaults to None.
266
- update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
267
- proxies (dict, optional): Http request proxies. Defaults to {}.
268
- history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
269
- act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
270
- model (str, optional): Model name. Defaults to "Phind Model".
271
- """
272
- self.max_tokens_to_sample = max_tokens
273
- self.is_conversation = is_conversation
274
- self.chat_endpoint = "https://www.blackbox.ai/api/chat"
275
- self.stream_chunk_size = 64
276
- self.timeout = timeout
277
- self.last_response = {}
278
- self.model = model
279
- self.previewToken: str = None
280
- self.userId: str = ""
281
- self.codeModelMode: bool = True
282
- self.id: str = ""
283
- self.agentMode: dict = {}
284
- self.trendingAgentMode: dict = {}
285
- self.isMicMode: bool = False
286
-
287
- self.headers = {
288
- "Content-Type": "application/json",
289
- "User-Agent": "",
290
- "Accept": "*/*",
291
- "Accept-Encoding": "Identity",
292
- }
293
-
294
- self.__available_optimizers = (
295
- method
296
- for method in dir(Optimizers)
297
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
298
- )
299
- Conversation.intro = (
300
- AwesomePrompts().get_act(
301
- act, raise_not_found=True, default=None, case_insensitive=True
302
- )
303
- if act
304
- else intro or Conversation.intro
305
- )
306
- self.conversation = Conversation(
307
- is_conversation, self.max_tokens_to_sample, filepath, update_file
308
- )
309
- self.conversation.history_offset = history_offset
310
- self.session = httpx.AsyncClient(headers=self.headers, proxies=proxies)
311
-
312
- async def ask(
313
- self,
314
- prompt: str,
315
- stream: bool = False,
316
- raw: bool = False,
317
- optimizer: str = None,
318
- conversationally: bool = False,
319
- ) -> dict | AsyncGenerator:
320
- """Chat with AI asynchronously.
321
-
322
- Args:
323
- prompt (str): Prompt to be send.
324
- stream (bool, optional): Flag for streaming response. Defaults to False.
325
- raw (bool, optional): Stream back raw response as received. Defaults to False.
326
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
327
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
328
- Returns:
329
- dict|AsyncGenerator : ai content
330
- ```json
331
- {
332
- "text" : "print('How may I help you today?')"
333
- }
334
- ```
335
- """
336
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
337
- if optimizer:
338
- if optimizer in self.__available_optimizers:
339
- conversation_prompt = getattr(Optimizers, optimizer)(
340
- conversation_prompt if conversationally else prompt
341
- )
342
- else:
343
- raise Exception(
344
- f"Optimizer is not one of {self.__available_optimizers}"
345
- )
346
-
347
- payload = {
348
- "messages": [
349
- # json.loads(prev_messages),
350
- {"content": conversation_prompt, "role": "user"}
351
- ],
352
- "id": self.id,
353
- "previewToken": self.previewToken,
354
- "userId": self.userId,
355
- "codeModelMode": self.codeModelMode,
356
- "agentMode": self.agentMode,
357
- "trendingAgentMode": self.trendingAgentMode,
358
- "isMicMode": self.isMicMode,
359
- }
360
-
361
- async def for_stream():
362
- async with self.session.stream(
363
- "POST", self.chat_endpoint, json=payload, timeout=self.timeout
364
- ) as response:
365
- if (
366
- not response.is_success
367
- or not response.headers.get("Content-Type")
368
- == "text/plain; charset=utf-8"
369
- ):
370
- raise exceptions.FailedToGenerateResponseError(
371
- f"Failed to generate response - ({response.status_code}, {response.reason_phrase})"
372
- )
373
- streaming_text = ""
374
- async for value in response.aiter_lines():
375
- try:
376
- if bool(value):
377
- streaming_text += value + ("\n" if stream else "")
378
- resp = dict(text=streaming_text)
379
- self.last_response.update(resp)
380
- yield value if raw else resp
381
- except json.decoder.JSONDecodeError:
382
- pass
383
- self.conversation.update_chat_history(
384
- prompt, await self.get_message(self.last_response)
385
- )
386
-
387
- async def for_non_stream():
388
- async for _ in for_stream():
389
- pass
390
- return self.last_response
391
-
392
- return for_stream() if stream else await for_non_stream()
393
-
394
- async def chat(
395
- self,
396
- prompt: str,
397
- stream: bool = False,
398
- optimizer: str = None,
399
- conversationally: bool = False,
400
- ) -> str | AsyncGenerator:
401
- """Generate response `str` asynchronously.
402
- Args:
403
- prompt (str): Prompt to be send.
404
- stream (bool, optional): Flag for streaming response. Defaults to False.
405
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
406
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
407
- Returns:
408
- str|AsyncGenerator: Response generated
409
- """
410
-
411
- async def for_stream():
412
- async_ask = await self.ask(
413
- prompt, True, optimizer=optimizer, conversationally=conversationally
414
- )
415
- async for response in async_ask:
416
- yield await self.get_message(response)
417
-
418
- async def for_non_stream():
419
- return await self.get_message(
420
- await self.ask(
421
- prompt,
422
- False,
423
- optimizer=optimizer,
424
- conversationally=conversationally,
425
- )
426
- )
427
-
428
- return for_stream() if stream else await for_non_stream()
429
-
430
- async def get_message(self, response: dict) -> str:
431
- """Retrieves message only from response
432
-
433
- Args:
434
- response (dict): Response generated by `self.ask`
435
-
436
- Returns:
437
- str: Message extracted
438
- """
439
- assert isinstance(response, dict), "Response should be of dict data-type only"
1
+ import time
2
+ import uuid
3
+ from selenium import webdriver
4
+ from selenium.webdriver.chrome.options import Options
5
+ from selenium.webdriver.common.by import By
6
+ from selenium.webdriver.support import expected_conditions as EC
7
+ from selenium.webdriver.support.ui import WebDriverWait
8
+ import click
9
+ import requests
10
+ from requests import get
11
+ from uuid import uuid4
12
+ from re import findall
13
+ from requests.exceptions import RequestException
14
+ from curl_cffi.requests import get, RequestsError
15
+ import g4f
16
+ from random import randint
17
+ from PIL import Image
18
+ import io
19
+ import re
20
+ import json
21
+ import yaml
22
+ from ..AIutel import Optimizers
23
+ from ..AIutel import Conversation
24
+ from ..AIutel import AwesomePrompts, sanitize_stream
25
+ from ..AIbase import Provider, AsyncProvider
26
+ from Helpingai_T2 import Perplexity
27
+ from webscout import exceptions
28
+ from typing import Any, AsyncGenerator, Dict
29
+ import logging
30
+ import httpx
31
+
32
+ #------------------------------------------------------BLACKBOXAI--------------------------------------------------------
33
+ class BLACKBOXAI:
34
+ def __init__(
35
+ self,
36
+ is_conversation: bool = True,
37
+ max_tokens: int = 8000,
38
+ timeout: int = 30,
39
+ intro: str = None,
40
+ filepath: str = None,
41
+ update_file: bool = True,
42
+ proxies: dict = {},
43
+ history_offset: int = 10250,
44
+ act: str = None,
45
+ model: str = None,
46
+ ):
47
+ """Instantiates BLACKBOXAI
48
+
49
+ Args:
50
+ is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True
51
+ max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
52
+ timeout (int, optional): Http request timeout. Defaults to 30.
53
+ intro (str, optional): Conversation introductory prompt. Defaults to None.
54
+ filepath (str, optional): Path to file containing conversation history. Defaults to None.
55
+ update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
56
+ proxies (dict, optional): Http request proxies. Defaults to {}.
57
+ history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
58
+ act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
59
+ model (str, optional): Model name. Defaults to "Phind Model".
60
+ """
61
+ self.session = requests.Session()
62
+ self.max_tokens_to_sample = max_tokens
63
+ self.is_conversation = is_conversation
64
+ self.chat_endpoint = "https://www.blackbox.ai/api/chat"
65
+ self.stream_chunk_size = 64
66
+ self.timeout = timeout
67
+ self.last_response = {}
68
+ self.model = model
69
+ self.previewToken: str = None
70
+ self.userId: str = ""
71
+ self.codeModelMode: bool = True
72
+ self.id: str = ""
73
+ self.agentMode: dict = {}
74
+ self.trendingAgentMode: dict = {}
75
+ self.isMicMode: bool = False
76
+
77
+ self.headers = {
78
+ "Content-Type": "application/json",
79
+ "User-Agent": "",
80
+ "Accept": "*/*",
81
+ "Accept-Encoding": "Identity",
82
+ }
83
+
84
+ self.__available_optimizers = (
85
+ method
86
+ for method in dir(Optimizers)
87
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
88
+ )
89
+ self.session.headers.update(self.headers)
90
+ Conversation.intro = (
91
+ AwesomePrompts().get_act(
92
+ act, raise_not_found=True, default=None, case_insensitive=True
93
+ )
94
+ if act
95
+ else intro or Conversation.intro
96
+ )
97
+ self.conversation = Conversation(
98
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
99
+ )
100
+ self.conversation.history_offset = history_offset
101
+ self.session.proxies = proxies
102
+
103
+ def ask(
104
+ self,
105
+ prompt: str,
106
+ stream: bool = False,
107
+ raw: bool = False,
108
+ optimizer: str = None,
109
+ conversationally: bool = False,
110
+ ) -> dict:
111
+ """Chat with AI
112
+
113
+ Args:
114
+ prompt (str): Prompt to be send.
115
+ stream (bool, optional): Flag for streaming response. Defaults to False.
116
+ raw (bool, optional): Stream back raw response as received. Defaults to False.
117
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
118
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
119
+ Returns:
120
+ dict : {}
121
+ ```json
122
+ {
123
+ "text" : "print('How may I help you today?')"
124
+ }
125
+ ```
126
+ """
127
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
128
+ if optimizer:
129
+ if optimizer in self.__available_optimizers:
130
+ conversation_prompt = getattr(Optimizers, optimizer)(
131
+ conversation_prompt if conversationally else prompt
132
+ )
133
+ else:
134
+ raise Exception(
135
+ f"Optimizer is not one of {self.__available_optimizers}"
136
+ )
137
+
138
+ self.session.headers.update(self.headers)
139
+ payload = {
140
+ "messages": [
141
+ # json.loads(prev_messages),
142
+ {"content": conversation_prompt, "role": "user"}
143
+ ],
144
+ "id": self.id,
145
+ "previewToken": self.previewToken,
146
+ "userId": self.userId,
147
+ "codeModelMode": self.codeModelMode,
148
+ "agentMode": self.agentMode,
149
+ "trendingAgentMode": self.trendingAgentMode,
150
+ "isMicMode": self.isMicMode,
151
+ }
152
+
153
+ def for_stream():
154
+ response = self.session.post(
155
+ self.chat_endpoint, json=payload, stream=True, timeout=self.timeout
156
+ )
157
+ if (
158
+ not response.ok
159
+ or not response.headers.get("Content-Type")
160
+ == "text/plain; charset=utf-8"
161
+ ):
162
+ raise Exception(
163
+ f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
164
+ )
165
+ streaming_text = ""
166
+ for value in response.iter_lines(
167
+ decode_unicode=True,
168
+ chunk_size=self.stream_chunk_size,
169
+ delimiter="\n",
170
+ ):
171
+ try:
172
+ if bool(value):
173
+ streaming_text += value + ("\n" if stream else "")
174
+
175
+ resp = dict(text=streaming_text)
176
+ self.last_response.update(resp)
177
+ yield value if raw else resp
178
+ except json.decoder.JSONDecodeError:
179
+ pass
180
+ self.conversation.update_chat_history(
181
+ prompt, self.get_message(self.last_response)
182
+ )
183
+
184
+ def for_non_stream():
185
+ for _ in for_stream():
186
+ pass
187
+ return self.last_response
188
+
189
+ return for_stream() if stream else for_non_stream()
190
+
191
+ def chat(
192
+ self,
193
+ prompt: str,
194
+ stream: bool = False,
195
+ optimizer: str = None,
196
+ conversationally: bool = False,
197
+ ) -> str:
198
+ """Generate response `str`
199
+ Args:
200
+ prompt (str): Prompt to be send.
201
+ stream (bool, optional): Flag for streaming response. Defaults to False.
202
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
203
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
204
+ Returns:
205
+ str: Response generated
206
+ """
207
+
208
+ def for_stream():
209
+ for response in self.ask(
210
+ prompt, True, optimizer=optimizer, conversationally=conversationally
211
+ ):
212
+ yield self.get_message(response)
213
+
214
+ def for_non_stream():
215
+ return self.get_message(
216
+ self.ask(
217
+ prompt,
218
+ False,
219
+ optimizer=optimizer,
220
+ conversationally=conversationally,
221
+ )
222
+ )
223
+
224
+ return for_stream() if stream else for_non_stream()
225
+
226
+ def get_message(self, response: dict) -> str:
227
+ """Retrieves message only from response
228
+
229
+ Args:
230
+ response (dict): Response generated by `self.ask`
231
+
232
+ Returns:
233
+ str: Message extracted
234
+ """
235
+ assert isinstance(response, dict), "Response should be of dict data-type only"
236
+ return response["text"]
237
+ @staticmethod
238
+ def chat_cli(prompt):
239
+ """Sends a request to the BLACKBOXAI API and processes the response."""
240
+ blackbox_ai = BLACKBOXAI() # Initialize a BLACKBOXAI instance
241
+ response = blackbox_ai.ask(prompt) # Perform a chat with the given prompt
242
+ processed_response = blackbox_ai.get_message(response) # Process the response
243
+ print(processed_response)
244
+ class AsyncBLACKBOXAI(AsyncProvider):
245
+ def __init__(
246
+ self,
247
+ is_conversation: bool = True,
248
+ max_tokens: int = 600,
249
+ timeout: int = 30,
250
+ intro: str = None,
251
+ filepath: str = None,
252
+ update_file: bool = True,
253
+ proxies: dict = {},
254
+ history_offset: int = 10250,
255
+ act: str = None,
256
+ model: str = None,
257
+ ):
258
+ """Instantiates BLACKBOXAI
259
+
260
+ Args:
261
+ is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True
262
+ max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
263
+ timeout (int, optional): Http request timeout. Defaults to 30.
264
+ intro (str, optional): Conversation introductory prompt. Defaults to None.
265
+ filepath (str, optional): Path to file containing conversation history. Defaults to None.
266
+ update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
267
+ proxies (dict, optional): Http request proxies. Defaults to {}.
268
+ history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
269
+ act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
270
+ model (str, optional): Model name. Defaults to "Phind Model".
271
+ """
272
+ self.max_tokens_to_sample = max_tokens
273
+ self.is_conversation = is_conversation
274
+ self.chat_endpoint = "https://www.blackbox.ai/api/chat"
275
+ self.stream_chunk_size = 64
276
+ self.timeout = timeout
277
+ self.last_response = {}
278
+ self.model = model
279
+ self.previewToken: str = None
280
+ self.userId: str = ""
281
+ self.codeModelMode: bool = True
282
+ self.id: str = ""
283
+ self.agentMode: dict = {}
284
+ self.trendingAgentMode: dict = {}
285
+ self.isMicMode: bool = False
286
+
287
+ self.headers = {
288
+ "Content-Type": "application/json",
289
+ "User-Agent": "",
290
+ "Accept": "*/*",
291
+ "Accept-Encoding": "Identity",
292
+ }
293
+
294
+ self.__available_optimizers = (
295
+ method
296
+ for method in dir(Optimizers)
297
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
298
+ )
299
+ Conversation.intro = (
300
+ AwesomePrompts().get_act(
301
+ act, raise_not_found=True, default=None, case_insensitive=True
302
+ )
303
+ if act
304
+ else intro or Conversation.intro
305
+ )
306
+ self.conversation = Conversation(
307
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
308
+ )
309
+ self.conversation.history_offset = history_offset
310
+ self.session = httpx.AsyncClient(headers=self.headers, proxies=proxies)
311
+
312
+ async def ask(
313
+ self,
314
+ prompt: str,
315
+ stream: bool = False,
316
+ raw: bool = False,
317
+ optimizer: str = None,
318
+ conversationally: bool = False,
319
+ ) -> dict | AsyncGenerator:
320
+ """Chat with AI asynchronously.
321
+
322
+ Args:
323
+ prompt (str): Prompt to be send.
324
+ stream (bool, optional): Flag for streaming response. Defaults to False.
325
+ raw (bool, optional): Stream back raw response as received. Defaults to False.
326
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
327
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
328
+ Returns:
329
+ dict|AsyncGenerator : ai content
330
+ ```json
331
+ {
332
+ "text" : "print('How may I help you today?')"
333
+ }
334
+ ```
335
+ """
336
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
337
+ if optimizer:
338
+ if optimizer in self.__available_optimizers:
339
+ conversation_prompt = getattr(Optimizers, optimizer)(
340
+ conversation_prompt if conversationally else prompt
341
+ )
342
+ else:
343
+ raise Exception(
344
+ f"Optimizer is not one of {self.__available_optimizers}"
345
+ )
346
+
347
+ payload = {
348
+ "messages": [
349
+ # json.loads(prev_messages),
350
+ {"content": conversation_prompt, "role": "user"}
351
+ ],
352
+ "id": self.id,
353
+ "previewToken": self.previewToken,
354
+ "userId": self.userId,
355
+ "codeModelMode": self.codeModelMode,
356
+ "agentMode": self.agentMode,
357
+ "trendingAgentMode": self.trendingAgentMode,
358
+ "isMicMode": self.isMicMode,
359
+ }
360
+
361
+ async def for_stream():
362
+ async with self.session.stream(
363
+ "POST", self.chat_endpoint, json=payload, timeout=self.timeout
364
+ ) as response:
365
+ if (
366
+ not response.is_success
367
+ or not response.headers.get("Content-Type")
368
+ == "text/plain; charset=utf-8"
369
+ ):
370
+ raise exceptions.FailedToGenerateResponseError(
371
+ f"Failed to generate response - ({response.status_code}, {response.reason_phrase})"
372
+ )
373
+ streaming_text = ""
374
+ async for value in response.aiter_lines():
375
+ try:
376
+ if bool(value):
377
+ streaming_text += value + ("\n" if stream else "")
378
+ resp = dict(text=streaming_text)
379
+ self.last_response.update(resp)
380
+ yield value if raw else resp
381
+ except json.decoder.JSONDecodeError:
382
+ pass
383
+ self.conversation.update_chat_history(
384
+ prompt, await self.get_message(self.last_response)
385
+ )
386
+
387
+ async def for_non_stream():
388
+ async for _ in for_stream():
389
+ pass
390
+ return self.last_response
391
+
392
+ return for_stream() if stream else await for_non_stream()
393
+
394
+ async def chat(
395
+ self,
396
+ prompt: str,
397
+ stream: bool = False,
398
+ optimizer: str = None,
399
+ conversationally: bool = False,
400
+ ) -> str | AsyncGenerator:
401
+ """Generate response `str` asynchronously.
402
+ Args:
403
+ prompt (str): Prompt to be send.
404
+ stream (bool, optional): Flag for streaming response. Defaults to False.
405
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
406
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
407
+ Returns:
408
+ str|AsyncGenerator: Response generated
409
+ """
410
+
411
+ async def for_stream():
412
+ async_ask = await self.ask(
413
+ prompt, True, optimizer=optimizer, conversationally=conversationally
414
+ )
415
+ async for response in async_ask:
416
+ yield await self.get_message(response)
417
+
418
+ async def for_non_stream():
419
+ return await self.get_message(
420
+ await self.ask(
421
+ prompt,
422
+ False,
423
+ optimizer=optimizer,
424
+ conversationally=conversationally,
425
+ )
426
+ )
427
+
428
+ return for_stream() if stream else await for_non_stream()
429
+
430
+ async def get_message(self, response: dict) -> str:
431
+ """Retrieves message only from response
432
+
433
+ Args:
434
+ response (dict): Response generated by `self.ask`
435
+
436
+ Returns:
437
+ str: Message extracted
438
+ """
439
+ assert isinstance(response, dict), "Response should be of dict data-type only"
440
440
  return response["text"]