webscout 8.2.6__py3-none-any.whl → 8.2.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 +97 -87
- webscout/version.py +1 -1
- {webscout-8.2.6.dist-info → webscout-8.2.7.dist-info}/METADATA +2 -15
- webscout-8.2.7.dist-info/RECORD +26 -0
- {webscout-8.2.6.dist-info → webscout-8.2.7.dist-info}/WHEEL +1 -1
- webscout-8.2.7.dist-info/entry_points.txt +3 -0
- webscout-8.2.7.dist-info/top_level.txt +1 -0
- webscout/Extra/GitToolkit/__init__.py +0 -10
- webscout/Extra/GitToolkit/gitapi/__init__.py +0 -12
- webscout/Extra/GitToolkit/gitapi/repository.py +0 -195
- webscout/Extra/GitToolkit/gitapi/user.py +0 -96
- webscout/Extra/GitToolkit/gitapi/utils.py +0 -62
- webscout/Extra/YTToolkit/YTdownloader.py +0 -957
- webscout/Extra/YTToolkit/__init__.py +0 -3
- webscout/Extra/YTToolkit/transcriber.py +0 -476
- webscout/Extra/YTToolkit/ytapi/__init__.py +0 -6
- webscout/Extra/YTToolkit/ytapi/channel.py +0 -307
- webscout/Extra/YTToolkit/ytapi/errors.py +0 -13
- webscout/Extra/YTToolkit/ytapi/extras.py +0 -45
- webscout/Extra/YTToolkit/ytapi/https.py +0 -88
- webscout/Extra/YTToolkit/ytapi/patterns.py +0 -61
- webscout/Extra/YTToolkit/ytapi/playlist.py +0 -59
- webscout/Extra/YTToolkit/ytapi/pool.py +0 -8
- webscout/Extra/YTToolkit/ytapi/query.py +0 -40
- webscout/Extra/YTToolkit/ytapi/stream.py +0 -63
- webscout/Extra/YTToolkit/ytapi/utils.py +0 -62
- webscout/Extra/YTToolkit/ytapi/video.py +0 -232
- webscout/Extra/__init__.py +0 -7
- webscout/Extra/autocoder/__init__.py +0 -9
- webscout/Extra/autocoder/autocoder.py +0 -910
- webscout/Extra/autocoder/autocoder_utiles.py +0 -332
- webscout/Extra/gguf.py +0 -684
- webscout/Extra/tempmail/__init__.py +0 -28
- webscout/Extra/tempmail/async_utils.py +0 -141
- webscout/Extra/tempmail/base.py +0 -161
- webscout/Extra/tempmail/cli.py +0 -187
- webscout/Extra/tempmail/emailnator.py +0 -84
- webscout/Extra/tempmail/mail_tm.py +0 -361
- webscout/Extra/tempmail/temp_mail_io.py +0 -292
- webscout/Extra/weather.py +0 -194
- webscout/Extra/weather_ascii.py +0 -76
- webscout/Litlogger/__init__.py +0 -67
- webscout/Litlogger/core/__init__.py +0 -6
- webscout/Litlogger/core/level.py +0 -23
- webscout/Litlogger/core/logger.py +0 -165
- webscout/Litlogger/handlers/__init__.py +0 -12
- webscout/Litlogger/handlers/console.py +0 -33
- webscout/Litlogger/handlers/file.py +0 -143
- webscout/Litlogger/handlers/network.py +0 -173
- webscout/Litlogger/styles/__init__.py +0 -7
- webscout/Litlogger/styles/colors.py +0 -249
- webscout/Litlogger/styles/formats.py +0 -458
- webscout/Litlogger/styles/text.py +0 -87
- webscout/Litlogger/utils/__init__.py +0 -6
- webscout/Litlogger/utils/detectors.py +0 -153
- webscout/Litlogger/utils/formatters.py +0 -200
- webscout/Provider/AI21.py +0 -177
- webscout/Provider/AISEARCH/DeepFind.py +0 -250
- webscout/Provider/AISEARCH/ISou.py +0 -256
- webscout/Provider/AISEARCH/Perplexity.py +0 -359
- webscout/Provider/AISEARCH/__init__.py +0 -10
- webscout/Provider/AISEARCH/felo_search.py +0 -228
- webscout/Provider/AISEARCH/genspark_search.py +0 -208
- webscout/Provider/AISEARCH/hika_search.py +0 -198
- webscout/Provider/AISEARCH/iask_search.py +0 -436
- webscout/Provider/AISEARCH/monica_search.py +0 -246
- webscout/Provider/AISEARCH/scira_search.py +0 -322
- webscout/Provider/AISEARCH/webpilotai_search.py +0 -281
- webscout/Provider/Aitopia.py +0 -316
- webscout/Provider/AllenAI.py +0 -447
- webscout/Provider/Andi.py +0 -228
- webscout/Provider/Blackboxai.py +0 -229
- webscout/Provider/ChatGPTClone.py +0 -237
- webscout/Provider/ChatGPTGratis.py +0 -194
- webscout/Provider/ChatSandbox.py +0 -342
- webscout/Provider/Cloudflare.py +0 -325
- webscout/Provider/Cohere.py +0 -208
- webscout/Provider/Deepinfra.py +0 -338
- webscout/Provider/ElectronHub.py +0 -773
- webscout/Provider/ExaAI.py +0 -261
- webscout/Provider/ExaChat.py +0 -358
- webscout/Provider/Free2GPT.py +0 -241
- webscout/Provider/GPTWeb.py +0 -249
- webscout/Provider/Gemini.py +0 -169
- webscout/Provider/GithubChat.py +0 -370
- webscout/Provider/GizAI.py +0 -285
- webscout/Provider/Glider.py +0 -222
- webscout/Provider/Groq.py +0 -801
- webscout/Provider/HF_space/__init__.py +0 -0
- webscout/Provider/HF_space/qwen_qwen2.py +0 -206
- webscout/Provider/HeckAI.py +0 -257
- webscout/Provider/HuggingFaceChat.py +0 -469
- webscout/Provider/Hunyuan.py +0 -283
- webscout/Provider/Jadve.py +0 -291
- webscout/Provider/Koboldai.py +0 -381
- webscout/Provider/LambdaChat.py +0 -411
- webscout/Provider/Llama3.py +0 -259
- webscout/Provider/MCPCore.py +0 -315
- webscout/Provider/Marcus.py +0 -206
- webscout/Provider/Nemotron.py +0 -218
- webscout/Provider/Netwrck.py +0 -270
- webscout/Provider/OLLAMA.py +0 -396
- webscout/Provider/OPENAI/__init__.py +0 -28
- webscout/Provider/OPENAI/ai4chat.py +0 -286
- webscout/Provider/OPENAI/base.py +0 -46
- webscout/Provider/OPENAI/c4ai.py +0 -367
- webscout/Provider/OPENAI/chatgpt.py +0 -549
- webscout/Provider/OPENAI/chatgptclone.py +0 -481
- webscout/Provider/OPENAI/deepinfra.py +0 -309
- webscout/Provider/OPENAI/e2b.py +0 -1350
- webscout/Provider/OPENAI/exaai.py +0 -404
- webscout/Provider/OPENAI/exachat.py +0 -437
- webscout/Provider/OPENAI/freeaichat.py +0 -352
- webscout/Provider/OPENAI/glider.py +0 -316
- webscout/Provider/OPENAI/groq.py +0 -354
- webscout/Provider/OPENAI/heckai.py +0 -341
- webscout/Provider/OPENAI/llmchatco.py +0 -327
- webscout/Provider/OPENAI/mcpcore.py +0 -376
- webscout/Provider/OPENAI/multichat.py +0 -368
- webscout/Provider/OPENAI/netwrck.py +0 -350
- webscout/Provider/OPENAI/opkfc.py +0 -488
- webscout/Provider/OPENAI/scirachat.py +0 -462
- webscout/Provider/OPENAI/sonus.py +0 -294
- webscout/Provider/OPENAI/standardinput.py +0 -425
- webscout/Provider/OPENAI/textpollinations.py +0 -329
- webscout/Provider/OPENAI/toolbaz.py +0 -406
- webscout/Provider/OPENAI/typegpt.py +0 -346
- webscout/Provider/OPENAI/uncovrAI.py +0 -455
- webscout/Provider/OPENAI/utils.py +0 -211
- webscout/Provider/OPENAI/venice.py +0 -413
- webscout/Provider/OPENAI/wisecat.py +0 -381
- webscout/Provider/OPENAI/writecream.py +0 -156
- webscout/Provider/OPENAI/x0gpt.py +0 -371
- webscout/Provider/OPENAI/yep.py +0 -327
- webscout/Provider/OpenGPT.py +0 -209
- webscout/Provider/Openai.py +0 -496
- webscout/Provider/PI.py +0 -429
- webscout/Provider/Perplexitylabs.py +0 -415
- webscout/Provider/QwenLM.py +0 -254
- webscout/Provider/Reka.py +0 -214
- webscout/Provider/StandardInput.py +0 -290
- webscout/Provider/TTI/AiForce/__init__.py +0 -22
- webscout/Provider/TTI/AiForce/async_aiforce.py +0 -224
- webscout/Provider/TTI/AiForce/sync_aiforce.py +0 -245
- webscout/Provider/TTI/FreeAIPlayground/__init__.py +0 -9
- webscout/Provider/TTI/FreeAIPlayground/async_freeaiplayground.py +0 -181
- webscout/Provider/TTI/FreeAIPlayground/sync_freeaiplayground.py +0 -180
- webscout/Provider/TTI/ImgSys/__init__.py +0 -23
- webscout/Provider/TTI/ImgSys/async_imgsys.py +0 -202
- webscout/Provider/TTI/ImgSys/sync_imgsys.py +0 -195
- webscout/Provider/TTI/MagicStudio/__init__.py +0 -2
- webscout/Provider/TTI/MagicStudio/async_magicstudio.py +0 -111
- webscout/Provider/TTI/MagicStudio/sync_magicstudio.py +0 -109
- webscout/Provider/TTI/Nexra/__init__.py +0 -22
- webscout/Provider/TTI/Nexra/async_nexra.py +0 -286
- webscout/Provider/TTI/Nexra/sync_nexra.py +0 -258
- webscout/Provider/TTI/PollinationsAI/__init__.py +0 -23
- webscout/Provider/TTI/PollinationsAI/async_pollinations.py +0 -311
- webscout/Provider/TTI/PollinationsAI/sync_pollinations.py +0 -265
- webscout/Provider/TTI/__init__.py +0 -12
- webscout/Provider/TTI/aiarta/__init__.py +0 -2
- webscout/Provider/TTI/aiarta/async_aiarta.py +0 -482
- webscout/Provider/TTI/aiarta/sync_aiarta.py +0 -440
- webscout/Provider/TTI/artbit/__init__.py +0 -22
- webscout/Provider/TTI/artbit/async_artbit.py +0 -155
- webscout/Provider/TTI/artbit/sync_artbit.py +0 -148
- webscout/Provider/TTI/fastflux/__init__.py +0 -22
- webscout/Provider/TTI/fastflux/async_fastflux.py +0 -261
- webscout/Provider/TTI/fastflux/sync_fastflux.py +0 -252
- webscout/Provider/TTI/huggingface/__init__.py +0 -22
- webscout/Provider/TTI/huggingface/async_huggingface.py +0 -199
- webscout/Provider/TTI/huggingface/sync_huggingface.py +0 -195
- webscout/Provider/TTI/piclumen/__init__.py +0 -23
- webscout/Provider/TTI/piclumen/async_piclumen.py +0 -268
- webscout/Provider/TTI/piclumen/sync_piclumen.py +0 -233
- webscout/Provider/TTI/pixelmuse/__init__.py +0 -4
- webscout/Provider/TTI/pixelmuse/async_pixelmuse.py +0 -249
- webscout/Provider/TTI/pixelmuse/sync_pixelmuse.py +0 -182
- webscout/Provider/TTI/talkai/__init__.py +0 -4
- webscout/Provider/TTI/talkai/async_talkai.py +0 -229
- webscout/Provider/TTI/talkai/sync_talkai.py +0 -207
- webscout/Provider/TTS/__init__.py +0 -8
- webscout/Provider/TTS/base.py +0 -159
- webscout/Provider/TTS/deepgram.py +0 -156
- webscout/Provider/TTS/elevenlabs.py +0 -111
- webscout/Provider/TTS/gesserit.py +0 -128
- webscout/Provider/TTS/murfai.py +0 -113
- webscout/Provider/TTS/parler.py +0 -111
- webscout/Provider/TTS/speechma.py +0 -180
- webscout/Provider/TTS/streamElements.py +0 -333
- webscout/Provider/TTS/utils.py +0 -280
- webscout/Provider/TeachAnything.py +0 -233
- webscout/Provider/TextPollinationsAI.py +0 -306
- webscout/Provider/TwoAI.py +0 -280
- webscout/Provider/TypliAI.py +0 -305
- webscout/Provider/Venice.py +0 -258
- webscout/Provider/VercelAI.py +0 -253
- webscout/Provider/WiseCat.py +0 -233
- webscout/Provider/WrDoChat.py +0 -370
- webscout/Provider/Writecream.py +0 -237
- webscout/Provider/WritingMate.py +0 -269
- webscout/Provider/Youchat.py +0 -330
- webscout/Provider/__init__.py +0 -178
- webscout/Provider/ai4chat.py +0 -203
- webscout/Provider/aimathgpt.py +0 -189
- webscout/Provider/akashgpt.py +0 -335
- webscout/Provider/asksteve.py +0 -212
- webscout/Provider/bagoodex.py +0 -145
- webscout/Provider/cerebras.py +0 -288
- webscout/Provider/chatglm.py +0 -215
- webscout/Provider/cleeai.py +0 -213
- webscout/Provider/copilot.py +0 -425
- webscout/Provider/elmo.py +0 -283
- webscout/Provider/freeaichat.py +0 -285
- webscout/Provider/geminiapi.py +0 -208
- webscout/Provider/geminiprorealtime.py +0 -160
- webscout/Provider/granite.py +0 -235
- webscout/Provider/hermes.py +0 -266
- webscout/Provider/julius.py +0 -223
- webscout/Provider/koala.py +0 -268
- webscout/Provider/learnfastai.py +0 -325
- webscout/Provider/llama3mitril.py +0 -215
- webscout/Provider/llmchat.py +0 -255
- webscout/Provider/llmchatco.py +0 -306
- webscout/Provider/meta.py +0 -798
- webscout/Provider/multichat.py +0 -364
- webscout/Provider/scira_chat.py +0 -297
- webscout/Provider/scnet.py +0 -243
- webscout/Provider/searchchat.py +0 -292
- webscout/Provider/sonus.py +0 -258
- webscout/Provider/talkai.py +0 -194
- webscout/Provider/toolbaz.py +0 -353
- webscout/Provider/turboseek.py +0 -266
- webscout/Provider/typefully.py +0 -330
- webscout/Provider/typegpt.py +0 -289
- webscout/Provider/uncovr.py +0 -368
- webscout/Provider/x0gpt.py +0 -299
- webscout/Provider/yep.py +0 -389
- webscout/litagent/__init__.py +0 -29
- webscout/litagent/agent.py +0 -455
- webscout/litagent/constants.py +0 -60
- webscout/litprinter/__init__.py +0 -59
- webscout/scout/__init__.py +0 -8
- webscout/scout/core/__init__.py +0 -7
- webscout/scout/core/crawler.py +0 -140
- webscout/scout/core/scout.py +0 -568
- webscout/scout/core/search_result.py +0 -96
- webscout/scout/core/text_analyzer.py +0 -63
- webscout/scout/core/text_utils.py +0 -277
- webscout/scout/core/web_analyzer.py +0 -52
- webscout/scout/core.py +0 -881
- webscout/scout/element.py +0 -460
- webscout/scout/parsers/__init__.py +0 -69
- webscout/scout/parsers/html5lib_parser.py +0 -172
- webscout/scout/parsers/html_parser.py +0 -236
- webscout/scout/parsers/lxml_parser.py +0 -178
- webscout/scout/utils.py +0 -37
- webscout/swiftcli/__init__.py +0 -95
- webscout/swiftcli/core/__init__.py +0 -7
- webscout/swiftcli/core/cli.py +0 -297
- webscout/swiftcli/core/context.py +0 -104
- webscout/swiftcli/core/group.py +0 -241
- webscout/swiftcli/decorators/__init__.py +0 -28
- webscout/swiftcli/decorators/command.py +0 -221
- webscout/swiftcli/decorators/options.py +0 -220
- webscout/swiftcli/decorators/output.py +0 -252
- webscout/swiftcli/exceptions.py +0 -21
- webscout/swiftcli/plugins/__init__.py +0 -9
- webscout/swiftcli/plugins/base.py +0 -135
- webscout/swiftcli/plugins/manager.py +0 -262
- webscout/swiftcli/utils/__init__.py +0 -59
- webscout/swiftcli/utils/formatting.py +0 -252
- webscout/swiftcli/utils/parsing.py +0 -267
- webscout/zeroart/__init__.py +0 -55
- webscout/zeroart/base.py +0 -60
- webscout/zeroart/effects.py +0 -99
- webscout/zeroart/fonts.py +0 -816
- webscout-8.2.6.dist-info/RECORD +0 -307
- webscout-8.2.6.dist-info/entry_points.txt +0 -3
- webscout-8.2.6.dist-info/top_level.txt +0 -2
- webstoken/__init__.py +0 -30
- webstoken/classifier.py +0 -189
- webstoken/keywords.py +0 -216
- webstoken/language.py +0 -128
- webstoken/ner.py +0 -164
- webstoken/normalizer.py +0 -35
- webstoken/processor.py +0 -77
- webstoken/sentiment.py +0 -206
- webstoken/stemmer.py +0 -73
- webstoken/tagger.py +0 -60
- webstoken/tokenizer.py +0 -158
- {webscout-8.2.6.dist-info → webscout-8.2.7.dist-info}/licenses/LICENSE.md +0 -0
|
@@ -1,286 +0,0 @@
|
|
|
1
|
-
import time
|
|
2
|
-
import uuid
|
|
3
|
-
import urllib.parse
|
|
4
|
-
from curl_cffi.requests import Session, RequestsError
|
|
5
|
-
from typing import List, Dict, Optional, Union, Generator, Any
|
|
6
|
-
|
|
7
|
-
# Import base classes and utility structures
|
|
8
|
-
from .base import OpenAICompatibleProvider, BaseChat, BaseCompletions
|
|
9
|
-
from .utils import (
|
|
10
|
-
ChatCompletionChunk, ChatCompletion, Choice, ChoiceDelta,
|
|
11
|
-
ChatCompletionMessage, CompletionUsage
|
|
12
|
-
)
|
|
13
|
-
|
|
14
|
-
# --- AI4Chat Client ---
|
|
15
|
-
|
|
16
|
-
class Completions(BaseCompletions):
|
|
17
|
-
def __init__(self, client: 'AI4Chat'):
|
|
18
|
-
self._client = client
|
|
19
|
-
|
|
20
|
-
def create(
|
|
21
|
-
self,
|
|
22
|
-
*,
|
|
23
|
-
model: str,
|
|
24
|
-
messages: List[Dict[str, str]],
|
|
25
|
-
max_tokens: Optional[int] = None,
|
|
26
|
-
stream: bool = False,
|
|
27
|
-
temperature: Optional[float] = None,
|
|
28
|
-
top_p: Optional[float] = None,
|
|
29
|
-
**kwargs: Any
|
|
30
|
-
) -> Union[ChatCompletion, Generator[ChatCompletionChunk, None, None]]:
|
|
31
|
-
"""
|
|
32
|
-
Creates a model response for the given chat conversation.
|
|
33
|
-
Mimics openai.chat.completions.create
|
|
34
|
-
"""
|
|
35
|
-
# Use the format_prompt utility to format the conversation
|
|
36
|
-
from .utils import format_prompt
|
|
37
|
-
|
|
38
|
-
# Format the messages into a single string
|
|
39
|
-
conversation_prompt = format_prompt(messages, add_special_tokens=True, include_system=True)
|
|
40
|
-
|
|
41
|
-
# Set up request parameters
|
|
42
|
-
country_param = kwargs.get("country", self._client.country)
|
|
43
|
-
user_id_param = kwargs.get("user_id", self._client.user_id)
|
|
44
|
-
|
|
45
|
-
# Generate request ID and timestamp
|
|
46
|
-
request_id = f"chatcmpl-{uuid.uuid4()}"
|
|
47
|
-
created_time = int(time.time())
|
|
48
|
-
|
|
49
|
-
# AI4Chat doesn't support streaming, so we'll simulate it if requested
|
|
50
|
-
if stream:
|
|
51
|
-
return self._create_stream(request_id, created_time, model, conversation_prompt, country_param, user_id_param)
|
|
52
|
-
else:
|
|
53
|
-
return self._create_non_stream(request_id, created_time, model, conversation_prompt, country_param, user_id_param)
|
|
54
|
-
|
|
55
|
-
def _create_stream(
|
|
56
|
-
self, request_id: str, created_time: int, model: str,
|
|
57
|
-
conversation_prompt: str, country: str, user_id: str
|
|
58
|
-
) -> Generator[ChatCompletionChunk, None, None]:
|
|
59
|
-
"""Simulate streaming by breaking up the full response."""
|
|
60
|
-
try:
|
|
61
|
-
# Get the full response first
|
|
62
|
-
full_response = self._get_ai4chat_response(conversation_prompt, country, user_id)
|
|
63
|
-
|
|
64
|
-
# Break it into chunks for simulated streaming
|
|
65
|
-
words = full_response.split()
|
|
66
|
-
chunk_size = max(1, len(words) // 10) # Divide into ~10 chunks
|
|
67
|
-
|
|
68
|
-
# Track token usage
|
|
69
|
-
prompt_tokens = len(conversation_prompt.split())
|
|
70
|
-
completion_tokens = 0
|
|
71
|
-
|
|
72
|
-
# Stream chunks
|
|
73
|
-
for i in range(0, len(words), chunk_size):
|
|
74
|
-
chunk_text = " ".join(words[i:i+chunk_size])
|
|
75
|
-
completion_tokens += len(chunk_text.split())
|
|
76
|
-
|
|
77
|
-
# Create the delta object
|
|
78
|
-
delta = ChoiceDelta(
|
|
79
|
-
content=chunk_text,
|
|
80
|
-
role="assistant",
|
|
81
|
-
tool_calls=None
|
|
82
|
-
)
|
|
83
|
-
|
|
84
|
-
# Create the choice object
|
|
85
|
-
choice = Choice(
|
|
86
|
-
index=0,
|
|
87
|
-
delta=delta,
|
|
88
|
-
finish_reason=None,
|
|
89
|
-
logprobs=None
|
|
90
|
-
)
|
|
91
|
-
|
|
92
|
-
# Create the chunk object
|
|
93
|
-
chunk = ChatCompletionChunk(
|
|
94
|
-
id=request_id,
|
|
95
|
-
choices=[choice],
|
|
96
|
-
created=created_time,
|
|
97
|
-
model=model,
|
|
98
|
-
system_fingerprint=None
|
|
99
|
-
)
|
|
100
|
-
|
|
101
|
-
yield chunk
|
|
102
|
-
|
|
103
|
-
# Final chunk with finish_reason="stop"
|
|
104
|
-
delta = ChoiceDelta(
|
|
105
|
-
content=None,
|
|
106
|
-
role=None,
|
|
107
|
-
tool_calls=None
|
|
108
|
-
)
|
|
109
|
-
|
|
110
|
-
choice = Choice(
|
|
111
|
-
index=0,
|
|
112
|
-
delta=delta,
|
|
113
|
-
finish_reason="stop",
|
|
114
|
-
logprobs=None
|
|
115
|
-
)
|
|
116
|
-
|
|
117
|
-
chunk = ChatCompletionChunk(
|
|
118
|
-
id=request_id,
|
|
119
|
-
choices=[choice],
|
|
120
|
-
created=created_time,
|
|
121
|
-
model=model,
|
|
122
|
-
system_fingerprint=None
|
|
123
|
-
)
|
|
124
|
-
|
|
125
|
-
yield chunk
|
|
126
|
-
|
|
127
|
-
except RequestsError as e:
|
|
128
|
-
print(f"Error during AI4Chat stream request: {e}")
|
|
129
|
-
raise IOError(f"AI4Chat request failed: {e}") from e
|
|
130
|
-
except Exception as e:
|
|
131
|
-
print(f"Unexpected error during AI4Chat stream request: {e}")
|
|
132
|
-
raise IOError(f"AI4Chat request failed: {e}") from e
|
|
133
|
-
|
|
134
|
-
def _create_non_stream(
|
|
135
|
-
self, request_id: str, created_time: int, model: str,
|
|
136
|
-
conversation_prompt: str, country: str, user_id: str
|
|
137
|
-
) -> ChatCompletion:
|
|
138
|
-
"""Get a complete response from AI4Chat."""
|
|
139
|
-
try:
|
|
140
|
-
# Get the full response
|
|
141
|
-
full_response = self._get_ai4chat_response(conversation_prompt, country, user_id)
|
|
142
|
-
|
|
143
|
-
# Estimate token counts
|
|
144
|
-
prompt_tokens = len(conversation_prompt.split())
|
|
145
|
-
completion_tokens = len(full_response.split())
|
|
146
|
-
total_tokens = prompt_tokens + completion_tokens
|
|
147
|
-
|
|
148
|
-
# Create the message object
|
|
149
|
-
message = ChatCompletionMessage(
|
|
150
|
-
role="assistant",
|
|
151
|
-
content=full_response
|
|
152
|
-
)
|
|
153
|
-
|
|
154
|
-
# Create the choice object
|
|
155
|
-
choice = Choice(
|
|
156
|
-
index=0,
|
|
157
|
-
message=message,
|
|
158
|
-
finish_reason="stop"
|
|
159
|
-
)
|
|
160
|
-
|
|
161
|
-
# Create the usage object
|
|
162
|
-
usage = CompletionUsage(
|
|
163
|
-
prompt_tokens=prompt_tokens,
|
|
164
|
-
completion_tokens=completion_tokens,
|
|
165
|
-
total_tokens=total_tokens
|
|
166
|
-
)
|
|
167
|
-
|
|
168
|
-
# Create the completion object
|
|
169
|
-
completion = ChatCompletion(
|
|
170
|
-
id=request_id,
|
|
171
|
-
choices=[choice],
|
|
172
|
-
created=created_time,
|
|
173
|
-
model=model,
|
|
174
|
-
usage=usage,
|
|
175
|
-
)
|
|
176
|
-
|
|
177
|
-
return completion
|
|
178
|
-
|
|
179
|
-
except RequestsError as e:
|
|
180
|
-
print(f"Error during AI4Chat non-stream request: {e}")
|
|
181
|
-
raise IOError(f"AI4Chat request failed: {e}") from e
|
|
182
|
-
except Exception as e:
|
|
183
|
-
print(f"Unexpected error during AI4Chat non-stream request: {e}")
|
|
184
|
-
raise IOError(f"AI4Chat request failed: {e}") from e
|
|
185
|
-
|
|
186
|
-
def _get_ai4chat_response(self, prompt: str, country: str, user_id: str) -> str:
|
|
187
|
-
"""Make the actual API request to AI4Chat."""
|
|
188
|
-
# URL encode parameters
|
|
189
|
-
encoded_text = urllib.parse.quote(prompt)
|
|
190
|
-
encoded_country = urllib.parse.quote(country)
|
|
191
|
-
encoded_user_id = urllib.parse.quote(user_id)
|
|
192
|
-
|
|
193
|
-
# Construct the API URL
|
|
194
|
-
url = f"{self._client.api_endpoint}?text={encoded_text}&country={encoded_country}&user_id={encoded_user_id}"
|
|
195
|
-
|
|
196
|
-
# Make the request
|
|
197
|
-
try:
|
|
198
|
-
response = self._client.session.get(url, headers=self._client.headers, timeout=self._client.timeout)
|
|
199
|
-
response.raise_for_status()
|
|
200
|
-
except RequestsError as e:
|
|
201
|
-
raise IOError(f"Failed to generate response: {e}")
|
|
202
|
-
|
|
203
|
-
# Process the response text
|
|
204
|
-
response_text = response.text
|
|
205
|
-
|
|
206
|
-
# Remove surrounding quotes if present
|
|
207
|
-
if response_text.startswith('"'):
|
|
208
|
-
response_text = response_text[1:]
|
|
209
|
-
if response_text.endswith('"'):
|
|
210
|
-
response_text = response_text[:-1]
|
|
211
|
-
|
|
212
|
-
# Replace escaped newlines
|
|
213
|
-
response_text = response_text.replace('\\n', '\n').replace('\\n\\n', '\n\n')
|
|
214
|
-
|
|
215
|
-
return response_text
|
|
216
|
-
|
|
217
|
-
class Chat(BaseChat):
|
|
218
|
-
def __init__(self, client: 'AI4Chat'):
|
|
219
|
-
self.completions = Completions(client)
|
|
220
|
-
|
|
221
|
-
class AI4Chat(OpenAICompatibleProvider):
|
|
222
|
-
"""
|
|
223
|
-
OpenAI-compatible client for AI4Chat API.
|
|
224
|
-
|
|
225
|
-
Usage:
|
|
226
|
-
client = AI4Chat()
|
|
227
|
-
response = client.chat.completions.create(
|
|
228
|
-
model="default",
|
|
229
|
-
messages=[{"role": "user", "content": "Hello!"}]
|
|
230
|
-
)
|
|
231
|
-
print(response.choices[0].message.content)
|
|
232
|
-
"""
|
|
233
|
-
|
|
234
|
-
AVAILABLE_MODELS = ["default"]
|
|
235
|
-
|
|
236
|
-
def __init__(
|
|
237
|
-
self,
|
|
238
|
-
timeout: int = 30,
|
|
239
|
-
proxies: dict = {},
|
|
240
|
-
system_prompt: str = "You are a helpful and informative AI assistant.",
|
|
241
|
-
country: str = "Asia",
|
|
242
|
-
user_id: str = "usersmjb2oaz7y"
|
|
243
|
-
):
|
|
244
|
-
"""
|
|
245
|
-
Initialize the AI4Chat client.
|
|
246
|
-
|
|
247
|
-
Args:
|
|
248
|
-
timeout: Request timeout in seconds
|
|
249
|
-
proxies: Optional proxy configuration
|
|
250
|
-
system_prompt: System prompt to guide the AI's behavior
|
|
251
|
-
country: Country parameter for API
|
|
252
|
-
user_id: User ID for API
|
|
253
|
-
"""
|
|
254
|
-
self.timeout = timeout
|
|
255
|
-
self.proxies = proxies
|
|
256
|
-
self.system_prompt = system_prompt
|
|
257
|
-
self.country = country
|
|
258
|
-
self.user_id = user_id
|
|
259
|
-
|
|
260
|
-
# API endpoint
|
|
261
|
-
self.api_endpoint = "https://yw85opafq6.execute-api.us-east-1.amazonaws.com/default/boss_mode_15aug"
|
|
262
|
-
|
|
263
|
-
# Initialize session
|
|
264
|
-
self.session = Session(timeout=timeout, proxies=proxies)
|
|
265
|
-
|
|
266
|
-
# Set headers
|
|
267
|
-
self.headers = {
|
|
268
|
-
"Accept": "*/*",
|
|
269
|
-
"Accept-Language": "id-ID,id;q=0.9",
|
|
270
|
-
"Origin": "https://www.ai4chat.co",
|
|
271
|
-
"Priority": "u=1, i",
|
|
272
|
-
"Referer": "https://www.ai4chat.co/",
|
|
273
|
-
"Sec-CH-UA": '"Chromium";v="131", "Not_A Brand";v="24", "Microsoft Edge Simulate";v="131", "Lemur";v="131"',
|
|
274
|
-
"Sec-CH-UA-Mobile": "?1",
|
|
275
|
-
"Sec-CH-UA-Platform": '"Android"',
|
|
276
|
-
"Sec-Fetch-Dest": "empty",
|
|
277
|
-
"Sec-Fetch-Mode": "cors",
|
|
278
|
-
"Sec-Fetch-Site": "cross-site",
|
|
279
|
-
"User-Agent": "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36"
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
# Update session headers
|
|
283
|
-
self.session.headers.update(self.headers)
|
|
284
|
-
|
|
285
|
-
# Initialize chat interface
|
|
286
|
-
self.chat = Chat(self)
|
webscout/Provider/OPENAI/base.py
DELETED
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
from abc import ABC, abstractmethod
|
|
2
|
-
from typing import List, Dict, Optional, Union, Generator, Any
|
|
3
|
-
|
|
4
|
-
# Re-define or import necessary response structure classes (like ChatCompletion, ChatCompletionChunk)
|
|
5
|
-
# For simplicity, we'll assume they are defined elsewhere or passed directly.
|
|
6
|
-
# You might want to define base versions of these classes here as well.
|
|
7
|
-
|
|
8
|
-
class BaseChatCompletionChunk: # Placeholder
|
|
9
|
-
pass
|
|
10
|
-
class BaseChatCompletion: # Placeholder
|
|
11
|
-
pass
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
class BaseCompletions(ABC):
|
|
15
|
-
@abstractmethod
|
|
16
|
-
def create(
|
|
17
|
-
self,
|
|
18
|
-
*,
|
|
19
|
-
model: str,
|
|
20
|
-
messages: List[Dict[str, str]],
|
|
21
|
-
max_tokens: Optional[int] = None,
|
|
22
|
-
stream: bool = False,
|
|
23
|
-
temperature: Optional[float] = None,
|
|
24
|
-
top_p: Optional[float] = None,
|
|
25
|
-
**kwargs: Any
|
|
26
|
-
) -> Union[BaseChatCompletion, Generator[BaseChatCompletionChunk, None, None]]:
|
|
27
|
-
"""Abstract method to create chat completions."""
|
|
28
|
-
raise NotImplementedError
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
class BaseChat(ABC):
|
|
32
|
-
completions: BaseCompletions
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
class OpenAICompatibleProvider(ABC):
|
|
36
|
-
"""
|
|
37
|
-
Abstract Base Class for providers mimicking the OpenAI Python client structure.
|
|
38
|
-
Requires a nested 'chat.completions' structure.
|
|
39
|
-
"""
|
|
40
|
-
chat: BaseChat
|
|
41
|
-
|
|
42
|
-
@abstractmethod
|
|
43
|
-
def __init__(self, api_key: Optional[str] = None, **kwargs: Any):
|
|
44
|
-
"""Initialize the provider, potentially with an API key."""
|
|
45
|
-
raise NotImplementedError
|
|
46
|
-
|
webscout/Provider/OPENAI/c4ai.py
DELETED
|
@@ -1,367 +0,0 @@
|
|
|
1
|
-
import time
|
|
2
|
-
import uuid
|
|
3
|
-
import requests
|
|
4
|
-
import json
|
|
5
|
-
import re
|
|
6
|
-
from typing import List, Dict, Optional, Union, Generator, Any
|
|
7
|
-
|
|
8
|
-
# Import base classes and utility structures
|
|
9
|
-
from .base import OpenAICompatibleProvider, BaseChat, BaseCompletions
|
|
10
|
-
from .utils import (
|
|
11
|
-
ChatCompletionChunk, ChatCompletion, Choice, ChoiceDelta,
|
|
12
|
-
ChatCompletionMessage, CompletionUsage,
|
|
13
|
-
get_system_prompt, get_last_user_message, format_prompt # Import format_prompt
|
|
14
|
-
)
|
|
15
|
-
|
|
16
|
-
# Attempt to import LitAgent, fallback if not available
|
|
17
|
-
try:
|
|
18
|
-
from webscout.litagent import LitAgent
|
|
19
|
-
except ImportError:
|
|
20
|
-
# Define a dummy LitAgent if webscout is not installed or accessible
|
|
21
|
-
class LitAgent:
|
|
22
|
-
def generate_fingerprint(self, browser: str = "chrome") -> Dict[str, Any]:
|
|
23
|
-
# Return minimal default headers if LitAgent is unavailable
|
|
24
|
-
print("Warning: LitAgent not found. Using default minimal headers.")
|
|
25
|
-
return {
|
|
26
|
-
"accept": "*/*",
|
|
27
|
-
"accept_language": "en-US,en;q=0.9",
|
|
28
|
-
"platform": "Windows",
|
|
29
|
-
"sec_ch_ua": '"Not/A)Brand";v="99", "Google Chrome";v="127", "Chromium";v="127"',
|
|
30
|
-
"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",
|
|
31
|
-
"browser_type": browser,
|
|
32
|
-
}
|
|
33
|
-
def random(self) -> str:
|
|
34
|
-
# Return a default user agent if LitAgent is unavailable
|
|
35
|
-
print("Warning: LitAgent not found. Using default user agent.")
|
|
36
|
-
return "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36"
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
class Completions(BaseCompletions):
|
|
40
|
-
def __init__(self, client: 'C4AI'):
|
|
41
|
-
self._client = client
|
|
42
|
-
|
|
43
|
-
def create(
|
|
44
|
-
self,
|
|
45
|
-
*,
|
|
46
|
-
model: str,
|
|
47
|
-
messages: List[Dict[str, str]],
|
|
48
|
-
max_tokens: Optional[int] = 2000,
|
|
49
|
-
stream: bool = False,
|
|
50
|
-
temperature: Optional[float] = None,
|
|
51
|
-
top_p: Optional[float] = None,
|
|
52
|
-
**kwargs: Any
|
|
53
|
-
) -> Union[ChatCompletion, Generator[ChatCompletionChunk, None, None]]:
|
|
54
|
-
"""
|
|
55
|
-
Creates a model response for the given chat conversation.
|
|
56
|
-
Mimics openai.chat.completions.create
|
|
57
|
-
"""
|
|
58
|
-
# Extract system prompt using utility function
|
|
59
|
-
system_prompt = get_system_prompt(messages)
|
|
60
|
-
if not system_prompt:
|
|
61
|
-
system_prompt = "You are a helpful assistant."
|
|
62
|
-
|
|
63
|
-
# Format the conversation history using format_prompt
|
|
64
|
-
# Note: C4AI API might expect only the *last* user message here.
|
|
65
|
-
# Sending the full history might cause issues.
|
|
66
|
-
# We exclude the system prompt from format_prompt as it's sent separately.
|
|
67
|
-
# We also set do_continue=True as C4AI adds its own assistant prompt implicitly.
|
|
68
|
-
conversation_prompt = format_prompt(messages, include_system=False, do_continue=True)
|
|
69
|
-
|
|
70
|
-
if not conversation_prompt:
|
|
71
|
-
# Fallback to last user message if formatted prompt is empty
|
|
72
|
-
last_user_message = get_last_user_message(messages)
|
|
73
|
-
if not last_user_message:
|
|
74
|
-
raise ValueError("No user message found or formatted prompt is empty.")
|
|
75
|
-
conversation_prompt = last_user_message
|
|
76
|
-
|
|
77
|
-
# Create or get conversation ID
|
|
78
|
-
if model not in self._client._conversation_data:
|
|
79
|
-
conversation_id = self._client.create_conversation(model, system_prompt)
|
|
80
|
-
if not conversation_id:
|
|
81
|
-
raise IOError(f"Failed to create conversation with model {model}")
|
|
82
|
-
else:
|
|
83
|
-
conversation_id = self._client._conversation_data[model]["conversationId"]
|
|
84
|
-
self._client._conversation_data[model]["messageId"] = self._client.fetch_message_id(conversation_id)
|
|
85
|
-
|
|
86
|
-
request_id = f"chatcmpl-{uuid.uuid4()}"
|
|
87
|
-
created_time = int(time.time())
|
|
88
|
-
|
|
89
|
-
# Pass the formatted conversation prompt
|
|
90
|
-
if stream:
|
|
91
|
-
return self._create_stream(request_id, created_time, model, conversation_id, conversation_prompt, system_prompt)
|
|
92
|
-
else:
|
|
93
|
-
return self._create_non_stream(request_id, created_time, model, conversation_id, conversation_prompt, system_prompt)
|
|
94
|
-
|
|
95
|
-
def _create_stream(
|
|
96
|
-
self, request_id: str, created_time: int, model: str, conversation_id: str, prompt: str, system_prompt: str
|
|
97
|
-
) -> Generator[ChatCompletionChunk, None, None]:
|
|
98
|
-
try:
|
|
99
|
-
message_id = self._client._conversation_data[model]["messageId"]
|
|
100
|
-
url = f"{self._client.url}/api/chat/message"
|
|
101
|
-
payload = {
|
|
102
|
-
"conversationId": conversation_id,
|
|
103
|
-
"messageId": message_id,
|
|
104
|
-
"model": model,
|
|
105
|
-
"prompt": prompt, # Use the formatted conversation history as prompt
|
|
106
|
-
"preprompt": system_prompt,
|
|
107
|
-
"temperature": 0.7,
|
|
108
|
-
"top_p": 1,
|
|
109
|
-
"top_k": 50,
|
|
110
|
-
"max_tokens": self._client.max_tokens_to_sample,
|
|
111
|
-
"stop": [],
|
|
112
|
-
"stream": True
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
response = self._client.session.post(
|
|
116
|
-
url,
|
|
117
|
-
headers=self._client.headers,
|
|
118
|
-
json=payload,
|
|
119
|
-
stream=True,
|
|
120
|
-
timeout=self._client.timeout
|
|
121
|
-
)
|
|
122
|
-
response.raise_for_status()
|
|
123
|
-
|
|
124
|
-
full_text = ""
|
|
125
|
-
for line in response.iter_lines():
|
|
126
|
-
if line:
|
|
127
|
-
line = line.decode('utf-8')
|
|
128
|
-
if line.startswith('data: '):
|
|
129
|
-
data = line[6:]
|
|
130
|
-
if data == "[DONE]":
|
|
131
|
-
break
|
|
132
|
-
|
|
133
|
-
try:
|
|
134
|
-
json_data = json.loads(data)
|
|
135
|
-
delta_text = json_data.get('text', '')
|
|
136
|
-
new_content = delta_text[len(full_text):]
|
|
137
|
-
full_text = delta_text
|
|
138
|
-
delta = ChoiceDelta(content=new_content)
|
|
139
|
-
choice = Choice(index=0, delta=delta, finish_reason=None)
|
|
140
|
-
chunk = ChatCompletionChunk(
|
|
141
|
-
id=request_id,
|
|
142
|
-
choices=[choice],
|
|
143
|
-
created=created_time,
|
|
144
|
-
model=model
|
|
145
|
-
)
|
|
146
|
-
yield chunk
|
|
147
|
-
except json.JSONDecodeError:
|
|
148
|
-
continue
|
|
149
|
-
|
|
150
|
-
delta = ChoiceDelta(content=None)
|
|
151
|
-
choice = Choice(index=0, delta=delta, finish_reason="stop")
|
|
152
|
-
chunk = ChatCompletionChunk(
|
|
153
|
-
id=request_id,
|
|
154
|
-
choices=[choice],
|
|
155
|
-
created=created_time,
|
|
156
|
-
model=model
|
|
157
|
-
)
|
|
158
|
-
yield chunk
|
|
159
|
-
|
|
160
|
-
except Exception as e:
|
|
161
|
-
print(f"Error during C4AI stream request: {e}")
|
|
162
|
-
raise IOError(f"C4AI request failed: {e}") from e
|
|
163
|
-
|
|
164
|
-
def _create_non_stream(
|
|
165
|
-
self, request_id: str, created_time: int, model: str, conversation_id: str, prompt: str, system_prompt: str
|
|
166
|
-
) -> ChatCompletion:
|
|
167
|
-
try:
|
|
168
|
-
message_id = self._client._conversation_data[model]["messageId"]
|
|
169
|
-
url = f"{self._client.url}/api/chat/message"
|
|
170
|
-
payload = {
|
|
171
|
-
"conversationId": conversation_id,
|
|
172
|
-
"messageId": message_id,
|
|
173
|
-
"model": model,
|
|
174
|
-
"prompt": prompt, # Use the formatted conversation history as prompt
|
|
175
|
-
"preprompt": system_prompt,
|
|
176
|
-
"temperature": 0.7,
|
|
177
|
-
"top_p": 1,
|
|
178
|
-
"top_k": 50,
|
|
179
|
-
"max_tokens": self._client.max_tokens_to_sample,
|
|
180
|
-
"stop": [],
|
|
181
|
-
"stream": False
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
response = self._client.session.post(
|
|
185
|
-
url,
|
|
186
|
-
headers=self._client.headers,
|
|
187
|
-
json=payload,
|
|
188
|
-
timeout=self._client.timeout
|
|
189
|
-
)
|
|
190
|
-
response.raise_for_status()
|
|
191
|
-
|
|
192
|
-
data = response.json()
|
|
193
|
-
response_text = data.get('text', '')
|
|
194
|
-
message = ChatCompletionMessage(role="assistant", content=response_text)
|
|
195
|
-
choice = Choice(index=0, message=message, finish_reason="stop")
|
|
196
|
-
# Estimate tokens based on the formatted prompt
|
|
197
|
-
prompt_tokens = len(prompt) // 4
|
|
198
|
-
completion_tokens = len(response_text) // 4
|
|
199
|
-
usage = CompletionUsage(
|
|
200
|
-
prompt_tokens=prompt_tokens,
|
|
201
|
-
completion_tokens=completion_tokens,
|
|
202
|
-
total_tokens=prompt_tokens + completion_tokens
|
|
203
|
-
)
|
|
204
|
-
completion = ChatCompletion(
|
|
205
|
-
id=request_id,
|
|
206
|
-
choices=[choice],
|
|
207
|
-
created=created_time,
|
|
208
|
-
model=model,
|
|
209
|
-
usage=usage
|
|
210
|
-
)
|
|
211
|
-
return completion
|
|
212
|
-
|
|
213
|
-
except Exception as e:
|
|
214
|
-
print(f"Error during C4AI non-stream request: {e}")
|
|
215
|
-
raise IOError(f"C4AI request failed: {e}") from e
|
|
216
|
-
|
|
217
|
-
class Chat(BaseChat):
|
|
218
|
-
def __init__(self, client: 'C4AI'):
|
|
219
|
-
self.completions = Completions(client)
|
|
220
|
-
|
|
221
|
-
class C4AI(OpenAICompatibleProvider):
|
|
222
|
-
"""
|
|
223
|
-
OpenAI-compatible client for C4AI API.
|
|
224
|
-
|
|
225
|
-
Usage:
|
|
226
|
-
client = C4AI()
|
|
227
|
-
response = client.chat.completions.create(
|
|
228
|
-
model="command-a-03-2025",
|
|
229
|
-
messages=[{"role": "user", "content": "Hello!"}]
|
|
230
|
-
)
|
|
231
|
-
"""
|
|
232
|
-
|
|
233
|
-
AVAILABLE_MODELS = [
|
|
234
|
-
'command-a-03-2025',
|
|
235
|
-
'command-r-plus-08-2024',
|
|
236
|
-
'command-r-08-2024',
|
|
237
|
-
'command-r-plus',
|
|
238
|
-
'command-r',
|
|
239
|
-
'command-r7b-12-2024',
|
|
240
|
-
'command-r7b-arabic-02-2025'
|
|
241
|
-
]
|
|
242
|
-
|
|
243
|
-
def __init__(
|
|
244
|
-
self,
|
|
245
|
-
timeout: Optional[int] = None,
|
|
246
|
-
browser: str = "chrome"
|
|
247
|
-
):
|
|
248
|
-
"""
|
|
249
|
-
Initialize the C4AI client.
|
|
250
|
-
|
|
251
|
-
Args:
|
|
252
|
-
timeout: Request timeout in seconds.
|
|
253
|
-
browser: Browser name for LitAgent to generate User-Agent.
|
|
254
|
-
"""
|
|
255
|
-
self.timeout = timeout
|
|
256
|
-
self.url = "https://cohereforai-c4ai-command.hf.space"
|
|
257
|
-
self.session = requests.Session()
|
|
258
|
-
self.max_tokens_to_sample = 2000
|
|
259
|
-
|
|
260
|
-
agent = LitAgent()
|
|
261
|
-
fingerprint = agent.generate_fingerprint(browser)
|
|
262
|
-
|
|
263
|
-
self.headers = {
|
|
264
|
-
"Content-Type": "application/json",
|
|
265
|
-
"User-Agent": fingerprint["user_agent"],
|
|
266
|
-
"Accept": "*/*",
|
|
267
|
-
"Accept-Encoding": "gzip, deflate, br, zstd",
|
|
268
|
-
"Accept-Language": fingerprint["accept_language"],
|
|
269
|
-
"Origin": "https://cohereforai-c4ai-command.hf.space",
|
|
270
|
-
"Referer": "https://cohereforai-c4ai-command.hf.space/",
|
|
271
|
-
"Sec-Ch-Ua": fingerprint["sec_ch_ua"] or "\"Chromium\";v=\"120\"",
|
|
272
|
-
"Sec-Ch-Ua-Mobile": "?0",
|
|
273
|
-
"Sec-Ch-Ua-Platform": f"\"{fingerprint['platform']}\"",
|
|
274
|
-
"Sec-Fetch-Dest": "empty",
|
|
275
|
-
"Sec-Fetch-Mode": "cors",
|
|
276
|
-
"Sec-Fetch-Site": "same-origin",
|
|
277
|
-
"DNT": "1",
|
|
278
|
-
"Priority": "u=1, i"
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
self._conversation_data = {}
|
|
282
|
-
self.chat = Chat(self)
|
|
283
|
-
self.update_available_models()
|
|
284
|
-
|
|
285
|
-
def update_available_models(self):
|
|
286
|
-
"""Update the list of available models from the server."""
|
|
287
|
-
try:
|
|
288
|
-
response = requests.get("https://cohereforai-c4ai-command.hf.space/")
|
|
289
|
-
text = response.text
|
|
290
|
-
models_match = re.search(r'models:(\[.+?\]),oldModels:', text)
|
|
291
|
-
|
|
292
|
-
if not models_match:
|
|
293
|
-
return
|
|
294
|
-
|
|
295
|
-
models_text = models_match.group(1)
|
|
296
|
-
models_text = re.sub(r',parameters:{[^}]+?}', '', models_text)
|
|
297
|
-
models_text = models_text.replace('void 0', 'null')
|
|
298
|
-
|
|
299
|
-
def add_quotation_mark(match):
|
|
300
|
-
return f'{match.group(1)}"{match.group(2)}":'
|
|
301
|
-
|
|
302
|
-
models_text = re.sub(r'([{,])([A-Za-z0-9_]+?):', add_quotation_mark, models_text)
|
|
303
|
-
|
|
304
|
-
models_data = json.loads(models_text)
|
|
305
|
-
self.AVAILABLE_MODELS = [model["id"] for model in models_data]
|
|
306
|
-
except Exception:
|
|
307
|
-
pass
|
|
308
|
-
|
|
309
|
-
def create_conversation(self, model: str, system_prompt: str):
|
|
310
|
-
"""Create a new conversation with the specified model."""
|
|
311
|
-
url = f"{self.url}/api/conversation"
|
|
312
|
-
payload = {
|
|
313
|
-
"model": model,
|
|
314
|
-
"preprompt": system_prompt,
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
try:
|
|
318
|
-
response = self.session.post(
|
|
319
|
-
url,
|
|
320
|
-
headers=self.headers,
|
|
321
|
-
json=payload,
|
|
322
|
-
timeout=self.timeout
|
|
323
|
-
)
|
|
324
|
-
response.raise_for_status()
|
|
325
|
-
|
|
326
|
-
data = response.json()
|
|
327
|
-
conversation_id = data.get("conversationId")
|
|
328
|
-
|
|
329
|
-
if conversation_id:
|
|
330
|
-
self._conversation_data[model] = {
|
|
331
|
-
"conversationId": conversation_id,
|
|
332
|
-
"messageId": self.fetch_message_id(conversation_id)
|
|
333
|
-
}
|
|
334
|
-
return conversation_id
|
|
335
|
-
|
|
336
|
-
return None
|
|
337
|
-
|
|
338
|
-
except Exception as e:
|
|
339
|
-
print(f"Error creating conversation: {e}")
|
|
340
|
-
return None
|
|
341
|
-
|
|
342
|
-
def fetch_message_id(self, conversation_id: str):
|
|
343
|
-
"""Fetch the latest message ID for a conversation."""
|
|
344
|
-
url = f"{self.url}/api/conversation/{conversation_id}"
|
|
345
|
-
|
|
346
|
-
try:
|
|
347
|
-
response = self.session.get(
|
|
348
|
-
url,
|
|
349
|
-
headers=self.headers,
|
|
350
|
-
timeout=self.timeout
|
|
351
|
-
)
|
|
352
|
-
response.raise_for_status()
|
|
353
|
-
|
|
354
|
-
json_data = response.json()
|
|
355
|
-
|
|
356
|
-
if json_data.get("nodes", []) and json_data["nodes"][-1].get("type") == "error":
|
|
357
|
-
return str(uuid.uuid4())
|
|
358
|
-
|
|
359
|
-
data = json_data["nodes"][1]["data"]
|
|
360
|
-
keys = data[data[0]["messages"]]
|
|
361
|
-
message_keys = data[keys[-1]]
|
|
362
|
-
message_id = data[message_keys["id"]]
|
|
363
|
-
|
|
364
|
-
return message_id
|
|
365
|
-
|
|
366
|
-
except Exception:
|
|
367
|
-
return str(uuid.uuid4())
|