webscout 5.3__py3-none-any.whl → 5.5__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 (52) hide show
  1. webscout/AIauto.py +8 -12
  2. webscout/Agents/Onlinesearcher.py +5 -5
  3. webscout/Agents/functioncall.py +123 -97
  4. webscout/Local/_version.py +2 -2
  5. webscout/Provider/Andi.py +1 -21
  6. webscout/Provider/BasedGPT.py +1 -21
  7. webscout/Provider/Blackboxai.py +1 -21
  8. webscout/Provider/Chatify.py +3 -2
  9. webscout/Provider/Cloudflare.py +1 -22
  10. webscout/Provider/Cohere.py +2 -23
  11. webscout/Provider/DARKAI.py +0 -1
  12. webscout/Provider/Deepinfra.py +2 -16
  13. webscout/Provider/EDITEE.py +3 -26
  14. webscout/Provider/Gemini.py +1 -24
  15. webscout/Provider/Groq.py +0 -2
  16. webscout/Provider/Koboldai.py +0 -21
  17. webscout/Provider/Llama.py +4 -21
  18. webscout/Provider/OLLAMA.py +0 -17
  19. webscout/Provider/Openai.py +2 -22
  20. webscout/Provider/Perplexity.py +1 -2
  21. webscout/Provider/Phind.py +3 -508
  22. webscout/Provider/Reka.py +4 -22
  23. webscout/Provider/TTI/__init__.py +2 -1
  24. webscout/Provider/TTI/aiforce.py +137 -0
  25. webscout/Provider/TTS/streamElements.py +0 -17
  26. webscout/Provider/TTS/voicepod.py +0 -1
  27. webscout/Provider/ThinkAnyAI.py +17 -78
  28. webscout/Provider/Youchat.py +3 -20
  29. webscout/Provider/__init__.py +12 -5
  30. webscout/Provider/cleeai.py +212 -0
  31. webscout/Provider/elmo.py +237 -0
  32. webscout/Provider/felo_search.py +4 -22
  33. webscout/Provider/geminiapi.py +198 -0
  34. webscout/Provider/genspark.py +222 -0
  35. webscout/Provider/julius.py +3 -20
  36. webscout/Provider/koala.py +1 -1
  37. webscout/Provider/lepton.py +194 -0
  38. webscout/Provider/turboseek.py +4 -21
  39. webscout/Provider/x0gpt.py +3 -2
  40. webscout/Provider/xdash.py +2 -22
  41. webscout/Provider/yep.py +391 -149
  42. webscout/YTdownloader.py +2 -3
  43. webscout/tempid.py +46 -2
  44. webscout/version.py +1 -1
  45. webscout/webscout_search_async.py +9 -9
  46. {webscout-5.3.dist-info → webscout-5.5.dist-info}/METADATA +39 -64
  47. webscout-5.5.dist-info/RECORD +99 -0
  48. webscout-5.3.dist-info/RECORD +0 -93
  49. {webscout-5.3.dist-info → webscout-5.5.dist-info}/LICENSE.md +0 -0
  50. {webscout-5.3.dist-info → webscout-5.5.dist-info}/WHEEL +0 -0
  51. {webscout-5.3.dist-info → webscout-5.5.dist-info}/entry_points.txt +0 -0
  52. {webscout-5.3.dist-info → webscout-5.5.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,137 @@
1
+ import requests
2
+ import os
3
+ import time
4
+ from typing import List
5
+ from string import punctuation
6
+ from random import choice
7
+ from requests.exceptions import RequestException
8
+
9
+ from webscout.AIbase import ImageProvider
10
+
11
+ class AiForceimagger(ImageProvider):
12
+ """Image provider for pollinations.ai"""
13
+
14
+ def __init__(self, timeout: int = 60, proxies: dict = {}):
15
+ """Initializes the PollinationsAI class.
16
+
17
+ Args:
18
+ timeout (int, optional): HTTP request timeout in seconds. Defaults to 60.
19
+ proxies (dict, optional): HTTP request proxies (socks). Defaults to {}.
20
+ """
21
+ self.image_gen_endpoint = "https://api.airforce/v1/imagine2?prompt={prompt}"
22
+ self.headers = {
23
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
24
+ "Accept-Language": "en-US,en;q=0.5",
25
+ "Accept-Encoding": "gzip, deflate",
26
+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:122.0) Gecko/20100101 Firefox/122.0",
27
+ }
28
+ self.session = requests.Session()
29
+ self.session.headers.update(self.headers)
30
+ self.session.proxies.update(proxies)
31
+ self.timeout = timeout
32
+ self.prompt: str = "AI-generated image - webscout"
33
+ self.image_extension: str = "png"
34
+
35
+ def generate(
36
+ self, prompt: str, amount: int = 1, additives: bool = True,
37
+ max_retries: int = 3, retry_delay: int = 5
38
+ ) -> List[bytes]:
39
+ """Generate image from prompt
40
+
41
+ Args:
42
+ prompt (str): Image description.
43
+ amount (int): Total images to be generated. Defaults to 1.
44
+ additives (bool, optional): Try to make each prompt unique. Defaults to True.
45
+ width (int, optional): Width of the generated image. Defaults to 768.
46
+ height (int, optional): Height of the generated image. Defaults to 768.
47
+ model (str, optional): The model to use for image generation. Defaults to "flux".
48
+ max_retries (int, optional): Maximum number of retry attempts. Defaults to 3.
49
+ retry_delay (int, optional): Delay between retries in seconds. Defaults to 5.
50
+
51
+ Returns:
52
+ List[bytes]: List of generated images as bytes.
53
+ """
54
+ assert bool(prompt), "Prompt cannot be null"
55
+ assert isinstance(amount, int), f"Amount should be an integer only not {type(amount)}"
56
+ assert amount > 0, "Amount should be greater than 0"
57
+
58
+ ads = lambda: (
59
+ ""
60
+ if not additives
61
+ else choice(punctuation)
62
+ + choice(punctuation)
63
+ + choice(punctuation)
64
+ + choice(punctuation)
65
+ + choice(punctuation)
66
+ )
67
+
68
+ self.prompt = prompt
69
+ response = []
70
+ for _ in range(amount):
71
+ url = self.image_gen_endpoint.format(
72
+ prompt=prompt
73
+ )
74
+
75
+ for attempt in range(max_retries):
76
+ try:
77
+ resp = self.session.get(url, timeout=self.timeout)
78
+ resp.raise_for_status()
79
+ response.append(resp.content)
80
+ break
81
+ except RequestException as e:
82
+ if attempt == max_retries - 1:
83
+ print(f"Failed to generate image after {max_retries} attempts: {e}")
84
+ raise
85
+ else:
86
+ print(f"Attempt {attempt + 1} failed. Retrying in {retry_delay} seconds...")
87
+ time.sleep(retry_delay)
88
+
89
+ return response
90
+
91
+ def save(
92
+ self,
93
+ response: List[bytes],
94
+ name: str = None,
95
+ dir: str = os.getcwd(),
96
+ filenames_prefix: str = "",
97
+ ) -> List[str]:
98
+ """Save generated images
99
+
100
+ Args:
101
+ response (List[bytes]): List of generated images as bytes.
102
+ name (str): Filename for the images. Defaults to the last prompt.
103
+ dir (str, optional): Directory for saving images. Defaults to os.getcwd().
104
+ filenames_prefix (str, optional): String to be prefixed at each filename to be returned.
105
+
106
+ Returns:
107
+ List[str]: List of saved filenames.
108
+ """
109
+ assert isinstance(response, list), f"Response should be of {list} not {type(response)}"
110
+ name = self.prompt if name is None else name
111
+
112
+ filenames = []
113
+ count = 0
114
+ for image in response:
115
+ def complete_path():
116
+ count_value = "" if count == 0 else f"_{count}"
117
+ return os.path.join(dir, name + count_value + "." + self.image_extension)
118
+
119
+ while os.path.isfile(complete_path()):
120
+ count += 1
121
+
122
+ absolute_path_to_file = complete_path()
123
+ filenames.append(filenames_prefix + os.path.split(absolute_path_to_file)[1])
124
+
125
+ with open(absolute_path_to_file, "wb") as fh:
126
+ fh.write(image)
127
+
128
+ return filenames
129
+
130
+
131
+ if __name__ == "__main__":
132
+ bot = AiForceimagger()
133
+ try:
134
+ resp = bot.generate("AI-generated image - webscout", 1)
135
+ print(bot.save(resp))
136
+ except Exception as e:
137
+ print(f"An error occurred: {e}")
@@ -1,5 +1,4 @@
1
1
  import time
2
- import pygame
3
2
  import requests
4
3
  import pathlib
5
4
  import urllib.parse
@@ -265,20 +264,7 @@ class StreamElements(TTSProvider):
265
264
  f"Failed to perform the operation: {e}"
266
265
  )
267
266
 
268
- def play_audio(self, filename: str):
269
- """
270
- Plays an audio file using playsound.
271
267
 
272
- Args:
273
- filename (str): The path to the audio file.
274
-
275
- Raises:
276
- RuntimeError: If there is an error playing the audio.
277
- """
278
- try:
279
- playsound(filename)
280
- except Exception as e:
281
- raise RuntimeError(f"Error playing audio: {e}")
282
268
 
283
269
  # Example usage
284
270
  if __name__ == "__main__":
@@ -287,6 +273,3 @@ if __name__ == "__main__":
287
273
 
288
274
  print("Generating audio...")
289
275
  audio_file = streamelements.tts(text, voice="Brian")
290
-
291
- print("Playing audio...")
292
- streamelements.play_audio(audio_file)
@@ -1,6 +1,5 @@
1
1
  import requests
2
2
  import json
3
- import pygame
4
3
  import time
5
4
  from pathlib import Path
6
5
  from typing import Generator
@@ -1,41 +1,21 @@
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
1
+
9
2
  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
3
+
4
+ from webscout.AIutel import Optimizers
5
+ from webscout.AIutel import Conversation
6
+ from webscout.AIutel import AwesomePrompts, sanitize_stream
7
+ from webscout.AIbase import Provider, AsyncProvider
27
8
  from webscout import exceptions
28
9
  from typing import Any, AsyncGenerator, Dict
29
- import logging
30
- import httpx
10
+
31
11
  #------------------------------------ThinkAnyAI------------
32
12
  class ThinkAnyAI(Provider):
33
13
  def __init__(
34
14
  self,
35
15
  model: str = "claude-3-haiku",
36
16
  locale: str = "en",
37
- web_search: bool = False,
38
- chunk_size: int = 1,
17
+ web_search: bool = True,
18
+ chunk_size: int = 64,
39
19
  streaming: bool = True,
40
20
  is_conversation: bool = True,
41
21
  max_tokens: int = 600,
@@ -101,54 +81,7 @@ class ThinkAnyAI(Provider):
101
81
  optimizer: str = None,
102
82
  conversationally: bool = False,
103
83
  ) -> dict | AsyncGenerator:
104
- """Chat with AI asynchronously.
105
-
106
- Args:
107
- prompt (str): Prompt to be send.
108
- stream (bool, optional): Flag for streaming response. Defaults to False.
109
- raw (bool, optional): Stream back raw response as received. Defaults to False.
110
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defeaults to None
111
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
112
- Returns:
113
- dict : {}
114
- ```json
115
- {
116
- "content": "General Kenobi! \n\n(I couldn't help but respond with the iconic Star Wars greeting since you used it first. )\n\nIs there anything I can help you with today?\n[Image of Hello there General Kenobi]",
117
- "conversation_id": "c_f13f6217f9a997aa",
118
- "response_id": "r_d3665f95975c368f",
119
- "factualityQueries": null,
120
- "textQuery": [
121
- "hello there",
122
- 1
123
- ],
124
- "choices": [
125
- {
126
- "id": "rc_ea075c9671bfd8cb",
127
- "content": [
128
- "General Kenobi! \n\n(I couldn't help but respond with the iconic Star Wars greeting since you used it first. )\n\nIs there anything I can help you with today?\n[Image of Hello there General Kenobi]"
129
- ]
130
- },
131
- {
132
- "id": "rc_de6dd3fb793a5402",
133
- "content": [
134
- "General Kenobi! (or just a friendly hello, whichever you prefer!). \n\nI see you're a person of culture as well. *Star Wars* references are always appreciated. \n\nHow can I help you today?\n"
135
- ]
136
- },
137
- {
138
- "id": "rc_a672ac089caf32db",
139
- "content": [
140
- "General Kenobi! (or just a friendly hello if you're not a Star Wars fan!). \n\nHow can I help you today? Feel free to ask me anything, or tell me what you'd like to chat about. I'm here to assist in any way I can.\n[Image of Obi-Wan Kenobi saying hello there]"
141
- ]
142
- }
143
- ],
144
84
 
145
- "images": [
146
- "https://i.pinimg.com/originals/40/74/60/407460925c9e419d82b93313f0b42f71.jpg"
147
- ]
148
- }
149
-
150
- ```
151
- """
152
85
  conversation_prompt = self.conversation.gen_complete_prompt(prompt)
153
86
  if optimizer:
154
87
  if optimizer in self.__available_optimizers:
@@ -204,7 +137,7 @@ class ThinkAnyAI(Provider):
204
137
  conversation_uuid = initiate_conversation(conversation_prompt)
205
138
  web_search_result, links = RAG_search(conversation_uuid)
206
139
  if not web_search_result:
207
- print("Failed to generate WEB response. Making normal Query...")
140
+ print("Failed to generate WEB response. Making normal Querywebscout..")
208
141
 
209
142
  url = f"{self.base_url}/chat"
210
143
  payload = {
@@ -277,4 +210,10 @@ class ThinkAnyAI(Provider):
277
210
  str: Message extracted
278
211
  """
279
212
  assert isinstance(response, dict), "Response should be of dict data-type only"
280
- return response["text"]
213
+ return response["text"]
214
+ if __name__ == "__main__":
215
+ from rich import print
216
+ ai = ThinkAnyAI()
217
+ response = ai.chat(input(">>> "))
218
+ for chunk in response:
219
+ print(chunk, end="", flush=True)
@@ -1,32 +1,15 @@
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
1
+
11
2
  from uuid import uuid4
12
3
  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
4
  import json
21
- import yaml
5
+
22
6
  from webscout.AIutel import Optimizers
23
7
  from webscout.AIutel import Conversation
24
8
  from webscout.AIutel import AwesomePrompts, sanitize_stream
25
9
  from webscout.AIbase import Provider, AsyncProvider
26
10
  from webscout import exceptions
27
11
  from typing import Any, AsyncGenerator, Dict
28
- import logging
29
- import httpx
12
+
30
13
  import cloudscraper
31
14
 
32
15
 
@@ -15,9 +15,7 @@ from .Perplexity import *
15
15
  from .Blackboxai import BLACKBOXAI
16
16
  from .Blackboxai import AsyncBLACKBOXAI
17
17
  from .Phind import PhindSearch
18
- from .Phind import AsyncPhindSearch
19
18
  from .Phind import Phindv2
20
- from .Phind import AsyncPhindv2
21
19
  from .ai4chat import *
22
20
  from .Gemini import GEMINI
23
21
  from .Poe import POE
@@ -25,6 +23,7 @@ from .BasedGPT import BasedGPT
25
23
  from .Deepseek import DeepSeek
26
24
  from .Deepinfra import DeepInfra, VLM, AsyncDeepInfra
27
25
  from .Farfalle import *
26
+ from .cleeai import *
28
27
  from .OLLAMA import OLLAMA
29
28
  from .Andi import AndiSearch
30
29
  from .PizzaGPT import *
@@ -48,6 +47,10 @@ from .AI21 import *
48
47
  from .Chatify import *
49
48
  from .x0gpt import *
50
49
  from .cerebras import *
50
+ from .lepton import *
51
+ from .geminiapi import *
52
+ from .elmo import *
53
+ from .genspark import *
51
54
  __all__ = [
52
55
  'ThinkAnyAI',
53
56
  'Farfalle',
@@ -64,7 +67,6 @@ __all__ = [
64
67
  'BLACKBOXAI',
65
68
  'AsyncBLACKBOXAI',
66
69
  'PhindSearch',
67
- 'AsyncPhindSearch',
68
70
  'Felo',
69
71
  'GEMINI',
70
72
  'POE',
@@ -74,7 +76,6 @@ __all__ = [
74
76
  'VLM',
75
77
  'AsyncDeepInfra',
76
78
  'AI4Chat',
77
- 'AsyncPhindv2',
78
79
  'Phindv2',
79
80
  'OLLAMA',
80
81
  'AndiSearch',
@@ -98,5 +99,11 @@ __all__ = [
98
99
  'AI21',
99
100
  'Chatify',
100
101
  'X0GPT',
101
- 'Cerebras'
102
+ 'Cerebras',
103
+ 'Lepton',
104
+ 'GEMINIAPI',
105
+ 'Cleeai',
106
+ 'Elmo',
107
+ 'Genspark'
108
+
102
109
  ]
@@ -0,0 +1,212 @@
1
+ import requests
2
+ import json
3
+ from uuid import uuid4
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
+
10
+ class Cleeai(Provider):
11
+ """
12
+ A class to interact with the Cleeai.com API.
13
+ """
14
+
15
+ def __init__(
16
+ self,
17
+ is_conversation: bool = True,
18
+ max_tokens: int = 600,
19
+ timeout: int = 30,
20
+ intro: str = None,
21
+ filepath: str = None,
22
+ update_file: bool = True,
23
+ proxies: dict = {},
24
+ history_offset: int = 10250,
25
+ act: str = None,
26
+ ) -> None:
27
+ """Instantiates Cleeai
28
+
29
+ Args:
30
+ is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
31
+ max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
32
+ timeout (int, optional): Http request timeout. Defaults to 30.
33
+ intro (str, optional): Conversation introductory prompt. Defaults to None.
34
+ filepath (str, optional): Path to file containing conversation history. Defaults to None.
35
+ update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
36
+ proxies (dict, optional): Http request proxies. Defaults to {}.
37
+ history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
38
+ act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
39
+ """
40
+ self.session = requests.Session()
41
+ self.is_conversation = is_conversation
42
+ self.max_tokens_to_sample = max_tokens
43
+ self.api_endpoint = "https://qna-api.cleeai.com/open_research"
44
+ self.stream_chunk_size = 64
45
+ self.timeout = timeout
46
+ self.last_response = {}
47
+ self.headers = {
48
+ "accept": "*/*",
49
+ "accept-encoding": "gzip, deflate, br, zstd",
50
+ "accept-language": "en-US,en;q=0.9,en-IN;q=0.8",
51
+ "content-type": "application/json",
52
+ "dnt": "1",
53
+ "origin": "https://www.cleeai.com",
54
+ "priority": "u=1, i",
55
+ "referer": "https://www.cleeai.com/",
56
+ "sec-ch-ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Microsoft Edge";v="128"',
57
+ "sec-ch-ua-mobile": "?0",
58
+ "sec-ch-ua-platform": '"Windows"',
59
+ "sec-fetch-dest": "empty",
60
+ "sec-fetch-mode": "cors",
61
+ "sec-fetch-site": "same-site",
62
+ "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",
63
+ }
64
+
65
+ self.__available_optimizers = (
66
+ method
67
+ for method in dir(Optimizers)
68
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
69
+ )
70
+ self.session.headers.update(self.headers)
71
+ Conversation.intro = (
72
+ AwesomePrompts().get_act(
73
+ act, raise_not_found=True, default=None, case_insensitive=True
74
+ )
75
+ if act
76
+ else intro or Conversation.intro
77
+ )
78
+ self.conversation = Conversation(
79
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
80
+ )
81
+ self.conversation.history_offset = history_offset
82
+ self.session.proxies = proxies
83
+
84
+ def ask(
85
+ self,
86
+ prompt: str,
87
+ stream: bool = False,
88
+ raw: bool = False,
89
+ optimizer: str = None,
90
+ conversationally: bool = False,
91
+ ) -> dict:
92
+ """Chat with AI
93
+
94
+ Args:
95
+ prompt (str): Prompt to be send.
96
+ stream (bool, optional): Flag for streaming response. Defaults to False.
97
+ raw (bool, optional): Stream back raw response as received. Defaults to False.
98
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
99
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
100
+ Returns:
101
+ dict : {}
102
+ ```json
103
+ {
104
+ "text" : "How may I assist you today?"
105
+ }
106
+ ```
107
+ """
108
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
109
+ if optimizer:
110
+ if optimizer in self.__available_optimizers:
111
+ conversation_prompt = getattr(Optimizers, optimizer)(
112
+ conversation_prompt if conversationally else prompt
113
+ )
114
+ else:
115
+ raise Exception(
116
+ f"Optimizer is not one of {self.__available_optimizers}"
117
+ )
118
+
119
+ payload = {
120
+ "data": {
121
+ "question": conversation_prompt,
122
+ "question_id": 69237,
123
+ "query_id": uuid4().hex,
124
+ "source_list": [],
125
+ "followup_qas": [],
126
+ "with_upload": True,
127
+ }
128
+ }
129
+
130
+ def for_stream():
131
+ response = self.session.post(
132
+ self.api_endpoint,
133
+ headers=self.headers,
134
+ json=payload,
135
+ stream=True,
136
+ timeout=self.timeout,
137
+ )
138
+ if not response.ok:
139
+ raise Exception(
140
+ f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
141
+ )
142
+ full_response = ''
143
+ for chunk in response.iter_content(chunk_size=self.stream_chunk_size):
144
+ full_response += chunk.decode('utf-8')
145
+ yield chunk.decode('utf-8') if raw else dict(text=full_response)
146
+
147
+ self.last_response.update(dict(text=full_response))
148
+ self.conversation.update_chat_history(
149
+ prompt, self.get_message(self.last_response)
150
+ )
151
+
152
+ def for_non_stream():
153
+ for _ in for_stream():
154
+ pass
155
+ return self.last_response
156
+
157
+ return for_stream() if stream else for_non_stream()
158
+
159
+ def chat(
160
+ self,
161
+ prompt: str,
162
+ stream: bool = False,
163
+ optimizer: str = None,
164
+ conversationally: bool = False,
165
+ ) -> str:
166
+ """Generate response `str`
167
+ Args:
168
+ prompt (str): Prompt to be send.
169
+ stream (bool, optional): Flag for streaming response. Defaults to False.
170
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
171
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
172
+ Returns:
173
+ str: Response generated
174
+ """
175
+
176
+ def for_stream():
177
+ for response in self.ask(
178
+ prompt, True, optimizer=optimizer, conversationally=conversationally
179
+ ):
180
+ yield self.get_message(response)
181
+
182
+ def for_non_stream():
183
+ return self.get_message(
184
+ self.ask(
185
+ prompt,
186
+ False,
187
+ optimizer=optimizer,
188
+ conversationally=conversationally,
189
+ )
190
+ )
191
+
192
+ return for_stream() if stream else for_non_stream()
193
+
194
+ def get_message(self, response: dict) -> str:
195
+ """Retrieves message only from response
196
+
197
+ Args:
198
+ response (dict): Response generated by `self.ask`
199
+
200
+ Returns:
201
+ str: Message extracted
202
+ """
203
+ assert isinstance(response, dict), "Response should be of dict data-type only"
204
+ return response["text"]
205
+
206
+
207
+ if __name__ == "__main__":
208
+ from rich import print
209
+ ai = Cleeai()
210
+ response = ai.chat(input(">>> "))
211
+ for chunk in response:
212
+ print(chunk, end="", flush=True)