webscout 8.3.5__py3-none-any.whl → 8.3.7__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 +2 -0
- webscout/Bard.py +12 -6
- webscout/DWEBS.py +66 -57
- webscout/Provider/{UNFINISHED → AISEARCH}/PERPLEXED_search.py +34 -74
- webscout/Provider/AISEARCH/__init__.py +18 -11
- webscout/Provider/AISEARCH/scira_search.py +3 -1
- webscout/Provider/Aitopia.py +2 -3
- webscout/Provider/Andi.py +3 -3
- webscout/Provider/ChatGPTClone.py +1 -1
- webscout/Provider/ChatSandbox.py +1 -0
- webscout/Provider/Cloudflare.py +1 -1
- webscout/Provider/Cohere.py +1 -0
- webscout/Provider/Deepinfra.py +13 -10
- webscout/Provider/ExaAI.py +1 -1
- webscout/Provider/ExaChat.py +1 -80
- webscout/Provider/Flowith.py +6 -1
- webscout/Provider/Gemini.py +7 -5
- webscout/Provider/GeminiProxy.py +1 -0
- webscout/Provider/GithubChat.py +4 -1
- webscout/Provider/Groq.py +1 -1
- webscout/Provider/HeckAI.py +8 -4
- webscout/Provider/Jadve.py +23 -38
- webscout/Provider/K2Think.py +308 -0
- webscout/Provider/Koboldai.py +8 -186
- webscout/Provider/LambdaChat.py +2 -4
- webscout/Provider/Nemotron.py +3 -4
- webscout/Provider/Netwrck.py +6 -8
- webscout/Provider/OLLAMA.py +1 -0
- webscout/Provider/OPENAI/Cloudflare.py +6 -7
- webscout/Provider/OPENAI/FalconH1.py +2 -7
- webscout/Provider/OPENAI/FreeGemini.py +6 -8
- webscout/Provider/OPENAI/{monochat.py → K2Think.py} +180 -77
- webscout/Provider/OPENAI/NEMOTRON.py +3 -6
- webscout/Provider/OPENAI/PI.py +5 -4
- webscout/Provider/OPENAI/Qwen3.py +2 -3
- webscout/Provider/OPENAI/README.md +2 -1
- webscout/Provider/OPENAI/TogetherAI.py +52 -57
- webscout/Provider/OPENAI/TwoAI.py +3 -4
- webscout/Provider/OPENAI/__init__.py +17 -56
- webscout/Provider/OPENAI/ai4chat.py +313 -303
- webscout/Provider/OPENAI/base.py +9 -29
- webscout/Provider/OPENAI/chatgpt.py +7 -2
- webscout/Provider/OPENAI/chatgptclone.py +4 -7
- webscout/Provider/OPENAI/chatsandbox.py +84 -59
- webscout/Provider/OPENAI/deepinfra.py +12 -6
- webscout/Provider/OPENAI/e2b.py +60 -8
- webscout/Provider/OPENAI/flowith.py +4 -3
- webscout/Provider/OPENAI/generate_api_key.py +48 -0
- webscout/Provider/OPENAI/heckai.py +4 -1
- webscout/Provider/OPENAI/netwrck.py +9 -12
- webscout/Provider/OPENAI/refact.py +274 -0
- webscout/Provider/OPENAI/scirachat.py +6 -0
- webscout/Provider/OPENAI/textpollinations.py +3 -14
- webscout/Provider/OPENAI/toolbaz.py +14 -10
- webscout/Provider/OpenGPT.py +1 -1
- webscout/Provider/Openai.py +150 -402
- webscout/Provider/PI.py +1 -0
- webscout/Provider/Perplexitylabs.py +1 -2
- webscout/Provider/QwenLM.py +107 -89
- webscout/Provider/STT/__init__.py +17 -2
- webscout/Provider/{Llama3.py → Sambanova.py} +9 -10
- webscout/Provider/StandardInput.py +1 -1
- webscout/Provider/TTI/__init__.py +18 -12
- webscout/Provider/TTI/bing.py +14 -2
- webscout/Provider/TTI/together.py +10 -9
- webscout/Provider/TTS/README.md +0 -1
- webscout/Provider/TTS/__init__.py +18 -11
- webscout/Provider/TTS/base.py +479 -159
- webscout/Provider/TTS/deepgram.py +409 -156
- webscout/Provider/TTS/elevenlabs.py +425 -111
- webscout/Provider/TTS/freetts.py +317 -140
- webscout/Provider/TTS/gesserit.py +192 -128
- webscout/Provider/TTS/murfai.py +248 -113
- webscout/Provider/TTS/openai_fm.py +347 -129
- webscout/Provider/TTS/speechma.py +620 -586
- webscout/Provider/TeachAnything.py +1 -0
- webscout/Provider/TextPollinationsAI.py +5 -15
- webscout/Provider/TogetherAI.py +136 -142
- webscout/Provider/TwoAI.py +53 -309
- webscout/Provider/TypliAI.py +2 -1
- webscout/Provider/{GizAI.py → UNFINISHED/GizAI.py} +1 -1
- webscout/Provider/UNFINISHED/VercelAIGateway.py +339 -0
- webscout/Provider/Venice.py +2 -1
- webscout/Provider/VercelAI.py +1 -0
- webscout/Provider/WiseCat.py +2 -1
- webscout/Provider/WrDoChat.py +2 -1
- webscout/Provider/__init__.py +18 -174
- webscout/Provider/ai4chat.py +1 -1
- webscout/Provider/akashgpt.py +7 -10
- webscout/Provider/cerebras.py +194 -38
- webscout/Provider/chatglm.py +170 -83
- webscout/Provider/cleeai.py +1 -2
- webscout/Provider/deepseek_assistant.py +1 -1
- webscout/Provider/elmo.py +1 -1
- webscout/Provider/geminiapi.py +1 -1
- webscout/Provider/granite.py +1 -1
- webscout/Provider/hermes.py +1 -3
- webscout/Provider/julius.py +1 -0
- webscout/Provider/learnfastai.py +1 -1
- webscout/Provider/llama3mitril.py +1 -1
- webscout/Provider/llmchat.py +1 -1
- webscout/Provider/llmchatco.py +1 -1
- webscout/Provider/meta.py +3 -3
- webscout/Provider/oivscode.py +2 -2
- webscout/Provider/scira_chat.py +51 -124
- webscout/Provider/searchchat.py +1 -0
- webscout/Provider/sonus.py +1 -1
- webscout/Provider/toolbaz.py +15 -11
- webscout/Provider/turboseek.py +31 -22
- webscout/Provider/typefully.py +2 -1
- webscout/Provider/x0gpt.py +1 -0
- webscout/Provider/yep.py +2 -1
- webscout/conversation.py +22 -20
- webscout/sanitize.py +14 -10
- webscout/scout/README.md +20 -23
- webscout/scout/core/crawler.py +125 -38
- webscout/scout/core/scout.py +26 -5
- webscout/tempid.py +6 -0
- webscout/version.py +1 -1
- webscout/webscout_search.py +13 -6
- webscout/webscout_search_async.py +10 -8
- webscout/yep_search.py +13 -5
- {webscout-8.3.5.dist-info → webscout-8.3.7.dist-info}/METADATA +3 -1
- {webscout-8.3.5.dist-info → webscout-8.3.7.dist-info}/RECORD +132 -155
- webscout/Provider/AllenAI.py +0 -440
- webscout/Provider/Blackboxai.py +0 -793
- webscout/Provider/FreeGemini.py +0 -250
- webscout/Provider/Glider.py +0 -225
- webscout/Provider/Hunyuan.py +0 -283
- webscout/Provider/MCPCore.py +0 -322
- webscout/Provider/MiniMax.py +0 -207
- webscout/Provider/OPENAI/BLACKBOXAI.py +0 -1045
- webscout/Provider/OPENAI/MiniMax.py +0 -298
- webscout/Provider/OPENAI/autoproxy.py +0 -1067
- webscout/Provider/OPENAI/c4ai.py +0 -394
- webscout/Provider/OPENAI/copilot.py +0 -305
- webscout/Provider/OPENAI/glider.py +0 -330
- webscout/Provider/OPENAI/mcpcore.py +0 -431
- webscout/Provider/OPENAI/multichat.py +0 -378
- webscout/Provider/Reka.py +0 -214
- webscout/Provider/TTS/sthir.py +0 -94
- webscout/Provider/UNFINISHED/fetch_together_models.py +0 -90
- webscout/Provider/asksteve.py +0 -220
- webscout/Provider/copilot.py +0 -422
- webscout/Provider/freeaichat.py +0 -294
- webscout/Provider/koala.py +0 -182
- webscout/Provider/lmarena.py +0 -198
- webscout/Provider/monochat.py +0 -275
- webscout/Provider/multichat.py +0 -375
- webscout/Provider/scnet.py +0 -244
- webscout/Provider/talkai.py +0 -194
- /webscout/Provider/{Marcus.py → UNFINISHED/Marcus.py} +0 -0
- /webscout/Provider/{Qodo.py → UNFINISHED/Qodo.py} +0 -0
- /webscout/Provider/{XenAI.py → UNFINISHED/XenAI.py} +0 -0
- /webscout/Provider/{samurai.py → UNFINISHED/samurai.py} +0 -0
- {webscout-8.3.5.dist-info → webscout-8.3.7.dist-info}/WHEEL +0 -0
- {webscout-8.3.5.dist-info → webscout-8.3.7.dist-info}/entry_points.txt +0 -0
- {webscout-8.3.5.dist-info → webscout-8.3.7.dist-info}/licenses/LICENSE.md +0 -0
- {webscout-8.3.5.dist-info → webscout-8.3.7.dist-info}/top_level.txt +0 -0
webscout/Provider/Openai.py
CHANGED
|
@@ -1,15 +1,22 @@
|
|
|
1
1
|
import json
|
|
2
|
-
|
|
3
|
-
from
|
|
4
|
-
from ..AIutel import AwesomePrompts, sanitize_stream
|
|
5
|
-
from ..AIbase import Provider, AsyncProvider
|
|
2
|
+
import os
|
|
3
|
+
from typing import Any, Dict, Optional, Generator, Union, List
|
|
6
4
|
|
|
5
|
+
from curl_cffi.requests import Session
|
|
6
|
+
from curl_cffi import CurlError
|
|
7
|
+
|
|
8
|
+
from webscout.AIutel import Optimizers
|
|
9
|
+
from webscout.AIutel import Conversation
|
|
10
|
+
from webscout.AIutel import AwesomePrompts, sanitize_stream
|
|
11
|
+
from webscout.AIbase import Provider
|
|
7
12
|
from webscout import exceptions
|
|
8
|
-
from
|
|
9
|
-
|
|
10
|
-
import httpx
|
|
11
|
-
#----------------------------------------------------------OpenAI-----------------------------------
|
|
13
|
+
from webscout.litagent import LitAgent
|
|
14
|
+
|
|
12
15
|
class OPENAI(Provider):
|
|
16
|
+
"""
|
|
17
|
+
A class to interact with the OpenAI API with LitAgent user-agent.
|
|
18
|
+
"""
|
|
19
|
+
required_auth = True
|
|
13
20
|
def __init__(
|
|
14
21
|
self,
|
|
15
22
|
api_key: str,
|
|
@@ -28,49 +35,46 @@ class OPENAI(Provider):
|
|
|
28
35
|
history_offset: int = 10250,
|
|
29
36
|
act: str = None,
|
|
30
37
|
base_url: str = "https://api.openai.com/v1/chat/completions",
|
|
38
|
+
system_prompt: str = "You are a helpful assistant.",
|
|
39
|
+
browser: str = "chrome"
|
|
31
40
|
):
|
|
32
|
-
"""
|
|
41
|
+
"""Initializes the OpenAI API client."""
|
|
42
|
+
self.url = base_url
|
|
33
43
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
44
|
+
# Initialize LitAgent
|
|
45
|
+
self.agent = LitAgent()
|
|
46
|
+
self.fingerprint = self.agent.generate_fingerprint(browser)
|
|
47
|
+
self.api_key = api_key
|
|
48
|
+
# Use the fingerprint for headers
|
|
49
|
+
self.headers = {
|
|
50
|
+
"Accept": self.fingerprint["accept"],
|
|
51
|
+
"Accept-Language": self.fingerprint["accept_language"],
|
|
52
|
+
"User-Agent": self.fingerprint.get("user_agent", ""),
|
|
53
|
+
}
|
|
54
|
+
if self.api_key:
|
|
55
|
+
self.headers["Authorization"] = f"Bearer {self.api_key}"
|
|
56
|
+
|
|
57
|
+
# Initialize curl_cffi Session
|
|
58
|
+
self.session = Session()
|
|
59
|
+
# Update curl_cffi session headers and proxies
|
|
60
|
+
self.session.headers.update(self.headers)
|
|
61
|
+
self.session.proxies = proxies # Assign proxies directly
|
|
62
|
+
self.system_prompt = system_prompt
|
|
51
63
|
self.is_conversation = is_conversation
|
|
52
64
|
self.max_tokens_to_sample = max_tokens
|
|
53
|
-
self.
|
|
65
|
+
self.timeout = timeout
|
|
66
|
+
self.last_response = {}
|
|
54
67
|
self.model = model
|
|
55
68
|
self.temperature = temperature
|
|
56
69
|
self.presence_penalty = presence_penalty
|
|
57
70
|
self.frequency_penalty = frequency_penalty
|
|
58
71
|
self.top_p = top_p
|
|
59
|
-
|
|
60
|
-
self.stream_chunk_size = 64
|
|
61
|
-
self.timeout = timeout
|
|
62
|
-
self.last_response = {}
|
|
63
|
-
self.headers = {
|
|
64
|
-
"Content-Type": "application/json",
|
|
65
|
-
"Authorization": f"Bearer {self.api_key}",
|
|
66
|
-
}
|
|
67
|
-
self.session = requests.session()
|
|
72
|
+
|
|
68
73
|
self.__available_optimizers = (
|
|
69
74
|
method
|
|
70
75
|
for method in dir(Optimizers)
|
|
71
76
|
if callable(getattr(Optimizers, method)) and not method.startswith("__")
|
|
72
77
|
)
|
|
73
|
-
self.session.headers.update(self.headers)
|
|
74
78
|
Conversation.intro = (
|
|
75
79
|
AwesomePrompts().get_act(
|
|
76
80
|
act, raise_not_found=True, default=None, case_insensitive=True
|
|
@@ -78,11 +82,32 @@ class OPENAI(Provider):
|
|
|
78
82
|
if act
|
|
79
83
|
else intro or Conversation.intro
|
|
80
84
|
)
|
|
85
|
+
|
|
81
86
|
self.conversation = Conversation(
|
|
82
87
|
is_conversation, self.max_tokens_to_sample, filepath, update_file
|
|
83
88
|
)
|
|
84
89
|
self.conversation.history_offset = history_offset
|
|
85
|
-
|
|
90
|
+
|
|
91
|
+
def refresh_identity(self, browser: str = None):
|
|
92
|
+
"""
|
|
93
|
+
Refreshes the browser identity fingerprint.
|
|
94
|
+
|
|
95
|
+
Args:
|
|
96
|
+
browser: Specific browser to use for the new fingerprint
|
|
97
|
+
"""
|
|
98
|
+
browser = browser or self.fingerprint.get("browser_type", "chrome")
|
|
99
|
+
self.fingerprint = self.agent.generate_fingerprint(browser)
|
|
100
|
+
|
|
101
|
+
# Update headers with new fingerprint (only relevant ones)
|
|
102
|
+
self.headers.update({
|
|
103
|
+
"Accept": self.fingerprint["accept"],
|
|
104
|
+
"Accept-Language": self.fingerprint["accept_language"],
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
# Update session headers
|
|
108
|
+
self.session.headers.update(self.headers)
|
|
109
|
+
|
|
110
|
+
return self.fingerprint
|
|
86
111
|
|
|
87
112
|
def ask(
|
|
88
113
|
self,
|
|
@@ -91,41 +116,7 @@ class OPENAI(Provider):
|
|
|
91
116
|
raw: bool = False,
|
|
92
117
|
optimizer: str = None,
|
|
93
118
|
conversationally: bool = False,
|
|
94
|
-
) ->
|
|
95
|
-
"""Chat with AI
|
|
96
|
-
|
|
97
|
-
Args:
|
|
98
|
-
prompt (str): Prompt to be send.
|
|
99
|
-
stream (bool, optional): Flag for streaming response. Defaults to False.
|
|
100
|
-
raw (bool, optional): Stream back raw response as received. Defaults to False.
|
|
101
|
-
optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
|
|
102
|
-
conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
|
|
103
|
-
Returns:
|
|
104
|
-
dict : {}
|
|
105
|
-
```json
|
|
106
|
-
{
|
|
107
|
-
"id": "chatcmpl-TaREJpBZsRVQFRFic1wIA7Q7XfnaD",
|
|
108
|
-
"object": "chat.completion",
|
|
109
|
-
"created": 1704623244,
|
|
110
|
-
"model": "gpt-3.5-turbo",
|
|
111
|
-
"usage": {
|
|
112
|
-
"prompt_tokens": 0,
|
|
113
|
-
"completion_tokens": 0,
|
|
114
|
-
"total_tokens": 0
|
|
115
|
-
},
|
|
116
|
-
"choices": [
|
|
117
|
-
{
|
|
118
|
-
"message": {
|
|
119
|
-
"role": "assistant",
|
|
120
|
-
"content": "Hello! How can I assist you today?"
|
|
121
|
-
},
|
|
122
|
-
"finish_reason": "stop",
|
|
123
|
-
"index": 0
|
|
124
|
-
}
|
|
125
|
-
]
|
|
126
|
-
}
|
|
127
|
-
```
|
|
128
|
-
"""
|
|
119
|
+
) -> Union[Dict[str, Any], Generator]:
|
|
129
120
|
conversation_prompt = self.conversation.gen_complete_prompt(prompt)
|
|
130
121
|
if optimizer:
|
|
131
122
|
if optimizer in self.__available_optimizers:
|
|
@@ -133,364 +124,121 @@ class OPENAI(Provider):
|
|
|
133
124
|
conversation_prompt if conversationally else prompt
|
|
134
125
|
)
|
|
135
126
|
else:
|
|
136
|
-
raise exceptions.FailedToGenerateResponseError(
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
self.session.headers.update(self.headers)
|
|
127
|
+
raise exceptions.FailedToGenerateResponseError(f"Optimizer is not one of {self.__available_optimizers}")
|
|
128
|
+
|
|
129
|
+
# Payload construction
|
|
140
130
|
payload = {
|
|
141
|
-
"frequency_penalty": self.frequency_penalty,
|
|
142
|
-
"messages": [{"content": conversation_prompt, "role": "user"}],
|
|
143
131
|
"model": self.model,
|
|
144
|
-
"
|
|
132
|
+
"messages": [
|
|
133
|
+
{"role": "system", "content": self.system_prompt},
|
|
134
|
+
{"role": "user", "content": conversation_prompt},
|
|
135
|
+
],
|
|
145
136
|
"stream": stream,
|
|
146
137
|
"temperature": self.temperature,
|
|
147
138
|
"top_p": self.top_p,
|
|
139
|
+
"presence_penalty": self.presence_penalty,
|
|
140
|
+
"frequency_penalty": self.frequency_penalty,
|
|
148
141
|
}
|
|
149
142
|
|
|
150
143
|
def for_stream():
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
144
|
+
streaming_text = ""
|
|
145
|
+
try:
|
|
146
|
+
# Use curl_cffi session post with impersonate
|
|
147
|
+
response = self.session.post(
|
|
148
|
+
self.url,
|
|
149
|
+
data=json.dumps(payload),
|
|
150
|
+
stream=True,
|
|
151
|
+
timeout=self.timeout,
|
|
152
|
+
impersonate="chrome110"
|
|
157
153
|
)
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
if incomplete_message:
|
|
169
|
-
message_load += incomplete_message
|
|
170
|
-
resp["choices"][0]["delta"]["content"] = message_load
|
|
171
|
-
self.last_response.update(resp)
|
|
172
|
-
yield value if raw else resp
|
|
173
|
-
elif raw:
|
|
174
|
-
yield value
|
|
175
|
-
except json.decoder.JSONDecodeError:
|
|
176
|
-
pass
|
|
177
|
-
self.conversation.update_chat_history(
|
|
178
|
-
prompt, self.get_message(self.last_response)
|
|
179
|
-
)
|
|
180
|
-
|
|
181
|
-
def for_non_stream():
|
|
182
|
-
response = self.session.post(
|
|
183
|
-
self.chat_endpoint, json=payload, stream=False, timeout=self.timeout
|
|
184
|
-
)
|
|
185
|
-
if (
|
|
186
|
-
not response.ok
|
|
187
|
-
or not response.headers.get("Content-Type", "") == "application/json"
|
|
188
|
-
):
|
|
189
|
-
raise exceptions.FailedToGenerateResponseError(
|
|
190
|
-
f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
|
|
154
|
+
response.raise_for_status()
|
|
155
|
+
|
|
156
|
+
# Use sanitize_stream
|
|
157
|
+
processed_stream = sanitize_stream(
|
|
158
|
+
data=response.iter_content(chunk_size=None),
|
|
159
|
+
intro_value="data:",
|
|
160
|
+
to_json=True,
|
|
161
|
+
skip_markers=["[DONE]"],
|
|
162
|
+
content_extractor=lambda chunk: chunk.get("choices", [{}])[0].get("delta", {}).get("content") if isinstance(chunk, dict) else None,
|
|
163
|
+
yield_raw_on_error=False
|
|
191
164
|
)
|
|
192
|
-
resp = response.json()
|
|
193
|
-
self.last_response.update(resp)
|
|
194
|
-
self.conversation.update_chat_history(
|
|
195
|
-
prompt, self.get_message(self.last_response)
|
|
196
|
-
)
|
|
197
|
-
return resp
|
|
198
|
-
|
|
199
|
-
return for_stream() if stream else for_non_stream()
|
|
200
|
-
|
|
201
|
-
def chat(
|
|
202
|
-
self,
|
|
203
|
-
prompt: str,
|
|
204
|
-
stream: bool = False,
|
|
205
|
-
optimizer: str = None,
|
|
206
|
-
conversationally: bool = False,
|
|
207
|
-
) -> str:
|
|
208
|
-
"""Generate response `str`
|
|
209
|
-
Args:
|
|
210
|
-
prompt (str): Prompt to be send.
|
|
211
|
-
stream (bool, optional): Flag for streaming response. Defaults to False.
|
|
212
|
-
optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
|
|
213
|
-
conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
|
|
214
|
-
Returns:
|
|
215
|
-
str: Response generated
|
|
216
|
-
"""
|
|
217
165
|
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
166
|
+
for content_chunk in processed_stream:
|
|
167
|
+
if content_chunk and isinstance(content_chunk, str):
|
|
168
|
+
streaming_text += content_chunk
|
|
169
|
+
resp = dict(text=content_chunk)
|
|
170
|
+
yield resp if not raw else content_chunk
|
|
171
|
+
|
|
172
|
+
except CurlError as e:
|
|
173
|
+
raise exceptions.FailedToGenerateResponseError(f"Request failed (CurlError): {str(e)}") from e
|
|
174
|
+
except Exception as e:
|
|
175
|
+
raise exceptions.FailedToGenerateResponseError(f"Request failed ({type(e).__name__}): {str(e)}") from e
|
|
176
|
+
finally:
|
|
177
|
+
if streaming_text:
|
|
178
|
+
self.last_response = {"text": streaming_text}
|
|
179
|
+
self.conversation.update_chat_history(prompt, streaming_text)
|
|
223
180
|
|
|
224
181
|
def for_non_stream():
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
182
|
+
try:
|
|
183
|
+
# Use curl_cffi session post with impersonate for non-streaming
|
|
184
|
+
response = self.session.post(
|
|
185
|
+
self.url,
|
|
186
|
+
data=json.dumps(payload),
|
|
187
|
+
timeout=self.timeout,
|
|
188
|
+
impersonate="chrome110"
|
|
231
189
|
)
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
return for_stream() if stream else for_non_stream()
|
|
235
|
-
|
|
236
|
-
def get_message(self, response: dict) -> str:
|
|
237
|
-
"""Retrieves message only from response
|
|
238
|
-
|
|
239
|
-
Args:
|
|
240
|
-
response (dict): Response generated by `self.ask`
|
|
241
|
-
|
|
242
|
-
Returns:
|
|
243
|
-
str: Message extracted
|
|
244
|
-
"""
|
|
245
|
-
assert isinstance(response, dict), "Response should be of dict data-type only"
|
|
246
|
-
try:
|
|
247
|
-
if response["choices"][0].get("delta"):
|
|
248
|
-
return response["choices"][0]["delta"]["content"]
|
|
249
|
-
return response["choices"][0]["message"]["content"]
|
|
250
|
-
except KeyError:
|
|
251
|
-
return ""
|
|
252
|
-
class AsyncOPENAI(AsyncProvider):
|
|
253
|
-
def __init__(
|
|
254
|
-
self,
|
|
255
|
-
api_key: str,
|
|
256
|
-
is_conversation: bool = True,
|
|
257
|
-
max_tokens: int = 600,
|
|
258
|
-
temperature: float = 1,
|
|
259
|
-
presence_penalty: int = 0,
|
|
260
|
-
frequency_penalty: int = 0,
|
|
261
|
-
top_p: float = 1,
|
|
262
|
-
model: str = "gpt-3.5-turbo",
|
|
263
|
-
timeout: int = 30,
|
|
264
|
-
intro: str = None,
|
|
265
|
-
filepath: str = None,
|
|
266
|
-
update_file: bool = True,
|
|
267
|
-
proxies: dict = {},
|
|
268
|
-
history_offset: int = 10250,
|
|
269
|
-
act: str = None,
|
|
270
|
-
):
|
|
271
|
-
"""Instantiates OPENAI
|
|
272
|
-
|
|
273
|
-
Args:
|
|
274
|
-
api_key (key): OpenAI's API key.
|
|
275
|
-
is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
|
|
276
|
-
max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
|
|
277
|
-
temperature (float, optional): Charge of the generated text's randomness. Defaults to 1.
|
|
278
|
-
presence_penalty (int, optional): Chances of topic being repeated. Defaults to 0.
|
|
279
|
-
frequency_penalty (int, optional): Chances of word being repeated. Defaults to 0.
|
|
280
|
-
top_p (float, optional): Sampling threshold during inference time. Defaults to 0.999.
|
|
281
|
-
model (str, optional): LLM model name. Defaults to "gpt-3.5-turbo".
|
|
282
|
-
timeout (int, optional): Http request timeout. Defaults to 30.
|
|
283
|
-
intro (str, optional): Conversation introductory prompt. Defaults to None.
|
|
284
|
-
filepath (str, optional): Path to file containing conversation history. Defaults to None.
|
|
285
|
-
update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
|
|
286
|
-
proxies (dict, optional): Http request proxies. Defaults to {}.
|
|
287
|
-
history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
|
|
288
|
-
act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
|
|
289
|
-
"""
|
|
290
|
-
self.is_conversation = is_conversation
|
|
291
|
-
self.max_tokens_to_sample = max_tokens
|
|
292
|
-
self.api_key = api_key
|
|
293
|
-
self.model = model
|
|
294
|
-
self.temperature = temperature
|
|
295
|
-
self.presence_penalty = presence_penalty
|
|
296
|
-
self.frequency_penalty = frequency_penalty
|
|
297
|
-
self.top_p = top_p
|
|
298
|
-
self.chat_endpoint = "https://api.openai.com/v1/chat/completions"
|
|
299
|
-
self.stream_chunk_size = 64
|
|
300
|
-
self.timeout = timeout
|
|
301
|
-
self.last_response = {}
|
|
302
|
-
self.headers = {
|
|
303
|
-
"Content-Type": "application/json",
|
|
304
|
-
"Authorization": f"Bearer {self.api_key}",
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
self.__available_optimizers = (
|
|
308
|
-
method
|
|
309
|
-
for method in dir(Optimizers)
|
|
310
|
-
if callable(getattr(Optimizers, method)) and not method.startswith("__")
|
|
311
|
-
)
|
|
312
|
-
Conversation.intro = (
|
|
313
|
-
AwesomePrompts().get_act(
|
|
314
|
-
act, raise_not_found=True, default=None, case_insensitive=True
|
|
315
|
-
)
|
|
316
|
-
if act
|
|
317
|
-
else intro or Conversation.intro
|
|
318
|
-
)
|
|
319
|
-
self.conversation = Conversation(
|
|
320
|
-
is_conversation, self.max_tokens_to_sample, filepath, update_file
|
|
321
|
-
)
|
|
322
|
-
self.conversation.history_offset = history_offset
|
|
323
|
-
self.session = httpx.AsyncClient(
|
|
324
|
-
headers=self.headers,
|
|
325
|
-
proxies=proxies,
|
|
326
|
-
)
|
|
190
|
+
response.raise_for_status()
|
|
327
191
|
|
|
328
|
-
|
|
329
|
-
self,
|
|
330
|
-
prompt: str,
|
|
331
|
-
stream: bool = False,
|
|
332
|
-
raw: bool = False,
|
|
333
|
-
optimizer: str = None,
|
|
334
|
-
conversationally: bool = False,
|
|
335
|
-
tools: Optional[List[Dict[str, Any]]] = None,
|
|
336
|
-
) -> Union[dict, AsyncGenerator]:
|
|
337
|
-
"""Chat with AI asynchronously.
|
|
192
|
+
response_text = response.text
|
|
338
193
|
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
Returns:
|
|
347
|
-
dict|AsyncGenerator : ai content.
|
|
348
|
-
```json
|
|
349
|
-
{
|
|
350
|
-
"id": "chatcmpl-TaREJpBZsRVQFRFic1wIA7Q7XfnaD",
|
|
351
|
-
"object": "chat.completion",
|
|
352
|
-
"created": 1704623244,
|
|
353
|
-
"model": "gpt-3.5-turbo",
|
|
354
|
-
"usage": {
|
|
355
|
-
"prompt_tokens": 0,
|
|
356
|
-
"completion_tokens": 0,
|
|
357
|
-
"total_tokens": 0
|
|
358
|
-
},
|
|
359
|
-
"choices": [
|
|
360
|
-
{
|
|
361
|
-
"message": {
|
|
362
|
-
"role": "assistant",
|
|
363
|
-
"content": "Hello! How can I assist you today?"
|
|
364
|
-
},
|
|
365
|
-
"finish_reason": "stop",
|
|
366
|
-
"index": 0
|
|
367
|
-
}
|
|
368
|
-
]
|
|
369
|
-
}
|
|
370
|
-
```
|
|
371
|
-
"""
|
|
372
|
-
conversation_prompt = self.conversation.gen_complete_prompt(prompt)
|
|
373
|
-
if optimizer:
|
|
374
|
-
if optimizer in self.__available_optimizers:
|
|
375
|
-
conversation_prompt = getattr(Optimizers, optimizer)(
|
|
376
|
-
conversation_prompt if conversationally else prompt
|
|
377
|
-
)
|
|
378
|
-
else:
|
|
379
|
-
raise Exception(
|
|
380
|
-
f"Optimizer is not one of {self.__available_optimizers}"
|
|
194
|
+
# Use sanitize_stream to parse the non-streaming JSON response
|
|
195
|
+
processed_stream = sanitize_stream(
|
|
196
|
+
data=response_text,
|
|
197
|
+
to_json=True,
|
|
198
|
+
intro_value=None,
|
|
199
|
+
content_extractor=lambda chunk: chunk.get("choices", [{}])[0].get("message", {}).get("content") if isinstance(chunk, dict) else None,
|
|
200
|
+
yield_raw_on_error=False
|
|
381
201
|
)
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
"model": self.model,
|
|
386
|
-
"presence_penalty": self.presence_penalty,
|
|
387
|
-
"stream": stream,
|
|
388
|
-
"temperature": self.temperature,
|
|
389
|
-
"top_p": self.top_p,
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
async def for_stream():
|
|
393
|
-
async with self.session.stream(
|
|
394
|
-
"POST", self.chat_endpoint, json=payload, timeout=self.timeout
|
|
395
|
-
) as response:
|
|
396
|
-
if not response.is_success:
|
|
397
|
-
raise Exception(
|
|
398
|
-
f"Failed to generate response - ({response.status_code}, {response.reason_phrase})"
|
|
399
|
-
)
|
|
400
|
-
|
|
401
|
-
message_load = ""
|
|
402
|
-
async for value in response.aiter_lines():
|
|
403
|
-
try:
|
|
202
|
+
# Extract the single result
|
|
203
|
+
content = next(processed_stream, None)
|
|
204
|
+
content = content if isinstance(content, str) else ""
|
|
404
205
|
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
message_load += incomplete_message
|
|
409
|
-
resp["choices"][0]["delta"]["content"] = message_load
|
|
410
|
-
self.last_response.update(resp)
|
|
411
|
-
yield value if raw else resp
|
|
412
|
-
elif raw:
|
|
413
|
-
yield value
|
|
414
|
-
except json.decoder.JSONDecodeError:
|
|
415
|
-
pass
|
|
416
|
-
self.conversation.update_chat_history(
|
|
417
|
-
prompt, await self.get_message(self.last_response)
|
|
418
|
-
)
|
|
206
|
+
self.last_response = {"text": content}
|
|
207
|
+
self.conversation.update_chat_history(prompt, content)
|
|
208
|
+
return self.last_response if not raw else content
|
|
419
209
|
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
headers=self.headers,
|
|
426
|
-
)
|
|
427
|
-
if (
|
|
428
|
-
not response.is_success
|
|
429
|
-
or not response.headers.get("Content-Type", "") == "application/json"
|
|
430
|
-
):
|
|
431
|
-
raise Exception(
|
|
432
|
-
f"Failed to generate response - ({response.status_code}, {response.reason_phrase})"
|
|
433
|
-
)
|
|
434
|
-
resp = response.json()
|
|
435
|
-
self.last_response.update(resp)
|
|
436
|
-
self.conversation.update_chat_history(
|
|
437
|
-
prompt, await self.get_message(self.last_response)
|
|
438
|
-
)
|
|
439
|
-
return resp
|
|
210
|
+
except CurlError as e:
|
|
211
|
+
raise exceptions.FailedToGenerateResponseError(f"Request failed (CurlError): {e}") from e
|
|
212
|
+
except Exception as e:
|
|
213
|
+
err_text = getattr(e, 'response', None) and getattr(e.response, 'text', '')
|
|
214
|
+
raise exceptions.FailedToGenerateResponseError(f"Request failed ({type(e).__name__}): {e} - {err_text}") from e
|
|
440
215
|
|
|
441
|
-
return for_stream() if stream else
|
|
216
|
+
return for_stream() if stream else for_non_stream()
|
|
442
217
|
|
|
443
|
-
|
|
218
|
+
def chat(
|
|
444
219
|
self,
|
|
445
220
|
prompt: str,
|
|
446
221
|
stream: bool = False,
|
|
447
222
|
optimizer: str = None,
|
|
448
223
|
conversationally: bool = False,
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
stream (bool, optional): Flag for streaming response. Defaults to False.
|
|
455
|
-
optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
|
|
456
|
-
conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
|
|
457
|
-
tools (Optional[List[Dict[str, Any]]], optional): List of tools to be used. Defaults to None.
|
|
458
|
-
Returns:
|
|
459
|
-
str|AsyncGenerator: Response generated
|
|
460
|
-
"""
|
|
461
|
-
|
|
462
|
-
async def for_stream():
|
|
463
|
-
async_ask = await self.ask(
|
|
464
|
-
prompt, True, optimizer=optimizer, conversationally=conversationally
|
|
224
|
+
) -> Union[str, Generator[str, None, None]]:
|
|
225
|
+
def for_stream_chat():
|
|
226
|
+
gen = self.ask(
|
|
227
|
+
prompt, stream=True, raw=False,
|
|
228
|
+
optimizer=optimizer, conversationally=conversationally
|
|
465
229
|
)
|
|
466
|
-
|
|
467
|
-
yield
|
|
230
|
+
for response_dict in gen:
|
|
231
|
+
yield self.get_message(response_dict)
|
|
468
232
|
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
False,
|
|
474
|
-
optimizer=optimizer,
|
|
475
|
-
conversationally=conversationally,
|
|
476
|
-
)
|
|
233
|
+
def for_non_stream_chat():
|
|
234
|
+
response_data = self.ask(
|
|
235
|
+
prompt, stream=False, raw=False,
|
|
236
|
+
optimizer=optimizer, conversationally=conversationally
|
|
477
237
|
)
|
|
238
|
+
return self.get_message(response_data)
|
|
478
239
|
|
|
479
|
-
return
|
|
240
|
+
return for_stream_chat() if stream else for_non_stream_chat()
|
|
480
241
|
|
|
481
|
-
|
|
482
|
-
"""Retrieves message only from response asynchronously.
|
|
483
|
-
|
|
484
|
-
Args:
|
|
485
|
-
response (dict): Response generated by `self.ask`
|
|
486
|
-
|
|
487
|
-
Returns:
|
|
488
|
-
str: Message extracted
|
|
489
|
-
"""
|
|
242
|
+
def get_message(self, response: dict) -> str:
|
|
490
243
|
assert isinstance(response, dict), "Response should be of dict data-type only"
|
|
491
|
-
|
|
492
|
-
if response["choices"][0].get("delta"):
|
|
493
|
-
return response["choices"][0]["delta"]["content"]
|
|
494
|
-
return response["choices"][0]["message"]["content"]
|
|
495
|
-
except KeyError:
|
|
496
|
-
return ""
|
|
244
|
+
return response["text"]
|
webscout/Provider/PI.py
CHANGED
|
@@ -21,6 +21,7 @@ class PiAI(Provider):
|
|
|
21
21
|
AVAILABLE_VOICES (Dict[str, int]): Available voice options for audio responses
|
|
22
22
|
AVAILABLE_MODELS (List[str]): Available model options for the API
|
|
23
23
|
"""
|
|
24
|
+
required_auth = False
|
|
24
25
|
AVAILABLE_MODELS = ["inflection_3_pi"]
|
|
25
26
|
AVAILABLE_VOICES: Dict[str, int] = {
|
|
26
27
|
"voice1": 1,
|