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/Hunyuan.py
DELETED
|
@@ -1,283 +0,0 @@
|
|
|
1
|
-
from curl_cffi.requests import Session
|
|
2
|
-
from curl_cffi import CurlError
|
|
3
|
-
import json
|
|
4
|
-
import os
|
|
5
|
-
from typing import Any, Dict, Optional, Generator, Union
|
|
6
|
-
import time
|
|
7
|
-
import uuid
|
|
8
|
-
import re
|
|
9
|
-
|
|
10
|
-
from webscout.AIutel import Optimizers
|
|
11
|
-
from webscout.AIutel import Conversation
|
|
12
|
-
from webscout.AIutel import AwesomePrompts, sanitize_stream
|
|
13
|
-
from webscout.AIbase import Provider, AsyncProvider
|
|
14
|
-
from webscout import exceptions
|
|
15
|
-
from webscout.litagent import LitAgent
|
|
16
|
-
|
|
17
|
-
class Hunyuan(Provider):
|
|
18
|
-
"""
|
|
19
|
-
A class to interact with the Tencent Hunyuan API with LitAgent user-agent.
|
|
20
|
-
"""
|
|
21
|
-
|
|
22
|
-
AVAILABLE_MODELS = [
|
|
23
|
-
"hunyuan-t1-latest",
|
|
24
|
-
# Add more models as they become available
|
|
25
|
-
]
|
|
26
|
-
|
|
27
|
-
def __init__(
|
|
28
|
-
self,
|
|
29
|
-
is_conversation: bool = True,
|
|
30
|
-
max_tokens: int = 2048, # Note: max_tokens is not used by this API
|
|
31
|
-
timeout: int = 30,
|
|
32
|
-
intro: str = None,
|
|
33
|
-
filepath: str = None,
|
|
34
|
-
update_file: bool = True,
|
|
35
|
-
proxies: dict = {},
|
|
36
|
-
history_offset: int = 10250,
|
|
37
|
-
act: str = None,
|
|
38
|
-
model: str = "hunyuan-t1-latest",
|
|
39
|
-
browser: str = "chrome", # Note: browser fingerprinting might be less effective with impersonate
|
|
40
|
-
api_key: str = None,
|
|
41
|
-
system_prompt: str = "You are a helpful assistant.",
|
|
42
|
-
):
|
|
43
|
-
|
|
44
|
-
"""Initializes the Hunyuan API client."""
|
|
45
|
-
if model not in self.AVAILABLE_MODELS:
|
|
46
|
-
raise ValueError(f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}")
|
|
47
|
-
|
|
48
|
-
self.url = "https://llm.hunyuan.tencent.com/aide/api/v2/triton_image/demo_text_chat/"
|
|
49
|
-
|
|
50
|
-
# Initialize LitAgent (keep if needed for other headers or logic)
|
|
51
|
-
self.agent = LitAgent()
|
|
52
|
-
# Fingerprint generation might be less relevant with impersonate
|
|
53
|
-
self.fingerprint = self.agent.generate_fingerprint(browser)
|
|
54
|
-
|
|
55
|
-
# Use the fingerprint for headers (keep relevant ones)
|
|
56
|
-
self.headers = {
|
|
57
|
-
"Accept": "*/*",
|
|
58
|
-
"Accept-Language": self.fingerprint["accept_language"], # Keep Accept-Language
|
|
59
|
-
"Content-Type": "application/json",
|
|
60
|
-
"DNT": "1", # Keep DNT
|
|
61
|
-
"Origin": "https://llm.hunyuan.tencent.com", # Keep Origin
|
|
62
|
-
"Referer": "https://llm.hunyuan.tencent.com/", # Keep Referer
|
|
63
|
-
"Sec-Fetch-Dest": "empty", # Keep Sec-Fetch-*
|
|
64
|
-
"Sec-Fetch-Mode": "cors",
|
|
65
|
-
"Sec-Fetch-Site": "same-origin",
|
|
66
|
-
"Sec-GPC": "1", # Keep Sec-GPC
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
# Add authorization if API key is provided
|
|
70
|
-
if api_key:
|
|
71
|
-
self.headers["Authorization"] = f"Bearer {api_key}"
|
|
72
|
-
else:
|
|
73
|
-
# Default test key (may not work long-term)
|
|
74
|
-
self.headers["Authorization"] = "Bearer 7auGXNATFSKl7dF"
|
|
75
|
-
|
|
76
|
-
# Initialize curl_cffi Session
|
|
77
|
-
self.session = Session()
|
|
78
|
-
# Update curl_cffi session headers and proxies
|
|
79
|
-
self.session.headers.update(self.headers)
|
|
80
|
-
self.session.proxies = proxies # Assign proxies directly
|
|
81
|
-
self.system_message = system_prompt
|
|
82
|
-
self.is_conversation = is_conversation
|
|
83
|
-
self.max_tokens_to_sample = max_tokens
|
|
84
|
-
self.timeout = timeout
|
|
85
|
-
self.last_response = {}
|
|
86
|
-
self.model = model
|
|
87
|
-
|
|
88
|
-
self.__available_optimizers = (
|
|
89
|
-
method
|
|
90
|
-
for method in dir(Optimizers)
|
|
91
|
-
if callable(getattr(Optimizers, method)) and not method.startswith("__")
|
|
92
|
-
)
|
|
93
|
-
Conversation.intro = (
|
|
94
|
-
AwesomePrompts().get_act(
|
|
95
|
-
act, raise_not_found=True, default=None, case_insensitive=True
|
|
96
|
-
)
|
|
97
|
-
if act
|
|
98
|
-
else intro or Conversation.intro
|
|
99
|
-
)
|
|
100
|
-
|
|
101
|
-
self.conversation = Conversation(
|
|
102
|
-
is_conversation, self.max_tokens_to_sample, filepath, update_file
|
|
103
|
-
)
|
|
104
|
-
self.conversation.history_offset = history_offset
|
|
105
|
-
|
|
106
|
-
def refresh_identity(self, browser: str = None):
|
|
107
|
-
"""
|
|
108
|
-
Refreshes the browser identity fingerprint.
|
|
109
|
-
|
|
110
|
-
Args:
|
|
111
|
-
browser: Specific browser to use for the new fingerprint
|
|
112
|
-
"""
|
|
113
|
-
browser = browser or self.fingerprint.get("browser_type", "chrome")
|
|
114
|
-
self.fingerprint = self.agent.generate_fingerprint(browser)
|
|
115
|
-
|
|
116
|
-
# Update headers with new fingerprint (only relevant ones)
|
|
117
|
-
self.headers.update({
|
|
118
|
-
"Accept-Language": self.fingerprint["accept_language"],
|
|
119
|
-
})
|
|
120
|
-
|
|
121
|
-
# Update session headers
|
|
122
|
-
self.session.headers.update(self.headers) # Update only relevant headers
|
|
123
|
-
|
|
124
|
-
return self.fingerprint
|
|
125
|
-
|
|
126
|
-
def ask(
|
|
127
|
-
self,
|
|
128
|
-
prompt: str,
|
|
129
|
-
stream: bool = False, # API supports streaming
|
|
130
|
-
raw: bool = False,
|
|
131
|
-
optimizer: str = None,
|
|
132
|
-
conversationally: bool = False,
|
|
133
|
-
) -> Union[Dict[str, Any], Generator]:
|
|
134
|
-
conversation_prompt = self.conversation.gen_complete_prompt(prompt)
|
|
135
|
-
if optimizer:
|
|
136
|
-
if optimizer in self.__available_optimizers:
|
|
137
|
-
conversation_prompt = getattr(Optimizers, optimizer)(conversation_prompt if conversationally else prompt)
|
|
138
|
-
else:
|
|
139
|
-
raise Exception(f"Optimizer is not one of {self.__available_optimizers}")
|
|
140
|
-
|
|
141
|
-
# Generate a unique query ID for each request
|
|
142
|
-
query_id = ''.join(re.findall(r'[a-z0-9]', str(uuid.uuid4())[:18]))
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
# Payload construction
|
|
146
|
-
payload = {
|
|
147
|
-
"stream": True, # API seems to require stream=True based on response format
|
|
148
|
-
"model": self.model,
|
|
149
|
-
"query_id": query_id,
|
|
150
|
-
"messages": [
|
|
151
|
-
{"role": "system", "content": self.system_message},
|
|
152
|
-
{"role": "user", "content": "Always response in English\n\n" + conversation_prompt},
|
|
153
|
-
],
|
|
154
|
-
"stream_moderation": True,
|
|
155
|
-
"enable_enhancement": False
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
def for_stream():
|
|
159
|
-
streaming_text = "" # Initialize outside try block
|
|
160
|
-
try:
|
|
161
|
-
# Use curl_cffi session post with impersonate
|
|
162
|
-
response = self.session.post(
|
|
163
|
-
self.url,
|
|
164
|
-
data=json.dumps(payload),
|
|
165
|
-
stream=True,
|
|
166
|
-
timeout=self.timeout,
|
|
167
|
-
impersonate="chrome110" # Use a common impersonation profile
|
|
168
|
-
)
|
|
169
|
-
response.raise_for_status() # Check for HTTP errors
|
|
170
|
-
|
|
171
|
-
# Iterate over bytes and decode manually
|
|
172
|
-
for line_bytes in response.iter_lines():
|
|
173
|
-
if line_bytes:
|
|
174
|
-
try:
|
|
175
|
-
line = line_bytes.decode('utf-8').strip()
|
|
176
|
-
if line.startswith("data: "):
|
|
177
|
-
json_str = line[6:]
|
|
178
|
-
if json_str == "[DONE]":
|
|
179
|
-
break
|
|
180
|
-
json_data = json.loads(json_str)
|
|
181
|
-
if 'choices' in json_data:
|
|
182
|
-
choice = json_data['choices'][0]
|
|
183
|
-
if 'delta' in choice and 'content' in choice['delta']:
|
|
184
|
-
content = choice['delta']['content']
|
|
185
|
-
if content: # Ensure content is not None or empty
|
|
186
|
-
streaming_text += content
|
|
187
|
-
resp = dict(text=content)
|
|
188
|
-
# Yield dict or raw string chunk
|
|
189
|
-
yield resp if not raw else content
|
|
190
|
-
except (json.JSONDecodeError, UnicodeDecodeError):
|
|
191
|
-
continue # Ignore lines that are not valid JSON or cannot be decoded
|
|
192
|
-
|
|
193
|
-
# Update history after stream finishes
|
|
194
|
-
self.last_response = {"text": streaming_text}
|
|
195
|
-
self.conversation.update_chat_history(prompt, streaming_text)
|
|
196
|
-
|
|
197
|
-
except CurlError as e: # Catch CurlError
|
|
198
|
-
raise exceptions.FailedToGenerateResponseError(f"Request failed (CurlError): {str(e)}") from e
|
|
199
|
-
except Exception as e: # Catch other potential exceptions (like HTTPError)
|
|
200
|
-
err_text = getattr(e, 'response', None) and getattr(e.response, 'text', '')
|
|
201
|
-
raise exceptions.FailedToGenerateResponseError(f"Request failed ({type(e).__name__}): {str(e)} - {err_text}") from e
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
def for_non_stream():
|
|
205
|
-
# Aggregate the stream using the updated for_stream logic
|
|
206
|
-
full_text = ""
|
|
207
|
-
try:
|
|
208
|
-
# Ensure raw=False so for_stream yields dicts
|
|
209
|
-
for chunk_data in for_stream():
|
|
210
|
-
if isinstance(chunk_data, dict) and "text" in chunk_data:
|
|
211
|
-
full_text += chunk_data["text"]
|
|
212
|
-
# Handle raw string case if raw=True was passed
|
|
213
|
-
elif raw and isinstance(chunk_data, str):
|
|
214
|
-
full_text += chunk_data
|
|
215
|
-
except Exception as e:
|
|
216
|
-
# If aggregation fails but some text was received, use it. Otherwise, re-raise.
|
|
217
|
-
if not full_text:
|
|
218
|
-
raise exceptions.FailedToGenerateResponseError(f"Failed to get non-stream response: {str(e)}") from e
|
|
219
|
-
|
|
220
|
-
# last_response and history are updated within for_stream
|
|
221
|
-
# Return the final aggregated response dict or raw string
|
|
222
|
-
return full_text if raw else self.last_response
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
# Since the API endpoint suggests streaming, always call the stream generator.
|
|
226
|
-
# The non-stream wrapper will handle aggregation if stream=False.
|
|
227
|
-
return for_stream() if stream else for_non_stream()
|
|
228
|
-
|
|
229
|
-
def chat(
|
|
230
|
-
self,
|
|
231
|
-
prompt: str,
|
|
232
|
-
stream: bool = False,
|
|
233
|
-
optimizer: str = None,
|
|
234
|
-
conversationally: bool = False,
|
|
235
|
-
) -> Union[str, Generator[str, None, None]]:
|
|
236
|
-
def for_stream_chat():
|
|
237
|
-
# ask() yields dicts or strings when streaming
|
|
238
|
-
gen = self.ask(
|
|
239
|
-
prompt, stream=True, raw=False, # Ensure ask yields dicts
|
|
240
|
-
optimizer=optimizer, conversationally=conversationally
|
|
241
|
-
)
|
|
242
|
-
for response_dict in gen:
|
|
243
|
-
yield self.get_message(response_dict) # get_message expects dict
|
|
244
|
-
|
|
245
|
-
def for_non_stream_chat():
|
|
246
|
-
# ask() returns dict or str when not streaming
|
|
247
|
-
response_data = self.ask(
|
|
248
|
-
prompt, stream=False, raw=False, # Ensure ask returns dict
|
|
249
|
-
optimizer=optimizer, conversationally=conversationally
|
|
250
|
-
)
|
|
251
|
-
return self.get_message(response_data) # get_message expects dict
|
|
252
|
-
|
|
253
|
-
return for_stream_chat() if stream else for_non_stream_chat()
|
|
254
|
-
|
|
255
|
-
def get_message(self, response: dict) -> str:
|
|
256
|
-
assert isinstance(response, dict), "Response should be of dict data-type only"
|
|
257
|
-
return response["text"]
|
|
258
|
-
|
|
259
|
-
if __name__ == "__main__":
|
|
260
|
-
# Ensure curl_cffi is installed
|
|
261
|
-
print("-" * 80)
|
|
262
|
-
print(f"{'Model':<50} {'Status':<10} {'Response'}")
|
|
263
|
-
print("-" * 80)
|
|
264
|
-
|
|
265
|
-
for model in Hunyuan.AVAILABLE_MODELS:
|
|
266
|
-
try:
|
|
267
|
-
test_ai = Hunyuan(model=model, timeout=60)
|
|
268
|
-
response = test_ai.chat("Say 'Hello' in one word", stream=True)
|
|
269
|
-
response_text = ""
|
|
270
|
-
for chunk in response:
|
|
271
|
-
response_text += chunk
|
|
272
|
-
|
|
273
|
-
if response_text and len(response_text.strip()) > 0:
|
|
274
|
-
status = "✓"
|
|
275
|
-
# Clean and truncate response
|
|
276
|
-
clean_text = response_text.strip().encode('utf-8', errors='ignore').decode('utf-8')
|
|
277
|
-
display_text = clean_text[:50] + "..." if len(clean_text) > 50 else clean_text
|
|
278
|
-
else:
|
|
279
|
-
status = "✗"
|
|
280
|
-
display_text = "Empty or invalid response"
|
|
281
|
-
print(f"\r{model:<50} {status:<10} {display_text}")
|
|
282
|
-
except Exception as e:
|
|
283
|
-
print(f"\r{model:<50} {'✗':<10} {str(e)}")
|
webscout/Provider/MCPCore.py
DELETED
|
@@ -1,322 +0,0 @@
|
|
|
1
|
-
import json
|
|
2
|
-
import uuid
|
|
3
|
-
import random
|
|
4
|
-
import string
|
|
5
|
-
from typing import Any, Dict, Generator, Union
|
|
6
|
-
|
|
7
|
-
# Use curl_cffi for requests
|
|
8
|
-
from curl_cffi.requests import Session
|
|
9
|
-
from curl_cffi import CurlError
|
|
10
|
-
|
|
11
|
-
from webscout.AIutel import Optimizers
|
|
12
|
-
from webscout.AIutel import Conversation
|
|
13
|
-
from webscout.AIutel import AwesomePrompts, sanitize_stream
|
|
14
|
-
from webscout.AIbase import Provider
|
|
15
|
-
from webscout import exceptions
|
|
16
|
-
from webscout.litagent import LitAgent
|
|
17
|
-
|
|
18
|
-
class MCPCore(Provider):
|
|
19
|
-
"""
|
|
20
|
-
A class to interact with the chat.mcpcore.xyz API.
|
|
21
|
-
Supports streaming responses.
|
|
22
|
-
"""
|
|
23
|
-
|
|
24
|
-
# Add more models if known, starting with the one from the example
|
|
25
|
-
AVAILABLE_MODELS = [
|
|
26
|
-
"@cf/deepseek-ai/deepseek-math-7b-instruct",
|
|
27
|
-
"@cf/deepseek-ai/deepseek-r1-distill-qwen-32b",
|
|
28
|
-
"@cf/defog/sqlcoder-7b-2",
|
|
29
|
-
"@cf/fblgit/una-cybertron-7b-v2-bf16",
|
|
30
|
-
"@cf/google/gemma-3-12b-it",
|
|
31
|
-
"@cf/meta/llama-2-7b-chat-int8",
|
|
32
|
-
"@hf/thebloke/llama-2-13b-chat-awq",
|
|
33
|
-
"@hf/thebloke/llamaguard-7b-awq",
|
|
34
|
-
"@hf/thebloke/mistral-7b-instruct-v0.1-awq",
|
|
35
|
-
"@hf/thebloke/neural-chat-7b-v3-1-awq",
|
|
36
|
-
"anthropic/claude-3.5-haiku",
|
|
37
|
-
"anthropic/claude-3.5-sonnet",
|
|
38
|
-
"anthropic/claude-3.7-sonnet",
|
|
39
|
-
"anthropic/claude-3.7-sonnet:thinking",
|
|
40
|
-
"anthropic/claude-opus-4",
|
|
41
|
-
"anthropic/claude-sonnet-4",
|
|
42
|
-
"openai/chatgpt-4o-latest",
|
|
43
|
-
"openai/gpt-3.5-turbo",
|
|
44
|
-
"openai/gpt-4.1",
|
|
45
|
-
"openai/gpt-4.1-mini",
|
|
46
|
-
"openai/gpt-4.1-nano",
|
|
47
|
-
"openai/gpt-4o-mini-search-preview",
|
|
48
|
-
"openai/gpt-4o-search-preview",
|
|
49
|
-
"openai/o1-pro",
|
|
50
|
-
"openai/o3-mini",
|
|
51
|
-
"sarvam-m",
|
|
52
|
-
"x-ai/grok-3-beta",
|
|
53
|
-
]
|
|
54
|
-
|
|
55
|
-
def __init__(
|
|
56
|
-
self,
|
|
57
|
-
is_conversation: bool = True,
|
|
58
|
-
max_tokens: int = 2048,
|
|
59
|
-
timeout: int = 60,
|
|
60
|
-
intro: str = None,
|
|
61
|
-
filepath: str = None,
|
|
62
|
-
update_file: bool = True,
|
|
63
|
-
proxies: dict = {},
|
|
64
|
-
history_offset: int = 10250,
|
|
65
|
-
act: str = None,
|
|
66
|
-
model: str = "qwen3-32b",
|
|
67
|
-
system_prompt: str = "You are a helpful assistant.",
|
|
68
|
-
):
|
|
69
|
-
"""Initializes the MCPCore API client."""
|
|
70
|
-
if model not in self.AVAILABLE_MODELS:
|
|
71
|
-
print(f"Warning: Model '{model}' is not listed in AVAILABLE_MODELS. Proceeding with the provided model.")
|
|
72
|
-
|
|
73
|
-
self.api_endpoint = "https://chat.mcpcore.xyz/api/chat/completions"
|
|
74
|
-
|
|
75
|
-
self.model = model
|
|
76
|
-
self.system_prompt = system_prompt
|
|
77
|
-
|
|
78
|
-
# Initialize curl_cffi Session
|
|
79
|
-
self.session = Session()
|
|
80
|
-
|
|
81
|
-
# Set up headers based on the provided request
|
|
82
|
-
self.headers = {
|
|
83
|
-
**LitAgent().generate_fingerprint(),
|
|
84
|
-
'origin': 'https://chat.mcpcore.xyz',
|
|
85
|
-
'referer': 'https://chat.mcpcore.xyz/',
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
# Apply headers, proxies, and cookies to the session
|
|
89
|
-
self.session.headers.update(self.headers)
|
|
90
|
-
self.session.proxies = proxies
|
|
91
|
-
|
|
92
|
-
# Provider settings
|
|
93
|
-
self.is_conversation = is_conversation
|
|
94
|
-
self.max_tokens_to_sample = max_tokens
|
|
95
|
-
self.timeout = timeout
|
|
96
|
-
self.last_response = {}
|
|
97
|
-
|
|
98
|
-
# Initialize optimizers
|
|
99
|
-
self.__available_optimizers = (
|
|
100
|
-
method
|
|
101
|
-
for method in dir(Optimizers)
|
|
102
|
-
if callable(getattr(Optimizers, method))
|
|
103
|
-
and not method.startswith("__")
|
|
104
|
-
)
|
|
105
|
-
Conversation.intro = (
|
|
106
|
-
AwesomePrompts().get_act(
|
|
107
|
-
act, raise_not_found=True, default=None, case_insensitive=True
|
|
108
|
-
)
|
|
109
|
-
if act
|
|
110
|
-
else intro or Conversation.intro
|
|
111
|
-
)
|
|
112
|
-
self.conversation = Conversation(
|
|
113
|
-
is_conversation, self.max_tokens_to_sample, filepath, update_file
|
|
114
|
-
)
|
|
115
|
-
self.conversation.history_offset = history_offset
|
|
116
|
-
|
|
117
|
-
# Token handling: always auto-fetch token, no cookies logic
|
|
118
|
-
self.token = self._auto_fetch_token()
|
|
119
|
-
|
|
120
|
-
# Set the Authorization header for the session
|
|
121
|
-
self.session.headers.update({
|
|
122
|
-
'authorization': f'Bearer {self.token}',
|
|
123
|
-
})
|
|
124
|
-
|
|
125
|
-
def _auto_fetch_token(self):
|
|
126
|
-
"""Automatically fetch a token from the signup endpoint."""
|
|
127
|
-
session = Session()
|
|
128
|
-
def random_string(length=8):
|
|
129
|
-
return ''.join(random.choices(string.ascii_lowercase, k=length))
|
|
130
|
-
name = random_string(6)
|
|
131
|
-
email = f"{random_string(8)}@gmail.com"
|
|
132
|
-
password = email
|
|
133
|
-
profile_image_url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAkRJREFUeF7tmDFOw0AUBdcSiIaKM3CKHIQ7UHEISq5AiUTFHYC0XADoTRsJEZFEjhFIaYAim92fjGFS736/zOTZzjavl0d98oMh0CgE4+IriEJYPhQC86EQhdAIwPL4DFEIjAAsjg1RCIwALI4NUQiMACyODVEIjAAsjg1RCIwALI4NUQiMACyODVEIjAAsjg1RCIwALI4NUQiMACyODVEIjAAsjg1RCIwALI4NUQiMACyODVEIjAAsjg1RCIwALI4NUQiMACyODVEIjAAsjg1RCIwALI4NUQiMACyODVEIjAAsjg2BCfkAIqwAA94KZ/EAAAAASUVORK5CYII="
|
|
134
|
-
payload = {
|
|
135
|
-
"name": name,
|
|
136
|
-
"email": email,
|
|
137
|
-
"password": password,
|
|
138
|
-
"profile_image_url": profile_image_url
|
|
139
|
-
}
|
|
140
|
-
headers = {
|
|
141
|
-
**LitAgent().generate_fingerprint(),
|
|
142
|
-
'origin': 'https://chat.mcpcore.xyz',
|
|
143
|
-
'referer': 'https://chat.mcpcore.xyz/auth',
|
|
144
|
-
}
|
|
145
|
-
try:
|
|
146
|
-
resp = session.post(
|
|
147
|
-
"https://chat.mcpcore.xyz/api/v1/auths/signup",
|
|
148
|
-
headers=headers,
|
|
149
|
-
json=payload,
|
|
150
|
-
timeout=30,
|
|
151
|
-
impersonate="chrome110"
|
|
152
|
-
)
|
|
153
|
-
if resp.ok:
|
|
154
|
-
data = resp.json()
|
|
155
|
-
token = data.get("token")
|
|
156
|
-
if token:
|
|
157
|
-
return token
|
|
158
|
-
# fallback: try to get from set-cookie
|
|
159
|
-
set_cookie = resp.headers.get("set-cookie", "")
|
|
160
|
-
if "token=" in set_cookie:
|
|
161
|
-
return set_cookie.split("token=")[1].split(";")[0]
|
|
162
|
-
raise exceptions.FailedToGenerateResponseError(f"Failed to auto-fetch token: {resp.status_code} {resp.text}")
|
|
163
|
-
except Exception as e:
|
|
164
|
-
raise exceptions.FailedToGenerateResponseError(f"Token auto-fetch failed: {e}")
|
|
165
|
-
|
|
166
|
-
def ask(
|
|
167
|
-
self,
|
|
168
|
-
prompt: str,
|
|
169
|
-
stream: bool = False,
|
|
170
|
-
raw: bool = False,
|
|
171
|
-
optimizer: str = None,
|
|
172
|
-
conversationally: bool = False,
|
|
173
|
-
**kwargs
|
|
174
|
-
) -> Union[Dict[str, Any], Generator]:
|
|
175
|
-
"""Sends a prompt to the MCPCore API and returns the response."""
|
|
176
|
-
|
|
177
|
-
conversation_prompt = self.conversation.gen_complete_prompt(prompt)
|
|
178
|
-
|
|
179
|
-
if optimizer:
|
|
180
|
-
if optimizer in self.__available_optimizers:
|
|
181
|
-
conversation_prompt = getattr(Optimizers, optimizer)(
|
|
182
|
-
conversation_prompt if conversationally else prompt
|
|
183
|
-
)
|
|
184
|
-
else:
|
|
185
|
-
raise exceptions.InvalidOptimizerError(
|
|
186
|
-
f"Optimizer is not one of {self.__available_optimizers}"
|
|
187
|
-
)
|
|
188
|
-
|
|
189
|
-
chat_id = kwargs.get("chat_id", str(uuid.uuid4()))
|
|
190
|
-
message_id = str(uuid.uuid4())
|
|
191
|
-
|
|
192
|
-
payload = {
|
|
193
|
-
"stream": stream,
|
|
194
|
-
"model": self.model,
|
|
195
|
-
"messages": [
|
|
196
|
-
{"role": "system", "content": self.system_prompt},
|
|
197
|
-
{"role": "user", "content": conversation_prompt}
|
|
198
|
-
],
|
|
199
|
-
"params": kwargs.get("params", {}),
|
|
200
|
-
"tool_servers": kwargs.get("tool_servers", []),
|
|
201
|
-
"features": kwargs.get("features", {"web_search": False}),
|
|
202
|
-
"chat_id": chat_id,
|
|
203
|
-
"id": message_id,
|
|
204
|
-
"stream_options": kwargs.get("stream_options", {"include_usage": True})
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
def for_stream():
|
|
208
|
-
streaming_text = ""
|
|
209
|
-
try:
|
|
210
|
-
response = self.session.post(
|
|
211
|
-
self.api_endpoint,
|
|
212
|
-
json=payload,
|
|
213
|
-
stream=True,
|
|
214
|
-
timeout=self.timeout,
|
|
215
|
-
impersonate="chrome110"
|
|
216
|
-
)
|
|
217
|
-
response.raise_for_status()
|
|
218
|
-
|
|
219
|
-
# Use sanitize_stream
|
|
220
|
-
processed_stream = sanitize_stream(
|
|
221
|
-
data=response.iter_content(chunk_size=None), # Pass byte iterator
|
|
222
|
-
intro_value="data:",
|
|
223
|
-
to_json=True, # Stream sends JSON
|
|
224
|
-
skip_markers=["[DONE]"],
|
|
225
|
-
content_extractor=lambda chunk: chunk.get('choices', [{}])[0].get('delta', {}).get('content') if isinstance(chunk, dict) else None,
|
|
226
|
-
yield_raw_on_error=False # Skip non-JSON or lines where extractor fails
|
|
227
|
-
)
|
|
228
|
-
|
|
229
|
-
for content_chunk in processed_stream:
|
|
230
|
-
# content_chunk is the string extracted by the content_extractor
|
|
231
|
-
if content_chunk and isinstance(content_chunk, str):
|
|
232
|
-
streaming_text += content_chunk
|
|
233
|
-
yield dict(text=content_chunk) if not raw else content_chunk
|
|
234
|
-
|
|
235
|
-
self.last_response = {"text": streaming_text}
|
|
236
|
-
self.conversation.update_chat_history(prompt, self.get_message(self.last_response))
|
|
237
|
-
|
|
238
|
-
except CurlError as e:
|
|
239
|
-
raise exceptions.FailedToGenerateResponseError(f"Request failed (CurlError): {e}") from e
|
|
240
|
-
except Exception as e:
|
|
241
|
-
err_text = getattr(e, 'response', None) and getattr(e.response, 'text', '')
|
|
242
|
-
raise exceptions.FailedToGenerateResponseError(f"An unexpected error occurred ({type(e).__name__}): {e} - {err_text}") from e
|
|
243
|
-
|
|
244
|
-
def for_non_stream():
|
|
245
|
-
full_text = ""
|
|
246
|
-
try:
|
|
247
|
-
stream_generator = self.ask(
|
|
248
|
-
prompt, stream=True, raw=False, optimizer=optimizer, conversationally=conversationally, **kwargs
|
|
249
|
-
)
|
|
250
|
-
for chunk_data in stream_generator:
|
|
251
|
-
if isinstance(chunk_data, dict):
|
|
252
|
-
full_text += chunk_data["text"]
|
|
253
|
-
elif isinstance(chunk_data, str):
|
|
254
|
-
full_text += chunk_data
|
|
255
|
-
except Exception as e:
|
|
256
|
-
raise exceptions.FailedToGenerateResponseError(f"Failed to aggregate non-stream response: {str(e)}") from e
|
|
257
|
-
|
|
258
|
-
return full_text if raw else self.last_response
|
|
259
|
-
|
|
260
|
-
return for_stream() if stream else for_non_stream()
|
|
261
|
-
|
|
262
|
-
def chat(
|
|
263
|
-
self,
|
|
264
|
-
prompt: str,
|
|
265
|
-
stream: bool = False,
|
|
266
|
-
optimizer: str = None,
|
|
267
|
-
conversationally: bool = False,
|
|
268
|
-
**kwargs
|
|
269
|
-
) -> Union[str, Generator[str, None, None]]:
|
|
270
|
-
"""Generates a response from the MCPCore API."""
|
|
271
|
-
|
|
272
|
-
def for_stream_chat() -> Generator[str, None, None]:
|
|
273
|
-
gen = self.ask(
|
|
274
|
-
prompt, stream=True, raw=False,
|
|
275
|
-
optimizer=optimizer, conversationally=conversationally, **kwargs
|
|
276
|
-
)
|
|
277
|
-
for response_dict in gen:
|
|
278
|
-
yield self.get_message(response_dict)
|
|
279
|
-
|
|
280
|
-
def for_non_stream_chat() -> str:
|
|
281
|
-
response_data = self.ask(
|
|
282
|
-
prompt, stream=False, raw=False,
|
|
283
|
-
optimizer=optimizer, conversationally=conversationally, **kwargs
|
|
284
|
-
)
|
|
285
|
-
return self.get_message(response_data)
|
|
286
|
-
|
|
287
|
-
return for_stream_chat() if stream else for_non_stream_chat()
|
|
288
|
-
|
|
289
|
-
def get_message(self, response: Dict[str, Any]) -> str:
|
|
290
|
-
"""Extracts the message from the API response."""
|
|
291
|
-
assert isinstance(response, dict), "Response should be of dict data-type only"
|
|
292
|
-
return response.get("text", "")
|
|
293
|
-
|
|
294
|
-
# Example usage (no cookies file needed)
|
|
295
|
-
if __name__ == "__main__":
|
|
296
|
-
from rich import print
|
|
297
|
-
|
|
298
|
-
print("-" * 80)
|
|
299
|
-
print(f"{'Model':<50} {'Status':<10} {'Response'}")
|
|
300
|
-
print("-" * 80)
|
|
301
|
-
|
|
302
|
-
for model in MCPCore.AVAILABLE_MODELS:
|
|
303
|
-
try:
|
|
304
|
-
test_ai = MCPCore(model=model, timeout=60)
|
|
305
|
-
response = test_ai.chat("Say 'Hello' in one word", stream=True)
|
|
306
|
-
response_text = ""
|
|
307
|
-
# Accumulate the response text without printing in the loop
|
|
308
|
-
for chunk in response:
|
|
309
|
-
response_text += chunk
|
|
310
|
-
|
|
311
|
-
if response_text and len(response_text.strip()) > 0:
|
|
312
|
-
status = "✓"
|
|
313
|
-
# Truncate response if too long
|
|
314
|
-
display_text = response_text.strip()[:50] + "..." if len(response_text.strip()) > 50 else response_text.strip()
|
|
315
|
-
else:
|
|
316
|
-
status = "✗"
|
|
317
|
-
display_text = "Empty or invalid response"
|
|
318
|
-
# Print the final status and response, overwriting the "Testing..." line
|
|
319
|
-
print(f"\r{model:<50} {status:<10} {display_text}")
|
|
320
|
-
except Exception as e:
|
|
321
|
-
# Print error, overwriting the "Testing..." line
|
|
322
|
-
print(f"\r{model:<50} {'✗':<10} {str(e)}")
|