webscout 8.2.2__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/AIauto.py +112 -22
- webscout/AIbase.py +144 -7
- webscout/AIutel.py +249 -131
- webscout/Bard.py +579 -206
- webscout/DWEBS.py +78 -35
- webscout/__init__.py +0 -1
- webscout/cli.py +256 -0
- webscout/conversation.py +307 -436
- webscout/exceptions.py +23 -0
- webscout/prompt_manager.py +56 -42
- webscout/version.py +1 -1
- webscout/webscout_search.py +65 -47
- webscout/webscout_search_async.py +81 -126
- webscout/yep_search.py +93 -43
- {webscout-8.2.2.dist-info → webscout-8.2.7.dist-info}/METADATA +172 -52
- webscout-8.2.7.dist-info/RECORD +26 -0
- {webscout-8.2.2.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
- inferno/__init__.py +0 -6
- inferno/__main__.py +0 -9
- inferno/cli.py +0 -6
- 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 -849
- webscout/Extra/autocoder/autocoder_utiles.py +0 -332
- webscout/Extra/gguf.py +0 -682
- 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/LLM.py +0 -442
- 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/Local/__init__.py +0 -12
- webscout/Local/__main__.py +0 -9
- webscout/Local/api.py +0 -576
- webscout/Local/cli.py +0 -516
- webscout/Local/config.py +0 -75
- webscout/Local/llm.py +0 -287
- webscout/Local/model_manager.py +0 -253
- webscout/Local/server.py +0 -721
- webscout/Local/utils.py +0 -93
- 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 -194
- webscout/Provider/AISEARCH/iask_search.py +0 -436
- webscout/Provider/AISEARCH/monica_search.py +0 -246
- webscout/Provider/AISEARCH/scira_search.py +0 -324
- webscout/Provider/AISEARCH/webpilotai_search.py +0 -281
- webscout/Provider/Aitopia.py +0 -292
- webscout/Provider/AllenAI.py +0 -413
- webscout/Provider/Andi.py +0 -228
- webscout/Provider/Blackboxai.py +0 -229
- webscout/Provider/C4ai.py +0 -432
- webscout/Provider/ChatGPTClone.py +0 -226
- webscout/Provider/ChatGPTES.py +0 -237
- webscout/Provider/ChatGPTGratis.py +0 -194
- webscout/Provider/Chatify.py +0 -175
- webscout/Provider/Cloudflare.py +0 -273
- webscout/Provider/Cohere.py +0 -208
- webscout/Provider/DeepSeek.py +0 -196
- webscout/Provider/Deepinfra.py +0 -297
- webscout/Provider/ElectronHub.py +0 -709
- webscout/Provider/ExaAI.py +0 -261
- webscout/Provider/ExaChat.py +0 -342
- webscout/Provider/Free2GPT.py +0 -241
- webscout/Provider/GPTWeb.py +0 -193
- webscout/Provider/Gemini.py +0 -169
- webscout/Provider/GithubChat.py +0 -367
- webscout/Provider/Glider.py +0 -211
- webscout/Provider/Groq.py +0 -670
- webscout/Provider/HF_space/__init__.py +0 -0
- webscout/Provider/HF_space/qwen_qwen2.py +0 -206
- webscout/Provider/HeckAI.py +0 -233
- webscout/Provider/HuggingFaceChat.py +0 -462
- webscout/Provider/Hunyuan.py +0 -272
- webscout/Provider/Jadve.py +0 -266
- webscout/Provider/Koboldai.py +0 -381
- webscout/Provider/LambdaChat.py +0 -392
- webscout/Provider/Llama.py +0 -200
- webscout/Provider/Llama3.py +0 -204
- webscout/Provider/Marcus.py +0 -148
- webscout/Provider/Netwrck.py +0 -228
- webscout/Provider/OLLAMA.py +0 -396
- webscout/Provider/OPENAI/__init__.py +0 -25
- 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 -460
- webscout/Provider/OPENAI/deepinfra.py +0 -272
- webscout/Provider/OPENAI/e2b.py +0 -1350
- webscout/Provider/OPENAI/exaai.py +0 -404
- webscout/Provider/OPENAI/exachat.py +0 -433
- webscout/Provider/OPENAI/freeaichat.py +0 -352
- webscout/Provider/OPENAI/glider.py +0 -316
- webscout/Provider/OPENAI/heckai.py +0 -337
- webscout/Provider/OPENAI/llmchatco.py +0 -327
- webscout/Provider/OPENAI/netwrck.py +0 -348
- webscout/Provider/OPENAI/opkfc.py +0 -488
- webscout/Provider/OPENAI/scirachat.py +0 -463
- webscout/Provider/OPENAI/sonus.py +0 -294
- webscout/Provider/OPENAI/standardinput.py +0 -425
- webscout/Provider/OPENAI/textpollinations.py +0 -285
- webscout/Provider/OPENAI/toolbaz.py +0 -405
- 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 -199
- webscout/Provider/Openai.py +0 -496
- webscout/Provider/PI.py +0 -344
- webscout/Provider/Perplexitylabs.py +0 -415
- webscout/Provider/Phind.py +0 -535
- webscout/Provider/PizzaGPT.py +0 -198
- webscout/Provider/QwenLM.py +0 -254
- webscout/Provider/Reka.py +0 -214
- webscout/Provider/StandardInput.py +0 -278
- 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 -7
- webscout/Provider/TTS/deepgram.py +0 -156
- webscout/Provider/TTS/elevenlabs.py +0 -111
- webscout/Provider/TTS/gesserit.py +0 -127
- 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 -187
- webscout/Provider/TextPollinationsAI.py +0 -231
- webscout/Provider/TwoAI.py +0 -199
- webscout/Provider/Venice.py +0 -219
- webscout/Provider/VercelAI.py +0 -234
- webscout/Provider/WebSim.py +0 -228
- webscout/Provider/WiseCat.py +0 -196
- webscout/Provider/Writecream.py +0 -211
- webscout/Provider/WritingMate.py +0 -197
- webscout/Provider/Youchat.py +0 -330
- webscout/Provider/__init__.py +0 -198
- webscout/Provider/ai4chat.py +0 -202
- webscout/Provider/aimathgpt.py +0 -189
- webscout/Provider/akashgpt.py +0 -342
- webscout/Provider/askmyai.py +0 -158
- webscout/Provider/asksteve.py +0 -203
- webscout/Provider/bagoodex.py +0 -145
- webscout/Provider/cerebras.py +0 -242
- webscout/Provider/chatglm.py +0 -205
- webscout/Provider/cleeai.py +0 -213
- webscout/Provider/copilot.py +0 -428
- webscout/Provider/elmo.py +0 -234
- webscout/Provider/freeaichat.py +0 -271
- webscout/Provider/gaurish.py +0 -244
- webscout/Provider/geminiapi.py +0 -208
- webscout/Provider/geminiprorealtime.py +0 -160
- webscout/Provider/granite.py +0 -187
- webscout/Provider/hermes.py +0 -219
- webscout/Provider/julius.py +0 -223
- webscout/Provider/koala.py +0 -268
- webscout/Provider/labyrinth.py +0 -340
- webscout/Provider/learnfastai.py +0 -266
- webscout/Provider/lepton.py +0 -194
- webscout/Provider/llama3mitril.py +0 -180
- webscout/Provider/llamatutor.py +0 -192
- webscout/Provider/llmchat.py +0 -213
- webscout/Provider/llmchatco.py +0 -311
- webscout/Provider/meta.py +0 -794
- webscout/Provider/multichat.py +0 -325
- webscout/Provider/promptrefine.py +0 -193
- webscout/Provider/scira_chat.py +0 -277
- webscout/Provider/scnet.py +0 -187
- webscout/Provider/searchchat.py +0 -293
- webscout/Provider/sonus.py +0 -208
- webscout/Provider/talkai.py +0 -194
- webscout/Provider/toolbaz.py +0 -320
- webscout/Provider/turboseek.py +0 -219
- webscout/Provider/tutorai.py +0 -252
- webscout/Provider/typefully.py +0 -280
- webscout/Provider/typegpt.py +0 -232
- webscout/Provider/uncovr.py +0 -312
- webscout/Provider/x0gpt.py +0 -256
- webscout/Provider/yep.py +0 -376
- 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 -809
- 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.2.dist-info/RECORD +0 -309
- webscout-8.2.2.dist-info/entry_points.txt +0 -5
- webscout-8.2.2.dist-info/top_level.txt +0 -3
- 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.2.dist-info → webscout-8.2.7.dist-info/licenses}/LICENSE.md +0 -0
webscout/Provider/Blackboxai.py
DELETED
|
@@ -1,229 +0,0 @@
|
|
|
1
|
-
import requests
|
|
2
|
-
import json
|
|
3
|
-
from typing import Any, Dict, Optional, Union, Generator, List
|
|
4
|
-
from webscout.AIutel import Optimizers, Conversation, AwesomePrompts
|
|
5
|
-
from webscout.AIbase import Provider
|
|
6
|
-
from webscout import exceptions
|
|
7
|
-
from webscout.Litlogger import Logger, LogFormat
|
|
8
|
-
|
|
9
|
-
class BLACKBOXAI(Provider):
|
|
10
|
-
"""
|
|
11
|
-
BlackboxAI provider for interacting with the Blackbox API.
|
|
12
|
-
Supports synchronous operations with multiple models.
|
|
13
|
-
"""
|
|
14
|
-
url = "https://api.blackbox.ai"
|
|
15
|
-
api_endpoint = "https://api.blackbox.ai/api/chat"
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
AVAILABLE_MODELS = {
|
|
20
|
-
"deepseek-v3": "deepseek-ai/DeepSeek-V3",
|
|
21
|
-
"deepseek-r1": "deepseek-ai/DeepSeek-R1",
|
|
22
|
-
"deepseek-chat": "deepseek-ai/deepseek-llm-67b-chat",
|
|
23
|
-
"mixtral-small-28b": "mistralai/Mistral-Small-24B-Instruct-2501",
|
|
24
|
-
"dbrx-instruct": "databricks/dbrx-instruct",
|
|
25
|
-
"qwq-32b": "Qwen/QwQ-32B-Preview",
|
|
26
|
-
"hermes-2-dpo": "NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO",
|
|
27
|
-
"claude-3.5-sonnet": "claude-sonnet-3.5",
|
|
28
|
-
"gemini-1.5-flash": "gemini-1.5-flash",
|
|
29
|
-
"gemini-1.5-pro": "gemini-pro",
|
|
30
|
-
"gemini-2.0-flash": "Gemini-Flash-2.0",
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
def __init__(
|
|
34
|
-
self,
|
|
35
|
-
is_conversation: bool = True,
|
|
36
|
-
max_tokens: int = 8000,
|
|
37
|
-
timeout: int = 30,
|
|
38
|
-
intro: str = None,
|
|
39
|
-
filepath: str = None,
|
|
40
|
-
update_file: bool = True,
|
|
41
|
-
proxies: dict = {},
|
|
42
|
-
history_offset: int = 10250,
|
|
43
|
-
act: str = None,
|
|
44
|
-
model: str = "deepseek-ai/DeepSeek-V3",
|
|
45
|
-
logging: bool = False,
|
|
46
|
-
system_message: str = "You are a helpful AI assistant."
|
|
47
|
-
):
|
|
48
|
-
"""Initialize BlackboxAI with enhanced configuration options."""
|
|
49
|
-
self.logger = Logger(
|
|
50
|
-
name="BlackboxAI",
|
|
51
|
-
format=LogFormat.MODERN_EMOJI,
|
|
52
|
-
|
|
53
|
-
) if logging else None
|
|
54
|
-
|
|
55
|
-
self.session = requests.Session()
|
|
56
|
-
self.max_tokens_to_sample = max_tokens
|
|
57
|
-
self.is_conversation = is_conversation
|
|
58
|
-
self.timeout = timeout
|
|
59
|
-
self.last_response = {}
|
|
60
|
-
self.model = self.get_model(model)
|
|
61
|
-
self.system_message = system_message
|
|
62
|
-
|
|
63
|
-
self.headers = {
|
|
64
|
-
"Content-Type": "application/json",
|
|
65
|
-
"Accept": "*/*",
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
if self.logger:
|
|
69
|
-
self.logger.info(f"Initializing BlackboxAI with model: {self.model}")
|
|
70
|
-
|
|
71
|
-
self.__available_optimizers = (
|
|
72
|
-
method for method in dir(Optimizers)
|
|
73
|
-
if callable(getattr(Optimizers, method)) and not method.startswith("__")
|
|
74
|
-
)
|
|
75
|
-
|
|
76
|
-
Conversation.intro = (
|
|
77
|
-
AwesomePrompts().get_act(
|
|
78
|
-
act, raise_not_found=True, default=None, case_insensitive=True
|
|
79
|
-
)
|
|
80
|
-
if act
|
|
81
|
-
else intro or Conversation.intro
|
|
82
|
-
)
|
|
83
|
-
|
|
84
|
-
self.conversation = Conversation(
|
|
85
|
-
is_conversation, self.max_tokens_to_sample, filepath, update_file
|
|
86
|
-
)
|
|
87
|
-
self.conversation.history_offset = history_offset
|
|
88
|
-
self.session.proxies = proxies
|
|
89
|
-
|
|
90
|
-
@classmethod
|
|
91
|
-
def get_model(self, model: str) -> str:
|
|
92
|
-
"""Resolve model name from alias"""
|
|
93
|
-
if model in self.AVAILABLE_MODELS:
|
|
94
|
-
return self.AVAILABLE_MODELS[model]
|
|
95
|
-
raise ValueError(f"Unknown model: {model}. Available models: {', '.join(self.AVAILABLE_MODELS)}")
|
|
96
|
-
|
|
97
|
-
def _make_request(
|
|
98
|
-
self,
|
|
99
|
-
messages: List[Dict[str, str]],
|
|
100
|
-
stream: bool = False
|
|
101
|
-
) -> Generator[str, None, None]:
|
|
102
|
-
"""Make synchronous request to BlackboxAI API."""
|
|
103
|
-
if self.logger:
|
|
104
|
-
self.logger.debug(f"Making request with {len(messages)} messages")
|
|
105
|
-
|
|
106
|
-
data = {
|
|
107
|
-
"messages": messages,
|
|
108
|
-
"model": self.model,
|
|
109
|
-
"max_tokens": self.max_tokens_to_sample
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
try:
|
|
113
|
-
response = self.session.post(
|
|
114
|
-
self.api_endpoint,
|
|
115
|
-
json=data,
|
|
116
|
-
headers=self.headers,
|
|
117
|
-
stream=stream,
|
|
118
|
-
timeout=self.timeout
|
|
119
|
-
)
|
|
120
|
-
|
|
121
|
-
if not response.ok:
|
|
122
|
-
error_msg = f"API request failed: {response.status_code} - {response.text}"
|
|
123
|
-
if self.logger:
|
|
124
|
-
self.logger.error(error_msg)
|
|
125
|
-
raise exceptions.FailedToGenerateResponseError(error_msg)
|
|
126
|
-
|
|
127
|
-
if stream:
|
|
128
|
-
for line in response.iter_lines(decode_unicode=True):
|
|
129
|
-
if line:
|
|
130
|
-
yield line
|
|
131
|
-
else:
|
|
132
|
-
yield response.text
|
|
133
|
-
|
|
134
|
-
except requests.exceptions.RequestException as e:
|
|
135
|
-
if self.logger:
|
|
136
|
-
self.logger.error(f"Request failed: {str(e)}")
|
|
137
|
-
raise exceptions.ProviderConnectionError(f"Connection error: {str(e)}")
|
|
138
|
-
|
|
139
|
-
def ask(
|
|
140
|
-
self,
|
|
141
|
-
prompt: str,
|
|
142
|
-
stream: bool = False,
|
|
143
|
-
raw: bool = False,
|
|
144
|
-
optimizer: str = None,
|
|
145
|
-
conversationally: bool = False,
|
|
146
|
-
) -> Union[Dict[str, str], Generator[Dict[str, str], None, None]]:
|
|
147
|
-
"""Send a prompt to BlackboxAI API and return the response."""
|
|
148
|
-
if self.logger:
|
|
149
|
-
self.logger.debug(f"Processing request [stream={stream}]")
|
|
150
|
-
|
|
151
|
-
conversation_prompt = self.conversation.gen_complete_prompt(prompt)
|
|
152
|
-
if optimizer:
|
|
153
|
-
if optimizer in self.__available_optimizers:
|
|
154
|
-
conversation_prompt = getattr(Optimizers, optimizer)(
|
|
155
|
-
conversation_prompt if conversationally else prompt
|
|
156
|
-
)
|
|
157
|
-
if self.logger:
|
|
158
|
-
self.logger.debug(f"Applied optimizer: {optimizer}")
|
|
159
|
-
else:
|
|
160
|
-
if self.logger:
|
|
161
|
-
self.logger.error(f"Invalid optimizer: {optimizer}")
|
|
162
|
-
raise ValueError(f"Optimizer is not one of {self.__available_optimizers}")
|
|
163
|
-
|
|
164
|
-
messages = [
|
|
165
|
-
{"role": "system", "content": self.system_message},
|
|
166
|
-
{"role": "user", "content": conversation_prompt}
|
|
167
|
-
]
|
|
168
|
-
|
|
169
|
-
def for_stream():
|
|
170
|
-
for text in self._make_request(messages, stream=True):
|
|
171
|
-
yield {"text": text}
|
|
172
|
-
|
|
173
|
-
def for_non_stream():
|
|
174
|
-
response_text = next(self._make_request(messages, stream=False))
|
|
175
|
-
self.last_response = {"text": response_text}
|
|
176
|
-
return self.last_response
|
|
177
|
-
|
|
178
|
-
return for_stream() if stream else for_non_stream()
|
|
179
|
-
|
|
180
|
-
def chat(
|
|
181
|
-
self,
|
|
182
|
-
prompt: str,
|
|
183
|
-
stream: bool = False,
|
|
184
|
-
optimizer: str = None,
|
|
185
|
-
conversationally: bool = False,
|
|
186
|
-
) -> Union[str, Generator[str, None, None]]:
|
|
187
|
-
"""Generate response as string."""
|
|
188
|
-
if self.logger:
|
|
189
|
-
self.logger.debug(f"Chat request initiated [stream={stream}]")
|
|
190
|
-
|
|
191
|
-
def for_stream():
|
|
192
|
-
for response in self.ask(
|
|
193
|
-
prompt,
|
|
194
|
-
stream=True,
|
|
195
|
-
optimizer=optimizer,
|
|
196
|
-
conversationally=conversationally
|
|
197
|
-
):
|
|
198
|
-
yield self.get_message(response)
|
|
199
|
-
|
|
200
|
-
def for_non_stream():
|
|
201
|
-
return self.get_message(
|
|
202
|
-
self.ask(
|
|
203
|
-
prompt,
|
|
204
|
-
stream=False,
|
|
205
|
-
optimizer=optimizer,
|
|
206
|
-
conversationally=conversationally,
|
|
207
|
-
)
|
|
208
|
-
)
|
|
209
|
-
|
|
210
|
-
return for_stream() if stream else for_non_stream()
|
|
211
|
-
|
|
212
|
-
def get_message(self, response: Dict[str, Any]) -> str:
|
|
213
|
-
"""Extract message from response dictionary."""
|
|
214
|
-
assert isinstance(response, dict), "Response should be of dict data-type only"
|
|
215
|
-
return response["text"].replace('\\n', '\n').replace('\\n\\n', '\n\n')
|
|
216
|
-
|
|
217
|
-
if __name__ == "__main__":
|
|
218
|
-
from rich import print
|
|
219
|
-
|
|
220
|
-
# Example usage
|
|
221
|
-
ai = BLACKBOXAI(model="deepseek-v3", logging=True)
|
|
222
|
-
|
|
223
|
-
try:
|
|
224
|
-
print("Non-streaming response:")
|
|
225
|
-
response = ai.chat("What is quantum computing?")
|
|
226
|
-
print(response)
|
|
227
|
-
|
|
228
|
-
except Exception as e:
|
|
229
|
-
print(f"Error: {str(e)}")
|
webscout/Provider/C4ai.py
DELETED
|
@@ -1,432 +0,0 @@
|
|
|
1
|
-
import requests
|
|
2
|
-
import uuid
|
|
3
|
-
import json
|
|
4
|
-
import time
|
|
5
|
-
import random
|
|
6
|
-
import re
|
|
7
|
-
from typing import Any, Dict, List, Optional, Union, Generator
|
|
8
|
-
|
|
9
|
-
from webscout.AIutel import Conversation
|
|
10
|
-
from webscout.AIbase import Provider
|
|
11
|
-
from webscout import exceptions
|
|
12
|
-
from webscout.litagent import LitAgent
|
|
13
|
-
|
|
14
|
-
class C4ai(Provider):
|
|
15
|
-
"""
|
|
16
|
-
A class to interact with the Hugging Face Chat API.
|
|
17
|
-
"""
|
|
18
|
-
# Default available models
|
|
19
|
-
AVAILABLE_MODELS = [
|
|
20
|
-
'command-a-03-2025',
|
|
21
|
-
'command-r-plus-08-2024',
|
|
22
|
-
'command-r-08-2024',
|
|
23
|
-
'command-r-plus',
|
|
24
|
-
'command-r',
|
|
25
|
-
'command-r7b-12-2024',
|
|
26
|
-
'command-r7b-arabic-02-2025'
|
|
27
|
-
] # Placeholder for available models, It will be updated in the constructor
|
|
28
|
-
|
|
29
|
-
def __repr__(self) -> str:
|
|
30
|
-
return f"C4ai({self.model})"
|
|
31
|
-
|
|
32
|
-
def __init__(
|
|
33
|
-
self,
|
|
34
|
-
is_conversation: bool = True,
|
|
35
|
-
max_tokens: int = 2000,
|
|
36
|
-
timeout: int = 60,
|
|
37
|
-
filepath: str = None,
|
|
38
|
-
update_file: bool = True,
|
|
39
|
-
proxies: dict = {},
|
|
40
|
-
model: str = "command-a-03-2025",
|
|
41
|
-
system_prompt: str = "You are a helpful assistant.",
|
|
42
|
-
):
|
|
43
|
-
"""Initialize the C4ai client."""
|
|
44
|
-
self.url = "https://cohereforai-c4ai-command.hf.space"
|
|
45
|
-
self.session = requests.Session()
|
|
46
|
-
self.session.proxies.update(proxies)
|
|
47
|
-
|
|
48
|
-
# Set up headers for all requests
|
|
49
|
-
self.headers = {
|
|
50
|
-
"Content-Type": "application/json",
|
|
51
|
-
"User-Agent": LitAgent().random(),
|
|
52
|
-
"Accept": "*/*",
|
|
53
|
-
"Accept-Encoding": "gzip, deflate, br, zstd",
|
|
54
|
-
"Accept-Language": "en-US,en;q=0.9",
|
|
55
|
-
"Origin": "https://cohereforai-c4ai-command.hf.space",
|
|
56
|
-
"Referer": "https://cohereforai-c4ai-command.hf.space/",
|
|
57
|
-
"Sec-Ch-Ua": "\"Chromium\";v=\"120\"",
|
|
58
|
-
"Sec-Ch-Ua-Mobile": "?0",
|
|
59
|
-
"Sec-Ch-Ua-Platform": "\"Windows\"",
|
|
60
|
-
"Sec-Fetch-Dest": "empty",
|
|
61
|
-
"Sec-Fetch-Mode": "cors",
|
|
62
|
-
"Sec-Fetch-Site": "same-origin",
|
|
63
|
-
"DNT": "1",
|
|
64
|
-
"Priority": "u=1, i"
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
# Update available models
|
|
68
|
-
self.update_available_models()
|
|
69
|
-
|
|
70
|
-
# Set default model if none provided
|
|
71
|
-
self.model = model
|
|
72
|
-
# Provider settings
|
|
73
|
-
self.is_conversation = is_conversation
|
|
74
|
-
self.max_tokens_to_sample = max_tokens
|
|
75
|
-
self.timeout = timeout
|
|
76
|
-
self.last_response = {}
|
|
77
|
-
|
|
78
|
-
# Initialize a simplified conversation history for file saving only
|
|
79
|
-
self.conversation = Conversation(is_conversation, max_tokens, filepath, update_file)
|
|
80
|
-
|
|
81
|
-
# Store conversation data for different models
|
|
82
|
-
self._conversation_data = {}
|
|
83
|
-
self.preprompt = system_prompt
|
|
84
|
-
|
|
85
|
-
def update_available_models(self):
|
|
86
|
-
"""Update the available models list from HuggingFace"""
|
|
87
|
-
try:
|
|
88
|
-
models = self.get_models()
|
|
89
|
-
if models and len(models) > 0:
|
|
90
|
-
self.AVAILABLE_MODELS = models
|
|
91
|
-
except Exception:
|
|
92
|
-
# Fallback to default models list if fetching fails
|
|
93
|
-
pass
|
|
94
|
-
|
|
95
|
-
@classmethod
|
|
96
|
-
def get_models(cls):
|
|
97
|
-
"""Fetch available models from HuggingFace."""
|
|
98
|
-
try:
|
|
99
|
-
response = requests.get("https://cohereforai-c4ai-command.hf.space/")
|
|
100
|
-
text = response.text
|
|
101
|
-
models_match = re.search(r'models:(\[.+?\]),oldModels:', text)
|
|
102
|
-
|
|
103
|
-
if not models_match:
|
|
104
|
-
return cls.AVAILABLE_MODELS
|
|
105
|
-
|
|
106
|
-
models_text = models_match.group(1)
|
|
107
|
-
models_text = re.sub(r',parameters:{[^}]+?}', '', models_text)
|
|
108
|
-
models_text = models_text.replace('void 0', 'null')
|
|
109
|
-
|
|
110
|
-
def add_quotation_mark(match):
|
|
111
|
-
return f'{match.group(1)}"{match.group(2)}":'
|
|
112
|
-
|
|
113
|
-
models_text = re.sub(r'([{,])([A-Za-z0-9_]+?):', add_quotation_mark, models_text)
|
|
114
|
-
|
|
115
|
-
models_data = json.loads(models_text)
|
|
116
|
-
# print([model["id"] for model in models_data])
|
|
117
|
-
return [model["id"] for model in models_data]
|
|
118
|
-
except Exception:
|
|
119
|
-
return cls.AVAILABLE_MODELS
|
|
120
|
-
|
|
121
|
-
def create_conversation(self, model: str):
|
|
122
|
-
"""Create a new conversation with the specified model."""
|
|
123
|
-
url = "https://cohereforai-c4ai-command.hf.space/conversation"
|
|
124
|
-
payload = {"model": model, "preprompt": self.preprompt,}
|
|
125
|
-
|
|
126
|
-
# Update referer for this specific request
|
|
127
|
-
headers = self.headers.copy()
|
|
128
|
-
headers["Referer"] = f"https://cohereforai-c4ai-command.hf.space/"
|
|
129
|
-
|
|
130
|
-
try:
|
|
131
|
-
response = self.session.post(url, json=payload, headers=headers)
|
|
132
|
-
|
|
133
|
-
if response.status_code == 401:
|
|
134
|
-
raise exceptions.AuthenticationError("Authentication failed.")
|
|
135
|
-
|
|
136
|
-
# Handle other error codes
|
|
137
|
-
if response.status_code != 200:
|
|
138
|
-
return None
|
|
139
|
-
|
|
140
|
-
data = response.json()
|
|
141
|
-
conversation_id = data.get("conversationId")
|
|
142
|
-
|
|
143
|
-
# Store conversation data
|
|
144
|
-
if model not in self._conversation_data:
|
|
145
|
-
self._conversation_data[model] = {
|
|
146
|
-
"conversationId": conversation_id,
|
|
147
|
-
"messageId": str(uuid.uuid4()) # Initial message ID
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
return conversation_id
|
|
151
|
-
except requests.exceptions.RequestException:
|
|
152
|
-
return None
|
|
153
|
-
|
|
154
|
-
def fetch_message_id(self, conversation_id: str) -> str:
|
|
155
|
-
"""Fetch the latest message ID for a conversation."""
|
|
156
|
-
try:
|
|
157
|
-
url = f"https://cohereforai-c4ai-command.hf.space/conversation/{conversation_id}/__data.json?x-sveltekit-invalidated=11"
|
|
158
|
-
response = self.session.get(url, headers=self.headers)
|
|
159
|
-
response.raise_for_status()
|
|
160
|
-
|
|
161
|
-
# Parse the JSON data from the response
|
|
162
|
-
json_data = None
|
|
163
|
-
for line in response.text.split('\n'):
|
|
164
|
-
if line.strip():
|
|
165
|
-
try:
|
|
166
|
-
parsed = json.loads(line)
|
|
167
|
-
if isinstance(parsed, dict) and "nodes" in parsed:
|
|
168
|
-
json_data = parsed
|
|
169
|
-
break
|
|
170
|
-
except json.JSONDecodeError:
|
|
171
|
-
continue
|
|
172
|
-
|
|
173
|
-
if not json_data:
|
|
174
|
-
# Fall back to a UUID if we can't parse the response
|
|
175
|
-
return str(uuid.uuid4())
|
|
176
|
-
|
|
177
|
-
# Extract message ID using the same pattern as in the example
|
|
178
|
-
if json_data.get("nodes", []) and json_data["nodes"][-1].get("type") == "error":
|
|
179
|
-
return str(uuid.uuid4())
|
|
180
|
-
|
|
181
|
-
data = json_data["nodes"][1]["data"]
|
|
182
|
-
keys = data[data[0]["messages"]]
|
|
183
|
-
message_keys = data[keys[-1]]
|
|
184
|
-
message_id = data[message_keys["id"]]
|
|
185
|
-
|
|
186
|
-
return message_id
|
|
187
|
-
|
|
188
|
-
except Exception:
|
|
189
|
-
# Fall back to a UUID if there's an error
|
|
190
|
-
return str(uuid.uuid4())
|
|
191
|
-
|
|
192
|
-
def generate_boundary(self):
|
|
193
|
-
"""Generate a random boundary for multipart/form-data requests"""
|
|
194
|
-
boundary_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
|
195
|
-
boundary = "----WebKitFormBoundary"
|
|
196
|
-
boundary += "".join(random.choice(boundary_chars) for _ in range(16))
|
|
197
|
-
return boundary
|
|
198
|
-
|
|
199
|
-
def process_response(self, response, prompt: str):
|
|
200
|
-
"""Process streaming response and extract content."""
|
|
201
|
-
full_text = ""
|
|
202
|
-
sources = None
|
|
203
|
-
reasoning_text = ""
|
|
204
|
-
has_reasoning = False
|
|
205
|
-
|
|
206
|
-
for line in response.iter_lines(decode_unicode=True):
|
|
207
|
-
if not line:
|
|
208
|
-
continue
|
|
209
|
-
|
|
210
|
-
try:
|
|
211
|
-
# Parse each line as JSON
|
|
212
|
-
data = json.loads(line)
|
|
213
|
-
|
|
214
|
-
# Handle different response types
|
|
215
|
-
if "type" not in data:
|
|
216
|
-
continue
|
|
217
|
-
|
|
218
|
-
if data["type"] == "stream" and "token" in data:
|
|
219
|
-
token = data["token"].replace("\u0000", "")
|
|
220
|
-
full_text += token
|
|
221
|
-
resp = {"text": token}
|
|
222
|
-
yield resp
|
|
223
|
-
elif data["type"] == "finalAnswer":
|
|
224
|
-
final_text = data.get("text", "")
|
|
225
|
-
if final_text and not full_text:
|
|
226
|
-
full_text = final_text
|
|
227
|
-
resp = {"text": final_text}
|
|
228
|
-
yield resp
|
|
229
|
-
elif data["type"] == "webSearch" and "sources" in data:
|
|
230
|
-
sources = data["sources"]
|
|
231
|
-
elif data["type"] == "reasoning":
|
|
232
|
-
has_reasoning = True
|
|
233
|
-
if data.get("subtype") == "stream" and "token" in data:
|
|
234
|
-
reasoning_text += data["token"]
|
|
235
|
-
# elif data.get("subtype") == "status":
|
|
236
|
-
# # For status updates in reasoning, we can just append them as a comment
|
|
237
|
-
# if data.get("status"):
|
|
238
|
-
# reasoning_text += f"\n# {data['status']}"
|
|
239
|
-
|
|
240
|
-
# If we have reasoning, prepend it to the next text output
|
|
241
|
-
if reasoning_text and not full_text:
|
|
242
|
-
resp = {"text": f"<think>\n{reasoning_text}\n</think>\n", "is_reasoning": True}
|
|
243
|
-
yield resp
|
|
244
|
-
|
|
245
|
-
except json.JSONDecodeError:
|
|
246
|
-
continue
|
|
247
|
-
|
|
248
|
-
# Update conversation history only for saving to file if needed
|
|
249
|
-
if full_text and self.conversation.file:
|
|
250
|
-
if has_reasoning:
|
|
251
|
-
full_text_with_reasoning = f"<think>\n{reasoning_text}\n</think>\n{full_text}"
|
|
252
|
-
self.last_response = {"text": full_text_with_reasoning}
|
|
253
|
-
self.conversation.update_chat_history(prompt, full_text_with_reasoning)
|
|
254
|
-
else:
|
|
255
|
-
self.last_response = {"text": full_text}
|
|
256
|
-
self.conversation.update_chat_history(prompt, full_text)
|
|
257
|
-
|
|
258
|
-
return full_text
|
|
259
|
-
|
|
260
|
-
def ask(
|
|
261
|
-
self,
|
|
262
|
-
prompt: str,
|
|
263
|
-
stream: bool = False,
|
|
264
|
-
raw: bool = False,
|
|
265
|
-
optimizer: str = None,
|
|
266
|
-
conversationally: bool = False,
|
|
267
|
-
web_search: bool = False,
|
|
268
|
-
) -> Union[Dict[str, Any], Generator]:
|
|
269
|
-
"""Send a message to the HuggingFace Chat API"""
|
|
270
|
-
model = self.model
|
|
271
|
-
|
|
272
|
-
# Check if we have a conversation for this model
|
|
273
|
-
if model not in self._conversation_data:
|
|
274
|
-
conversation_id = self.create_conversation(model)
|
|
275
|
-
if not conversation_id:
|
|
276
|
-
raise exceptions.FailedToGenerateResponseError(f"Failed to create conversation with model {model}")
|
|
277
|
-
else:
|
|
278
|
-
conversation_id = self._conversation_data[model]["conversationId"]
|
|
279
|
-
# Refresh message ID
|
|
280
|
-
self._conversation_data[model]["messageId"] = self.fetch_message_id(conversation_id)
|
|
281
|
-
|
|
282
|
-
url = f"https://cohereforai-c4ai-command.hf.space/conversation/{conversation_id}"
|
|
283
|
-
message_id = self._conversation_data[model]["messageId"]
|
|
284
|
-
|
|
285
|
-
# Data to send - use the prompt directly without generating a complete prompt
|
|
286
|
-
# since HuggingFace maintains conversation state internally
|
|
287
|
-
request_data = {
|
|
288
|
-
"inputs": prompt,
|
|
289
|
-
"id": message_id,
|
|
290
|
-
"is_retry": False,
|
|
291
|
-
"is_continue": False,
|
|
292
|
-
"web_search": web_search,
|
|
293
|
-
"tools": ["66e85bb396d054c5771bc6cb", "00000000000000000000000a"]
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
# Update headers for this specific request
|
|
297
|
-
headers = self.headers.copy()
|
|
298
|
-
headers["Referer"] = f"https://cohereforai-c4ai-command.hf.space/conversation/{conversation_id}"
|
|
299
|
-
|
|
300
|
-
# Create multipart form data
|
|
301
|
-
boundary = self.generate_boundary()
|
|
302
|
-
multipart_headers = headers.copy()
|
|
303
|
-
multipart_headers["Content-Type"] = f"multipart/form-data; boundary={boundary}"
|
|
304
|
-
|
|
305
|
-
# Serialize the data to JSON
|
|
306
|
-
data_json = json.dumps(request_data, separators=(',', ':'))
|
|
307
|
-
|
|
308
|
-
# Create the multipart form data body
|
|
309
|
-
body = f"--{boundary}\r\n"
|
|
310
|
-
body += f'Content-Disposition: form-data; name="data"\r\n'
|
|
311
|
-
body += f"Content-Type: application/json\r\n\r\n"
|
|
312
|
-
body += f"{data_json}\r\n"
|
|
313
|
-
body += f"--{boundary}--\r\n"
|
|
314
|
-
|
|
315
|
-
multipart_headers["Content-Length"] = str(len(body))
|
|
316
|
-
|
|
317
|
-
def for_stream():
|
|
318
|
-
try:
|
|
319
|
-
# Try with multipart/form-data first
|
|
320
|
-
response = None
|
|
321
|
-
try:
|
|
322
|
-
response = self.session.post(
|
|
323
|
-
url,
|
|
324
|
-
data=body,
|
|
325
|
-
headers=multipart_headers,
|
|
326
|
-
stream=True,
|
|
327
|
-
timeout=self.timeout
|
|
328
|
-
)
|
|
329
|
-
except requests.exceptions.RequestException:
|
|
330
|
-
pass
|
|
331
|
-
|
|
332
|
-
# If multipart fails or returns error, try with regular JSON
|
|
333
|
-
if not response or response.status_code != 200:
|
|
334
|
-
response = self.session.post(
|
|
335
|
-
url,
|
|
336
|
-
json=request_data,
|
|
337
|
-
headers=headers,
|
|
338
|
-
stream=True,
|
|
339
|
-
timeout=self.timeout
|
|
340
|
-
)
|
|
341
|
-
|
|
342
|
-
# If both methods fail, raise exception
|
|
343
|
-
if response.status_code != 200:
|
|
344
|
-
raise exceptions.FailedToGenerateResponseError(f"Request failed with status code {response.status_code}")
|
|
345
|
-
|
|
346
|
-
# Process the streaming response
|
|
347
|
-
yield from self.process_response(response, prompt)
|
|
348
|
-
|
|
349
|
-
except Exception as e:
|
|
350
|
-
if isinstance(e, requests.exceptions.RequestException):
|
|
351
|
-
if hasattr(e, 'response') and e.response is not None:
|
|
352
|
-
status_code = e.response.status_code
|
|
353
|
-
if status_code == 401:
|
|
354
|
-
raise exceptions.AuthenticationError("Authentication failed.")
|
|
355
|
-
|
|
356
|
-
# Try another model if current one fails
|
|
357
|
-
if len(self.AVAILABLE_MODELS) > 1:
|
|
358
|
-
current_model_index = self.AVAILABLE_MODELS.index(self.model) if self.model in self.AVAILABLE_MODELS else 0
|
|
359
|
-
next_model_index = (current_model_index + 1) % len(self.AVAILABLE_MODELS)
|
|
360
|
-
self.model = self.AVAILABLE_MODELS[next_model_index]
|
|
361
|
-
|
|
362
|
-
# Create new conversation with the alternate model
|
|
363
|
-
conversation_id = self.create_conversation(self.model)
|
|
364
|
-
if conversation_id:
|
|
365
|
-
# Try again with the new model
|
|
366
|
-
yield from self.ask(prompt, stream=True, raw=raw, optimizer=optimizer,
|
|
367
|
-
conversationally=conversationally, web_search=web_search)
|
|
368
|
-
return
|
|
369
|
-
|
|
370
|
-
# If we get here, all models failed
|
|
371
|
-
raise exceptions.FailedToGenerateResponseError(f"Request failed: {str(e)}")
|
|
372
|
-
|
|
373
|
-
def for_non_stream():
|
|
374
|
-
response_text = ""
|
|
375
|
-
for response in for_stream():
|
|
376
|
-
if "text" in response:
|
|
377
|
-
response_text += response["text"]
|
|
378
|
-
self.last_response = {"text": response_text}
|
|
379
|
-
return self.last_response
|
|
380
|
-
|
|
381
|
-
return for_stream() if stream else for_non_stream()
|
|
382
|
-
|
|
383
|
-
def chat(
|
|
384
|
-
self,
|
|
385
|
-
prompt: str,
|
|
386
|
-
stream: bool = False,
|
|
387
|
-
optimizer: str = None,
|
|
388
|
-
conversationally: bool = False,
|
|
389
|
-
web_search: bool = False
|
|
390
|
-
) -> Union[str, Generator]:
|
|
391
|
-
"""Generate a response to a prompt"""
|
|
392
|
-
def for_stream():
|
|
393
|
-
for response in self.ask(
|
|
394
|
-
prompt, True, optimizer=optimizer, conversationally=conversationally, web_search=web_search
|
|
395
|
-
):
|
|
396
|
-
yield self.get_message(response)
|
|
397
|
-
|
|
398
|
-
def for_non_stream():
|
|
399
|
-
return self.get_message(
|
|
400
|
-
self.ask(
|
|
401
|
-
prompt, False, optimizer=optimizer, conversationally=conversationally, web_search=web_search
|
|
402
|
-
)
|
|
403
|
-
)
|
|
404
|
-
|
|
405
|
-
return for_stream() if stream else for_non_stream()
|
|
406
|
-
|
|
407
|
-
def get_message(self, response: dict) -> str:
|
|
408
|
-
"""Extract message text from response"""
|
|
409
|
-
assert isinstance(response, dict), "Response should be of dict data-type only"
|
|
410
|
-
return response.get("text", "")
|
|
411
|
-
|
|
412
|
-
if __name__ == "__main__":
|
|
413
|
-
print("-" * 80)
|
|
414
|
-
print(f"{'Model':<50} {'Status':<10} {'Response'}")
|
|
415
|
-
print("-" * 80)
|
|
416
|
-
|
|
417
|
-
for model in C4ai.AVAILABLE_MODELS:
|
|
418
|
-
try:
|
|
419
|
-
test_ai = C4ai(model=model, timeout=60)
|
|
420
|
-
response = test_ai.chat("Say 'Hello' in one word")
|
|
421
|
-
response_text = response
|
|
422
|
-
|
|
423
|
-
if response_text and len(response_text.strip()) > 0:
|
|
424
|
-
status = "✓"
|
|
425
|
-
# Truncate response if too long
|
|
426
|
-
display_text = response_text.strip()[:50] + "..." if len(response_text.strip()) > 50 else response_text.strip()
|
|
427
|
-
else:
|
|
428
|
-
status = "✗"
|
|
429
|
-
display_text = "Empty or invalid response"
|
|
430
|
-
print(f"{model:<50} {status:<10} {display_text}")
|
|
431
|
-
except Exception as e:
|
|
432
|
-
print(f"{model:<50} {'✗':<10} {str(e)}")
|