webscout 8.2.4__py3-none-any.whl → 8.2.6__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of webscout might be problematic. Click here for more details.
- webscout/AIauto.py +112 -22
- webscout/AIutel.py +240 -344
- webscout/Extra/autocoder/autocoder.py +66 -5
- webscout/Extra/gguf.py +2 -0
- webscout/Provider/AISEARCH/scira_search.py +3 -5
- webscout/Provider/Aitopia.py +75 -51
- webscout/Provider/AllenAI.py +64 -67
- webscout/Provider/ChatGPTClone.py +33 -34
- webscout/Provider/ChatSandbox.py +342 -0
- webscout/Provider/Cloudflare.py +79 -32
- webscout/Provider/Deepinfra.py +69 -56
- webscout/Provider/ElectronHub.py +48 -39
- webscout/Provider/ExaChat.py +36 -20
- webscout/Provider/GPTWeb.py +24 -18
- webscout/Provider/GithubChat.py +52 -49
- webscout/Provider/GizAI.py +285 -0
- webscout/Provider/Glider.py +39 -28
- webscout/Provider/Groq.py +48 -20
- webscout/Provider/HeckAI.py +18 -36
- webscout/Provider/Jadve.py +30 -37
- webscout/Provider/LambdaChat.py +36 -59
- webscout/Provider/MCPCore.py +18 -21
- webscout/Provider/Marcus.py +23 -14
- webscout/Provider/Nemotron.py +218 -0
- webscout/Provider/Netwrck.py +35 -26
- webscout/Provider/OPENAI/__init__.py +1 -1
- webscout/Provider/OPENAI/exachat.py +4 -0
- webscout/Provider/OPENAI/scirachat.py +3 -4
- webscout/Provider/OPENAI/textpollinations.py +20 -22
- webscout/Provider/OPENAI/toolbaz.py +1 -0
- webscout/Provider/PI.py +22 -13
- webscout/Provider/StandardInput.py +42 -30
- webscout/Provider/TeachAnything.py +24 -12
- webscout/Provider/TextPollinationsAI.py +78 -76
- webscout/Provider/TwoAI.py +120 -88
- webscout/Provider/TypliAI.py +305 -0
- webscout/Provider/Venice.py +24 -22
- webscout/Provider/VercelAI.py +31 -12
- webscout/Provider/WiseCat.py +1 -1
- webscout/Provider/WrDoChat.py +370 -0
- webscout/Provider/__init__.py +11 -13
- webscout/Provider/ai4chat.py +5 -3
- webscout/Provider/akashgpt.py +59 -66
- webscout/Provider/asksteve.py +53 -44
- webscout/Provider/cerebras.py +77 -31
- webscout/Provider/chatglm.py +47 -37
- webscout/Provider/elmo.py +38 -32
- webscout/Provider/freeaichat.py +57 -43
- webscout/Provider/granite.py +24 -21
- webscout/Provider/hermes.py +27 -20
- webscout/Provider/learnfastai.py +25 -20
- webscout/Provider/llmchatco.py +48 -78
- webscout/Provider/multichat.py +13 -3
- webscout/Provider/scira_chat.py +50 -30
- webscout/Provider/scnet.py +27 -21
- webscout/Provider/searchchat.py +16 -24
- webscout/Provider/sonus.py +37 -39
- webscout/Provider/toolbaz.py +24 -46
- webscout/Provider/turboseek.py +37 -41
- webscout/Provider/typefully.py +30 -22
- webscout/Provider/typegpt.py +47 -51
- webscout/Provider/uncovr.py +46 -40
- webscout/__init__.py +0 -1
- webscout/cli.py +256 -0
- webscout/conversation.py +305 -448
- webscout/exceptions.py +3 -0
- webscout/swiftcli/__init__.py +80 -794
- webscout/swiftcli/core/__init__.py +7 -0
- webscout/swiftcli/core/cli.py +297 -0
- webscout/swiftcli/core/context.py +104 -0
- webscout/swiftcli/core/group.py +241 -0
- webscout/swiftcli/decorators/__init__.py +28 -0
- webscout/swiftcli/decorators/command.py +221 -0
- webscout/swiftcli/decorators/options.py +220 -0
- webscout/swiftcli/decorators/output.py +252 -0
- webscout/swiftcli/exceptions.py +21 -0
- webscout/swiftcli/plugins/__init__.py +9 -0
- webscout/swiftcli/plugins/base.py +135 -0
- webscout/swiftcli/plugins/manager.py +262 -0
- webscout/swiftcli/utils/__init__.py +59 -0
- webscout/swiftcli/utils/formatting.py +252 -0
- webscout/swiftcli/utils/parsing.py +267 -0
- webscout/version.py +1 -1
- {webscout-8.2.4.dist-info → webscout-8.2.6.dist-info}/METADATA +166 -45
- {webscout-8.2.4.dist-info → webscout-8.2.6.dist-info}/RECORD +89 -89
- {webscout-8.2.4.dist-info → webscout-8.2.6.dist-info}/WHEEL +1 -1
- webscout-8.2.6.dist-info/entry_points.txt +3 -0
- {webscout-8.2.4.dist-info → webscout-8.2.6.dist-info}/top_level.txt +0 -1
- inferno/__init__.py +0 -6
- inferno/__main__.py +0 -9
- inferno/cli.py +0 -6
- inferno/lol.py +0 -589
- webscout/LLM.py +0 -442
- webscout/Local/__init__.py +0 -12
- webscout/Local/__main__.py +0 -9
- webscout/Local/api.py +0 -576
- webscout/Local/cli.py +0 -516
- webscout/Local/config.py +0 -75
- webscout/Local/llm.py +0 -287
- webscout/Local/model_manager.py +0 -253
- webscout/Local/server.py +0 -721
- webscout/Local/utils.py +0 -93
- webscout/Provider/Chatify.py +0 -175
- webscout/Provider/PizzaGPT.py +0 -228
- webscout/Provider/askmyai.py +0 -158
- webscout/Provider/gaurish.py +0 -244
- webscout/Provider/promptrefine.py +0 -193
- webscout/Provider/tutorai.py +0 -270
- webscout-8.2.4.dist-info/entry_points.txt +0 -5
- {webscout-8.2.4.dist-info → webscout-8.2.6.dist-info}/licenses/LICENSE.md +0 -0
webscout/Provider/gaurish.py
DELETED
|
@@ -1,244 +0,0 @@
|
|
|
1
|
-
import requests
|
|
2
|
-
import json
|
|
3
|
-
from typing import Dict, Generator, Union
|
|
4
|
-
|
|
5
|
-
from webscout.AIutel import Optimizers
|
|
6
|
-
from webscout.AIutel import Conversation
|
|
7
|
-
from webscout.AIutel import AwesomePrompts
|
|
8
|
-
from webscout.AIbase import Provider
|
|
9
|
-
from webscout import exceptions
|
|
10
|
-
from webscout.Litlogger import Logger, LogFormat
|
|
11
|
-
|
|
12
|
-
class GaurishCerebras(Provider):
|
|
13
|
-
"""
|
|
14
|
-
A class to interact with the Gaurish Cerebras API with comprehensive logging.
|
|
15
|
-
"""
|
|
16
|
-
|
|
17
|
-
def __init__(
|
|
18
|
-
self,
|
|
19
|
-
is_conversation: bool = True,
|
|
20
|
-
max_tokens: int = 2049,
|
|
21
|
-
timeout: int = 30,
|
|
22
|
-
intro: str = None,
|
|
23
|
-
filepath: str = None,
|
|
24
|
-
update_file: bool = True,
|
|
25
|
-
proxies: dict = {},
|
|
26
|
-
history_offset: int = 10250,
|
|
27
|
-
act: str = None,
|
|
28
|
-
system_prompt: str = "You are a helpful assistant.",
|
|
29
|
-
logging: bool = False
|
|
30
|
-
):
|
|
31
|
-
"""Initializes the Gaurish Cerebras API client with logging capabilities."""
|
|
32
|
-
self.logger = Logger(
|
|
33
|
-
name="GaurishCerebras",
|
|
34
|
-
format=LogFormat.MODERN_EMOJI,
|
|
35
|
-
) if logging else None
|
|
36
|
-
|
|
37
|
-
if self.logger:
|
|
38
|
-
self.logger.info("Initializing GaurishCerebras client")
|
|
39
|
-
|
|
40
|
-
self.chat_endpoint = "https://proxy.gaurish.xyz/api/cerebras/v1/chat/completions"
|
|
41
|
-
|
|
42
|
-
self.headers = {
|
|
43
|
-
"Content-Type": "application/json",
|
|
44
|
-
"Accept": "application/json",
|
|
45
|
-
"authorization": "Bearer 123",
|
|
46
|
-
"accept-encoding": "gzip, deflate, br, zstd",
|
|
47
|
-
"accept-language": "en-US,en;q=0.9,en-IN;q=0.8",
|
|
48
|
-
"dnt": "1",
|
|
49
|
-
"origin": "https://chat.gaurish.xyz",
|
|
50
|
-
"priority": "u=1, i",
|
|
51
|
-
"referer": "https://chat.gaurish.xyz/",
|
|
52
|
-
"sec-ch-ua": '"Not A(Brand";v="8", "Chromium";v="132", "Microsoft Edge";v="132"',
|
|
53
|
-
"sec-ch-ua-mobile": "?0",
|
|
54
|
-
"sec-ch-ua-platform": '"Windows"',
|
|
55
|
-
"sec-fetch-dest": "empty",
|
|
56
|
-
"sec-fetch-mode": "cors",
|
|
57
|
-
"sec-fetch-site": "same-site",
|
|
58
|
-
"user-agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
|
59
|
-
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
|
60
|
-
"Chrome/132.0.0.0 Safari/537.36 Edg/132.0.0.0"),
|
|
61
|
-
}
|
|
62
|
-
self.session = requests.Session()
|
|
63
|
-
self.session.headers.update(self.headers)
|
|
64
|
-
self.session.proxies.update(proxies)
|
|
65
|
-
self.timeout = timeout
|
|
66
|
-
self.last_response = {}
|
|
67
|
-
|
|
68
|
-
self.is_conversation = is_conversation
|
|
69
|
-
self.max_tokens_to_sample = max_tokens
|
|
70
|
-
|
|
71
|
-
if self.logger:
|
|
72
|
-
self.logger.debug(f"Session configured with timeout: {timeout}")
|
|
73
|
-
self.logger.debug(f"Max tokens set to: {max_tokens}")
|
|
74
|
-
|
|
75
|
-
self.__available_optimizers = (
|
|
76
|
-
method
|
|
77
|
-
for method in dir(Optimizers)
|
|
78
|
-
if callable(getattr(Optimizers, method)) and not method.startswith("__")
|
|
79
|
-
)
|
|
80
|
-
Conversation.intro = (
|
|
81
|
-
AwesomePrompts().get_act(
|
|
82
|
-
act, raise_not_found=True, default=None, case_insensitive=True
|
|
83
|
-
)
|
|
84
|
-
if act
|
|
85
|
-
else intro or system_prompt or Conversation.intro
|
|
86
|
-
)
|
|
87
|
-
self.conversation = Conversation(
|
|
88
|
-
is_conversation, self.max_tokens_to_sample, filepath, update_file
|
|
89
|
-
)
|
|
90
|
-
self.conversation.history_offset = history_offset
|
|
91
|
-
self.system_prompt = system_prompt
|
|
92
|
-
|
|
93
|
-
if self.logger:
|
|
94
|
-
self.logger.info("GaurishCerebras initialization completed successfully")
|
|
95
|
-
|
|
96
|
-
def ask(
|
|
97
|
-
self,
|
|
98
|
-
prompt: str,
|
|
99
|
-
stream: bool = False,
|
|
100
|
-
raw: bool = False,
|
|
101
|
-
optimizer: str = None,
|
|
102
|
-
conversationally: bool = False,
|
|
103
|
-
) -> Union[Dict, Generator]:
|
|
104
|
-
"""
|
|
105
|
-
Sends a prompt to the API and returns the response with logging.
|
|
106
|
-
If stream is True, returns a generator for streamed responses.
|
|
107
|
-
"""
|
|
108
|
-
if self.logger:
|
|
109
|
-
self.logger.debug(f"Processing request - Prompt: {prompt[:50]}...")
|
|
110
|
-
self.logger.debug(f"Stream: {stream}, Optimizer: {optimizer}")
|
|
111
|
-
|
|
112
|
-
conversation_prompt = self.conversation.gen_complete_prompt(prompt)
|
|
113
|
-
if optimizer:
|
|
114
|
-
if optimizer in self.__available_optimizers:
|
|
115
|
-
conversation_prompt = getattr(Optimizers, optimizer)(
|
|
116
|
-
conversation_prompt if conversationally else prompt
|
|
117
|
-
)
|
|
118
|
-
if self.logger:
|
|
119
|
-
self.logger.debug(f"Applied optimizer: {optimizer}")
|
|
120
|
-
else:
|
|
121
|
-
if self.logger:
|
|
122
|
-
self.logger.error(f"Invalid optimizer requested: {optimizer}")
|
|
123
|
-
raise Exception(f"Optimizer is not one of {list(self.__available_optimizers)}")
|
|
124
|
-
|
|
125
|
-
payload = {
|
|
126
|
-
"messages": [
|
|
127
|
-
{"role": "system", "content": self.system_prompt},
|
|
128
|
-
{"role": "user", "content": conversation_prompt},
|
|
129
|
-
],
|
|
130
|
-
"model": "llama3.3-70b",
|
|
131
|
-
"max_tokens": self.max_tokens_to_sample,
|
|
132
|
-
"temperature": 0.75,
|
|
133
|
-
"stream": stream,
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
def for_stream():
|
|
137
|
-
try:
|
|
138
|
-
if self.logger:
|
|
139
|
-
self.logger.debug("Initiating streaming request to API")
|
|
140
|
-
|
|
141
|
-
with self.session.post(self.chat_endpoint, json=payload, stream=True, timeout=self.timeout) as response:
|
|
142
|
-
if response.status_code != 200:
|
|
143
|
-
if self.logger:
|
|
144
|
-
self.logger.error(f"API request failed. Status: {response.status_code}")
|
|
145
|
-
raise exceptions.FailedToGenerateResponseError(
|
|
146
|
-
f"Request failed with status code {response.status_code}"
|
|
147
|
-
)
|
|
148
|
-
|
|
149
|
-
if self.logger:
|
|
150
|
-
self.logger.info(f"API connection established successfully. Status: {response.status_code}")
|
|
151
|
-
|
|
152
|
-
streaming_text = ""
|
|
153
|
-
for line in response.iter_lines(decode_unicode=True):
|
|
154
|
-
if line:
|
|
155
|
-
line = line.strip()
|
|
156
|
-
if line.startswith("data: "):
|
|
157
|
-
json_str = line[6:]
|
|
158
|
-
if json_str == "[DONE]":
|
|
159
|
-
if self.logger:
|
|
160
|
-
self.logger.debug("Stream completed")
|
|
161
|
-
break
|
|
162
|
-
try:
|
|
163
|
-
json_data = json.loads(json_str)
|
|
164
|
-
if 'choices' in json_data:
|
|
165
|
-
choice = json_data['choices'][0]
|
|
166
|
-
if 'delta' in choice and 'content' in choice['delta']:
|
|
167
|
-
content = choice['delta']['content']
|
|
168
|
-
streaming_text += content
|
|
169
|
-
yield dict(text=content) if raw else dict(text=content)
|
|
170
|
-
except json.JSONDecodeError as e:
|
|
171
|
-
if self.logger:
|
|
172
|
-
self.logger.error(f"JSON parsing error: {str(e)}")
|
|
173
|
-
pass
|
|
174
|
-
|
|
175
|
-
self.conversation.update_chat_history(prompt, streaming_text)
|
|
176
|
-
if self.logger:
|
|
177
|
-
self.logger.debug("Response processing completed")
|
|
178
|
-
|
|
179
|
-
except requests.RequestException as e:
|
|
180
|
-
if self.logger:
|
|
181
|
-
self.logger.error(f"Request failed: {str(e)}")
|
|
182
|
-
raise exceptions.FailedToGenerateResponseError(f"Request failed: {e}")
|
|
183
|
-
|
|
184
|
-
def for_non_stream():
|
|
185
|
-
if self.logger:
|
|
186
|
-
self.logger.debug("Processing non-streaming request")
|
|
187
|
-
for _ in for_stream():
|
|
188
|
-
pass
|
|
189
|
-
return self.last_response
|
|
190
|
-
|
|
191
|
-
return for_stream() if stream else for_non_stream()
|
|
192
|
-
|
|
193
|
-
def chat(
|
|
194
|
-
self,
|
|
195
|
-
prompt: str,
|
|
196
|
-
stream: bool = False,
|
|
197
|
-
optimizer: str = None,
|
|
198
|
-
conversationally: bool = False,
|
|
199
|
-
) -> Union[str, Generator]:
|
|
200
|
-
"""
|
|
201
|
-
A convenience method to return just the text message from the response with logging.
|
|
202
|
-
"""
|
|
203
|
-
if self.logger:
|
|
204
|
-
self.logger.debug(f"Chat request initiated - Prompt: {prompt[:50]}...")
|
|
205
|
-
|
|
206
|
-
def for_stream():
|
|
207
|
-
for response in self.ask(
|
|
208
|
-
prompt, stream=True, optimizer=optimizer, conversationally=conversationally
|
|
209
|
-
):
|
|
210
|
-
yield response if isinstance(response, str) else self.get_message(response)
|
|
211
|
-
|
|
212
|
-
def for_non_stream():
|
|
213
|
-
resp = self.ask(
|
|
214
|
-
prompt, stream=False, optimizer=optimizer, conversationally=conversationally
|
|
215
|
-
)
|
|
216
|
-
return resp if isinstance(resp, str) else self.get_message(resp)
|
|
217
|
-
|
|
218
|
-
return for_stream() if stream else for_non_stream()
|
|
219
|
-
|
|
220
|
-
def get_message(self, response: dict) -> str:
|
|
221
|
-
"""
|
|
222
|
-
Retrieve the message text from the API response with logging.
|
|
223
|
-
"""
|
|
224
|
-
if not isinstance(response, dict):
|
|
225
|
-
if self.logger:
|
|
226
|
-
self.logger.warning("Invalid response format received")
|
|
227
|
-
return ""
|
|
228
|
-
|
|
229
|
-
if "text" in response and response["text"]:
|
|
230
|
-
return response["text"]
|
|
231
|
-
|
|
232
|
-
if self.logger:
|
|
233
|
-
self.logger.warning("No valid message content found in response")
|
|
234
|
-
return ""
|
|
235
|
-
|
|
236
|
-
if __name__ == "__main__":
|
|
237
|
-
from rich import print
|
|
238
|
-
bot = GaurishCerebras(logging=True)
|
|
239
|
-
try:
|
|
240
|
-
response = bot.chat("what is meaning of life", stream=True)
|
|
241
|
-
for chunk in response:
|
|
242
|
-
print(chunk, end="", flush=True)
|
|
243
|
-
except Exception as e:
|
|
244
|
-
print(f"An error occurred: {e}")
|
|
@@ -1,193 +0,0 @@
|
|
|
1
|
-
import requests
|
|
2
|
-
import uuid
|
|
3
|
-
import json
|
|
4
|
-
|
|
5
|
-
from webscout.AIutel import Optimizers
|
|
6
|
-
from webscout.AIutel import Conversation
|
|
7
|
-
from webscout.AIutel import AwesomePrompts
|
|
8
|
-
from webscout.AIbase import Provider
|
|
9
|
-
from webscout.litagent import LitAgent as UserAgent
|
|
10
|
-
|
|
11
|
-
class PromptRefine(Provider):
|
|
12
|
-
"""
|
|
13
|
-
A class to interact with the PromptRefine API.
|
|
14
|
-
"""
|
|
15
|
-
AVAILABLE_MODELS = ["openai/gpt-4", "openai/gpt-4o", "openai/gpt-4-1106-preview"]
|
|
16
|
-
def __init__(
|
|
17
|
-
self,
|
|
18
|
-
is_conversation: bool = True,
|
|
19
|
-
max_tokens: int = 600,
|
|
20
|
-
timeout: int = 30,
|
|
21
|
-
intro: str = None,
|
|
22
|
-
filepath: str = None,
|
|
23
|
-
update_file: bool = True,
|
|
24
|
-
proxies: dict = {},
|
|
25
|
-
history_offset: int = 10250,
|
|
26
|
-
act: str = None,
|
|
27
|
-
system_prompt: str = "You are a helpful AI assistant.",
|
|
28
|
-
model: str = "openai/gpt-4o", # Default model
|
|
29
|
-
):
|
|
30
|
-
"""
|
|
31
|
-
Initializes the PromptRefine API with given parameters.
|
|
32
|
-
|
|
33
|
-
Args:
|
|
34
|
-
is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
|
|
35
|
-
max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
|
|
36
|
-
timeout (int, optional): Http request timeout. Defaults to 30.
|
|
37
|
-
intro (str, optional): Conversation introductory prompt. Defaults to None.
|
|
38
|
-
filepath (str, optional): Path to file containing conversation history. Defaults to None.
|
|
39
|
-
update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
|
|
40
|
-
proxies (dict, optional): Http request proxies. Defaults to {}.
|
|
41
|
-
history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
|
|
42
|
-
act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
|
|
43
|
-
system_prompt (str, optional): System prompt for PromptRefine. Defaults to "You are a helpful AI assistant.".
|
|
44
|
-
model (str, optional): Model to use for generation. Defaults to "openai/gpt-4o".
|
|
45
|
-
"""
|
|
46
|
-
self.session = requests.Session()
|
|
47
|
-
self.is_conversation = is_conversation
|
|
48
|
-
self.max_tokens_to_sample = max_tokens
|
|
49
|
-
self.api_endpoint = 'https://www.promptrefine.com/api/completion'
|
|
50
|
-
self.stream_chunk_size = 64
|
|
51
|
-
self.timeout = timeout
|
|
52
|
-
self.last_response = {}
|
|
53
|
-
self.system_prompt = system_prompt
|
|
54
|
-
self.model = model
|
|
55
|
-
self.headers = {
|
|
56
|
-
'origin': 'https://www.promptrefine.com',
|
|
57
|
-
'referer': 'https://www.promptrefine.com/prompt/new',
|
|
58
|
-
'user-agent': UserAgent().random()
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
self.__available_optimizers = (
|
|
62
|
-
method
|
|
63
|
-
for method in dir(Optimizers)
|
|
64
|
-
if callable(getattr(Optimizers, method)) and not method.startswith("__")
|
|
65
|
-
)
|
|
66
|
-
self.session.headers.update(self.headers)
|
|
67
|
-
Conversation.intro = (
|
|
68
|
-
AwesomePrompts().get_act(
|
|
69
|
-
act, raise_not_found=True, default=None, case_insensitive=True
|
|
70
|
-
)
|
|
71
|
-
if act
|
|
72
|
-
else intro or Conversation.intro
|
|
73
|
-
)
|
|
74
|
-
self.conversation = Conversation(
|
|
75
|
-
is_conversation, self.max_tokens_to_sample, filepath, update_file
|
|
76
|
-
)
|
|
77
|
-
self.conversation.history_offset = history_offset
|
|
78
|
-
self.session.proxies = proxies
|
|
79
|
-
if self.model not in self.AVAILABLE_MODELS:
|
|
80
|
-
raise ValueError(f"Invalid model: {self.model}. Available models: {', '.join(self.AVAILABLE_MODELS)}")
|
|
81
|
-
|
|
82
|
-
def ask(
|
|
83
|
-
self,
|
|
84
|
-
prompt: str,
|
|
85
|
-
stream: bool = False,
|
|
86
|
-
raw: bool = False,
|
|
87
|
-
optimizer: str = None,
|
|
88
|
-
conversationally: bool = False,
|
|
89
|
-
) -> dict:
|
|
90
|
-
"""Chat with PromptRefine
|
|
91
|
-
|
|
92
|
-
Args:
|
|
93
|
-
prompt (str): Prompt to be send.
|
|
94
|
-
stream (bool, optional): Flag for streaming response. Defaults to False.
|
|
95
|
-
raw (bool, optional): Stream back raw response as received. Defaults to False.
|
|
96
|
-
optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
|
|
97
|
-
conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
|
|
98
|
-
Returns:
|
|
99
|
-
dict : {}
|
|
100
|
-
```json
|
|
101
|
-
{
|
|
102
|
-
"text" : "How may I assist you today?"
|
|
103
|
-
}
|
|
104
|
-
```
|
|
105
|
-
"""
|
|
106
|
-
conversation_prompt = self.conversation.gen_complete_prompt(prompt)
|
|
107
|
-
if optimizer:
|
|
108
|
-
if optimizer in self.__available_optimizers:
|
|
109
|
-
conversation_prompt = getattr(Optimizers, optimizer)(
|
|
110
|
-
conversation_prompt if conversationally else prompt
|
|
111
|
-
)
|
|
112
|
-
else:
|
|
113
|
-
raise Exception(
|
|
114
|
-
f"Optimizer is not one of {self.__available_optimizers}"
|
|
115
|
-
)
|
|
116
|
-
|
|
117
|
-
payload = {
|
|
118
|
-
"messages": [
|
|
119
|
-
{"role": "system", "content": self.system_prompt},
|
|
120
|
-
{"role": "user", "content": conversation_prompt}
|
|
121
|
-
],
|
|
122
|
-
"variables": {},
|
|
123
|
-
"parameters": {},
|
|
124
|
-
"model": self.model,
|
|
125
|
-
"userId": str(uuid.uuid4()),
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
def for_stream():
|
|
129
|
-
response = self.session.post(self.api_endpoint, headers=self.headers, json=payload, stream=True, timeout=self.timeout)
|
|
130
|
-
if not response.ok:
|
|
131
|
-
raise Exception(
|
|
132
|
-
f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
|
|
133
|
-
)
|
|
134
|
-
|
|
135
|
-
full_response = ""
|
|
136
|
-
for line in response.iter_lines(decode_unicode=True):
|
|
137
|
-
if line:
|
|
138
|
-
full_response += line # No need to decode here
|
|
139
|
-
yield full_response if raw else dict(text=line)
|
|
140
|
-
self.last_response.update(dict(text=full_response))
|
|
141
|
-
self.conversation.update_chat_history(
|
|
142
|
-
prompt, self.get_message(self.last_response)
|
|
143
|
-
)
|
|
144
|
-
|
|
145
|
-
def for_non_stream():
|
|
146
|
-
for _ in for_stream():
|
|
147
|
-
pass
|
|
148
|
-
return self.last_response
|
|
149
|
-
|
|
150
|
-
return for_stream() if stream else for_non_stream()
|
|
151
|
-
|
|
152
|
-
def chat(
|
|
153
|
-
self,
|
|
154
|
-
prompt: str,
|
|
155
|
-
stream: bool = False,
|
|
156
|
-
optimizer: str = None,
|
|
157
|
-
conversationally: bool = False,
|
|
158
|
-
) -> str:
|
|
159
|
-
"""Generate response `str`
|
|
160
|
-
Args:
|
|
161
|
-
prompt (str): Prompt to be send.
|
|
162
|
-
stream (bool, optional): Flag for streaming response. Defaults to False.
|
|
163
|
-
optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
|
|
164
|
-
conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
|
|
165
|
-
Returns:
|
|
166
|
-
str: Response generated
|
|
167
|
-
"""
|
|
168
|
-
return self.get_message(
|
|
169
|
-
self.ask(
|
|
170
|
-
prompt,
|
|
171
|
-
optimizer=optimizer,
|
|
172
|
-
conversationally=conversationally,
|
|
173
|
-
)
|
|
174
|
-
)
|
|
175
|
-
|
|
176
|
-
def get_message(self, response: dict) -> str:
|
|
177
|
-
"""Retrieves message only from response
|
|
178
|
-
|
|
179
|
-
Args:
|
|
180
|
-
response (dict): Response generated by `self.ask`
|
|
181
|
-
|
|
182
|
-
Returns:
|
|
183
|
-
str: Message extracted
|
|
184
|
-
"""
|
|
185
|
-
assert isinstance(response, dict), "Response should be of dict data-type only"
|
|
186
|
-
return response["text"]
|
|
187
|
-
|
|
188
|
-
if __name__ == '__main__':
|
|
189
|
-
from rich import print
|
|
190
|
-
ai = PromptRefine(timeout=5000)
|
|
191
|
-
response = ai.chat("write a poem about AI", stream=True)
|
|
192
|
-
for chunk in response:
|
|
193
|
-
print(chunk, end="", flush=True)
|