webscout 2.8__py3-none-any.whl → 3.0__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/AIutel.py +1 -0
- webscout/Local/_version.py +1 -1
- webscout/Local/model.py +73 -4
- webscout/Local/thread.py +10 -2
- webscout/Local/utils.py +3 -2
- webscout/Provider/BasedGPT.py +225 -225
- webscout/Provider/Berlin4h.py +210 -210
- webscout/Provider/Blackboxai.py +439 -439
- webscout/Provider/ChatGPTUK.py +213 -213
- webscout/Provider/Cohere.py +222 -222
- webscout/Provider/Gemini.py +216 -216
- webscout/Provider/Groq.py +511 -511
- webscout/Provider/Koboldai.py +401 -401
- webscout/Provider/Leo.py +468 -468
- webscout/Provider/Llama2.py +436 -436
- webscout/Provider/OpenGPT.py +486 -486
- webscout/Provider/Openai.py +510 -510
- webscout/Provider/Perplexity.py +229 -229
- webscout/Provider/Phind.py +517 -517
- webscout/Provider/Poe.py +207 -207
- webscout/Provider/Reka.py +225 -225
- webscout/Provider/Xjai.py +230 -230
- webscout/Provider/Yepchat.py +477 -477
- webscout/Provider/Youchat.py +220 -220
- webscout/Provider/__init__.py +61 -60
- webscout/__init__.py +1 -0
- webscout/version.py +1 -1
- {webscout-2.8.dist-info → webscout-3.0.dist-info}/METADATA +378 -29
- {webscout-2.8.dist-info → webscout-3.0.dist-info}/RECORD +33 -33
- {webscout-2.8.dist-info → webscout-3.0.dist-info}/LICENSE.md +0 -0
- {webscout-2.8.dist-info → webscout-3.0.dist-info}/WHEEL +0 -0
- {webscout-2.8.dist-info → webscout-3.0.dist-info}/entry_points.txt +0 -0
- {webscout-2.8.dist-info → webscout-3.0.dist-info}/top_level.txt +0 -0
webscout/AIutel.py
CHANGED
webscout/Local/_version.py
CHANGED
webscout/Local/model.py
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import json
|
|
1
2
|
from ._version import __version__, __llama_cpp_version__
|
|
2
3
|
|
|
3
4
|
"""Submodule containing the Model class to work with language models"""
|
|
@@ -15,7 +16,7 @@ from .utils import (
|
|
|
15
16
|
|
|
16
17
|
from .samplers import SamplerSettings, DefaultSampling
|
|
17
18
|
from llama_cpp import Llama, StoppingCriteriaList
|
|
18
|
-
from typing import Generator, Optional, Union
|
|
19
|
+
from typing import Callable, Generator, Optional, Union
|
|
19
20
|
from os.path import isdir, exists
|
|
20
21
|
from heapq import nlargest
|
|
21
22
|
|
|
@@ -26,6 +27,8 @@ class ModelUnloadedException(Exception):
|
|
|
26
27
|
"""Exception raised when trying to use a Model that has been unloaded"""
|
|
27
28
|
def __init__(self, message):
|
|
28
29
|
self.message = message
|
|
30
|
+
self.tool_code_start = "```tool_code\n" # Define tool code markers
|
|
31
|
+
self.tool_code_end = "\n```tool_code```"
|
|
29
32
|
super().__init__(self.message)
|
|
30
33
|
self.add_note('Are you trying to use a Model that has been unloaded?')
|
|
31
34
|
|
|
@@ -68,7 +71,7 @@ class Model:
|
|
|
68
71
|
n_gpu_layers: int = 0,
|
|
69
72
|
offload_kqv: bool = True,
|
|
70
73
|
flash_attn: bool = False,
|
|
71
|
-
verbose: bool = False
|
|
74
|
+
verbose: bool = False,
|
|
72
75
|
):
|
|
73
76
|
"""
|
|
74
77
|
Given the path to a GGUF file, construct a Model instance.
|
|
@@ -105,7 +108,7 @@ class Model:
|
|
|
105
108
|
self._offload_kqv = offload_kqv
|
|
106
109
|
self._flash_attn = flash_attn
|
|
107
110
|
self._verbose = self.verbose = verbose
|
|
108
|
-
|
|
111
|
+
self.tools = {}
|
|
109
112
|
# if context_length <= 0, use n_ctx_train
|
|
110
113
|
if isinstance(context_length, int) and context_length <= 0:
|
|
111
114
|
context_length = None
|
|
@@ -269,7 +272,73 @@ class Model:
|
|
|
269
272
|
print_verbose(f"param: self.context_length == {self.context_length}")
|
|
270
273
|
print_verbose(f" gguf: rope_freq_base_train == {rope_freq_base_train}")
|
|
271
274
|
print_verbose(f"param: rope_freq_base == {rope_freq_base}")
|
|
272
|
-
|
|
275
|
+
def register_tool(self, name: str, function: Callable):
|
|
276
|
+
"""Registers a tool for function calling."""
|
|
277
|
+
self.tools[name] = function
|
|
278
|
+
|
|
279
|
+
def _extract_tool_code(self, text: str) -> dict:
|
|
280
|
+
"""Extracts tool code from the model's output."""
|
|
281
|
+
try:
|
|
282
|
+
start = text.find(self.tool_code_start) + len(self.tool_code_start)
|
|
283
|
+
end = text.find(self.tool_code_end)
|
|
284
|
+
tool_code_json = text[start:end]
|
|
285
|
+
tool_code = json.loads(tool_code_json)
|
|
286
|
+
return tool_code
|
|
287
|
+
except (ValueError, json.JSONDecodeError):
|
|
288
|
+
return None
|
|
289
|
+
def _should_call_tool(self, response_text: str) -> bool:
|
|
290
|
+
"""Determines if the model suggests a tool call."""
|
|
291
|
+
# Simple check for tool code markers in response
|
|
292
|
+
return self.tool_code_start in response_text and self.tool_code_end in response_text
|
|
293
|
+
def generate(
|
|
294
|
+
self,
|
|
295
|
+
prompt: Union[str, list[int]],
|
|
296
|
+
stops: list[Union[str, int]] = [],
|
|
297
|
+
sampler: SamplerSettings = DefaultSampling,
|
|
298
|
+
max_iterations: int = 3, # Maximum iterations for tool calls
|
|
299
|
+
) -> str:
|
|
300
|
+
"""
|
|
301
|
+
Generates text and handles tool calls.
|
|
302
|
+
|
|
303
|
+
Args:
|
|
304
|
+
prompt (Union[str, list[int]]): The input prompt.
|
|
305
|
+
stops (list[Union[str, int]]): Stop sequences.
|
|
306
|
+
sampler (SamplerSettings): Sampler settings.
|
|
307
|
+
max_iterations (int): Maximum number of tool call iterations.
|
|
308
|
+
|
|
309
|
+
Returns:
|
|
310
|
+
str: The generated text.
|
|
311
|
+
"""
|
|
312
|
+
assert_model_is_loaded(self)
|
|
313
|
+
response_text = self.llama.create_completion(
|
|
314
|
+
prompt,
|
|
315
|
+
max_tokens=sampler.max_len_tokens,
|
|
316
|
+
temperature=sampler.temp,
|
|
317
|
+
top_p=sampler.top_p,
|
|
318
|
+
min_p=sampler.min_p,
|
|
319
|
+
frequency_penalty=sampler.frequency_penalty,
|
|
320
|
+
presence_penalty=sampler.presence_penalty,
|
|
321
|
+
repeat_penalty=sampler.repeat_penalty,
|
|
322
|
+
top_k=sampler.top_k,
|
|
323
|
+
stop=stops
|
|
324
|
+
)['choices'][0]['text']
|
|
325
|
+
|
|
326
|
+
iteration = 0
|
|
327
|
+
while self._should_call_tool(response_text) and iteration < max_iterations:
|
|
328
|
+
tool_code = self._extract_tool_code(response_text)
|
|
329
|
+
if tool_code:
|
|
330
|
+
tool_name = tool_code.get("function", {}).get("name")
|
|
331
|
+
arguments = tool_code.get("function", {}).get("arguments", "")
|
|
332
|
+
if tool_name and arguments and tool_name in self.tools:
|
|
333
|
+
# Execute the tool and append its output
|
|
334
|
+
tool_output = self.tools[tool_name](**json.loads(arguments))
|
|
335
|
+
response_text = response_text.replace(
|
|
336
|
+
f"{self.tool_code_start}{json.dumps(tool_code)}{self.tool_code_end}",
|
|
337
|
+
tool_output
|
|
338
|
+
)
|
|
339
|
+
iteration += 1
|
|
340
|
+
|
|
341
|
+
return response_text
|
|
273
342
|
def __repr__(self) -> str:
|
|
274
343
|
return \
|
|
275
344
|
f"Model({repr(self._model_path)}, " + \
|
webscout/Local/thread.py
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import json
|
|
1
2
|
from ._version import __version__, __llama_cpp_version__
|
|
2
3
|
|
|
3
4
|
"""Submodule containing the Thread class, used for interaction with a Model"""
|
|
@@ -80,7 +81,9 @@ class Thread:
|
|
|
80
81
|
format: Union[dict, AdvancedFormat],
|
|
81
82
|
sampler: SamplerSettings = DefaultSampling,
|
|
82
83
|
messages: Optional[list[Message]] = None,
|
|
84
|
+
|
|
83
85
|
):
|
|
86
|
+
|
|
84
87
|
"""
|
|
85
88
|
Given a Model and a format, construct a Thread instance.
|
|
86
89
|
|
|
@@ -141,7 +144,7 @@ class Thread:
|
|
|
141
144
|
self.create_message("system", self.format['system_content'])
|
|
142
145
|
] if self._messages is None else self._messages
|
|
143
146
|
self.sampler: SamplerSettings = sampler
|
|
144
|
-
|
|
147
|
+
self.tools = []
|
|
145
148
|
if self.model.verbose:
|
|
146
149
|
print_verbose("new Thread instance with the following attributes:")
|
|
147
150
|
print_verbose(f"model == {self.model}")
|
|
@@ -162,8 +165,13 @@ class Thread:
|
|
|
162
165
|
print_verbose(f"sampler.presence_penalty == {self.sampler.presence_penalty}")
|
|
163
166
|
print_verbose(f"sampler.repeat_penalty == {self.sampler.repeat_penalty}")
|
|
164
167
|
print_verbose(f"sampler.top_k == {self.sampler.top_k}")
|
|
165
|
-
|
|
168
|
+
def add_tool(self, tool: dict):
|
|
169
|
+
"""Adds a tool to the Thread for function calling."""
|
|
170
|
+
self.tools.append(tool)
|
|
171
|
+
self.model.register_tool(tool['function']['name'], tool['function']['execute']) # Register the tool
|
|
166
172
|
|
|
173
|
+
# Include tool information in the system message (optional, but helpful)
|
|
174
|
+
self.messages[0]['content'] += f"\nYou have access to the following tool:\n{tool['function']['description']}"
|
|
167
175
|
def __repr__(self) -> str:
|
|
168
176
|
return \
|
|
169
177
|
f"Thread({repr(self.model)}, {repr(self.format)}, " + \
|
webscout/Local/utils.py
CHANGED
|
@@ -25,18 +25,19 @@ class _ArrayLike(Iterable):
|
|
|
25
25
|
class _SupportsWriteAndFlush(TextIO):
|
|
26
26
|
pass
|
|
27
27
|
|
|
28
|
-
def download_model(repo_id: str, filename: str, cache_dir: str = ".cache") -> str:
|
|
28
|
+
def download_model(repo_id: str, filename: str, token: str, cache_dir: str = ".cache") -> str:
|
|
29
29
|
"""
|
|
30
30
|
Downloads a GGUF model file from Hugging Face Hub.
|
|
31
31
|
|
|
32
32
|
repo_id: The Hugging Face repository ID (e.g., 'facebook/bart-large-cnn').
|
|
33
33
|
filename: The name of the GGUF file within the repository (e.g., 'model.gguf').
|
|
34
|
+
token: The Hugging Face token for authentication.
|
|
34
35
|
cache_dir: The directory where the downloaded file should be stored.
|
|
35
36
|
|
|
36
37
|
Returns: The path to the downloaded file.
|
|
37
38
|
"""
|
|
38
39
|
url = hf_hub_url(repo_id, filename)
|
|
39
|
-
filepath = cached_download(url, cache_dir=cache_dir, force_filename=filename)
|
|
40
|
+
filepath = cached_download(url, cache_dir=cache_dir, force_filename=filename, use_auth_token=token)
|
|
40
41
|
return filepath
|
|
41
42
|
|
|
42
43
|
class GGUFReader:
|
webscout/Provider/BasedGPT.py
CHANGED
|
@@ -1,226 +1,226 @@
|
|
|
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
|
|
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 webscout import exceptions
|
|
27
|
-
from typing import Any, AsyncGenerator, Dict
|
|
28
|
-
import logging
|
|
29
|
-
import httpx
|
|
30
|
-
|
|
31
|
-
class BasedGPT(Provider):
|
|
32
|
-
def __init__(
|
|
33
|
-
self,
|
|
34
|
-
is_conversation: bool = True,
|
|
35
|
-
max_tokens: int = 600,
|
|
36
|
-
timeout: int = 30,
|
|
37
|
-
intro: str = None,
|
|
38
|
-
filepath: str = None,
|
|
39
|
-
update_file: bool = True,
|
|
40
|
-
proxies: dict = {},
|
|
41
|
-
history_offset: int = 10250,
|
|
42
|
-
act: str = None,
|
|
43
|
-
system_prompt: str = "Be Helpful and Friendly",
|
|
44
|
-
):
|
|
45
|
-
"""Instantiates BasedGPT
|
|
46
|
-
|
|
47
|
-
Args:
|
|
48
|
-
is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
|
|
49
|
-
max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
|
|
50
|
-
timeout (int, optional): Http request timeout. Defaults to 30.
|
|
51
|
-
intro (str, optional): Conversation introductory prompt. Defaults to None.
|
|
52
|
-
filepath (str, optional): Path to file containing conversation history. Defaults to None.
|
|
53
|
-
update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
|
|
54
|
-
proxies (dict, optional): Http request proxies. Defaults to {}.
|
|
55
|
-
history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
|
|
56
|
-
act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
|
|
57
|
-
system_prompt (str, optional): System prompt for BasedGPT. Defaults to "Be Helpful and Friendly".
|
|
58
|
-
"""
|
|
59
|
-
self.session = requests.Session()
|
|
60
|
-
self.is_conversation = is_conversation
|
|
61
|
-
self.max_tokens_to_sample = max_tokens
|
|
62
|
-
self.chat_endpoint = "https://www.basedgpt.chat/api/chat"
|
|
63
|
-
self.stream_chunk_size = 64
|
|
64
|
-
self.timeout = timeout
|
|
65
|
-
self.last_response = {}
|
|
66
|
-
self.system_prompt = system_prompt
|
|
67
|
-
|
|
68
|
-
self.__available_optimizers = (
|
|
69
|
-
method
|
|
70
|
-
for method in dir(Optimizers)
|
|
71
|
-
if callable(getattr(Optimizers, method)) and not method.startswith("__")
|
|
72
|
-
)
|
|
73
|
-
self.session.headers.update(
|
|
74
|
-
{"Content-Type": "application/json"}
|
|
75
|
-
)
|
|
76
|
-
Conversation.intro = (
|
|
77
|
-
AwesomePrompts().get_act(
|
|
78
|
-
act, raise_not_found=True, default=None, case_insensitive=True
|
|
79
|
-
)
|
|
80
|
-
if act
|
|
81
|
-
else intro or Conversation.intro
|
|
82
|
-
)
|
|
83
|
-
self.conversation = Conversation(
|
|
84
|
-
is_conversation, self.max_tokens_to_sample, filepath, update_file
|
|
85
|
-
)
|
|
86
|
-
self.conversation.history_offset = history_offset
|
|
87
|
-
self.session.proxies = proxies
|
|
88
|
-
|
|
89
|
-
def ask(
|
|
90
|
-
self,
|
|
91
|
-
prompt: str,
|
|
92
|
-
stream: bool = False,
|
|
93
|
-
raw: bool = False,
|
|
94
|
-
optimizer: str = None,
|
|
95
|
-
conversationally: bool = False,
|
|
96
|
-
) -> dict:
|
|
97
|
-
"""Chat with AI
|
|
98
|
-
|
|
99
|
-
Args:
|
|
100
|
-
prompt (str): Prompt to be send.
|
|
101
|
-
stream (bool, optional): Flag for streaming response. Defaults to False.
|
|
102
|
-
raw (bool, optional): Stream back raw response as received. Defaults to False.
|
|
103
|
-
optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
|
|
104
|
-
conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
|
|
105
|
-
Returns:
|
|
106
|
-
dict : {}
|
|
107
|
-
```json
|
|
108
|
-
{
|
|
109
|
-
"id": "chatcmpl-TaREJpBZsRVQFRFic1wIA7Q7XfnaD",
|
|
110
|
-
"object": "chat.completion",
|
|
111
|
-
"created": 1704623244,
|
|
112
|
-
"model": "gpt-3.5-turbo",
|
|
113
|
-
"usage": {
|
|
114
|
-
"prompt_tokens": 0,
|
|
115
|
-
"completion_tokens": 0,
|
|
116
|
-
"total_tokens": 0
|
|
117
|
-
},
|
|
118
|
-
"choices": [
|
|
119
|
-
{
|
|
120
|
-
"message": {
|
|
121
|
-
"role": "assistant",
|
|
122
|
-
"content": "Hello! How can I assist you today?"
|
|
123
|
-
},
|
|
124
|
-
"finish_reason": "stop",
|
|
125
|
-
"index": 0
|
|
126
|
-
}
|
|
127
|
-
]
|
|
128
|
-
}
|
|
129
|
-
```
|
|
130
|
-
"""
|
|
131
|
-
conversation_prompt = self.conversation.gen_complete_prompt(prompt)
|
|
132
|
-
if optimizer:
|
|
133
|
-
if optimizer in self.__available_optimizers:
|
|
134
|
-
conversation_prompt = getattr(Optimizers, optimizer)(
|
|
135
|
-
conversation_prompt if conversationally else prompt
|
|
136
|
-
)
|
|
137
|
-
else:
|
|
138
|
-
raise Exception(
|
|
139
|
-
f"Optimizer is not one of {self.__available_optimizers}"
|
|
140
|
-
)
|
|
141
|
-
|
|
142
|
-
payload = {
|
|
143
|
-
"messages": [
|
|
144
|
-
{"role": "system", "content": self.system_prompt},
|
|
145
|
-
{"role": "user", "content": conversation_prompt},
|
|
146
|
-
],
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
def for_stream():
|
|
150
|
-
response = self.session.post(
|
|
151
|
-
self.chat_endpoint, json=payload, stream=True, timeout=self.timeout
|
|
152
|
-
)
|
|
153
|
-
if not response.ok:
|
|
154
|
-
raise exceptions.FailedToGenerateResponseError(
|
|
155
|
-
f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
|
|
156
|
-
)
|
|
157
|
-
|
|
158
|
-
message_load = ""
|
|
159
|
-
for value in response.iter_lines(
|
|
160
|
-
decode_unicode=True,
|
|
161
|
-
delimiter="",
|
|
162
|
-
chunk_size=self.stream_chunk_size,
|
|
163
|
-
):
|
|
164
|
-
try:
|
|
165
|
-
message_load += value
|
|
166
|
-
yield value if raw else dict(text=message_load)
|
|
167
|
-
except json.decoder.JSONDecodeError:
|
|
168
|
-
pass
|
|
169
|
-
self.last_response.update(dict(text=message_load))
|
|
170
|
-
self.conversation.update_chat_history(
|
|
171
|
-
prompt, self.get_message(self.last_response)
|
|
172
|
-
)
|
|
173
|
-
|
|
174
|
-
def for_non_stream():
|
|
175
|
-
for _ in for_stream():
|
|
176
|
-
pass
|
|
177
|
-
return self.last_response
|
|
178
|
-
|
|
179
|
-
return for_stream() if stream else for_non_stream()
|
|
180
|
-
|
|
181
|
-
def chat(
|
|
182
|
-
self,
|
|
183
|
-
prompt: str,
|
|
184
|
-
stream: bool = False,
|
|
185
|
-
optimizer: str = None,
|
|
186
|
-
conversationally: bool = False,
|
|
187
|
-
) -> str:
|
|
188
|
-
"""Generate response `str`
|
|
189
|
-
Args:
|
|
190
|
-
prompt (str): Prompt to be send.
|
|
191
|
-
stream (bool, optional): Flag for streaming response. Defaults to False.
|
|
192
|
-
optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
|
|
193
|
-
conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
|
|
194
|
-
Returns:
|
|
195
|
-
str: Response generated
|
|
196
|
-
"""
|
|
197
|
-
|
|
198
|
-
def for_stream():
|
|
199
|
-
for response in self.ask(
|
|
200
|
-
prompt, True, optimizer=optimizer, conversationally=conversationally
|
|
201
|
-
):
|
|
202
|
-
yield self.get_message(response)
|
|
203
|
-
|
|
204
|
-
def for_non_stream():
|
|
205
|
-
return self.get_message(
|
|
206
|
-
self.ask(
|
|
207
|
-
prompt,
|
|
208
|
-
False,
|
|
209
|
-
optimizer=optimizer,
|
|
210
|
-
conversationally=conversationally,
|
|
211
|
-
)
|
|
212
|
-
)
|
|
213
|
-
|
|
214
|
-
return for_stream() if stream else for_non_stream()
|
|
215
|
-
|
|
216
|
-
def get_message(self, response: dict) -> str:
|
|
217
|
-
"""Retrieves message only from response
|
|
218
|
-
|
|
219
|
-
Args:
|
|
220
|
-
response (dict): Response generated by `self.ask`
|
|
221
|
-
|
|
222
|
-
Returns:
|
|
223
|
-
str: Message extracted
|
|
224
|
-
"""
|
|
225
|
-
assert isinstance(response, dict), "Response should be of dict data-type only"
|
|
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
|
|
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 webscout import exceptions
|
|
27
|
+
from typing import Any, AsyncGenerator, Dict
|
|
28
|
+
import logging
|
|
29
|
+
import httpx
|
|
30
|
+
|
|
31
|
+
class BasedGPT(Provider):
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
is_conversation: bool = True,
|
|
35
|
+
max_tokens: int = 600,
|
|
36
|
+
timeout: int = 30,
|
|
37
|
+
intro: str = None,
|
|
38
|
+
filepath: str = None,
|
|
39
|
+
update_file: bool = True,
|
|
40
|
+
proxies: dict = {},
|
|
41
|
+
history_offset: int = 10250,
|
|
42
|
+
act: str = None,
|
|
43
|
+
system_prompt: str = "Be Helpful and Friendly",
|
|
44
|
+
):
|
|
45
|
+
"""Instantiates BasedGPT
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
|
|
49
|
+
max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
|
|
50
|
+
timeout (int, optional): Http request timeout. Defaults to 30.
|
|
51
|
+
intro (str, optional): Conversation introductory prompt. Defaults to None.
|
|
52
|
+
filepath (str, optional): Path to file containing conversation history. Defaults to None.
|
|
53
|
+
update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
|
|
54
|
+
proxies (dict, optional): Http request proxies. Defaults to {}.
|
|
55
|
+
history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
|
|
56
|
+
act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
|
|
57
|
+
system_prompt (str, optional): System prompt for BasedGPT. Defaults to "Be Helpful and Friendly".
|
|
58
|
+
"""
|
|
59
|
+
self.session = requests.Session()
|
|
60
|
+
self.is_conversation = is_conversation
|
|
61
|
+
self.max_tokens_to_sample = max_tokens
|
|
62
|
+
self.chat_endpoint = "https://www.basedgpt.chat/api/chat"
|
|
63
|
+
self.stream_chunk_size = 64
|
|
64
|
+
self.timeout = timeout
|
|
65
|
+
self.last_response = {}
|
|
66
|
+
self.system_prompt = system_prompt
|
|
67
|
+
|
|
68
|
+
self.__available_optimizers = (
|
|
69
|
+
method
|
|
70
|
+
for method in dir(Optimizers)
|
|
71
|
+
if callable(getattr(Optimizers, method)) and not method.startswith("__")
|
|
72
|
+
)
|
|
73
|
+
self.session.headers.update(
|
|
74
|
+
{"Content-Type": "application/json"}
|
|
75
|
+
)
|
|
76
|
+
Conversation.intro = (
|
|
77
|
+
AwesomePrompts().get_act(
|
|
78
|
+
act, raise_not_found=True, default=None, case_insensitive=True
|
|
79
|
+
)
|
|
80
|
+
if act
|
|
81
|
+
else intro or Conversation.intro
|
|
82
|
+
)
|
|
83
|
+
self.conversation = Conversation(
|
|
84
|
+
is_conversation, self.max_tokens_to_sample, filepath, update_file
|
|
85
|
+
)
|
|
86
|
+
self.conversation.history_offset = history_offset
|
|
87
|
+
self.session.proxies = proxies
|
|
88
|
+
|
|
89
|
+
def ask(
|
|
90
|
+
self,
|
|
91
|
+
prompt: str,
|
|
92
|
+
stream: bool = False,
|
|
93
|
+
raw: bool = False,
|
|
94
|
+
optimizer: str = None,
|
|
95
|
+
conversationally: bool = False,
|
|
96
|
+
) -> dict:
|
|
97
|
+
"""Chat with AI
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
prompt (str): Prompt to be send.
|
|
101
|
+
stream (bool, optional): Flag for streaming response. Defaults to False.
|
|
102
|
+
raw (bool, optional): Stream back raw response as received. Defaults to False.
|
|
103
|
+
optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
|
|
104
|
+
conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
|
|
105
|
+
Returns:
|
|
106
|
+
dict : {}
|
|
107
|
+
```json
|
|
108
|
+
{
|
|
109
|
+
"id": "chatcmpl-TaREJpBZsRVQFRFic1wIA7Q7XfnaD",
|
|
110
|
+
"object": "chat.completion",
|
|
111
|
+
"created": 1704623244,
|
|
112
|
+
"model": "gpt-3.5-turbo",
|
|
113
|
+
"usage": {
|
|
114
|
+
"prompt_tokens": 0,
|
|
115
|
+
"completion_tokens": 0,
|
|
116
|
+
"total_tokens": 0
|
|
117
|
+
},
|
|
118
|
+
"choices": [
|
|
119
|
+
{
|
|
120
|
+
"message": {
|
|
121
|
+
"role": "assistant",
|
|
122
|
+
"content": "Hello! How can I assist you today?"
|
|
123
|
+
},
|
|
124
|
+
"finish_reason": "stop",
|
|
125
|
+
"index": 0
|
|
126
|
+
}
|
|
127
|
+
]
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
"""
|
|
131
|
+
conversation_prompt = self.conversation.gen_complete_prompt(prompt)
|
|
132
|
+
if optimizer:
|
|
133
|
+
if optimizer in self.__available_optimizers:
|
|
134
|
+
conversation_prompt = getattr(Optimizers, optimizer)(
|
|
135
|
+
conversation_prompt if conversationally else prompt
|
|
136
|
+
)
|
|
137
|
+
else:
|
|
138
|
+
raise Exception(
|
|
139
|
+
f"Optimizer is not one of {self.__available_optimizers}"
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
payload = {
|
|
143
|
+
"messages": [
|
|
144
|
+
{"role": "system", "content": self.system_prompt},
|
|
145
|
+
{"role": "user", "content": conversation_prompt},
|
|
146
|
+
],
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
def for_stream():
|
|
150
|
+
response = self.session.post(
|
|
151
|
+
self.chat_endpoint, json=payload, stream=True, timeout=self.timeout
|
|
152
|
+
)
|
|
153
|
+
if not response.ok:
|
|
154
|
+
raise exceptions.FailedToGenerateResponseError(
|
|
155
|
+
f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
message_load = ""
|
|
159
|
+
for value in response.iter_lines(
|
|
160
|
+
decode_unicode=True,
|
|
161
|
+
delimiter="",
|
|
162
|
+
chunk_size=self.stream_chunk_size,
|
|
163
|
+
):
|
|
164
|
+
try:
|
|
165
|
+
message_load += value
|
|
166
|
+
yield value if raw else dict(text=message_load)
|
|
167
|
+
except json.decoder.JSONDecodeError:
|
|
168
|
+
pass
|
|
169
|
+
self.last_response.update(dict(text=message_load))
|
|
170
|
+
self.conversation.update_chat_history(
|
|
171
|
+
prompt, self.get_message(self.last_response)
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
def for_non_stream():
|
|
175
|
+
for _ in for_stream():
|
|
176
|
+
pass
|
|
177
|
+
return self.last_response
|
|
178
|
+
|
|
179
|
+
return for_stream() if stream else for_non_stream()
|
|
180
|
+
|
|
181
|
+
def chat(
|
|
182
|
+
self,
|
|
183
|
+
prompt: str,
|
|
184
|
+
stream: bool = False,
|
|
185
|
+
optimizer: str = None,
|
|
186
|
+
conversationally: bool = False,
|
|
187
|
+
) -> str:
|
|
188
|
+
"""Generate response `str`
|
|
189
|
+
Args:
|
|
190
|
+
prompt (str): Prompt to be send.
|
|
191
|
+
stream (bool, optional): Flag for streaming response. Defaults to False.
|
|
192
|
+
optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
|
|
193
|
+
conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
|
|
194
|
+
Returns:
|
|
195
|
+
str: Response generated
|
|
196
|
+
"""
|
|
197
|
+
|
|
198
|
+
def for_stream():
|
|
199
|
+
for response in self.ask(
|
|
200
|
+
prompt, True, optimizer=optimizer, conversationally=conversationally
|
|
201
|
+
):
|
|
202
|
+
yield self.get_message(response)
|
|
203
|
+
|
|
204
|
+
def for_non_stream():
|
|
205
|
+
return self.get_message(
|
|
206
|
+
self.ask(
|
|
207
|
+
prompt,
|
|
208
|
+
False,
|
|
209
|
+
optimizer=optimizer,
|
|
210
|
+
conversationally=conversationally,
|
|
211
|
+
)
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
return for_stream() if stream else for_non_stream()
|
|
215
|
+
|
|
216
|
+
def get_message(self, response: dict) -> str:
|
|
217
|
+
"""Retrieves message only from response
|
|
218
|
+
|
|
219
|
+
Args:
|
|
220
|
+
response (dict): Response generated by `self.ask`
|
|
221
|
+
|
|
222
|
+
Returns:
|
|
223
|
+
str: Message extracted
|
|
224
|
+
"""
|
|
225
|
+
assert isinstance(response, dict), "Response should be of dict data-type only"
|
|
226
226
|
return response["text"]
|