webscout 5.0__py3-none-any.whl → 5.2__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 +83 -277
- webscout/AIbase.py +106 -4
- webscout/AIutel.py +31 -0
- webscout/Agents/Onlinesearcher.py +91 -104
- webscout/Agents/__init__.py +2 -1
- webscout/Agents/ai.py +186 -0
- webscout/Agents/functioncall.py +57 -27
- webscout/Bing_search.py +73 -43
- webscout/Extra/autollama.py +173 -203
- webscout/Local/_version.py +1 -1
- webscout/Provider/AI21.py +177 -0
- webscout/Provider/Cloudflare.py +0 -4
- webscout/Provider/EDITEE.py +215 -0
- webscout/Provider/Llama3.py +1 -1
- webscout/Provider/NetFly.py +256 -0
- webscout/Provider/OLLAMA.py +11 -10
- webscout/Provider/TTI/PollinationsAI.py +138 -0
- webscout/Provider/TTI/__init__.py +2 -0
- webscout/Provider/TTI/deepinfra.py +148 -0
- webscout/Provider/TTS/__init__.py +2 -0
- webscout/Provider/TTS/streamElements.py +296 -0
- webscout/Provider/TTS/voicepod.py +114 -0
- webscout/Provider/TeachAnything.py +177 -0
- webscout/Provider/__init__.py +8 -0
- webscout/__init__.py +2 -0
- webscout/version.py +1 -1
- {webscout-5.0.dist-info → webscout-5.2.dist-info}/METADATA +38 -18
- {webscout-5.0.dist-info → webscout-5.2.dist-info}/RECORD +32 -22
- webscout/async_providers.py +0 -21
- {webscout-5.0.dist-info → webscout-5.2.dist-info}/LICENSE.md +0 -0
- {webscout-5.0.dist-info → webscout-5.2.dist-info}/WHEEL +0 -0
- {webscout-5.0.dist-info → webscout-5.2.dist-info}/entry_points.txt +0 -0
- {webscout-5.0.dist-info → webscout-5.2.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import requests
|
|
2
|
+
import json
|
|
3
|
+
from typing import Dict, Any
|
|
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
|
+
|
|
11
|
+
class AI21(Provider):
|
|
12
|
+
"""
|
|
13
|
+
A class to interact with the AI21 Studio API.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
api_key: str,
|
|
19
|
+
model: str = "jamba-1.5-large",
|
|
20
|
+
max_tokens: int = 1024,
|
|
21
|
+
temperature: float = 0.4,
|
|
22
|
+
top_p: float = 1,
|
|
23
|
+
is_conversation: bool = True,
|
|
24
|
+
timeout: int = 30,
|
|
25
|
+
intro: str = None,
|
|
26
|
+
filepath: str = None,
|
|
27
|
+
update_file: bool = True,
|
|
28
|
+
proxies: dict = {},
|
|
29
|
+
history_offset: int = 10250,
|
|
30
|
+
act: str = None,
|
|
31
|
+
system_prompt: str = "You are a helpful and informative AI assistant."
|
|
32
|
+
):
|
|
33
|
+
"""
|
|
34
|
+
Initializes the AI21 Studio API with given parameters.
|
|
35
|
+
"""
|
|
36
|
+
self.api_key = api_key
|
|
37
|
+
self.api_endpoint = "https://api.ai21.com/studio/v1/chat/completions"
|
|
38
|
+
self.model = model
|
|
39
|
+
self.max_tokens = max_tokens
|
|
40
|
+
self.temperature = temperature
|
|
41
|
+
self.top_p = top_p
|
|
42
|
+
self.system_prompt = system_prompt
|
|
43
|
+
self.session = requests.Session()
|
|
44
|
+
self.is_conversation = is_conversation
|
|
45
|
+
self.max_tokens_to_sample = max_tokens
|
|
46
|
+
self.timeout = timeout
|
|
47
|
+
self.last_response = {}
|
|
48
|
+
self.headers = {
|
|
49
|
+
'Accept': 'application/json, text/plain, */*',
|
|
50
|
+
'Accept-Encoding': 'gzip, deflate, br, zstd',
|
|
51
|
+
'Accept-Language': 'en-US,en;q=0.9,en-IN;q=0.8',
|
|
52
|
+
'Authorization': f"Bearer {self.api_key}",
|
|
53
|
+
'Content-Type': 'application/json',
|
|
54
|
+
'DNT': '1',
|
|
55
|
+
'Origin': 'https://studio.ai21.com',
|
|
56
|
+
'Referer': 'https://studio.ai21.com/',
|
|
57
|
+
'Sec-CH-UA': '"Chromium";v="128", "Not;A=Brand";v="24", "Microsoft Edge";v="128"',
|
|
58
|
+
'Sec-CH-UA-Mobile': '?0',
|
|
59
|
+
'Sec-CH-UA-Platform': '"Windows"',
|
|
60
|
+
'Sec-Fetch-Dest': 'empty',
|
|
61
|
+
'Sec-Fetch-Mode': 'cors',
|
|
62
|
+
'Sec-Fetch-Site': 'same-site',
|
|
63
|
+
'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',
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
self.__available_optimizers = (
|
|
67
|
+
method
|
|
68
|
+
for method in dir(Optimizers)
|
|
69
|
+
if callable(getattr(Optimizers, method)) and not method.startswith("__")
|
|
70
|
+
)
|
|
71
|
+
self.session.headers.update(self.headers)
|
|
72
|
+
Conversation.intro = (
|
|
73
|
+
AwesomePrompts().get_act(
|
|
74
|
+
act, raise_not_found=True, default=None, case_insensitive=True
|
|
75
|
+
)
|
|
76
|
+
if act
|
|
77
|
+
else intro or Conversation.intro
|
|
78
|
+
)
|
|
79
|
+
self.conversation = Conversation(
|
|
80
|
+
is_conversation, self.max_tokens_to_sample, filepath, update_file
|
|
81
|
+
)
|
|
82
|
+
self.conversation.history_offset = history_offset
|
|
83
|
+
self.session.proxies = proxies
|
|
84
|
+
|
|
85
|
+
def ask(
|
|
86
|
+
self,
|
|
87
|
+
prompt: str,
|
|
88
|
+
stream: bool = False,
|
|
89
|
+
raw: bool = False,
|
|
90
|
+
optimizer: str = None,
|
|
91
|
+
conversationally: bool = False,
|
|
92
|
+
) -> Dict[str, Any]:
|
|
93
|
+
"""
|
|
94
|
+
Sends a prompt to the AI21 Studio API and returns the response.
|
|
95
|
+
"""
|
|
96
|
+
conversation_prompt = self.conversation.gen_complete_prompt(prompt)
|
|
97
|
+
if optimizer:
|
|
98
|
+
if optimizer in self.__available_optimizers:
|
|
99
|
+
conversation_prompt = getattr(Optimizers, optimizer)(
|
|
100
|
+
conversation_prompt if conversationally else prompt
|
|
101
|
+
)
|
|
102
|
+
else:
|
|
103
|
+
raise Exception(
|
|
104
|
+
f"Optimizer is not one of {self.__available_optimizers}"
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
payload = {
|
|
108
|
+
"messages": [
|
|
109
|
+
{"role": "system", "content": self.system_prompt},
|
|
110
|
+
{"role": "user", "content": conversation_prompt}
|
|
111
|
+
],
|
|
112
|
+
"n": 1,
|
|
113
|
+
"max_tokens": self.max_tokens,
|
|
114
|
+
"model": self.model,
|
|
115
|
+
"stop": [],
|
|
116
|
+
"temperature": self.temperature,
|
|
117
|
+
"top_p": self.top_p,
|
|
118
|
+
"documents": [],
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
response = self.session.post(self.api_endpoint, headers=self.headers, json=payload, timeout=self.timeout)
|
|
122
|
+
|
|
123
|
+
if not response.ok:
|
|
124
|
+
raise exceptions.FailedToGenerateResponseError(
|
|
125
|
+
f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
resp = response.json()
|
|
129
|
+
self.last_response.update(resp)
|
|
130
|
+
self.conversation.update_chat_history(
|
|
131
|
+
prompt, self.get_message(self.last_response)
|
|
132
|
+
)
|
|
133
|
+
return self.last_response
|
|
134
|
+
|
|
135
|
+
def chat(
|
|
136
|
+
self,
|
|
137
|
+
prompt: str,
|
|
138
|
+
stream: bool = False,
|
|
139
|
+
optimizer: str = None,
|
|
140
|
+
conversationally: bool = False,
|
|
141
|
+
) -> str:
|
|
142
|
+
"""
|
|
143
|
+
Generates a response from the AI21 API.
|
|
144
|
+
"""
|
|
145
|
+
|
|
146
|
+
def for_stream():
|
|
147
|
+
for response in self.ask(
|
|
148
|
+
prompt, True, optimizer=optimizer, conversationally=conversationally
|
|
149
|
+
):
|
|
150
|
+
yield self.get_message(response)
|
|
151
|
+
|
|
152
|
+
def for_non_stream():
|
|
153
|
+
return self.get_message(
|
|
154
|
+
self.ask(
|
|
155
|
+
prompt,
|
|
156
|
+
False,
|
|
157
|
+
optimizer=optimizer,
|
|
158
|
+
conversationally=conversationally,
|
|
159
|
+
)
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
return for_stream() if stream else for_non_stream()
|
|
163
|
+
|
|
164
|
+
def get_message(self, response: dict) -> str:
|
|
165
|
+
"""
|
|
166
|
+
Extracts the message from the API response.
|
|
167
|
+
"""
|
|
168
|
+
assert isinstance(response, dict), "Response should be of dict data-type only"
|
|
169
|
+
return response['choices'][0]['message']['content']
|
|
170
|
+
|
|
171
|
+
# Example usage
|
|
172
|
+
if __name__ == "__main__":
|
|
173
|
+
from rich import print
|
|
174
|
+
ai = AI21(api_key="api_key")
|
|
175
|
+
response = ai.chat(input(">>> "))
|
|
176
|
+
for line in response:
|
|
177
|
+
print(line, end="", flush=True)
|
webscout/Provider/Cloudflare.py
CHANGED
|
@@ -30,10 +30,6 @@ import httpx
|
|
|
30
30
|
import cloudscraper
|
|
31
31
|
|
|
32
32
|
class Cloudflare(Provider):
|
|
33
|
-
"""
|
|
34
|
-
This class provides methods for interacting with the Playground AI API
|
|
35
|
-
(Cloudflare) in a consistent provider structure for webscout.
|
|
36
|
-
"""
|
|
37
33
|
|
|
38
34
|
AVAILABLE_MODELS = [
|
|
39
35
|
"@cf/llava-hf/llava-1.5-7b-hf",
|
|
@@ -0,0 +1,215 @@
|
|
|
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 webscout.AIutel import Optimizers
|
|
23
|
+
from webscout.AIutel import Conversation, Proxy
|
|
24
|
+
from webscout.AIutel import AwesomePrompts, sanitize_stream
|
|
25
|
+
from webscout.AIbase import Provider, AsyncProvider
|
|
26
|
+
from webscout import exceptions
|
|
27
|
+
from typing import Any, AsyncGenerator, Dict
|
|
28
|
+
import logging
|
|
29
|
+
import httpx
|
|
30
|
+
import random
|
|
31
|
+
proxy = Proxy()
|
|
32
|
+
|
|
33
|
+
class Editee(Provider):
|
|
34
|
+
"""
|
|
35
|
+
A class to interact with the Editee.com API.
|
|
36
|
+
"""
|
|
37
|
+
AVAILABLE_MODELS = [
|
|
38
|
+
"gemini", # it is gemini 1.5pro
|
|
39
|
+
"claude", # it is claude 3.5
|
|
40
|
+
"gpt4", # it is gpt4o
|
|
41
|
+
"mistrallarge", # it is mistral large2
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
is_conversation: bool = True,
|
|
47
|
+
max_tokens: int = 600,
|
|
48
|
+
timeout: int = 30,
|
|
49
|
+
intro: str = None,
|
|
50
|
+
filepath: str = None,
|
|
51
|
+
update_file: bool = True,
|
|
52
|
+
proxies: dict = {},
|
|
53
|
+
history_offset: int = 10250,
|
|
54
|
+
act: str = None,
|
|
55
|
+
model: str = "mistrallarge",
|
|
56
|
+
) -> None:
|
|
57
|
+
"""
|
|
58
|
+
Initializes the Editee API with given parameters.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
|
|
62
|
+
max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
|
|
63
|
+
timeout (int, optional): Http request timeout. Defaults to 30.
|
|
64
|
+
intro (str, optional): Conversation introductory prompt. Defaults to None.
|
|
65
|
+
filepath (str, optional): Path to file containing conversation history. Defaults to None.
|
|
66
|
+
update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
|
|
67
|
+
proxies (dict, optional): Http request proxies. Defaults to {}.
|
|
68
|
+
history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
|
|
69
|
+
act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
|
|
70
|
+
model (str, optional): AI model to use for text generation. Defaults to "gemini".
|
|
71
|
+
"""
|
|
72
|
+
if model not in self.AVAILABLE_MODELS:
|
|
73
|
+
raise ValueError(f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}")
|
|
74
|
+
|
|
75
|
+
self.session = requests.Session()
|
|
76
|
+
self.is_conversation = is_conversation
|
|
77
|
+
self.max_tokens_to_sample = max_tokens
|
|
78
|
+
self.api_endpoint = "https://editee.com/submit/chatgptfree"
|
|
79
|
+
self.stream_chunk_size = 64
|
|
80
|
+
self.timeout = timeout
|
|
81
|
+
self.last_response = {}
|
|
82
|
+
self.model = model
|
|
83
|
+
self._sessionValue = self._get_session()
|
|
84
|
+
self.headers = {
|
|
85
|
+
"authority": "editee.com",
|
|
86
|
+
"path": "/submit/chatgptfree",
|
|
87
|
+
"scheme": "https",
|
|
88
|
+
"accept": "application/json, text/plain, */*",
|
|
89
|
+
"accept-encoding": "gzip, deflate, br",
|
|
90
|
+
"accept-language": "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7",
|
|
91
|
+
"content-type": "application/json",
|
|
92
|
+
"cookie": f"editeecom_session={self._sessionValue}",
|
|
93
|
+
"origin": "https://editee.com",
|
|
94
|
+
"referer": "https://editee.com/chat-gpt",
|
|
95
|
+
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36",
|
|
96
|
+
"x-requested-with": "XMLHttpRequest"
|
|
97
|
+
}
|
|
98
|
+
self.__available_optimizers = (
|
|
99
|
+
method
|
|
100
|
+
for method in dir(Optimizers)
|
|
101
|
+
if callable(getattr(Optimizers, method)) and not method.startswith("__")
|
|
102
|
+
)
|
|
103
|
+
self.session.headers.update(self.headers)
|
|
104
|
+
Conversation.intro = (
|
|
105
|
+
AwesomePrompts().get_act(
|
|
106
|
+
act, raise_not_found=True, default=None, case_insensitive=True
|
|
107
|
+
)
|
|
108
|
+
if act
|
|
109
|
+
else intro or Conversation.intro
|
|
110
|
+
)
|
|
111
|
+
self.conversation = Conversation(
|
|
112
|
+
is_conversation, self.max_tokens_to_sample, filepath, update_file
|
|
113
|
+
)
|
|
114
|
+
self.conversation.history_offset = history_offset
|
|
115
|
+
self.session.proxies = proxies
|
|
116
|
+
|
|
117
|
+
def _get_session(self):
|
|
118
|
+
"""Gets the editeecom_session value."""
|
|
119
|
+
res = proxy.get("https://editee.com/chat-gpt")
|
|
120
|
+
if res.cookies.get_dict():
|
|
121
|
+
first_cookie_name, session_value = next(iter(res.cookies.get_dict().items()))
|
|
122
|
+
return session_value
|
|
123
|
+
|
|
124
|
+
def ask(
|
|
125
|
+
self,
|
|
126
|
+
prompt: str,
|
|
127
|
+
stream: bool = False,
|
|
128
|
+
raw: bool = False,
|
|
129
|
+
optimizer: str = None,
|
|
130
|
+
conversationally: bool = False,
|
|
131
|
+
) -> dict:
|
|
132
|
+
"""Chat with AI
|
|
133
|
+
|
|
134
|
+
Args:
|
|
135
|
+
prompt (str): Prompt to be send.
|
|
136
|
+
stream (bool, optional): Whether to stream the response. Defaults to False.
|
|
137
|
+
raw (bool, optional): Whether to return the raw response. Defaults to False.
|
|
138
|
+
optimizer (str, optional): The name of the optimizer to use. Defaults to None.
|
|
139
|
+
conversationally (bool, optional): Whether to chat conversationally. Defaults to False.
|
|
140
|
+
|
|
141
|
+
Returns:
|
|
142
|
+
The response from the API.
|
|
143
|
+
"""
|
|
144
|
+
conversation_prompt = self.conversation.gen_complete_prompt(prompt)
|
|
145
|
+
if optimizer:
|
|
146
|
+
if optimizer in self.__available_optimizers:
|
|
147
|
+
conversation_prompt = getattr(Optimizers, optimizer)(
|
|
148
|
+
conversation_prompt if conversationally else prompt
|
|
149
|
+
)
|
|
150
|
+
else:
|
|
151
|
+
raise Exception(
|
|
152
|
+
f"Optimizer is not one of {self.__available_optimizers}"
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
payload = {
|
|
156
|
+
"context": " ",
|
|
157
|
+
"selected_model": self.model,
|
|
158
|
+
"template_id": "",
|
|
159
|
+
"user_input": conversation_prompt
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
response = proxy.post(self.api_endpoint, headers=self.headers, json=payload, timeout=self.timeout)
|
|
163
|
+
if not response.ok:
|
|
164
|
+
raise exceptions.FailedToGenerateResponseError(
|
|
165
|
+
f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
resp = response.json()
|
|
169
|
+
self.last_response.update(dict(text=resp['text']))
|
|
170
|
+
self.conversation.update_chat_history(
|
|
171
|
+
prompt, self.get_message(self.last_response)
|
|
172
|
+
)
|
|
173
|
+
return self.last_response
|
|
174
|
+
|
|
175
|
+
def chat(
|
|
176
|
+
self,
|
|
177
|
+
prompt: str,
|
|
178
|
+
stream: bool = False,
|
|
179
|
+
optimizer: str = None,
|
|
180
|
+
conversationally: bool = False,
|
|
181
|
+
) -> str:
|
|
182
|
+
"""Generate response `str`
|
|
183
|
+
Args:
|
|
184
|
+
prompt (str): Prompt to be send.
|
|
185
|
+
stream (bool, optional): Flag for streaming response. Defaults to False.
|
|
186
|
+
optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
|
|
187
|
+
conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
|
|
188
|
+
Returns:
|
|
189
|
+
str: Response generated
|
|
190
|
+
"""
|
|
191
|
+
return self.get_message(
|
|
192
|
+
self.ask(
|
|
193
|
+
prompt,
|
|
194
|
+
optimizer=optimizer,
|
|
195
|
+
conversationally=conversationally,
|
|
196
|
+
)
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
def get_message(self, response: dict) -> str:
|
|
200
|
+
"""Retrieves message only from response
|
|
201
|
+
|
|
202
|
+
Args:
|
|
203
|
+
response (dict): Response generated by `self.ask`
|
|
204
|
+
|
|
205
|
+
Returns:
|
|
206
|
+
str: Message extracted
|
|
207
|
+
"""
|
|
208
|
+
assert isinstance(response, dict), "Response should be of dict data-type only"
|
|
209
|
+
return response["text"]
|
|
210
|
+
if __name__ == '__main__':
|
|
211
|
+
from rich import print
|
|
212
|
+
ai = Editee()
|
|
213
|
+
response = ai.chat("tell me about india")
|
|
214
|
+
for chunk in response:
|
|
215
|
+
print(chunk, end="", flush=True)
|
webscout/Provider/Llama3.py
CHANGED
|
@@ -0,0 +1,256 @@
|
|
|
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 webscout.AIutel import Optimizers
|
|
23
|
+
from webscout.AIutel import Conversation
|
|
24
|
+
from webscout.AIutel import AwesomePrompts, sanitize_stream
|
|
25
|
+
from webscout.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 NetFly(Provider):
|
|
32
|
+
"""
|
|
33
|
+
A class to interact with the NetFly API.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
AVAILABLE_MODELS = ["gpt-3.5-turbo"]
|
|
37
|
+
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
is_conversation: bool = True,
|
|
41
|
+
max_tokens: int = 600,
|
|
42
|
+
timeout: int = 30,
|
|
43
|
+
intro: str = None,
|
|
44
|
+
filepath: str = None,
|
|
45
|
+
update_file: bool = True,
|
|
46
|
+
proxies: dict = {},
|
|
47
|
+
history_offset: int = 10250,
|
|
48
|
+
act: str = None,
|
|
49
|
+
model: str = "gpt-3.5-turbo",
|
|
50
|
+
system_prompt: str = "You are a helpful and friendly AI assistant.",
|
|
51
|
+
):
|
|
52
|
+
"""
|
|
53
|
+
Initializes the NetFly API with given parameters.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
|
|
57
|
+
max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
|
|
58
|
+
timeout (int, optional): Http request timeout. Defaults to 30.
|
|
59
|
+
intro (str, optional): Conversation introductory prompt. Defaults to None.
|
|
60
|
+
filepath (str, optional): Path to file containing conversation history. Defaults to None.
|
|
61
|
+
update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
|
|
62
|
+
proxies (dict, optional): Http request proxies. Defaults to {}.
|
|
63
|
+
history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
|
|
64
|
+
act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
|
|
65
|
+
model (str, optional): AI model to use for text generation. Defaults to "gpt-3.5-turbo".
|
|
66
|
+
system_prompt (str, optional): System prompt for NetFly. Defaults to the provided string.
|
|
67
|
+
"""
|
|
68
|
+
if model not in self.AVAILABLE_MODELS:
|
|
69
|
+
raise ValueError(f"Invalid model: {model}. Available model is: {self.AVAILABLE_MODELS[0]}")
|
|
70
|
+
|
|
71
|
+
self.session = requests.Session()
|
|
72
|
+
self.is_conversation = is_conversation
|
|
73
|
+
self.max_tokens_to_sample = max_tokens
|
|
74
|
+
self.api_endpoint = "https://free.netfly.top/api/openai/v1/chat/completions"
|
|
75
|
+
self.stream_chunk_size = 64
|
|
76
|
+
self.timeout = timeout
|
|
77
|
+
self.last_response = {}
|
|
78
|
+
self.model = model
|
|
79
|
+
self.system_prompt = system_prompt
|
|
80
|
+
self.headers = {
|
|
81
|
+
"accept": "application/json, text/event-stream",
|
|
82
|
+
"accept-encoding": "gzip, deflate, br, zstd",
|
|
83
|
+
"accept-language": "en-US,en;q=0.9,en-IN;q=0.8",
|
|
84
|
+
"content-type": "application/json",
|
|
85
|
+
"dnt": "1",
|
|
86
|
+
"origin": "https://free.netfly.top",
|
|
87
|
+
"referer": "https://free.netfly.top/",
|
|
88
|
+
"sec-ch-ua": '"Not)A;Brand";v="99", "Microsoft Edge";v="127", "Chromium";v="127"',
|
|
89
|
+
"sec-ch-ua-mobile": "?0",
|
|
90
|
+
"sec-ch-ua-platform": '"Windows"',
|
|
91
|
+
"sec-fetch-dest": "empty",
|
|
92
|
+
"sec-fetch-mode": "cors",
|
|
93
|
+
"sec-fetch-site": "same-origin",
|
|
94
|
+
"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"
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
self.__available_optimizers = (
|
|
98
|
+
method
|
|
99
|
+
for method in dir(Optimizers)
|
|
100
|
+
if callable(getattr(Optimizers, method)) and not method.startswith("__")
|
|
101
|
+
)
|
|
102
|
+
self.session.headers.update(self.headers)
|
|
103
|
+
Conversation.intro = (
|
|
104
|
+
AwesomePrompts().get_act(
|
|
105
|
+
act, raise_not_found=True, default=None, case_insensitive=True
|
|
106
|
+
)
|
|
107
|
+
if act
|
|
108
|
+
else intro or Conversation.intro
|
|
109
|
+
)
|
|
110
|
+
self.conversation = Conversation(
|
|
111
|
+
is_conversation, self.max_tokens_to_sample, filepath, update_file
|
|
112
|
+
)
|
|
113
|
+
self.conversation.history_offset = history_offset
|
|
114
|
+
self.session.proxies = proxies
|
|
115
|
+
|
|
116
|
+
def ask(
|
|
117
|
+
self,
|
|
118
|
+
prompt: str,
|
|
119
|
+
stream: bool = False,
|
|
120
|
+
raw: bool = False,
|
|
121
|
+
optimizer: str = None,
|
|
122
|
+
conversationally: bool = False,
|
|
123
|
+
) -> dict:
|
|
124
|
+
"""Chat with AI
|
|
125
|
+
|
|
126
|
+
Args:
|
|
127
|
+
prompt (str): Prompt to be send.
|
|
128
|
+
stream (bool, optional): Whether to stream the response. Defaults to False.
|
|
129
|
+
raw (bool, optional): Whether to return the raw response. Defaults to False.
|
|
130
|
+
optimizer (str, optional): The name of the optimizer to use. Defaults to None.
|
|
131
|
+
conversationally (bool, optional): Whether to chat conversationally. Defaults to False.
|
|
132
|
+
|
|
133
|
+
Returns:
|
|
134
|
+
The response from the API.
|
|
135
|
+
"""
|
|
136
|
+
conversation_prompt = self.conversation.gen_complete_prompt(prompt)
|
|
137
|
+
if optimizer:
|
|
138
|
+
if optimizer in self.__available_optimizers:
|
|
139
|
+
conversation_prompt = getattr(Optimizers, optimizer)(
|
|
140
|
+
conversation_prompt if conversationally else prompt
|
|
141
|
+
)
|
|
142
|
+
else:
|
|
143
|
+
raise Exception(
|
|
144
|
+
f"Optimizer is not one of {self.__available_optimizers}"
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
payload = {
|
|
148
|
+
"messages": [
|
|
149
|
+
{"role": "system", "content": self.system_prompt},
|
|
150
|
+
{"role": "user", "content": conversation_prompt},
|
|
151
|
+
],
|
|
152
|
+
"stream": True,
|
|
153
|
+
"model": self.model,
|
|
154
|
+
"temperature": 0.5,
|
|
155
|
+
"presence_penalty": 0,
|
|
156
|
+
"frequency_penalty": 0,
|
|
157
|
+
"top_p": 1
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
def for_stream():
|
|
161
|
+
response = self.session.post(
|
|
162
|
+
self.api_endpoint, json=payload, headers=self.headers, stream=True, timeout=self.timeout
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
if not response.ok:
|
|
166
|
+
raise exceptions.FailedToGenerateResponseError(
|
|
167
|
+
f"Failed to generate response - ({response.status_code}, {response.reason})"
|
|
168
|
+
)
|
|
169
|
+
buffer = ""
|
|
170
|
+
for line in response.iter_lines(decode_unicode=True):
|
|
171
|
+
if line:
|
|
172
|
+
if line.startswith("data: "):
|
|
173
|
+
json_data = line[6:]
|
|
174
|
+
if json_data == "[DONE]":
|
|
175
|
+
break
|
|
176
|
+
try:
|
|
177
|
+
data = json.loads(json_data)
|
|
178
|
+
# Check if 'content' key exists in 'delta' dictionary
|
|
179
|
+
if 'content' in data["choices"][0]["delta"]:
|
|
180
|
+
content = data["choices"][0]["delta"].get("content", "")
|
|
181
|
+
buffer += content
|
|
182
|
+
# Check for completion marker (period in this case)
|
|
183
|
+
if buffer.endswith(".") or buffer.endswith("\n"):
|
|
184
|
+
yield buffer if raw else dict(text=buffer)
|
|
185
|
+
buffer = "" # Clear the buffer
|
|
186
|
+
except json.decoder.JSONDecodeError:
|
|
187
|
+
continue
|
|
188
|
+
|
|
189
|
+
# Yield any remaining text in the buffer
|
|
190
|
+
if buffer:
|
|
191
|
+
yield buffer if raw else dict(text=buffer)
|
|
192
|
+
|
|
193
|
+
self.last_response.update(dict(text=buffer))
|
|
194
|
+
self.conversation.update_chat_history(
|
|
195
|
+
prompt, self.get_message(self.last_response)
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
def for_non_stream():
|
|
199
|
+
for _ in for_stream():
|
|
200
|
+
pass
|
|
201
|
+
return self.last_response
|
|
202
|
+
|
|
203
|
+
return for_stream() if stream else for_non_stream()
|
|
204
|
+
|
|
205
|
+
def chat(
|
|
206
|
+
self,
|
|
207
|
+
prompt: str,
|
|
208
|
+
stream: bool = False,
|
|
209
|
+
optimizer: str = None,
|
|
210
|
+
conversationally: bool = False,
|
|
211
|
+
) -> str:
|
|
212
|
+
"""Generate response `str`
|
|
213
|
+
Args:
|
|
214
|
+
prompt (str): Prompt to be send.
|
|
215
|
+
stream (bool, optional): Flag for streaming response. Defaults to False.
|
|
216
|
+
optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
|
|
217
|
+
conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
|
|
218
|
+
Returns:
|
|
219
|
+
str: Response generated
|
|
220
|
+
"""
|
|
221
|
+
|
|
222
|
+
def for_stream():
|
|
223
|
+
for response in self.ask(
|
|
224
|
+
prompt, True, optimizer=optimizer, conversationally=conversationally
|
|
225
|
+
):
|
|
226
|
+
yield self.get_message(response)
|
|
227
|
+
|
|
228
|
+
def for_non_stream():
|
|
229
|
+
return self.get_message(
|
|
230
|
+
self.ask(
|
|
231
|
+
prompt,
|
|
232
|
+
False,
|
|
233
|
+
optimizer=optimizer,
|
|
234
|
+
conversationally=conversationally,
|
|
235
|
+
)
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
return for_stream() if stream else for_non_stream()
|
|
239
|
+
|
|
240
|
+
def get_message(self, response: dict) -> str:
|
|
241
|
+
"""Retrieves message only from response
|
|
242
|
+
|
|
243
|
+
Args:
|
|
244
|
+
response (dict): Response generated by `self.ask`
|
|
245
|
+
|
|
246
|
+
Returns:
|
|
247
|
+
str: Message extracted
|
|
248
|
+
"""
|
|
249
|
+
assert isinstance(response, dict), "Response should be of dict data-type only"
|
|
250
|
+
return response["text"]
|
|
251
|
+
if __name__ == '__main__':
|
|
252
|
+
from rich import print
|
|
253
|
+
ai = NetFly()
|
|
254
|
+
response = ai.chat("tell me about india")
|
|
255
|
+
for chunk in response:
|
|
256
|
+
print(chunk, end="", flush=True)
|