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

@@ -0,0 +1,264 @@
1
+ import requests
2
+ import json
3
+ import random
4
+ from typing import Any, Dict, Optional, Generator
5
+
6
+ from webscout.AIutel import Optimizers
7
+ from webscout.AIutel import Conversation
8
+ from webscout.AIutel import AwesomePrompts
9
+ from webscout.AIbase import Provider
10
+ from webscout import exceptions
11
+
12
+
13
+ class Bixin(Provider):
14
+ """
15
+ A class to interact with the Bixin API.
16
+ """
17
+
18
+ AVAILABLE_MODELS = [
19
+ 'gpt-3.5-turbo-0125', 'gpt-3.5-turbo-16k-0613', 'gpt-4-turbo', 'qwen-turbo'
20
+ ]
21
+
22
+ def __init__(
23
+ self,
24
+ is_conversation: bool = True,
25
+ max_tokens: int = 600,
26
+ timeout: int = 30,
27
+ intro: str = None,
28
+ filepath: str = None,
29
+ update_file: bool = True,
30
+ proxies: dict = {},
31
+ history_offset: int = 10250,
32
+ act: str = None,
33
+ model: str = 'gpt-4-turbo', # Default model
34
+ system_prompt: str = "You are a helpful assistant.",
35
+ ):
36
+ """
37
+ Initializes the Bixin API with given parameters.
38
+
39
+ Args:
40
+ is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
41
+ max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
42
+ timeout (int, optional): Http request timeout. Defaults to 30.
43
+ intro (str, optional): Conversation introductory prompt. Defaults to None.
44
+ filepath (str, optional): Path to file containing conversation history. Defaults to None.
45
+ update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
46
+ proxies (dict, optional): Http request proxies. Defaults to {}.
47
+ history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
48
+ act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
49
+ model (str, optional): AI model to use. Defaults to "gpt-4-turbo".
50
+ system_prompt (str, optional): System prompt for Bixin.
51
+ Defaults to "You are a helpful assistant.".
52
+ """
53
+ if model not in self.AVAILABLE_MODELS:
54
+ raise ValueError(f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}")
55
+
56
+ self.session = requests.Session()
57
+ self.is_conversation = is_conversation
58
+ self.max_tokens_to_sample = max_tokens
59
+ self.api_endpoint = "https://chat.bixin123.com/api/chatgpt/chat-process"
60
+ self.stream_chunk_size = 1024
61
+ self.timeout = timeout
62
+ self.last_response = {}
63
+ self.model = model
64
+ self.system_prompt = system_prompt
65
+ self.headers = {
66
+ "Accept": "application/json, text/plain, */*",
67
+ "Accept-Language": "en-US,en;q=0.9",
68
+ "Cache-Control": "no-cache",
69
+ "Content-Type": "application/json",
70
+ "Fingerprint": self.generate_fingerprint(),
71
+ "Origin": "https://chat.bixin123.com",
72
+ "Pragma": "no-cache",
73
+ "Priority": "u=1, i",
74
+ "Referer": "https://chat.bixin123.com/chat",
75
+ "Sec-CH-UA": '"Chromium";v="127", "Not)A;Brand";v="99"',
76
+ "Sec-CH-UA-Mobile": "?0",
77
+ "Sec-CH-UA-Platform": '"Linux"',
78
+ "Sec-Fetch-Dest": "empty",
79
+ "Sec-Fetch-Mode": "cors",
80
+ "Sec-Fetch-Site": "same-origin",
81
+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
82
+ "X-Website-Domain": "chat.bixin123.com",
83
+ }
84
+
85
+ self.__available_optimizers = (
86
+ method
87
+ for method in dir(Optimizers)
88
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
89
+ )
90
+ self.session.headers.update(self.headers)
91
+ Conversation.intro = (
92
+ AwesomePrompts().get_act(
93
+ act, raise_not_found=True, default=None, case_insensitive=True
94
+ )
95
+ if act
96
+ else intro or Conversation.intro
97
+ )
98
+ self.conversation = Conversation(
99
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
100
+ )
101
+ self.conversation.history_offset = history_offset
102
+ self.session.proxies = proxies
103
+
104
+ def generate_fingerprint(self) -> str:
105
+ """
106
+ Generates a random fingerprint number as a string.
107
+ """
108
+ return str(random.randint(100000000, 999999999))
109
+
110
+ def ask(
111
+ self,
112
+ prompt: str,
113
+ stream: bool = False,
114
+ raw: bool = False,
115
+ optimizer: str = None,
116
+ conversationally: bool = False,
117
+ ) -> dict:
118
+ """Chat with Bixin
119
+
120
+ Args:
121
+ prompt (str): Prompt to be send.
122
+ stream (bool, optional): Flag for streaming response. Defaults to False.
123
+ raw (bool, optional): Stream back raw response as received. Defaults to False.
124
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
125
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
126
+ Returns:
127
+ dict : {}
128
+ ```json
129
+ {
130
+ "text" : "How may I assist you today?"
131
+ }
132
+ ```
133
+ """
134
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
135
+ if optimizer:
136
+ if optimizer in self.__available_optimizers:
137
+ conversation_prompt = getattr(Optimizers, optimizer)(
138
+ conversation_prompt if conversationally else prompt
139
+ )
140
+ else:
141
+ raise Exception(
142
+ f"Optimizer is not one of {self.__available_optimizers}"
143
+ )
144
+
145
+ messages = [
146
+ {"role": "system", "content": self.system_prompt},
147
+ {"role": "user", "content": conversation_prompt},
148
+ ]
149
+
150
+ data = {
151
+ "prompt": self.format_prompt(messages),
152
+ "options": {
153
+ "usingNetwork": False,
154
+ "file": ""
155
+ }
156
+ }
157
+
158
+ def for_stream():
159
+ try:
160
+ with requests.post(self.api_endpoint, headers=self.headers, json=data, stream=True, timeout=self.timeout) as response:
161
+ response.raise_for_status()
162
+
163
+ # Initialize variable to keep track of the last printed text
164
+ previous_text = ""
165
+
166
+ full_response = ''
167
+ for chunk in response.iter_content(chunk_size=self.stream_chunk_size, decode_unicode=True):
168
+ if chunk:
169
+ try:
170
+ json_chunk = json.loads(chunk)
171
+ text = json_chunk.get("text", "")
172
+
173
+ # Determine the new text to print
174
+ if text.startswith(previous_text):
175
+ new_text = text[len(previous_text):]
176
+ full_response += new_text
177
+ yield new_text if raw else dict(text=full_response)
178
+ previous_text = text
179
+ else:
180
+ full_response += text
181
+ yield text if raw else dict(text=full_response)
182
+ previous_text = text
183
+ except json.JSONDecodeError:
184
+ # If the chunk isn't a complete JSON object, skip it
185
+ continue
186
+ self.last_response.update(dict(text=full_response))
187
+ self.conversation.update_chat_history(
188
+ prompt, self.get_message(self.last_response)
189
+ )
190
+ except requests.RequestException as e:
191
+ raise exceptions.FailedToGenerateResponseError(f"\nRequest failed: {e}")
192
+
193
+ def for_non_stream():
194
+ for _ in for_stream():
195
+ pass
196
+ return self.last_response
197
+
198
+ return for_stream() if stream else for_non_stream()
199
+
200
+ def format_prompt(self, messages: list) -> str:
201
+ """
202
+ Formats the list of messages into a single prompt string.
203
+ """
204
+ formatted_messages = []
205
+ for message in messages:
206
+ role = message.get("role", "")
207
+ content = message.get("content", "")
208
+ formatted_messages.append(f"{role}: {content}")
209
+ return "\n".join(formatted_messages)
210
+
211
+ def chat(
212
+ self,
213
+ prompt: str,
214
+ stream: bool = False,
215
+ optimizer: str = None,
216
+ conversationally: bool = False,
217
+ ) -> str:
218
+ """Generate response `str`
219
+ Args:
220
+ prompt (str): Prompt to be send.
221
+ stream (bool, optional): Flag for streaming response. Defaults to False.
222
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
223
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
224
+ Returns:
225
+ str: Response generated
226
+ """
227
+
228
+ def for_stream():
229
+ for response in self.ask(
230
+ prompt, True, optimizer=optimizer, conversationally=conversationally
231
+ ):
232
+ yield self.get_message(response)
233
+
234
+ def for_non_stream():
235
+ return self.get_message(
236
+ self.ask(
237
+ prompt,
238
+ False,
239
+ optimizer=optimizer,
240
+ conversationally=conversationally,
241
+ )
242
+ )
243
+
244
+ return for_stream() if stream else for_non_stream()
245
+
246
+ def get_message(self, response: dict) -> str:
247
+ """Retrieves message only from response
248
+
249
+ Args:
250
+ response (dict): Response generated by `self.ask`
251
+
252
+ Returns:
253
+ str: Message extracted
254
+ """
255
+ assert isinstance(response, dict), "Response should be of dict data-type only"
256
+ return response["text"]
257
+
258
+ if __name__ == "__main__":
259
+ from rich import print
260
+
261
+ ai = Bixin()
262
+ response = ai.chat(input(">>> "))
263
+ for chunk in response:
264
+ print(chunk, end="", flush=True)
@@ -1,13 +1,12 @@
1
1
  import cloudscraper
2
2
  from uuid import uuid4
3
3
  import json
4
-
4
+ import re
5
5
  from webscout.AIutel import Optimizers
6
6
  from webscout.AIutel import Conversation
7
7
  from webscout.AIutel import AwesomePrompts
8
8
  from webscout.AIbase import Provider
9
9
 
10
-
11
10
  class Genspark(Provider):
12
11
  """
13
12
  A class to interact with the Genspark.ai API.
@@ -25,7 +24,8 @@ class Genspark(Provider):
25
24
  history_offset: int = 10250,
26
25
  act: str = None,
27
26
  ) -> None:
28
- """Instantiates Genspark
27
+ """
28
+ Instantiates Genspark
29
29
 
30
30
  Args:
31
31
  is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
@@ -67,11 +67,11 @@ class Genspark(Provider):
67
67
  "session_id": uuid4().hex,
68
68
  }
69
69
 
70
- self.__available_optimizers = (
70
+ self.__available_optimizers = [
71
71
  method
72
72
  for method in dir(Optimizers)
73
73
  if callable(getattr(Optimizers, method)) and not method.startswith("__")
74
- )
74
+ ]
75
75
  self.session.headers.update(self.headers)
76
76
  Conversation.intro = (
77
77
  AwesomePrompts().get_act(
@@ -94,7 +94,8 @@ class Genspark(Provider):
94
94
  optimizer: str = None,
95
95
  conversationally: bool = False,
96
96
  ) -> dict:
97
- """Chat with AI
97
+ """
98
+ Chat with AI
98
99
 
99
100
  Args:
100
101
  prompt (str): Prompt to be send.
@@ -102,11 +103,12 @@ class Genspark(Provider):
102
103
  raw (bool, optional): Stream back raw response as received. Defaults to False.
103
104
  optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
104
105
  conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
106
+
105
107
  Returns:
106
- dict : {}
108
+ dict : {}
107
109
  ```json
108
110
  {
109
- "text" : "How may I assist you today?"
111
+ "text" : "How may I assist you today?"
110
112
  }
111
113
  ```
112
114
  """
@@ -121,11 +123,10 @@ class Genspark(Provider):
121
123
  f"Optimizer is not one of {self.__available_optimizers}"
122
124
  )
123
125
 
124
- self.url = (
125
- f"https://www.genspark.ai/api/search/stream?query={conversation_prompt}"
126
- )
126
+ self.url = f"https://www.genspark.ai/api/search/stream?query={conversation_prompt}"
127
127
 
128
128
  payload = {}
129
+
129
130
  def for_stream():
130
131
  response = self.session.post(
131
132
  self.url,
@@ -135,26 +136,24 @@ class Genspark(Provider):
135
136
  stream=True,
136
137
  timeout=self.timeout,
137
138
  )
139
+ if not response.ok:
140
+ raise Exception(
141
+ f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
142
+ )
138
143
 
139
- partial_response = ""
144
+ full_response = ""
140
145
  for line in response.iter_lines(decode_unicode=True):
141
146
  if line:
142
- try:
143
- data = json.loads(line[5:])
144
- if (
145
- data["type"] == "result_field"
146
- and data["field_name"] == "deep_dive_result"
147
- ):
148
- deep_dive_result = data["field_value"]
149
- if "detailAnswer" in deep_dive_result:
150
- new_content = deep_dive_result["detailAnswer"][
151
- len(partial_response) :
152
- ]
153
- partial_response = deep_dive_result["detailAnswer"]
154
- self.last_response.update(dict(text=new_content))
155
- yield new_content if raw else dict(text=new_content)
156
- except json.JSONDecodeError:
157
- print(f"Skipping invalid JSON line: {line}")
147
+ if line.startswith("data: "):
148
+ try:
149
+ data = json.loads(line[6:])
150
+ if data.get("type") == "result_field" and data["field_name"] == "streaming_summary":
151
+ full_response = data.get("field_value", "")
152
+ yield full_response if raw else {"text": full_response}
153
+ except json.JSONDecodeError as e:
154
+ print(f"Error decoding JSON: {line} - {e}")
155
+
156
+ self.last_response.update({"text": full_response})
158
157
  self.conversation.update_chat_history(
159
158
  prompt, self.get_message(self.last_response)
160
159
  )
@@ -173,7 +172,8 @@ class Genspark(Provider):
173
172
  optimizer: str = None,
174
173
  conversationally: bool = False,
175
174
  ) -> str:
176
- """Generate response `str`
175
+ """
176
+ Generate response `str`
177
177
  Args:
178
178
  prompt (str): Prompt to be send.
179
179
  stream (bool, optional): Flag for streaming response. Defaults to False.
@@ -190,19 +190,14 @@ class Genspark(Provider):
190
190
  yield self.get_message(response)
191
191
 
192
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
- )
193
+ response = self.ask(prompt, False, optimizer=optimizer, conversationally=conversationally)
194
+ return self.get_message(response)
201
195
 
202
196
  return for_stream() if stream else for_non_stream()
203
197
 
204
198
  def get_message(self, response: dict) -> str:
205
- """Retrieves message only from response
199
+ """
200
+ Retrieves message only from response
206
201
 
207
202
  Args:
208
203
  response (dict): Response generated by `self.ask`
@@ -211,12 +206,20 @@ class Genspark(Provider):
211
206
  str: Message extracted
212
207
  """
213
208
  assert isinstance(response, dict), "Response should be of dict data-type only"
214
- return response["text"]
215
-
216
-
217
- if __name__ == "__main__":
209
+ text = response.get('text', '')
210
+ # Remove footnote references from the text
211
+ text = re.sub(r"\[.*?\]\(.*?\)", "", text)
212
+ try:
213
+ # Attempt to parse the text as JSON
214
+ text_json = json.loads(text)
215
+ return text_json.get('detailAnswer', text)
216
+ except json.JSONDecodeError:
217
+ # If text is not JSON, return it as is
218
+ return text
219
+
220
+ if __name__ == '__main__':
218
221
  from rich import print
219
222
  ai = Genspark()
220
- response = ai.chat("hi")
223
+ response = ai.chat(input(">>> "))
221
224
  for chunk in response:
222
225
  print(chunk, end="", flush=True)
@@ -0,0 +1,253 @@
1
+ import os
2
+ import json
3
+ from typing import Optional
4
+ import uuid
5
+ import requests
6
+ import cloudscraper
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
+
14
+
15
+ class LearnFast(Provider):
16
+ """
17
+ A class to interact with the LearnFast.ai API.
18
+ """
19
+
20
+ def __init__(
21
+ self,
22
+ is_conversation: bool = True,
23
+ max_tokens: int = 600,
24
+ timeout: int = 30,
25
+ intro: str = None,
26
+ filepath: str = None,
27
+ update_file: bool = True,
28
+ proxies: dict = {},
29
+ history_offset: int = 10250,
30
+ act: str = None,
31
+ system_prompt: str = "You are a helpful AI assistant.",
32
+ ):
33
+ """
34
+ Initializes the LearnFast.ai API with given parameters.
35
+ """
36
+ self.session = cloudscraper.create_scraper()
37
+ self.is_conversation = is_conversation
38
+ self.max_tokens_to_sample = max_tokens
39
+ self.api_endpoint = 'https://autosite.erweima.ai/api/v1/chat'
40
+ self.stream_chunk_size = 64
41
+ self.timeout = timeout
42
+ self.last_response = {}
43
+ self.system_prompt = system_prompt
44
+ self.headers = {
45
+ "authority": "autosite.erweima.ai",
46
+ "accept": "*/*",
47
+ "accept-encoding": "gzip, deflate, br, zstd",
48
+ "accept-language": "en-US,en;q=0.9,en-IN;q=0.8",
49
+ "authorization": "", # Always empty
50
+ "content-type": "application/json",
51
+ "dnt": "1",
52
+ "origin": "https://learnfast.ai",
53
+ "priority": "u=1, i",
54
+ "referer": "https://learnfast.ai/",
55
+ "sec-ch-ua": '"Microsoft Edge";v="129", "Not=A?Brand";v="8", "Chromium";v="129"',
56
+ "sec-ch-ua-mobile": "?0",
57
+ "sec-ch-ua-platform": '"Windows"',
58
+ "sec-fetch-dest": "empty",
59
+ "sec-fetch-mode": "cors",
60
+ "sec-fetch-site": "cross-site",
61
+ "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",
62
+ }
63
+
64
+ self.__available_optimizers = (
65
+ method
66
+ for method in dir(Optimizers)
67
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
68
+ )
69
+ self.session.headers.update(self.headers)
70
+ Conversation.intro = (
71
+ AwesomePrompts().get_act(
72
+ act, raise_not_found=True, default=None, case_insensitive=True
73
+ )
74
+ if act
75
+ else intro or Conversation.intro
76
+ )
77
+ self.conversation = Conversation(
78
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
79
+ )
80
+ self.conversation.history_offset = history_offset
81
+ self.session.proxies = proxies
82
+
83
+ def generate_unique_id(self) -> str:
84
+ """Generate a 32-character hexadecimal unique ID."""
85
+ return uuid.uuid4().hex
86
+
87
+ def generate_session_id(self) -> str:
88
+ """Generate a 32-character hexadecimal session ID."""
89
+ return uuid.uuid4().hex
90
+
91
+ def upload_image_to_0x0(self, image_path: str) -> str:
92
+ """
93
+ Uploads an image to 0x0.st and returns the public URL.
94
+ """
95
+ if not os.path.isfile(image_path):
96
+ raise FileNotFoundError(f"The file '{image_path}' does not exist.")
97
+
98
+ with open(image_path, "rb") as img_file:
99
+ files = {"file": img_file}
100
+ try:
101
+ response = requests.post("https://0x0.st", files=files)
102
+ response.raise_for_status()
103
+ image_url = response.text.strip()
104
+ if not image_url.startswith("http"):
105
+ raise ValueError("Received an invalid URL from 0x0.st.")
106
+ return image_url
107
+ except requests.exceptions.RequestException as e:
108
+ raise Exception(f"Failed to upload image to 0x0.st: {e}") from e
109
+
110
+ def create_payload(
111
+ self,
112
+ session_id: str,
113
+ conversation_prompt: str,
114
+ image_url: Optional[str] = None
115
+ ) -> dict:
116
+ """
117
+ Creates the JSON payload for the request.
118
+ """
119
+ payload = {
120
+ "prompt": conversation_prompt,
121
+ "sessionId": session_id,
122
+ }
123
+ if image_url:
124
+ payload["attachments"] = [
125
+ {
126
+ "fileType": "image/jpeg",
127
+ "file": {},
128
+ "fileContent": image_url
129
+ }
130
+ ]
131
+ return payload
132
+
133
+ def ask(
134
+ self,
135
+ prompt: str,
136
+ stream: bool = False,
137
+ raw: bool = False,
138
+ optimizer: str = None,
139
+ conversationally: bool = False,
140
+ image_path: Optional[str] = None,
141
+ ) -> dict:
142
+ """Chat with LearnFast
143
+
144
+ Args:
145
+ prompt (str): Prompt to be send.
146
+ stream (bool, optional): Flag for streaming response. Defaults to False.
147
+ raw (bool, optional): Stream back raw response as received. Defaults to False.
148
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
149
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
150
+ image_path (Optional[str], optional): Path to the image to be uploaded.
151
+ Defaults to None.
152
+
153
+ Returns:
154
+ dict : {}
155
+ """
156
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
157
+ if optimizer:
158
+ if optimizer in self.__available_optimizers:
159
+ conversation_prompt = getattr(Optimizers, optimizer)(
160
+ conversation_prompt if conversationally else prompt
161
+ )
162
+ else:
163
+ raise Exception(
164
+ f"Optimizer is not one of {self.__available_optimizers}"
165
+ )
166
+
167
+ # Generate unique ID and session ID
168
+ unique_id = self.generate_unique_id()
169
+ session_id = self.generate_session_id()
170
+
171
+ # Update headers with the unique ID
172
+ self.headers["uniqueid"] = unique_id
173
+
174
+ # Upload image and get URL if image_path is provided
175
+ image_url = None
176
+ if image_path:
177
+ try:
178
+ image_url = self.upload_image_to_0x0(image_path)
179
+ except Exception as e:
180
+ raise exceptions.FailedToGenerateResponseError(f"Error uploading image: {e}") from e
181
+
182
+ # Create the payload
183
+ payload = self.create_payload(session_id, conversation_prompt, image_url)
184
+
185
+ # Convert the payload to a JSON string
186
+ data = json.dumps(payload)
187
+
188
+ try:
189
+ # Send the POST request with streaming enabled
190
+ response = self.session.post(self.api_endpoint, headers=self.headers, data=data, stream=True, timeout=self.timeout)
191
+ response.raise_for_status() # Check for HTTP errors
192
+
193
+ # Process the streamed response
194
+ full_response = ""
195
+ for line in response.iter_lines(decode_unicode=True):
196
+ if line:
197
+ if line.strip() == "[DONE]":
198
+ break
199
+ try:
200
+ json_response = json.loads(line)
201
+ message = json_response.get('data', {}).get('message', '')
202
+ if message:
203
+ full_response += message
204
+ # print(message, end='', flush=True)
205
+ except json.JSONDecodeError:
206
+ print(f"\nFailed to parse JSON: {line}")
207
+ self.last_response.update({"text": full_response})
208
+ self.conversation.update_chat_history(prompt, full_response)
209
+
210
+ return self.last_response
211
+ except requests.exceptions.RequestException as e:
212
+ raise exceptions.FailedToGenerateResponseError(f"An error occurred: {e}")
213
+
214
+ def chat(
215
+ self,
216
+ prompt: str,
217
+ stream: bool = False,
218
+ optimizer: str = None,
219
+ conversationally: bool = False,
220
+ image_path: Optional[str] = None,
221
+ ) -> str:
222
+ """Generate response `str`
223
+ Args:
224
+ prompt (str): Prompt to be send.
225
+ stream (bool, optional): Flag for streaming response. Defaults to False.
226
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
227
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
228
+ image_path (Optional[str], optional): Path to the image to be uploaded.
229
+ Defaults to None.
230
+ Returns:
231
+ str: Response generated
232
+ """
233
+ response = self.ask(prompt, stream, optimizer=optimizer, conversationally=conversationally, image_path=image_path)
234
+ return self.get_message(response)
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 = LearnFast()
251
+ response = ai.chat(input(">>> "), image_path="photo_2024-07-06_22-19-42.jpg")
252
+ for chunk in response:
253
+ print(chunk, end="", flush=True)