webscout 6.0__py3-none-any.whl → 6.2b0__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 +77 -259
- webscout/Agents/Onlinesearcher.py +22 -10
- webscout/Agents/functioncall.py +2 -2
- webscout/Bard.py +21 -21
- webscout/Extra/autollama.py +37 -20
- webscout/Local/__init__.py +6 -7
- webscout/Local/formats.py +404 -194
- webscout/Local/model.py +1074 -477
- webscout/Local/samplers.py +108 -144
- webscout/Local/thread.py +251 -410
- webscout/Local/ui.py +401 -0
- webscout/Local/utils.py +338 -136
- webscout/Provider/Amigo.py +51 -38
- webscout/Provider/Deepseek.py +7 -6
- webscout/Provider/EDITEE.py +2 -2
- webscout/Provider/GPTWeb.py +1 -1
- webscout/Provider/NinjaChat.py +200 -0
- webscout/Provider/OLLAMA.py +1 -1
- webscout/Provider/Perplexity.py +1 -1
- webscout/Provider/Reka.py +12 -5
- webscout/Provider/TTI/AIuncensored.py +103 -0
- webscout/Provider/TTI/Nexra.py +3 -3
- webscout/Provider/TTI/__init__.py +3 -2
- webscout/Provider/TTI/aiforce.py +2 -2
- webscout/Provider/TTI/imgninza.py +136 -0
- webscout/Provider/TeachAnything.py +0 -3
- webscout/Provider/Youchat.py +1 -1
- webscout/Provider/__init__.py +12 -11
- webscout/Provider/{ChatHub.py → aimathgpt.py} +72 -88
- webscout/Provider/cerebras.py +125 -118
- webscout/Provider/cleeai.py +1 -1
- webscout/Provider/felo_search.py +1 -1
- webscout/Provider/gaurish.py +207 -0
- webscout/Provider/geminiprorealtime.py +160 -0
- webscout/Provider/genspark.py +1 -1
- webscout/Provider/julius.py +8 -3
- webscout/Provider/learnfastai.py +1 -1
- webscout/Provider/promptrefine.py +3 -1
- webscout/Provider/turboseek.py +3 -8
- webscout/Provider/tutorai.py +1 -1
- webscout/__init__.py +2 -43
- webscout/exceptions.py +5 -1
- webscout/tempid.py +4 -73
- webscout/utils.py +3 -0
- webscout/version.py +1 -1
- webscout/webai.py +1 -1
- webscout/webscout_search.py +154 -123
- {webscout-6.0.dist-info → webscout-6.2b0.dist-info}/METADATA +156 -236
- {webscout-6.0.dist-info → webscout-6.2b0.dist-info}/RECORD +53 -54
- webscout/Local/rawdog.py +0 -946
- webscout/Provider/BasedGPT.py +0 -214
- webscout/Provider/TTI/amigo.py +0 -148
- webscout/Provider/aigames.py +0 -213
- webscout/Provider/bixin.py +0 -264
- webscout/Provider/xdash.py +0 -182
- webscout/websx_search.py +0 -19
- {webscout-6.0.dist-info → webscout-6.2b0.dist-info}/LICENSE.md +0 -0
- {webscout-6.0.dist-info → webscout-6.2b0.dist-info}/WHEEL +0 -0
- {webscout-6.0.dist-info → webscout-6.2b0.dist-info}/entry_points.txt +0 -0
- {webscout-6.0.dist-info → webscout-6.2b0.dist-info}/top_level.txt +0 -0
webscout/Provider/BasedGPT.py
DELETED
|
@@ -1,214 +0,0 @@
|
|
|
1
|
-
import requests
|
|
2
|
-
import json
|
|
3
|
-
from webscout.AIutel import Optimizers
|
|
4
|
-
from webscout.AIutel import Conversation
|
|
5
|
-
from webscout.AIutel import AwesomePrompts, sanitize_stream
|
|
6
|
-
from webscout.AIbase import Provider, AsyncProvider
|
|
7
|
-
from webscout import exceptions
|
|
8
|
-
from typing import Any, AsyncGenerator, Dict
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
class BasedGPT(Provider):
|
|
12
|
-
def __init__(
|
|
13
|
-
self,
|
|
14
|
-
is_conversation: bool = True,
|
|
15
|
-
max_tokens: int = 600,
|
|
16
|
-
timeout: int = 30,
|
|
17
|
-
intro: str = None,
|
|
18
|
-
filepath: str = None,
|
|
19
|
-
update_file: bool = True,
|
|
20
|
-
proxies: dict = {},
|
|
21
|
-
history_offset: int = 10250,
|
|
22
|
-
act: str = None,
|
|
23
|
-
model: str = "gpt-3.5-turbo"
|
|
24
|
-
):
|
|
25
|
-
"""Instantiates BasedGPT
|
|
26
|
-
|
|
27
|
-
Args:
|
|
28
|
-
is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
|
|
29
|
-
max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
|
|
30
|
-
timeout (int, optional): Http request timeout. Defaults to 30.
|
|
31
|
-
intro (str, optional): Conversation introductory prompt. Defaults to None.
|
|
32
|
-
filepath (str, optional): Path to file containing conversation history. Defaults to None.
|
|
33
|
-
update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
|
|
34
|
-
proxies (dict, optional): Http request proxies. Defaults to {}.
|
|
35
|
-
history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
|
|
36
|
-
act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
|
|
37
|
-
model (str, optional): Model to use for generating text. Defaults to "gpt-3.5-turbo".
|
|
38
|
-
"""
|
|
39
|
-
self.session = requests.Session()
|
|
40
|
-
self.is_conversation = is_conversation
|
|
41
|
-
self.max_tokens_to_sample = max_tokens
|
|
42
|
-
self.chat_endpoint = "https://www.basedgpt.chat/api/chat"
|
|
43
|
-
self.timeout = timeout
|
|
44
|
-
self.last_response = {}
|
|
45
|
-
self.model = model
|
|
46
|
-
self.headers = {
|
|
47
|
-
"accept": "*/*",
|
|
48
|
-
"accept-encoding": "gzip, deflate, br, zstd",
|
|
49
|
-
"accept-language": "en-US,en;q=0.9,en-IN;q=0.8",
|
|
50
|
-
"content-length": "109",
|
|
51
|
-
"content-type": "application/json",
|
|
52
|
-
"dnt": "1",
|
|
53
|
-
"origin": "https://www.basedgpt.chat",
|
|
54
|
-
"priority": "u=1, i",
|
|
55
|
-
"referer": "https://www.basedgpt.chat/",
|
|
56
|
-
"sec-ch-ua": '"Not)A;Brand";v="99", "Microsoft Edge";v="127", "Chromium";v="127"',
|
|
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-origin",
|
|
62
|
-
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.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
|
-
self.session.headers.update(self.headers)
|
|
120
|
-
payload = {
|
|
121
|
-
"messages": [
|
|
122
|
-
{
|
|
123
|
-
"role": "user",
|
|
124
|
-
"content": conversation_prompt
|
|
125
|
-
}
|
|
126
|
-
]
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
def for_stream():
|
|
130
|
-
response = self.session.post(
|
|
131
|
-
self.chat_endpoint, json=payload, stream=True, timeout=self.timeout
|
|
132
|
-
)
|
|
133
|
-
if not response.ok:
|
|
134
|
-
raise Exception(
|
|
135
|
-
f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
|
|
136
|
-
)
|
|
137
|
-
|
|
138
|
-
streaming_text = ""
|
|
139
|
-
for value in response.iter_lines(
|
|
140
|
-
decode_unicode=True,
|
|
141
|
-
chunk_size=64,
|
|
142
|
-
delimiter="\n",
|
|
143
|
-
):
|
|
144
|
-
try:
|
|
145
|
-
if bool(value):
|
|
146
|
-
streaming_text += value + ("\n" if stream else "")
|
|
147
|
-
resp = dict(text=streaming_text)
|
|
148
|
-
self.last_response.update(resp)
|
|
149
|
-
yield value if raw else resp
|
|
150
|
-
except json.decoder.JSONDecodeError:
|
|
151
|
-
pass
|
|
152
|
-
self.conversation.update_chat_history(
|
|
153
|
-
prompt, self.get_message(self.last_response)
|
|
154
|
-
)
|
|
155
|
-
|
|
156
|
-
def for_non_stream():
|
|
157
|
-
for _ in for_stream():
|
|
158
|
-
pass
|
|
159
|
-
return self.last_response
|
|
160
|
-
|
|
161
|
-
return for_stream() if stream else for_non_stream()
|
|
162
|
-
|
|
163
|
-
def chat(
|
|
164
|
-
self,
|
|
165
|
-
prompt: str,
|
|
166
|
-
stream: bool = False,
|
|
167
|
-
optimizer: str = None,
|
|
168
|
-
conversationally: bool = False,
|
|
169
|
-
) -> str:
|
|
170
|
-
"""Generate response `str`
|
|
171
|
-
Args:
|
|
172
|
-
prompt (str): Prompt to be send.
|
|
173
|
-
stream (bool, optional): Flag for streaming response. Defaults to False.
|
|
174
|
-
optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
|
|
175
|
-
conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
|
|
176
|
-
Returns:
|
|
177
|
-
str: Response generated
|
|
178
|
-
"""
|
|
179
|
-
|
|
180
|
-
def for_stream():
|
|
181
|
-
for response in self.ask(
|
|
182
|
-
prompt, True, optimizer=optimizer, conversationally=conversationally
|
|
183
|
-
):
|
|
184
|
-
yield self.get_message(response)
|
|
185
|
-
|
|
186
|
-
def for_non_stream():
|
|
187
|
-
return self.get_message(
|
|
188
|
-
self.ask(
|
|
189
|
-
prompt,
|
|
190
|
-
False,
|
|
191
|
-
optimizer=optimizer,
|
|
192
|
-
conversationally=conversationally,
|
|
193
|
-
)
|
|
194
|
-
)
|
|
195
|
-
|
|
196
|
-
return for_stream() if stream else for_non_stream()
|
|
197
|
-
|
|
198
|
-
def get_message(self, response: dict) -> str:
|
|
199
|
-
"""Retrieves message only from response
|
|
200
|
-
|
|
201
|
-
Args:
|
|
202
|
-
response (dict): Response generated by `self.ask`
|
|
203
|
-
|
|
204
|
-
Returns:
|
|
205
|
-
str: Message extracted
|
|
206
|
-
"""
|
|
207
|
-
assert isinstance(response, dict), "Response should be of dict data-type only"
|
|
208
|
-
return response["text"]
|
|
209
|
-
if __name__ == '__main__':
|
|
210
|
-
from rich import print
|
|
211
|
-
ai = BasedGPT()
|
|
212
|
-
response = ai.chat("tell me about india")
|
|
213
|
-
for chunk in response:
|
|
214
|
-
print(chunk, end="", flush=True)
|
webscout/Provider/TTI/amigo.py
DELETED
|
@@ -1,148 +0,0 @@
|
|
|
1
|
-
import requests
|
|
2
|
-
import json
|
|
3
|
-
import uuid
|
|
4
|
-
import os
|
|
5
|
-
from typing import List
|
|
6
|
-
|
|
7
|
-
from webscout.AIbase import ImageProvider
|
|
8
|
-
|
|
9
|
-
class AmigoImager(ImageProvider):
|
|
10
|
-
"""
|
|
11
|
-
Image provider for AmigoChat.io.
|
|
12
|
-
"""
|
|
13
|
-
AVAILABLE_MODELS = ["dalle-e-3", "flux-pro", "flux-realism"]
|
|
14
|
-
def __init__(self, timeout: int = 60, proxies: dict = {}):
|
|
15
|
-
"""Initializes the AmigoImager class.
|
|
16
|
-
|
|
17
|
-
Args:
|
|
18
|
-
timeout (int, optional): HTTP request timeout in seconds. Defaults to 60.
|
|
19
|
-
proxies (dict, optional): HTTP request proxies. Defaults to {}.
|
|
20
|
-
"""
|
|
21
|
-
self.url = "https://api.amigochat.io/v1/images/generations"
|
|
22
|
-
self.headers = {
|
|
23
|
-
"Accept": "*/*",
|
|
24
|
-
"Accept-Encoding": "gzip, deflate, br, zstd",
|
|
25
|
-
"Accept-Language": "en-US,en;q=0.9,en-IN;q=0.8",
|
|
26
|
-
"Authorization": "Bearer ", # Empty
|
|
27
|
-
"Content-Type": "application/json; charset=utf-8",
|
|
28
|
-
"DNT": "1",
|
|
29
|
-
"Origin": "https://amigochat.io",
|
|
30
|
-
"Referer": "https://amigochat.io/",
|
|
31
|
-
"Sec-CH-UA": '"Microsoft Edge";v="129", "Not=A?Brand";v="8", "Chromium";v="129"',
|
|
32
|
-
"Sec-CH-UA-Mobile": "?0",
|
|
33
|
-
"Sec-CH-UA-Platform": '"Windows"',
|
|
34
|
-
"Sec-Fetch-Dest": "empty",
|
|
35
|
-
"Sec-Fetch-Mode": "cors",
|
|
36
|
-
"Sec-Fetch-Site": "same-site",
|
|
37
|
-
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0",
|
|
38
|
-
"X-Device-Language": "en-US",
|
|
39
|
-
"X-Device-Platform": "web",
|
|
40
|
-
"X-Device-UUID": str(uuid.uuid4()),
|
|
41
|
-
"X-Device-Version": "1.0.22"
|
|
42
|
-
}
|
|
43
|
-
self.session = requests.Session()
|
|
44
|
-
self.session.headers.update(self.headers)
|
|
45
|
-
self.session.proxies.update(proxies)
|
|
46
|
-
self.timeout = timeout
|
|
47
|
-
self.prompt: str = "AI-generated image - webscout"
|
|
48
|
-
self.image_extension: str = "png"
|
|
49
|
-
|
|
50
|
-
def generate(self, prompt: str, amount: int = 1, model: str = "flux-pro") -> List[str]:
|
|
51
|
-
"""Generate image from prompt
|
|
52
|
-
|
|
53
|
-
Args:
|
|
54
|
-
prompt (str): Image description.
|
|
55
|
-
amount (int, optional): Total images to be generated. Defaults to 1.
|
|
56
|
-
model (str, optional): Model to use for generating images. Defaults to "flux-pro".
|
|
57
|
-
|
|
58
|
-
Returns:
|
|
59
|
-
List[str]: List of generated image URLs.
|
|
60
|
-
"""
|
|
61
|
-
assert bool(prompt), "Prompt cannot be null"
|
|
62
|
-
assert isinstance(amount, int), f"Amount should be an integer only not {type(amount)}"
|
|
63
|
-
assert amount > 0, "Amount should be greater than 0"
|
|
64
|
-
assert model in self.AVAILABLE_MODELS, f"Model should be one of {self.AVAILABLE_MODELS}"
|
|
65
|
-
|
|
66
|
-
self.prompt = prompt
|
|
67
|
-
response = []
|
|
68
|
-
|
|
69
|
-
for _ in range(amount):
|
|
70
|
-
# JSON payload for the request
|
|
71
|
-
payload = {
|
|
72
|
-
"prompt": prompt,
|
|
73
|
-
"model": model,
|
|
74
|
-
"personaId": "image-generator"
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
try:
|
|
78
|
-
# Sending the POST request
|
|
79
|
-
resp = requests.post(self.url, headers=self.headers, data=json.dumps(payload), timeout=self.timeout)
|
|
80
|
-
resp.raise_for_status()
|
|
81
|
-
|
|
82
|
-
# Process the response
|
|
83
|
-
response_data = resp.json()
|
|
84
|
-
image_url = response_data['data'][0]['url']
|
|
85
|
-
response.append(image_url)
|
|
86
|
-
|
|
87
|
-
except requests.exceptions.RequestException as e:
|
|
88
|
-
print(f"An error occurred: {e}")
|
|
89
|
-
raise
|
|
90
|
-
|
|
91
|
-
return response
|
|
92
|
-
|
|
93
|
-
def save(
|
|
94
|
-
self,
|
|
95
|
-
response: List[str], # List of image URLs
|
|
96
|
-
name: str = None,
|
|
97
|
-
dir: str = os.getcwd(),
|
|
98
|
-
filenames_prefix: str = "",
|
|
99
|
-
) -> List[str]:
|
|
100
|
-
"""Save generated images
|
|
101
|
-
|
|
102
|
-
Args:
|
|
103
|
-
response (List[str]): List of generated image URLs.
|
|
104
|
-
name (str): Filename for the images. Defaults to the last prompt.
|
|
105
|
-
dir (str, optional): Directory for saving images. Defaults to os.getcwd().
|
|
106
|
-
filenames_prefix (str, optional): String to be prefixed at each filename to be returned.
|
|
107
|
-
|
|
108
|
-
Returns:
|
|
109
|
-
List[str]: List of saved filenames.
|
|
110
|
-
"""
|
|
111
|
-
assert isinstance(response, list), f"Response should be of {list} not {type(response)}"
|
|
112
|
-
name = self.prompt if name is None else name
|
|
113
|
-
|
|
114
|
-
filenames = []
|
|
115
|
-
count = 0
|
|
116
|
-
for img_url in response:
|
|
117
|
-
def complete_path():
|
|
118
|
-
count_value = "" if count == 0 else f"_{count}"
|
|
119
|
-
return os.path.join(dir, name + count_value + "." + self.image_extension)
|
|
120
|
-
|
|
121
|
-
while os.path.isfile(complete_path()):
|
|
122
|
-
count += 1
|
|
123
|
-
|
|
124
|
-
absolute_path_to_file = complete_path()
|
|
125
|
-
filenames.append(filenames_prefix + os.path.split(absolute_path_to_file)[1])
|
|
126
|
-
|
|
127
|
-
# Download and save the image
|
|
128
|
-
try:
|
|
129
|
-
img_response = requests.get(img_url, stream=True, timeout=self.timeout)
|
|
130
|
-
img_response.raise_for_status()
|
|
131
|
-
|
|
132
|
-
with open(absolute_path_to_file, "wb") as fh:
|
|
133
|
-
for chunk in img_response.iter_content(chunk_size=8192):
|
|
134
|
-
fh.write(chunk)
|
|
135
|
-
except requests.exceptions.RequestException as e:
|
|
136
|
-
print(f"An error occurred while downloading image from {img_url}: {e}")
|
|
137
|
-
raise
|
|
138
|
-
|
|
139
|
-
return filenames
|
|
140
|
-
|
|
141
|
-
# Example usage
|
|
142
|
-
if __name__ == "__main__":
|
|
143
|
-
bot = AmigoImager()
|
|
144
|
-
try:
|
|
145
|
-
resp = bot.generate("A shiny red sports car speeding down a scenic mountain road", 1)
|
|
146
|
-
print(bot.save(resp))
|
|
147
|
-
except Exception as e:
|
|
148
|
-
print(f"An error occurred: {e}")
|
webscout/Provider/aigames.py
DELETED
|
@@ -1,213 +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
|
-
|
|
10
|
-
class AIGameIO(Provider):
|
|
11
|
-
"""
|
|
12
|
-
A class to interact with the AI-Game.io 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
|
-
system_prompt: str = "You are a Helpful ai"
|
|
27
|
-
):
|
|
28
|
-
"""
|
|
29
|
-
Initializes the AI-Game.io API with given parameters.
|
|
30
|
-
|
|
31
|
-
Args:
|
|
32
|
-
is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
|
|
33
|
-
max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
|
|
34
|
-
timeout (int, optional): Http request timeout. Defaults to 30.
|
|
35
|
-
intro (str, optional): Conversation introductory prompt. Defaults to None.
|
|
36
|
-
filepath (str, optional): Path to file containing conversation history. Defaults to None.
|
|
37
|
-
update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
|
|
38
|
-
proxies (dict, optional): Http request proxies. Defaults to {}.
|
|
39
|
-
history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
|
|
40
|
-
act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
|
|
41
|
-
system_prompt (str, optional): System prompt for AI-Game.io.
|
|
42
|
-
Defaults to "You are a Helpful ai".
|
|
43
|
-
"""
|
|
44
|
-
self.session = requests.Session()
|
|
45
|
-
self.is_conversation = is_conversation
|
|
46
|
-
self.max_tokens_to_sample = max_tokens
|
|
47
|
-
self.api_endpoint = 'https://stream-chat-blmeirpipa-uc.a.run.app/streamChat'
|
|
48
|
-
self.stream_chunk_size = 64
|
|
49
|
-
self.timeout = timeout
|
|
50
|
-
self.last_response = {}
|
|
51
|
-
self.system_prompt = system_prompt
|
|
52
|
-
self.headers = {
|
|
53
|
-
'authority': 'stream-chat-blmeirpipa-uc.a.run.app',
|
|
54
|
-
'method': 'POST',
|
|
55
|
-
'path': '/streamChat',
|
|
56
|
-
'accept': 'text/event-stream',
|
|
57
|
-
'content-type': 'application/json',
|
|
58
|
-
'origin': 'https://www.ai-game.io',
|
|
59
|
-
'priority': 'u=1, i',
|
|
60
|
-
'referer': 'https://www.ai-game.io/',
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
self.__available_optimizers = (
|
|
64
|
-
method
|
|
65
|
-
for method in dir(Optimizers)
|
|
66
|
-
if callable(getattr(Optimizers, method)) and not method.startswith("__")
|
|
67
|
-
)
|
|
68
|
-
self.session.headers.update(self.headers)
|
|
69
|
-
Conversation.intro = (
|
|
70
|
-
AwesomePrompts().get_act(
|
|
71
|
-
act, raise_not_found=True, default=None, case_insensitive=True
|
|
72
|
-
)
|
|
73
|
-
if act
|
|
74
|
-
else intro or Conversation.intro
|
|
75
|
-
)
|
|
76
|
-
self.conversation = Conversation(
|
|
77
|
-
is_conversation, self.max_tokens_to_sample, filepath, update_file
|
|
78
|
-
)
|
|
79
|
-
self.conversation.history_offset = history_offset
|
|
80
|
-
self.session.proxies = proxies
|
|
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 AI
|
|
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
|
-
"history": [
|
|
119
|
-
{
|
|
120
|
-
"role": "system",
|
|
121
|
-
"content": self.system_prompt
|
|
122
|
-
},
|
|
123
|
-
{
|
|
124
|
-
"role": "user",
|
|
125
|
-
"content": conversation_prompt
|
|
126
|
-
}
|
|
127
|
-
]
|
|
128
|
-
}
|
|
129
|
-
def for_stream():
|
|
130
|
-
response = self.session.post(
|
|
131
|
-
self.api_endpoint, headers=self.headers, data=json.dumps(payload), stream=True, timeout=self.timeout
|
|
132
|
-
)
|
|
133
|
-
if not response.ok:
|
|
134
|
-
raise Exception(
|
|
135
|
-
f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
|
|
136
|
-
)
|
|
137
|
-
|
|
138
|
-
full_response = ''
|
|
139
|
-
for line in response.iter_lines(decode_unicode=True):
|
|
140
|
-
if line.startswith("data: "):
|
|
141
|
-
try:
|
|
142
|
-
event_data = json.loads(line[6:])
|
|
143
|
-
if event_data['event'] == 'text-chunk':
|
|
144
|
-
full_response += event_data['data']['text']
|
|
145
|
-
yield event_data['data']['text'] if raw else dict(text=full_response)
|
|
146
|
-
except json.JSONDecodeError:
|
|
147
|
-
pass
|
|
148
|
-
self.last_response.update(dict(text=full_response))
|
|
149
|
-
self.conversation.update_chat_history(
|
|
150
|
-
prompt, self.get_message(self.last_response)
|
|
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
|
-
|
|
210
|
-
ai = AIGameIO()
|
|
211
|
-
response = ai.chat("hi")
|
|
212
|
-
for chunk in response:
|
|
213
|
-
print(chunk, end="", flush=True)
|