webscout 7.2__py3-none-any.whl → 7.4__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 (47) hide show
  1. webscout/Bard.py +2 -2
  2. webscout/Litlogger/core/level.py +3 -0
  3. webscout/Litlogger/core/logger.py +101 -58
  4. webscout/Litlogger/handlers/console.py +14 -31
  5. webscout/Litlogger/handlers/network.py +16 -17
  6. webscout/Litlogger/styles/colors.py +81 -63
  7. webscout/Litlogger/styles/formats.py +163 -80
  8. webscout/Provider/AISEARCH/ISou.py +277 -0
  9. webscout/Provider/AISEARCH/__init__.py +4 -2
  10. webscout/Provider/AISEARCH/genspark_search.py +208 -0
  11. webscout/Provider/AllenAI.py +282 -0
  12. webscout/Provider/Deepinfra.py +52 -37
  13. webscout/Provider/ElectronHub.py +634 -0
  14. webscout/Provider/Glider.py +7 -41
  15. webscout/Provider/HeckAI.py +200 -0
  16. webscout/Provider/Jadve.py +49 -63
  17. webscout/Provider/PI.py +106 -93
  18. webscout/Provider/Perplexitylabs.py +395 -0
  19. webscout/Provider/QwenLM.py +7 -61
  20. webscout/Provider/TTI/FreeAIPlayground/__init__.py +9 -0
  21. webscout/Provider/TTI/FreeAIPlayground/async_freeaiplayground.py +206 -0
  22. webscout/Provider/TTI/FreeAIPlayground/sync_freeaiplayground.py +192 -0
  23. webscout/Provider/TTI/__init__.py +3 -1
  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 +28 -6
  28. webscout/Provider/TwoAI.py +200 -0
  29. webscout/Provider/Venice.py +200 -0
  30. webscout/Provider/WiseCat.py +1 -18
  31. webscout/Provider/__init__.py +14 -0
  32. webscout/Provider/akashgpt.py +312 -0
  33. webscout/Provider/chatglm.py +5 -5
  34. webscout/Provider/freeaichat.py +251 -0
  35. webscout/Provider/koala.py +9 -1
  36. webscout/Provider/yep.py +5 -25
  37. webscout/__init__.py +1 -0
  38. webscout/version.py +1 -1
  39. webscout/webscout_search.py +82 -2
  40. webscout/webscout_search_async.py +58 -1
  41. webscout/yep_search.py +297 -0
  42. {webscout-7.2.dist-info → webscout-7.4.dist-info}/METADATA +99 -65
  43. {webscout-7.2.dist-info → webscout-7.4.dist-info}/RECORD +47 -30
  44. {webscout-7.2.dist-info → webscout-7.4.dist-info}/WHEEL +1 -1
  45. {webscout-7.2.dist-info → webscout-7.4.dist-info}/LICENSE.md +0 -0
  46. {webscout-7.2.dist-info → webscout-7.4.dist-info}/entry_points.txt +0 -0
  47. {webscout-7.2.dist-info → webscout-7.4.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,312 @@
1
+ from typing import Any, Dict, Generator
2
+ from uuid import uuid4
3
+ import requests
4
+ import re
5
+ import json
6
+ import time
7
+
8
+ from webscout.AIutel import Optimizers
9
+ from webscout.AIutel import Conversation
10
+ from webscout.AIutel import AwesomePrompts
11
+ from webscout.AIbase import Provider
12
+ from webscout import exceptions
13
+ from webscout.litagent import LitAgent
14
+
15
+ class AkashGPT(Provider):
16
+ """
17
+ A class to interact with the Akash Network Chat API.
18
+
19
+ Attributes:
20
+ system_prompt (str): The system prompt to define the assistant's role.
21
+ model (str): The model to use for generation.
22
+
23
+ Examples:
24
+ >>> from webscout.Provider.akashgpt import AkashGPT
25
+ >>> ai = AkashGPT()
26
+ >>> response = ai.chat("What's the weather today?")
27
+ >>> print(response)
28
+ 'The weather today depends on your location. I don't have access to real-time weather data.'
29
+ """
30
+
31
+ AVAILABLE_MODELS = [
32
+ "Meta-Llama-3-3-70B-Instruct",
33
+ "DeepSeek-R1",
34
+ "Meta-Llama-3-1-405B-Instruct-FP8",
35
+ "Meta-Llama-3-2-3B-Instruct",
36
+ "Meta-Llama-3-1-8B-Instruct-FP8",
37
+ "mistral",
38
+ "nous-hermes2-mixtral",
39
+ "dolphin-mixtral"
40
+ ]
41
+
42
+ def __init__(
43
+ self,
44
+ is_conversation: bool = True,
45
+ max_tokens: int = 600,
46
+ timeout: int = 30,
47
+ intro: str = None,
48
+ filepath: str = None,
49
+ update_file: bool = True,
50
+ proxies: dict = {},
51
+ history_offset: int = 10250,
52
+ act: str = None,
53
+ system_prompt: str = "You are a helpful assistant.",
54
+ model: str = "Meta-Llama-3-3-70B-Instruct",
55
+ temperature: float = 0.6,
56
+ top_p: float = 0.9,
57
+ session_token: str = None
58
+ ):
59
+ """
60
+ Initializes the AkashGPT API with given parameters.
61
+
62
+ Args:
63
+ is_conversation (bool): Whether the provider is in conversation mode.
64
+ max_tokens (int): Maximum number of tokens to sample.
65
+ timeout (int): Timeout for API requests.
66
+ intro (str): Introduction message for the conversation.
67
+ filepath (str): Filepath for storing conversation history.
68
+ update_file (bool): Whether to update the conversation history file.
69
+ proxies (dict): Proxies for the API requests.
70
+ history_offset (int): Offset for conversation history.
71
+ act (str): Act for the conversation.
72
+ system_prompt (str): The system prompt to define the assistant's role.
73
+ model (str): The model to use for generation.
74
+ temperature (float): Controls randomness in generation.
75
+ top_p (float): Controls diversity via nucleus sampling.
76
+ session_token (str): Session token for authentication. If None, auto-generates one.
77
+ """
78
+ # Validate model choice
79
+ if model not in self.AVAILABLE_MODELS:
80
+ raise ValueError(f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}")
81
+
82
+ self.session = requests.Session()
83
+ self.is_conversation = is_conversation
84
+ self.max_tokens_to_sample = max_tokens
85
+ self.api_endpoint = "https://chat.akash.network/api/chat"
86
+ self.timeout = timeout
87
+ self.last_response = {}
88
+ self.system_prompt = system_prompt
89
+ self.model = model
90
+ self.temperature = temperature
91
+ self.top_p = top_p
92
+
93
+ # Generate session token if not provided
94
+ if not session_token:
95
+ self.session_token = str(uuid4()).replace("-", "") + str(int(time.time()))
96
+ else:
97
+ self.session_token = session_token
98
+
99
+ self.agent = LitAgent()
100
+
101
+ self.headers = {
102
+ "authority": "chat.akash.network",
103
+ "method": "POST",
104
+ "path": "/api/chat",
105
+ "scheme": "https",
106
+ "accept": "*/*",
107
+ "accept-encoding": "gzip, deflate, br, zstd",
108
+ "accept-language": "en-US,en;q=0.9",
109
+ "content-type": "application/json",
110
+ "dnt": "1",
111
+ "origin": "https://chat.akash.network",
112
+ "priority": "u=1, i",
113
+ "referer": "https://chat.akash.network/",
114
+ "sec-ch-ua": '"Not(A:Brand";v="99", "Microsoft Edge";v="133", "Chromium";v="133"',
115
+ "sec-ch-ua-mobile": "?0",
116
+ "sec-ch-ua-platform": '"Windows"',
117
+ "user-agent": self.agent.random()
118
+
119
+ }
120
+
121
+ # Set cookies with the session token
122
+ self.session.cookies.set("session_token", self.session_token, domain="chat.akash.network")
123
+
124
+ self.__available_optimizers = (
125
+ method
126
+ for method in dir(Optimizers)
127
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
128
+ )
129
+ self.session.headers.update(self.headers)
130
+ Conversation.intro = (
131
+ AwesomePrompts().get_act(
132
+ act, raise_not_found=True, default=None, case_insensitive=True
133
+ )
134
+ if act
135
+ else intro or Conversation.intro
136
+ )
137
+ self.conversation = Conversation(
138
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
139
+ )
140
+ self.conversation.history_offset = history_offset
141
+ self.session.proxies = proxies
142
+
143
+ def ask(
144
+ self,
145
+ prompt: str,
146
+ stream: bool = False,
147
+ raw: bool = False,
148
+ optimizer: str = None,
149
+ conversationally: bool = False,
150
+ ) -> Dict[str, Any]:
151
+ """
152
+ Sends a prompt to the Akash Network API and returns the response.
153
+
154
+ Args:
155
+ prompt (str): The prompt to send to the API.
156
+ stream (bool): Whether to stream the response.
157
+ raw (bool): Whether to return the raw response.
158
+ optimizer (str): Optimizer to use for the prompt.
159
+ conversationally (bool): Whether to generate the prompt conversationally.
160
+
161
+ Returns:
162
+ Dict[str, Any]: The API response.
163
+
164
+ Examples:
165
+ >>> ai = AkashGPT()
166
+ >>> response = ai.ask("Tell me a joke!")
167
+ >>> print(response)
168
+ {'text': 'Why did the scarecrow win an award? Because he was outstanding in his field!'}
169
+ """
170
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
171
+ if optimizer:
172
+ if optimizer in self.__available_optimizers:
173
+ conversation_prompt = getattr(Optimizers, optimizer)(
174
+ conversation_prompt if conversationally else prompt
175
+ )
176
+ else:
177
+ raise Exception(
178
+ f"Optimizer is not one of {self.__available_optimizers}"
179
+ )
180
+
181
+ payload = {
182
+ "id": str(uuid4()), # Generate a unique request ID
183
+ "messages": [
184
+ {"role": "system", "content": self.system_prompt},
185
+ {"role": "user", "content": conversation_prompt}
186
+ ],
187
+ "model": self.model,
188
+ "temperature": self.temperature,
189
+ "topP": self.top_p
190
+ }
191
+
192
+ def for_stream():
193
+ response = self.session.post(self.api_endpoint, headers=self.headers, json=payload, stream=True, timeout=self.timeout)
194
+ if not response.ok:
195
+ raise exceptions.FailedToGenerateResponseError(
196
+ f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
197
+ )
198
+
199
+ streaming_response = ""
200
+ message_id = None
201
+
202
+ for line in response.iter_lines(decode_unicode=True):
203
+ if not line:
204
+ continue
205
+
206
+ # Parse message ID from the f: line
207
+ if line.startswith('f:'):
208
+ try:
209
+ f_data = json.loads(line[2:])
210
+ message_id = f_data.get("messageId")
211
+ continue
212
+ except json.JSONDecodeError:
213
+ pass
214
+
215
+ # Parse content chunks
216
+ if line.startswith('0:'):
217
+ try:
218
+ # Extract content between quotes
219
+ content = line[2:].strip('"')
220
+ if content.startswith('"') and content.endswith('"'):
221
+ content = content[1:-1]
222
+ streaming_response += content
223
+ yield content if raw else dict(text=content)
224
+ except Exception:
225
+ continue
226
+
227
+ # End of stream
228
+ if line.startswith('e:') or line.startswith('d:'):
229
+ break
230
+
231
+ self.last_response.update(dict(text=streaming_response, message_id=message_id))
232
+ self.conversation.update_chat_history(
233
+ prompt, self.get_message(self.last_response)
234
+ )
235
+
236
+ def for_non_stream():
237
+ for _ in for_stream():
238
+ pass
239
+ return self.last_response
240
+
241
+ return for_stream() if stream else for_non_stream()
242
+
243
+ def chat(
244
+ self,
245
+ prompt: str,
246
+ stream: bool = False,
247
+ optimizer: str = None,
248
+ conversationally: bool = False,
249
+ ) -> str:
250
+ """
251
+ Generates a response from the AkashGPT API.
252
+
253
+ Args:
254
+ prompt (str): The prompt to send to the API.
255
+ stream (bool): Whether to stream the response.
256
+ optimizer (str): Optimizer to use for the prompt.
257
+ conversationally (bool): Whether to generate the prompt conversationally.
258
+
259
+ Returns:
260
+ str: The API response.
261
+
262
+ Examples:
263
+ >>> ai = AkashGPT()
264
+ >>> response = ai.chat("What's the weather today?")
265
+ >>> print(response)
266
+ 'The weather today depends on your location. I don't have access to real-time weather data.'
267
+ """
268
+
269
+ def for_stream():
270
+ for response in self.ask(
271
+ prompt, True, optimizer=optimizer, conversationally=conversationally
272
+ ):
273
+ yield self.get_message(response)
274
+
275
+ def for_non_stream():
276
+ return self.get_message(
277
+ self.ask(
278
+ prompt,
279
+ False,
280
+ optimizer=optimizer,
281
+ conversationally=conversationally,
282
+ )
283
+ )
284
+
285
+ return for_stream() if stream else for_non_stream()
286
+
287
+ def get_message(self, response: dict) -> str:
288
+ """
289
+ Extracts the message from the API response.
290
+
291
+ Args:
292
+ response (dict): The API response.
293
+
294
+ Returns:
295
+ str: The message content.
296
+
297
+ Examples:
298
+ >>> ai = AkashGPT()
299
+ >>> response = ai.ask("Tell me a joke!")
300
+ >>> message = ai.get_message(response)
301
+ >>> print(message)
302
+ 'Why did the scarecrow win an award? Because he was outstanding in his field!'
303
+ """
304
+ assert isinstance(response, dict), "Response should be of dict data-type only"
305
+ return response.get("text", "")
306
+
307
+ if __name__ == "__main__":
308
+ from rich import print
309
+ ai = AkashGPT()
310
+ resp = ai.chat("Tell me a joke!", stream=True)
311
+ for c in resp:
312
+ print(c, end="", flush=True)
@@ -7,7 +7,7 @@ from webscout.AIutel import Optimizers
7
7
  from webscout.AIutel import Conversation
8
8
  from webscout.AIutel import AwesomePrompts
9
9
  from webscout.AIbase import Provider
10
- from webscout import exceptions
10
+ from webscout import exceptions, LitAgent
11
11
 
12
12
 
13
13
  class ChatGLM(Provider):
@@ -26,7 +26,7 @@ class ChatGLM(Provider):
26
26
  proxies: dict = {},
27
27
  history_offset: int = 10250,
28
28
  act: str = None,
29
- model: str = "all-tools-230b",
29
+ plus_model: bool = True,
30
30
  ):
31
31
  """Initializes the ChatGLM API client."""
32
32
  self.session = requests.Session()
@@ -36,14 +36,14 @@ class ChatGLM(Provider):
36
36
  self.stream_chunk_size = 64
37
37
  self.timeout = timeout
38
38
  self.last_response = {}
39
- self.model = model
39
+ self.plus_model = plus_model
40
40
  self.headers = {
41
41
  'Accept-Language': 'en-US,en;q=0.9',
42
42
  'App-Name': 'chatglm',
43
43
  'Authorization': 'undefined',
44
44
  'Content-Type': 'application/json',
45
45
  'Origin': 'https://chatglm.cn',
46
- 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
46
+ 'User-Agent': LitAgent().random(),
47
47
  'X-App-Platform': 'pc',
48
48
  'X-App-Version': '0.0.1',
49
49
  'X-Device-Id': '', #Will be generated each time
@@ -102,7 +102,7 @@ class ChatGLM(Provider):
102
102
  "assistant_id": "65940acff94777010aa6b796",
103
103
  "conversation_id": "",
104
104
  "meta_data": {
105
- "if_plus_model": False,
105
+ "if_plus_model": self.plus_model,
106
106
  "is_test": False,
107
107
  "input_question_type": "xxxx",
108
108
  "channel": "",
@@ -0,0 +1,251 @@
1
+ import requests
2
+ import json
3
+ import time
4
+ from typing import Any, Dict, Optional, Generator, Union
5
+
6
+ from webscout.AIutel import Optimizers
7
+ from webscout.AIutel import Conversation
8
+ from webscout.AIutel import AwesomePrompts, sanitize_stream
9
+ from webscout.AIbase import Provider, AsyncProvider
10
+ from webscout import exceptions
11
+ from webscout import LitAgent
12
+ from webscout.Litlogger import Logger, LogFormat
13
+
14
+ class FreeAIChat(Provider):
15
+ """
16
+ A class to interact with the FreeAIChat API with logging and LitAgent user-agent.
17
+ """
18
+
19
+ AVAILABLE_MODELS = [
20
+ "mistral-nemo",
21
+ "mistral-large",
22
+ "gemini-2.0-flash",
23
+ "gemini-1.5-pro",
24
+ "gemini-1.5-flash",
25
+ "gemini-2.0-pro-exp-02-05",
26
+ "deepseek-r1",
27
+ "deepseek-v3",
28
+ "Deepseek r1 14B",
29
+ "Deepseek r1 32B",
30
+ "o3-mini-high",
31
+ "o3-mini-medium",
32
+ "o3-mini-low",
33
+ "o3-mini",
34
+ "GPT-4o-mini",
35
+ "o1",
36
+ "o1-mini",
37
+ "GPT-4o",
38
+ "Qwen coder",
39
+ "Qwen 2.5 72B",
40
+ "Llama 3.1 405B",
41
+ "llama3.1-70b-fast",
42
+ "Llama 3.3 70B",
43
+ "claude 3.5 haiku",
44
+ "claude 3.5 sonnet",
45
+ ]
46
+
47
+ def __init__(
48
+ self,
49
+ is_conversation: bool = True,
50
+ max_tokens: int = 2049,
51
+ timeout: int = 30,
52
+ intro: str = None,
53
+ filepath: str = None,
54
+ update_file: bool = True,
55
+ proxies: dict = {},
56
+ history_offset: int = 10250,
57
+ act: str = None,
58
+ model: str = "GPT-4o",
59
+ system_prompt: str = "You are a helpful AI assistant.",
60
+ logging: bool = False
61
+ ):
62
+ """Initializes the FreeAIChat API client with logging support."""
63
+ if model not in self.AVAILABLE_MODELS:
64
+ raise ValueError(f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}")
65
+
66
+ self.url = "https://freeaichatplayground.com/api/v1/chat/completions"
67
+ self.headers = {
68
+ 'User-Agent': LitAgent().random(),
69
+ 'Accept': '*/*',
70
+ 'Content-Type': 'application/json',
71
+ 'Origin': 'https://freeaichatplayground.com',
72
+ 'Referer': 'https://freeaichatplayground.com/',
73
+ 'Sec-Fetch-Mode': 'cors',
74
+ 'Sec-Fetch-Site': 'same-origin'
75
+ }
76
+ self.session = requests.Session()
77
+ self.session.headers.update(self.headers)
78
+ self.session.proxies.update(proxies)
79
+
80
+ self.is_conversation = is_conversation
81
+ self.max_tokens_to_sample = max_tokens
82
+ self.timeout = timeout
83
+ self.last_response = {}
84
+ self.model = model
85
+ self.system_prompt = system_prompt
86
+
87
+ self.__available_optimizers = (
88
+ method
89
+ for method in dir(Optimizers)
90
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
91
+ )
92
+ Conversation.intro = (
93
+ AwesomePrompts().get_act(
94
+ act, raise_not_found=True, default=None, case_insensitive=True
95
+ )
96
+ if act
97
+ else intro or Conversation.intro
98
+ )
99
+
100
+ self.conversation = Conversation(
101
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
102
+ )
103
+ self.conversation.history_offset = history_offset
104
+
105
+ self.logger = Logger(
106
+ name="FreeAIChat",
107
+ format=LogFormat.MODERN_EMOJI,
108
+ ) if logging else None
109
+
110
+ if self.logger:
111
+ self.logger.info(f"FreeAIChat initialized successfully with model: {model}")
112
+
113
+ def ask(
114
+ self,
115
+ prompt: str,
116
+ stream: bool = False,
117
+ raw: bool = False,
118
+ optimizer: str = None,
119
+ conversationally: bool = False,
120
+ ) -> Union[Dict[str, Any], Generator]:
121
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
122
+ if optimizer:
123
+ if optimizer in self.__available_optimizers:
124
+ conversation_prompt = getattr(Optimizers, optimizer)(
125
+ conversation_prompt if conversationally else prompt
126
+ )
127
+ if self.logger:
128
+ self.logger.debug(f"Applied optimizer: {optimizer}")
129
+ else:
130
+ if self.logger:
131
+ self.logger.error(f"Invalid optimizer requested: {optimizer}")
132
+ raise Exception(f"Optimizer is not one of {self.__available_optimizers}")
133
+
134
+ messages = [
135
+ {
136
+ "role": "system",
137
+ "content": self.system_prompt
138
+ },
139
+ {
140
+ "role": "user",
141
+ "content": conversation_prompt
142
+ }
143
+ ]
144
+
145
+ payload = {
146
+ "model": self.model,
147
+ "messages": messages
148
+ }
149
+
150
+ def for_stream():
151
+ if self.logger:
152
+ self.logger.debug("Sending streaming request to FreeAIChat API...")
153
+ try:
154
+ with requests.post(self.url, headers=self.headers, json=payload, stream=True, timeout=self.timeout) as response:
155
+ if response.status_code != 200:
156
+ if self.logger:
157
+ self.logger.error(f"Request failed with status code {response.status_code}")
158
+ raise exceptions.FailedToGenerateResponseError(
159
+ f"Request failed with status code {response.status_code}"
160
+ )
161
+
162
+ streaming_text = ""
163
+ for line in response.iter_lines(decode_unicode=True):
164
+ if line:
165
+ line = line.strip()
166
+ if line.startswith("data: "):
167
+ json_str = line[6:] # Remove "data: " prefix
168
+ if json_str == "[DONE]":
169
+ break
170
+ try:
171
+ json_data = json.loads(json_str)
172
+ if 'choices' in json_data:
173
+ choice = json_data['choices'][0]
174
+ if 'delta' in choice and 'content' in choice['delta']:
175
+ content = choice['delta']['content']
176
+ streaming_text += content
177
+ resp = dict(text=content)
178
+ yield resp if raw else resp
179
+ except json.JSONDecodeError:
180
+ if self.logger:
181
+ self.logger.error("JSON decode error in streaming data")
182
+ pass
183
+
184
+ self.conversation.update_chat_history(prompt, streaming_text)
185
+ if self.logger:
186
+ self.logger.info("Streaming response completed successfully")
187
+
188
+ except requests.RequestException as e:
189
+ if self.logger:
190
+ self.logger.error(f"Request failed: {e}")
191
+ raise exceptions.FailedToGenerateResponseError(f"Request failed: {e}")
192
+
193
+ def for_non_stream():
194
+ full_text = ""
195
+ for chunk in for_stream():
196
+ full_text += chunk["text"]
197
+ return {"text": full_text}
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
+ def for_stream():
209
+ for response in self.ask(prompt, True, optimizer=optimizer, conversationally=conversationally):
210
+ yield self.get_message(response)
211
+
212
+ def for_non_stream():
213
+ return self.get_message(
214
+ self.ask(prompt, False, optimizer=optimizer, conversationally=conversationally)
215
+ )
216
+
217
+ return for_stream() if stream else for_non_stream()
218
+
219
+ def get_message(self, response: dict) -> str:
220
+ assert isinstance(response, dict), "Response should be of dict data-type only"
221
+ return response["text"]
222
+
223
+ @staticmethod
224
+ def fix_encoding(text):
225
+ if isinstance(text, dict) and "text" in text:
226
+ try:
227
+ text["text"] = text["text"].encode("latin1").decode("utf-8")
228
+ return text
229
+ except (UnicodeError, AttributeError) as e:
230
+ return text
231
+ elif isinstance(text, str):
232
+ try:
233
+ return text.encode("latin1").decode("utf-8")
234
+ except (UnicodeError, AttributeError) as e:
235
+ return text
236
+ return text
237
+
238
+
239
+ if __name__ == "__main__":
240
+ from rich import print
241
+ ai = FreeAIChat(model="GPT-4o", logging=True)
242
+ # response = ai.chat(input(">>>"), stream=True)
243
+ # full_text = ""
244
+
245
+ # for chunk in response:
246
+ # corrected_chunk = ai.fix_encoding(chunk)
247
+ # full_text += corrected_chunk
248
+
249
+ response = ai.chat(input(">>>"), stream=False)
250
+ response = ai.fix_encoding(response)
251
+ print(response)
@@ -12,6 +12,11 @@ class KOALA(Provider):
12
12
  A class to interact with the Koala.sh API.
13
13
  """
14
14
 
15
+ AVAILABLE_MODELS = [
16
+ "gpt-4o-mini",
17
+ "gpt-4o",
18
+ ]
19
+
15
20
  def __init__(
16
21
  self,
17
22
  is_conversation: bool = True,
@@ -23,7 +28,7 @@ class KOALA(Provider):
23
28
  proxies: dict = {},
24
29
  history_offset: int = 10250,
25
30
  act: str = None,
26
- model: str = "gpt-4o-mini",
31
+ model: str = "gpt-4o",
27
32
  web_search: bool = True,
28
33
 
29
34
  ) -> None:
@@ -44,6 +49,9 @@ class KOALA(Provider):
44
49
  act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
45
50
  model (str, optional): AI model to use. Defaults to "gpt-4o-mini".
46
51
  """
52
+ if model not in self.AVAILABLE_MODELS:
53
+ raise ValueError(f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}")
54
+
47
55
  self.session = requests.Session()
48
56
  self.is_conversation = is_conversation
49
57
  self.max_tokens_to_sample = max_tokens