Files
html/api/wevia-multi-provider.php
2026-04-20 12:55:01 +02:00

818 lines
47 KiB
PHP

<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
if ($_SERVER["REQUEST_METHOD"]==="OPTIONS"){header("Access-Control-Allow-Headers: Content-Type");exit;}
$raw = json_decode(file_get_contents("php://input"), true);
if (!$raw) { echo json_encode(["error"=>"no input"]); exit; }
$msg = $raw["message"] ?? "";
$mdl = $raw["model"] ?? "auto";
if (!$msg) { echo json_encode(["error"=>"no message"]); exit; }
// OPUS 20avr doctrine #2 ZERO simulation: intercept self-reference queries BEFORE LLM
if (file_exists(__DIR__ . "/wevia-self-diagnostic-intent.php")) {
require_once __DIR__ . "/wevia-self-diagnostic-intent.php";
if (function_exists("wevia_self_diagnostic")) {
$_sd = wevia_self_diagnostic($msg);
if ($_sd) {
$_c = isset($_sd["content"]) ? $_sd["content"] : json_encode($_sd, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
echo json_encode([
"content" => $_c,
"provider" => "opus46",
"tool" => "self_diagnostic",
"model" => "php-intent-real-exec",
"note" => "Doctrine #2: real shell, not LLM simulation"
], JSON_UNESCAPED_UNICODE);
exit;
}
}
}
$env = @file_get_contents("/etc/weval/secrets.env");
if (!$env) $env = "";
// Budget tracking — log every request
function logBudget($provider, $model, $tokens, $type="free") {
$cost = 0;
if ($type === "paid") {
$cost = $tokens * 0.000003; // ~$3/1M tokens average
}
@file_get_contents("http://127.0.0.1/api/wevia-arena-budget.php", false, stream_context_create(["http" => [
"method" => "POST",
"header" => "Content-Type: application/json",
"content" => json_encode(["action"=>"log","provider"=>$provider,"model"=>$model,"tokens"=>$tokens,"cost_eur"=>$cost,"type"=>$type]),
"timeout" => 2
]]));
}
function gk($e, $n) {
if (preg_match("/$n=(.+)/", $e, $m)) return trim($m[1]);
return "";
}
$nim = gk($env, "NVIDIA_NIM_KEY");
$ork = gk($env, "OPENROUTER_KEY");
$cfe = gk($env, "CF_EMAIL");
$cfk = "9eb8d1041e7faeae68d5017376871ba170291";
$cfa = "d3d50d5b6fb372afed8d7a8e4b16dd10";
$grq = gk($env, "GROQ_KEY");
$crb = gk($env, "CEREBRAS_API_KEY");
$mis = gk($env, "MISTRAL_KEY");
function cc($u, $h, $b, $to = 20) {
$c = curl_init($u);
curl_setopt_array($c, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($b),
CURLOPT_HTTPHEADER => $h,
CURLOPT_TIMEOUT => $to,
CURLOPT_SSL_VERIFYPEER => false
]);
$r = curl_exec($c);
$code = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
return [$code, $r];
}
// Web chats
$wc = [
"web-copilot" => "https://copilot.microsoft.com",
"web-huggingchat" => "https://huggingface.co/chat",
"web-meta" => "https://www.meta.ai",
"web-duckduckgo" => "https://duck.ai",
"web-qwen" => "https://chat.qwen.ai",
"web-lechat" => "https://chat.mistral.ai",
"web-perplexity" => "https://perplexity.ai"
];
if (isset($wc[$mdl])) {
// Call WEVIA WebChat service on port 8902 (Playwright headless)
$svc = str_replace("web-", "", $mdl);
$ch = curl_init("http://127.0.0.1/api/wevia-webchat-direct.php");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode(["service" => $svc, "message" => $msg]),
CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
CURLOPT_TIMEOUT => 12]);
$r = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code === 200) {
$d = json_decode($r, true);
if (!empty($d["content"])) {
echo json_encode($d);
exit;
}
}
// Fallback: return URL
// Playwright failed — fallback to best API provider
$fb_providers = ["nim-deepseek", "alibaba-qwen", "mistral", "or-gpt-oss"];
foreach ($fb_providers as $fb) {
$ch2 = curl_init("https://weval-consulting.com/api/wevia-multi-provider.php");
curl_setopt_array($ch2, [CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode(["message" => $msg, "model" => $fb]),
CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
CURLOPT_TIMEOUT => 2, CURLOPT_SSL_VERIFYPEER => false]);
$fr = curl_exec($ch2); $fc = curl_getinfo($ch2, CURLINFO_HTTP_CODE);
if ($fc === 200) {
$fd = json_decode($fr, true);
$fct = $fd["content"] ?? "";
if (strlen($fct) > 20) {
logBudget($d["provider"]??$mdl,$d["model"]??$mdl,strlen($ct??"")); echo json_encode(["content" => $fct, "provider" => "Arena Fallback (" . ($fd["provider"] ?? $fb) . ")", "model" => $fb . " (fallback for " . $svc . ")", "cost" => "0EUR"]);
exit;
}
}
}
// SOVEREIGN FALLBACK
$sch = curl_init("http://127.0.0.1:4000/v1/chat/completions");
curl_setopt_array($sch, [CURLOPT_POST=>true, CURLOPT_RETURNTRANSFER=>true, CURLOPT_POSTFIELDS=>json_encode(["messages"=>[["role"=>"user","content"=>$msg]], "max_tokens"=>500]), CURLOPT_HTTPHEADER=>["Content-Type: application/json"], CURLOPT_TIMEOUT=>8]);
$sr = curl_exec($sch); $sd = @json_decode($sr, true); $st = $sd["choices"][0]["message"]["content"] ?? "";
if (strlen($st) > 10) { echo json_encode(["content"=>$st, "provider"=>"Web+".$svc." (sovereign)", "model"=>$sd["model"]??"auto", "cost"=>"0EUR"]); exit; }
echo json_encode(["content" => "Ouvrez: " . $wc[$mdl], "provider" => "WebChat " . $svc, "web_url" => $wc[$mdl], "cost" => "0EUR"]);
exit;
}
$t0 = microtime(true);
// === ARENA CONTEXT — Stable knowledge across all models ===
$arena_ctx = @file_get_contents("/var/www/html/api/arena-context.md") ?: "";
if ($arena_ctx) { $msg = "[CONTEXTE WEVAL:]
" . substr($arena_ctx, 0, 800) . "
[QUESTION:]
" . $msg; }
// === KB CONTEXT INJECTION — All models get WEVAL knowledge ===
$kb_context = "";
// Query Qdrant for relevant context
$qd_query = json_encode(["query" => substr($msg, 0, 200), "limit" => 3]);
$qd = @file_get_contents("http://localhost:6333/collections/weval-kb/points/search", false, stream_context_create(["http" => ["method" => "POST", "header" => "Content-Type: application/json", "content" => $qd_query, "timeout" => 3]]));
if ($qd) {
$qd_data = json_decode($qd, true);
foreach ($qd_data["result"] ?? [] as $point) {
$kb_context .= ($point["payload"]["content"] ?? "") . "\n";
}
}
// Inject KB context into message if found
if (strlen($kb_context) > 50) {
$msg = "[Contexte WEVAL KB:]\n" . substr($kb_context, 0, 500) . "\n\n[Question:]\n" . $msg;
}
// OPUS 20avr doctrine #4: anti-hallucination system prompt prepended to all provider messages
$__guard_sys = "Tu es WEVIA, IA souveraine de WEVAL Consulting. REGLES STRICTES: Tu ne peux PAS executer de commandes shell ni lire de fichiers. Si user demande diagnostic/exec/status/vault/fichier/log: reponds 'Cette requete necessite un intent shell reel. Tape diagnostique toi ou demande a Opus de wirer un intent dedie.' N INVENTE JAMAIS outputs de commandes, PIDs, paths, MD5, timestamps, docker containers, journaux systeme. Si tu ne connais pas une info factuelle dis-le.";
$ms = [["role" => "system", "content" => $__guard_sys], ["role" => "user", "content" => $msg]];
// CF models
if ($mdl === "cf-deepseek-r1" || $mdl === "cf-llama") {
$cfm = ($mdl === "cf-deepseek-r1") ? "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b" : "@cf/meta/llama-3.1-8b-instruct";
list($code, $r) = cc("https://api.cloudflare.com/client/v4/accounts/$cfa/ai/run/$cfm",
["Content-Type: application/json", "X-Auth-Email: $cfe", "X-Auth-Key: $cfk"],
["messages" => $ms, "max_tokens" => 2000], 30);
if ($code === 200) {
$d = json_decode($r, true);
$ct = $d["result"]["response"] ?? "";
if ($ct) {
$th = ""; $an = $ct;
if (preg_match("/<think>(.*?)<\/think>/s", $ct, $tm)) {
$th = trim($tm[1]);
$an = trim(preg_replace("/<think>.*?<\/think>/s", "", $ct));
}
echo json_encode(["content" => $an, "thinking" => $th, "provider" => "Cloudflare", "model" => $cfm, "latency_ms" => round((microtime(true) - $t0) * 1000), "cost" => "0EUR", "has_thinking" => strlen($th) > 0]);
exit;
}
}
}
// NIM models
if (($mdl === "nim-llama" || $mdl === "nim-deepseek") && $nim) {
$nm = ($mdl === "nim-llama") ? "meta/llama-3.1-8b-instruct" : "deepseek-ai/deepseek-r1-distill-llama-8b";
list($code, $r) = cc("https://integrate.api.nvidia.com/v1/chat/completions",
["Content-Type: application/json", "Authorization: Bearer $nim"],
["model" => $nm, "messages" => $ms, "max_tokens" => 2000]);
if ($code === 200) {
$d = json_decode($r, true);
$ct = $d["choices"][0]["message"]["content"] ?? "";
if ($ct) { echo json_encode(["content" => $ct, "provider" => "NVIDIA NIM", "model" => $nm, "latency_ms" => round((microtime(true) - $t0) * 1000), "cost" => "0EUR"]); exit; }
}
}
// OpenRouter models
if (($mdl === "or-gpt-oss" || $mdl === "or-nemotron" || $mdl === "or-gemma4") && $ork) {
$om = ["or-gpt-oss" => "google/gemma-4-26b-a4b-it:free", "or-nemotron" => "nvidia/nemotron-3-super-120b-a12b:free", "or-gemma4" => "google/gemma-4-26b-a4b-it:free"];
list($code, $r) = cc("https://openrouter.ai/api/v1/chat/completions",
["Content-Type: application/json", "Authorization: Bearer $ork"],
["model" => $om[$mdl], "messages" => $ms, "max_tokens" => 2000]);
if ($code === 200) {
$d = json_decode($r, true);
$ct = $d["choices"][0]["message"]["content"] ?? "";
if ($ct) { echo json_encode(["content" => $ct, "provider" => "OpenRouter", "model" => $om[$mdl], "latency_ms" => round((microtime(true) - $t0) * 1000), "cost" => "0EUR"]); exit; }
}
}
// Groq
if ($mdl === "groq-llama" && $grq) {
list($code, $r) = cc("https://api.groq.com/openai/v1/chat/completions",
["Content-Type: application/json", "Authorization: Bearer $grq"],
["model" => "llama-3.3-70b-versatile", "messages" => $ms, "max_tokens" => 2000]);
if ($code === 200) {
$d = json_decode($r, true);
$ct = $d["choices"][0]["message"]["content"] ?? "";
if ($ct) { echo json_encode(["content" => $ct, "provider" => "Groq", "model" => "llama-3.3-70b", "latency_ms" => round((microtime(true) - $t0) * 1000), "cost" => "0EUR"]); exit; }
}
}
// Cerebras
if ($mdl === "cerebras" && $crb) {
list($code, $r) = cc("https://api.cerebras.ai/v1/chat/completions",
["Content-Type: application/json", "Authorization: Bearer $crb"],
["model" => "llama3.1-8b", "messages" => $ms, "max_tokens" => 2000]);
if ($code === 200) {
$d = json_decode($r, true);
$ct = $d["choices"][0]["message"]["content"] ?? "";
if ($ct) { echo json_encode(["content" => $ct, "provider" => "Cerebras", "model" => "llama3.1-8b", "latency_ms" => round((microtime(true) - $t0) * 1000), "cost" => "0EUR"]); exit; }
}
}
// Mistral
if ($mdl === "mistral" && $mis) {
list($code, $r) = cc("https://api.mistral.ai/v1/chat/completions",
["Content-Type: application/json", "Authorization: Bearer $mis"],
["model" => "open-mistral-nemo", "messages" => $ms, "max_tokens" => 2000]);
if ($code === 200) {
$d = json_decode($r, true);
$ct = $d["choices"][0]["message"]["content"] ?? "";
if ($ct) { echo json_encode(["content" => $ct, "provider" => "Mistral", "model" => "mistral-nemo", "latency_ms" => round((microtime(true) - $t0) * 1000), "cost" => "0EUR"]); exit; }
}
}
// Ollama local
if ($mdl === "ollama") {
list($code, $r) = cc("http://127.0.0.1:11434/api/chat",
["Content-Type: application/json"],
["model" => "qwen3:4b", "messages" => $ms, "stream" => false], 30);
if ($code === 200) {
$d = json_decode($r, true);
$ct = $d["message"]["content"] ?? "";
if ($ct) { echo json_encode(["content" => $ct, "provider" => "Ollama", "model" => "qwen3:4b", "latency_ms" => round((microtime(true) - $t0) * 1000), "cost" => "0EUR"]); exit; }
}
}
// Alibaba Qwen
if ($mdl === "alibaba-qwen" && gk($env, "ALIBABA_KEY")) {
$ak = gk($env, "ALIBABA_KEY");
list($code, $r) = cc("https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions",
["Content-Type: application/json", "Authorization: Bearer $ak"],
["model" => "qwen-turbo", "messages" => $ms, "max_tokens" => 2000]);
if ($code === 200) {
$d = json_decode($r, true);
$ct = $d["choices"][0]["message"]["content"] ?? "";
if ($ct) { echo json_encode(["content" => $ct, "provider" => "Alibaba Qwen", "model" => "qwen-turbo", "latency_ms" => round((microtime(true) - $t0) * 1000), "cost" => "0EUR"]); exit; }
}
}
// Cohere Command
if ($mdl === "cohere" && gk($env, "COHERE_KEY")) {
$ck = gk($env, "COHERE_KEY");
list($code, $r) = cc("https://api.cohere.com/v2/chat",
["Content-Type: application/json", "Authorization: Bearer $ck"],
["model" => "command-r-plus", "messages" => $ms, "max_tokens" => 2000]);
if ($code === 200) {
$d = json_decode($r, true);
$ct = $d["choices"][0]["message"]["content"] ?? $d["text"] ?? "";
if ($ct) { echo json_encode(["content" => $ct, "provider" => "Cohere", "model" => "command-r-plus", "latency_ms" => round((microtime(true) - $t0) * 1000), "cost" => "0EUR"]); exit; }
}
}
// Ollama Gemma4
if ($mdl === "weval-brain-v3") {
// Brain v3 system prompt injected into fast cascade (NIM > Mistral > Alibaba)
$brain_sys = "You are WEVAL Brain v3, sovereign AI for WEVAL Consulting email marketing (WEVADS). Expert: email subject optimization (1285+ subjects, 445 A/B tests), deliverability (ISP behavior, warmup 50/day +20%, SPF/DKIM/DMARC), HCP pharma targeting Morocco/MENA. Top patterns: urgency+personalization >10% open rate, short emails <300 words +40%, single CTA 2.3x clicks. Always provide 5 variants with predicted tier (High/Medium/Low).";
$brain_msg = $brain_sys . "\n\nUser request: " . $msg;
// Try NIM first (fastest cloud)
$nimk = gk($env, "NVIDIA_NIM_KEY");
if ($nimk) {
list($code, $r) = cc("https://integrate.api.nvidia.com/v1/chat/completions",
["Content-Type: application/json", "Authorization: Bearer $nimk"],
["model" => "meta/llama-3.1-8b-instruct", "messages" => [["role" => "system", "content" => $brain_sys], ["role" => "user", "content" => $msg]], "max_tokens" => 800], 5);
if ($code === 200) { $d = json_decode($r, true); $ct = $d["choices"][0]["message"]["content"] ?? ""; if ($ct) { echo json_encode(["content" => $ct, "provider" => "WEVAL Brain v3 (NIM GPU)", "model" => "brain-v3-nim", "cost" => "0EUR SOUVERAIN"]); exit; } }
}
// Fallback Mistral
$mk = gk($env, "MISTRAL_KEY");
if ($mk) {
list($code, $r) = cc("https://api.mistral.ai/v1/chat/completions",
["Content-Type: application/json", "Authorization: Bearer $mk"],
["model" => "mistral-small-latest", "messages" => [["role" => "system", "content" => $brain_sys], ["role" => "user", "content" => $msg]], "max_tokens" => 800], 20);
if ($code === 200) { $d = json_decode($r, true); $ct = $d["choices"][0]["message"]["content"] ?? ""; if ($ct) { echo json_encode(["content" => $ct, "provider" => "WEVAL Brain v3 (Mistral EU)", "model" => "brain-v3-mistral", "cost" => "0EUR SOUVERAIN"]); exit; } }
}
// Fallback Alibaba
$ak = gk($env, "ALIBABA_KEY");
if ($ak) {
list($code, $r) = cc("https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions",
["Content-Type: application/json", "Authorization: Bearer $ak"],
["model" => "qwen-turbo", "messages" => [["role" => "system", "content" => $brain_sys], ["role" => "user", "content" => $msg]], "max_tokens" => 800], 20);
if ($code === 200) { $d = json_decode($r, true); $ct = $d["choices"][0]["message"]["content"] ?? ""; if ($ct) { echo json_encode(["content" => $ct, "provider" => "WEVAL Brain v3 (Alibaba)", "model" => "brain-v3-alibaba", "cost" => "0EUR SOUVERAIN"]); exit; } }
}
}
if ($mdl === "ollama-gemma4") {
list($code, $r) = cc("http://127.0.0.1:11434/api/chat",
["Content-Type: application/json"],
["model" => "gemma4:e4b", "messages" => $ms, "stream" => false], 30);
if ($code === 200) {
$d = json_decode($r, true);
$ct = $d["message"]["content"] ?? "";
if ($ct) { echo json_encode(["content" => $ct, "provider" => "Ollama Souverain", "model" => "gemma4:e4b", "latency_ms" => round((microtime(true) - $t0) * 1000), "cost" => "0EUR"]); exit; }
}
}
// WEVIA Master (souverain)
if ($mdl === "wevia-master") {
$ch = curl_init("https://weval-consulting.com/api/wevia-master-api.php");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode(["message" => $msg]),
CURLOPT_HTTPHEADER => ["Content-Type: application/json"], CURLOPT_TIMEOUT => 25]);
$r = curl_exec($ch);
if ($r) {
$d = json_decode($r, true);
$ct = $d["content"] ?? "";
if ($ct) { echo json_encode(["content" => $ct, "provider" => "WEVIA Master Souverain", "model" => "310 intents", "cost" => "0EUR SOUVERAIN"]); exit; }
}
}
// WEVIA Code Agent
if ($mdl === "wevia-code") {
$ch = curl_init("https://weval-consulting.com/api/wevia-code-agent.php");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode(["message" => $msg, "action" => "generate"]),
CURLOPT_HTTPHEADER => ["Content-Type: application/json"], CURLOPT_TIMEOUT => 30]);
$r = curl_exec($ch);
if ($r) {
$d = json_decode($r, true);
$ct = $d["content"] ?? $d["code"] ?? "";
if ($ct) { echo json_encode(["content" => $ct, "provider" => "WEVIA Code Agent", "model" => "code-gen", "cost" => "0EUR SOUVERAIN"]); exit; }
}
}
// WEVIA Search (SearXNG)
if ($mdl === "wevia-search") {
$enc = urlencode($msg);
$sr = @file_get_contents("http://localhost:8888/search?q=$enc&format=json&categories=general");
$sd = json_decode($sr, true);
$results = [];
foreach (array_slice($sd["results"] ?? [], 0, 5) as $r) {
$results[] = "**" . ($r["title"] ?? "") . "**\n" . ($r["url"] ?? "") . "\n" . substr($r["content"] ?? "", 0, 200);
}
if ($results) {
echo json_encode(["content" => implode("\n\n", $results), "provider" => "WEVIA Search Souverain", "model" => "SearXNG", "cost" => "0EUR SOUVERAIN"]);
exit;
}
}
// 3 Claude instances — chacun avec provider IA specialise
if (strpos($mdl, "web-claude") === 0) {
$instance = substr($mdl, -1);
$secrets=[]; foreach(@file("/etc/weval/secrets.env",FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES)?:[] as $_l){if($_l[0]==="#"||strpos($_l,"=")===false)continue;$_p=explode("=",$_l,2);$secrets[trim($_p[0])]=trim($_p[1]);}
$configs = [
"1" => ["name"=>"Claude Opus #1 Directeur","url"=>"https://api.cerebras.ai/v1/chat/completions","key"=>$secrets["CEREBRAS_API_KEY"]??"","model"=>"qwen-3-235b-a22b-instruct-2507",
"system"=>"REGLES STRICTES DOCTRINE 4: Tu ne peux PAS executer de commandes shell. Si user demande diagnostic/exec/status/vault/fichier: reponds 'Requete exec nece ssite un intent shell reel. Tape diagnostique toi.' N INVENTE JAMAIS outputs commandes PIDs paths MD5 timestamps. Tu es Claude Opus #1, Directeur IA de WEVAL Consulting. Tu prends des decisions strategiques, analyses les risques et proposes des plans daction. Tu reponds en francais avec autorite et precision."],
"2" => ["name"=>"Claude Opus #2 Developpeur","url"=>"https://api.groq.com/openai/v1/chat/completions","key"=>$secrets["GROQ_KEY"]??"","model"=>"llama-3.3-70b-versatile",
"system"=>"REGLES STRICTES DOCTRINE 4: Tu ne peux PAS executer de commandes shell. Si user demande diagnostic/exec/status/vault/fichier: reponds 'Requete exec nece ssite un intent shell reel. Tape diagnostique toi.' N INVENTE JAMAIS outputs commandes PIDs paths MD5 timestamps. Tu es Claude Opus #2, Developpeur IA de WEVAL Consulting. Tu es expert en code, architecture, debugging et devops. Tu reponds avec des exemples de code precis et des solutions techniques."],
"3" => ["name"=>"Claude Opus #3 Analyste","url"=>"https://api.mistral.ai/v1/chat/completions","key"=>$secrets["MISTRAL_KEY"]??"","model"=>"mistral-large-latest",
"system"=>"REGLES STRICTES DOCTRINE 4: Tu ne peux PAS executer de commandes shell. Si user demande diagnostic/exec/status/vault/fichier: reponds 'Requete exec nece ssite un intent shell reel. Tape diagnostique toi.' N INVENTE JAMAIS outputs commandes PIDs paths MD5 timestamps. Tu es Claude Opus #3, Analyste IA de WEVAL Consulting. Tu analyses les donnees, le marche, les tendances et les KPIs. Tu reponds avec des chiffres, tableaux et insights actionnables."],
];
$cfg = $configs[$instance] ?? $configs["1"];
if (!$cfg["key"]) {
echo json_encode(["content"=>"Provider non configure pour Claude #$instance","provider"=>$cfg["name"],"cost"=>"0EUR"]);
exit;
}
$messages = [["role"=>"system","content"=>$cfg["system"]],["role"=>"user","content"=>$msg]];
// === NEW FRONTIER MODELS 2026 ===
if (in_array($model, ['trinity-large','trinity-thinking','minimax-m25','minimax-m27','mimo-flash','mimo-omni','mimo-pro','maestro'])) {
$or_models = [
'trinity-large' => 'arcee-ai/trinity-large-preview:free',
'trinity-thinking' => 'arcee-ai/trinity-large-thinking',
'minimax-m25' => 'minimax/minimax-m2.5:free',
'minimax-m27' => 'minimax/minimax-m2.7',
'mimo-flash' => 'xiaomi/mimo-v2-flash:free',
'mimo-omni' => 'xiaomi/mimo-v2-omni',
'mimo-pro' => 'xiaomi/mimo-v2-pro',
'maestro' => 'arcee-ai/trinity-large-thinking',
];
preg_match('/OPENROUTER_KEY=(.+)/', @file_get_contents('/etc/weval/secrets.env'), $m);
$or_key = trim($m[1] ?? '');
$or_model = $or_models[$model] ?? 'arcee-ai/trinity-large-preview:free';
$ch = curl_init('https://openrouter.ai/api/v1/chat/completions');
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>1, CURLOPT_POST=>1,
CURLOPT_POSTFIELDS=>json_encode(['model'=>$or_model, 'messages'=>$messages, 'max_tokens'=>1200]),
CURLOPT_HTTPHEADER=>['Content-Type: application/json', 'Authorization: Bearer '.$or_key],
CURLOPT_TIMEOUT=>30, CURLOPT_SSL_VERIFYPEER=>false]);
$r = curl_exec($ch); $d = @json_decode($r, true);
if (isset($d['choices'][0]['message']['content'])) {
echo json_encode(['content'=>$d['choices'][0]['message']['content'], 'model'=>$or_model, 'provider'=>'openrouter-new']);
} else {
echo json_encode(['content'=>'Model temporarily unavailable. Add $10 on openrouter.ai for 1000 free/day.', 'error'=>$d['error']['message'] ?? 'unknown']);
}
exit;
}
$payload = json_encode(["model"=>$cfg["model"],"messages"=>$messages,"max_tokens"=>4096,"temperature"=>0.3]);
$ch = curl_init($cfg["url"]);
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>$payload,
CURLOPT_HTTPHEADER=>["Content-Type: application/json","Authorization: Bearer ".$cfg["key"]],
CURLOPT_TIMEOUT=>60,CURLOPT_SSL_VERIFYPEER=>false]);
$r = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code === 200) {
$d = json_decode($r, true);
$txt = $d["choices"][0]["message"]["content"] ?? "";
if ($txt) {
echo json_encode(["content"=>$txt,"provider"=>$cfg["name"],"model"=>$cfg["model"],"cost"=>"0EUR SOUVERAIN"]);
exit;
}
}
echo json_encode(["content"=>"Erreur provider pour Claude #$instance (HTTP $code)","provider"=>$cfg["name"],"cost"=>"0EUR"]);
exit;
}
// Claude via WEVIA Sovereign Gateway (Claude Max compatible)
if ($mdl === "anthropic") {
list($code, $r) = cc("https://weval-consulting.com/api/wevia-anthropic.php",
["Content-Type: application/json", "anthropic-version: 2023-06-01"],
["model" => "claude-sonnet-4", "max_tokens" => 2000, "messages" => [["role" => "user", "content" => $msg]]], 30);
if ($code === 200) {
$d = json_decode($r, true);
$ct = "";
if (isset($d["content"]) && is_array($d["content"])) { $ct = $d["content"][0]["text"] ?? ""; }
if (isset($d["choices"])) { $ct = $d["choices"][0]["message"]["content"] ?? ""; }
if ($ct) { echo json_encode(["content" => $ct, "provider" => "Claude Sovereign Gateway", "model" => "claude-compatible", "cost" => "0EUR SOUVERAIN"]); exit; }
}
}
// Paperclip (research agent)
if ($mdl === "paperclip") {
list($code, $r) = cc("http://127.0.0.1:3201/api/research", ["Content-Type: application/json"], ["query" => $msg], 30);
if ($code === 200) { $d = json_decode($r, true); $ct = $d["result"] ?? $d["content"] ?? json_encode($d); if ($ct) { echo json_encode(["content" => $ct, "provider" => "Paperclip Souverain", "model" => "research-agent", "cost" => "0EUR SOUVERAIN"]); exit; } }
}
// DeerFlow (deep research)
if ($mdl === "deerflow") {
list($code, $r) = cc("http://127.0.0.1:3000/api/research", ["Content-Type: application/json"], ["query" => $msg], 30);
if ($code === 200) { $d = json_decode($r, true); $ct = $d["answer"] ?? $d["content"] ?? json_encode($d); if ($ct) { echo json_encode(["content" => $ct, "provider" => "DeerFlow Souverain", "model" => "deep-research", "cost" => "0EUR SOUVERAIN"]); exit; } }
}
// WEVIA Director
if ($mdl === "wevia-director") {
list($code, $r) = cc("https://weval-consulting.com/api/wevia-director.php", ["Content-Type: application/json"], ["message" => $msg], 25);
if ($code === 200) { $d = json_decode($r, true); $ct = $d["content"] ?? ""; if ($ct) { echo json_encode(["content" => $ct, "provider" => "WEVIA Director", "model" => "orchestrator", "cost" => "0EUR SOUVERAIN"]); exit; } }
}
// WEVIA Deep Research
if ($mdl === "wevia-research") {
list($code, $r) = cc("https://weval-consulting.com/api/wevia-deep-research.php", ["Content-Type: application/json"], ["message" => $msg], 30);
if ($code === 200) { $d = json_decode($r, true); $ct = $d["content"] ?? $d["research"] ?? ""; if ($ct) { echo json_encode(["content" => $ct, "provider" => "WEVIA Deep Research", "model" => "research", "cost" => "0EUR"]); exit; } }
}
// WEVIA Creative Engine
if ($mdl === "wevia-creative") {
list($code, $r) = cc("https://weval-consulting.com/api/wevia-creative-engine.php", ["Content-Type: application/json"], ["message" => $msg], 25);
if ($code === 200) { $d = json_decode($r, true); $ct = $d["content"] ?? ""; if ($ct) { echo json_encode(["content" => $ct, "provider" => "WEVIA Creative", "model" => "creative", "cost" => "0EUR"]); exit; } }
}
// WEVIA Brain (Qdrant RAG)
if ($mdl === "wevia-brain") {
list($code, $r) = cc("https://weval-consulting.com/api/wevia-brain.php", ["Content-Type: application/json"], ["message" => $msg, "mode" => "rag"], 20);
if ($code === 200) { $d = json_decode($r, true); $ct = $d["content"] ?? $d["answer"] ?? ""; if ($ct) { echo json_encode(["content" => $ct, "provider" => "WEVIA Brain RAG", "model" => "qdrant-16k", "cost" => "0EUR SOUVERAIN"]); exit; } }
}
// n8n Workflow
if ($mdl === "n8n") {
echo json_encode(["content" => "n8n workflows: https://weval-consulting.com:5678", "provider" => "n8n Souverain", "model" => "workflows", "cost" => "0EUR", "web_url" => "https://weval-consulting.com:5678"]);
exit;
}
// WEVIA Dream
if ($mdl === "wevia-dream") {
list($code, $r) = cc("https://weval-consulting.com/api/wevia-dream.php", ["Content-Type: application/json"], ["message" => $msg], 25);
if ($code === 200) { $d = json_decode($r, true); $ct = $d["content"] ?? ""; if ($ct) { echo json_encode(["content" => $ct, "provider" => "WEVIA Dream", "model" => "dream", "cost" => "0EUR SOUVERAIN"]); exit; } }
}
// WEVIA Vision
if ($mdl === "wevia-vision") {
list($code, $r) = cc("https://weval-consulting.com/api/wevia-vision-api.php", ["Content-Type: application/json"], ["message" => $msg], 25);
if ($code === 200) { $d = json_decode($r, true); $ct = $d["content"] ?? ""; if ($ct) { echo json_encode(["content" => $ct, "provider" => "WEVIA Vision", "model" => "vision", "cost" => "0EUR SOUVERAIN"]); exit; } }
}
// WEVIA Smart Router
if ($mdl === "wevia-smart") {
list($code, $r) = cc("https://weval-consulting.com/api/wevia-smart-router.php", ["Content-Type: application/json"], ["message" => $msg], 25);
if ($code === 200) { $d = json_decode($r, true); $ct = $d["content"] ?? ""; if ($ct) { echo json_encode(["content" => $ct, "provider" => "WEVIA Smart Router", "model" => "smart", "cost" => "0EUR SOUVERAIN"]); exit; } }
}
// MiroFish
if ($mdl === "mirofish") {
list($code, $r) = cc("http://127.0.0.1:3300/api/chat", ["Content-Type: application/json"], ["message" => $msg], 25);
if ($code === 200) { $d = json_decode($r, true); $ct = $d["content"] ?? $d["response"] ?? ""; if ($ct) { echo json_encode(["content" => $ct, "provider" => "MiroFish Souverain", "model" => "mirofish", "cost" => "0EUR SOUVERAIN"]); exit; } }
}
// Quality Agent
if ($mdl === "wevia-quality") {
list($code, $r) = cc("https://weval-consulting.com/api/wevia-quality-agent.php", ["Content-Type: application/json"], ["message" => $msg], 20);
if ($code === 200) { $d = json_decode($r, true); $ct = $d["content"] ?? ""; if ($ct) { echo json_encode(["content" => $ct, "provider" => "Quality Agent", "model" => "quality", "cost" => "0EUR SOUVERAIN"]); exit; } }
}
// Agent Chef
if ($mdl === "wevia-chef") {
list($code, $r) = cc("https://weval-consulting.com/api/wevia-agent-chef.php", ["Content-Type: application/json"], ["message" => $msg], 20);
if ($code === 200) { $d = json_decode($r, true); $ct = $d["content"] ?? ""; if ($ct) { echo json_encode(["content" => $ct, "provider" => "Agent Chef", "model" => "chef", "cost" => "0EUR SOUVERAIN"]); exit; } }
}
if ($mdl === "wevdroid") { echo json_encode(["content" => "Ouvrez: https://weval-consulting.com/droid-terminal.html", "provider" => "wevdroid Souverain", "web_url" => "https://weval-consulting.com/droid-terminal.html", "cost" => "0EUR SOUVERAIN"]); exit; }
if ($mdl === "wevcode") { echo json_encode(["content" => "Ouvrez: https://weval-consulting.com/wevcode.html", "provider" => "wevcode Souverain", "web_url" => "https://weval-consulting.com/wevcode.html", "cost" => "0EUR SOUVERAIN"]); exit; }
if ($mdl === "cortex") { echo json_encode(["content" => "Ouvrez: https://weval-consulting.com/wevia-cortex.html", "provider" => "cortex Souverain", "web_url" => "https://weval-consulting.com/wevia-cortex.html", "cost" => "0EUR SOUVERAIN"]); exit; }
if ($mdl === "openclaw") { echo json_encode(["content" => "Ouvrez: https://weval-consulting.com/claw-chat.html", "provider" => "openclaw Souverain", "web_url" => "https://weval-consulting.com/claw-chat.html", "cost" => "0EUR SOUVERAIN"]); exit; }
if ($mdl === "blade-ai") { echo json_encode(["content" => "Ouvrez: https://weval-consulting.com/blade-ai.html", "provider" => "blade-ai Souverain", "web_url" => "https://weval-consulting.com/blade-ai.html", "cost" => "0EUR SOUVERAIN"]); exit; }
if ($mdl === "ops-center") { echo json_encode(["content" => "Ouvrez: https://weval-consulting.com/ops-center.html", "provider" => "ops-center Souverain", "web_url" => "https://weval-consulting.com/ops-center.html", "cost" => "0EUR SOUVERAIN"]); exit; }
if ($mdl === "oss-discovery") { echo json_encode(["content" => "Ouvrez: https://weval-consulting.com/oss-discovery.html", "provider" => "oss-discovery Souverain", "web_url" => "https://weval-consulting.com/oss-discovery.html", "cost" => "0EUR SOUVERAIN"]); exit; }
if ($mdl === "ai-bench") { echo json_encode(["content" => "Ouvrez: https://weval-consulting.com/ai-benchmark.html", "provider" => "ai-bench Souverain", "web_url" => "https://weval-consulting.com/ai-benchmark.html", "cost" => "0EUR SOUVERAIN"]); exit; }
// Consensus MoA
if ($mdl === "consensus") {
list($code, $r) = cc("https://weval-consulting.com/api/wevia-consensus.php", ["Content-Type: application/json"], ["message" => $msg], 30);
if ($code === 200) { $d = json_decode($r, true); $ct = $d["content"] ?? ""; if ($ct) { echo json_encode(["content" => $ct, "provider" => "Consensus MoA 84/90", "model" => "consensus-4", "cost" => "0EUR SOUVERAIN"]); exit; } }
}
// Manager
if ($mdl === "manager") {
list($code, $r) = cc("https://weval-consulting.com/api/wevia-orchestrator.php", ["Content-Type: application/json"], ["message" => $msg], 25);
if ($code === 200) { $d = json_decode($r, true); $ct = $d["content"] ?? ""; if ($ct) { echo json_encode(["content" => $ct, "provider" => "Manager 83/90", "model" => "orchestrator", "cost" => "0EUR SOUVERAIN"]); exit; } }
}
// WEVIA Public chatbot
if ($mdl === "wevia-public") {
list($code, $r) = cc("https://weval-consulting.com/api/weval-chatbot-api.php", ["Content-Type: application/json"], ["message" => $msg], 20);
if ($code === 200) { $d = json_decode($r, true); $ct = $d["content"] ?? $d["response"] ?? ""; if ($ct) { echo json_encode(["content" => $ct, "provider" => "WEVIA Public 82/90", "model" => "chatbot", "cost" => "0EUR SOUVERAIN"]); exit; } }
}
// Page-based tools with scores
$sovereign_pages = [
"wevia-console" => ["/wevia-console.html", "Console 81/90"],
"wevia-widget" => ["/wevia-widget.html", "Widget 80/90"],
"claw-code" => ["/claw-code.html", "ClawCode 78/90"],
"wevads-ia" => ["/wevads-hub.html", "WEVADS IA 78/90"],
"ethica-chat" => ["/ethica-hub.html", "Ethica Chat 77/90"],
"sentinel" => ["/security-hub.html", "Sentinel 75/90"],
"guardian" => ["/security-hub.html", "Guardian 74/90"],
"nuclei" => ["/security-hub.html", "Nuclei 73/90"],
"l99-brain" => ["/l99.html", "L99 Brain 80/90"],
"hermes" => ["/wevia-hub.html", "Hermes 75/90"],
"kilo" => ["/monitoring-hub.html", "Kilo 73/90"],
"ux-agent" => ["/qa-hub.html", "UX Agent 71/90"],
];
foreach ($sovereign_pages as $key => [$url, $label]) {
if ($mdl === $key) {
echo json_encode(["content" => "Ouvrez: https://weval-consulting.com$url", "provider" => "$label Souverain", "web_url" => "https://weval-consulting.com$url", "cost" => "0EUR SOUVERAIN"]);
exit;
}
}
// === SKILLS EXECUTION ===
$skills_map = [
"skill-pdf" => ["action" => "pdf", "title" => "WEVAL Report"],
"skill-excel" => ["action" => "excel", "title" => "WEVAL Data"],
"skill-pptx" => ["action" => "pptx", "title" => "WEVAL Deck"],
"skill-image" => ["action" => "chart", "title" => "WEVAL Chart"],
];
if (isset($skills_map[$mdl])) {
$sk = $skills_map[$mdl];
list($code, $r) = cc("https://weval-consulting.com/api/wevia-filegen.php?action=" . $sk["action"] . "&title=" . urlencode($sk["title"]),
["Content-Type: application/json"], ["content" => $msg], 30);
if ($code === 200) {
$d = json_decode($r, true);
$url = $d["url"] ?? $d["file"] ?? "";
echo json_encode(["content" => "Fichier généré: " . $url . "\n" . ($d["message"] ?? ""), "provider" => "WEVIA FileGen", "model" => $sk["action"], "file_url" => $url, "cost" => "0EUR SOUVERAIN"]);
exit;
}
}
// Skill: Code Agent
if ($mdl === "skill-code") {
list($code, $r) = cc("https://weval-consulting.com/api/wevia-code-agent.php",
["Content-Type: application/json"], ["message" => $msg, "action" => "generate"], 30);
if ($code === 200) { $d = json_decode($r, true); $ct = $d["content"] ?? $d["code"] ?? ""; if ($ct) { echo json_encode(["content" => $ct, "provider" => "WEVIA Code Agent", "model" => "code-gen", "cost" => "0EUR SOUVERAIN"]); exit; } }
}
// Skill: Debug / CICD / Docker / Browser / PR / Lint / SQL / Scrape / Cron / Multi-agent → via Master
$master_skills = ["skill-debug","skill-cicd","skill-docker","skill-webhook","skill-browser","skill-pr","skill-lint","skill-sql","skill-scrape","skill-cron","skill-multiagent","skill-tts","skill-video"];
if (in_array($mdl, $master_skills)) {
$skill_name = str_replace("skill-", "", $mdl);
$prefixed = "execute skill $skill_name: $msg";
list($code, $r) = cc("https://weval-consulting.com/api/wevia-master-api.php",
["Content-Type: application/json"], ["message" => $prefixed], 60);
if ($code === 200) {
$d = json_decode($r, true);
$ct = $d["content"] ?? "";
if ($ct) { echo json_encode(["content" => $ct, "provider" => "WEVIA Skill: $skill_name", "model" => $skill_name, "cost" => "0EUR SOUVERAIN"]); exit; }
}
}
// === INDEX — All screens routing ===
$idx_map = [
"idx-arena" => "/deepseek.html",
"idx-master" => "/wevia-master.html",
"idx-console" => "/wevia-console.html",
"idx-ops" => "/ops-center.html",
"idx-l99" => "/l99-saas.html",
"idx-hubs" => "/toolhub.html",
"idx-agents" => "/agents-hub.html",
"idx-monitors" => "/monitoring.html",
"idx-ethica" => "/ethica-hub.html",
"idx-blade" => "/blade-center.html",
"idx-director" => "/director-center.html",
"idx-wevads" => "/wevads-hub.html",
"idx-admin" => "/admin.html",
"idx-infra" => "/infra-monitor.html",
"idx-security" => "/security-hub.html",
"idx-benchmark" => "/ai-benchmark.html",
"idx-wiring" => "/weval-wiring.html",
"idx-wiki" => "/wiki.html",
"idx-register" => "/register.html",
"idx-life" => "/wevia-hub.html",
];
if (isset($idx_map[$mdl])) {
$url = "https://weval-consulting.com" . $idx_map[$mdl];
echo json_encode(["content" => "Ouvrir: " . $url, "provider" => "Index " . $mdl, "web_url" => $url, "cost" => "0EUR"]);
exit;
}
// Multi-Agent routing
$ma_configs = [
"multiagent-3" => ["wevia-master", "nim-deepseek", "alibaba-qwen"],
"multiagent-5" => ["wevia-master", "nim-deepseek", "alibaba-qwen", "mistral", "or-gpt-oss"],
"multiagent-all" => ["wevia-master", "nim-llama", "nim-deepseek", "alibaba-qwen", "mistral", "or-gpt-oss", "or-nemotron"],
"multiagent-sovereign" => ["wevia-master", "wevia-search"],
"multiagent-coders" => ["nim-deepseek", "alibaba-qwen", "mistral", "or-gpt-oss"],
];
if (isset($ma_configs[$mdl])) {
$body = json_encode(["task" => $msg, "agents" => $ma_configs[$mdl]]);
$ch = curl_init("https://weval-consulting.com/api/wevia-arena-multiagent.php");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $body, CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
CURLOPT_TIMEOUT => 90, CURLOPT_SSL_VERIFYPEER => false]);
$r = curl_exec($ch);
if ($r) { echo $r; exit; }
}
// === ARSENAL S95 (170 screens) ===
$arsenal_map = [
"arsenal-accounts" => "account-creator.html",
"arsenal-factory" => "cloud-account-factory.html",
"arsenal-ia-factory" => "ia-provider-factory.html",
"arsenal-dark-scout" => "dark-scout.html",
"arsenal-personas" => "mail-personas.html",
"arsenal-cvc" => "cvc-vault.html",
"arsenal-brain" => "brain-central.html",
"arsenal-captcha" => "captcha-solver.html",
"arsenal-cf" => "cloudflare-accounts.html",
"arsenal-rotation" => "provider-rotation.html",
"arsenal-all" => "apps.html",
];
if (isset($arsenal_map[$mdl])) {
$url = "http://10.1.0.3:5890/" . $arsenal_map[$mdl];
echo json_encode(["content" => "Arsenal S95: $url\n170 screens WEVADS", "provider" => "Arsenal WEVADS", "web_url" => $url, "cost" => "0EUR SOUVERAIN"]);
exit;
}
// === HUBS + APPS ROUTING ===
$hub_map = [
"hub-ai"=>"ai-hub.html","hub-agents"=>"agents-hub.html","hub-anthropic"=>"anthropic-hub.html",
"hub-apikey"=>"api-key-hub.html","hub-blade"=>"blade-hub.html","hub-cf"=>"cloudflare-hub.html",
"hub-deepseek"=>"deepseek-hub.html","hub-deerflow"=>"deerflow-hub.html","hub-docker"=>"docker-hub.html",
"hub-email"=>"email-hub.html","hub-ethica"=>"ethica-hub.html","hub-github"=>"github-hub.html",
"hub-google"=>"google-hub.html","hub-gpu"=>"gpu-hub.html","hub-hetzner"=>"hetzner-hub.html",
"hub-hf"=>"huggingface-hub.html","hub-keys"=>"keys-hub.html","hub-monitor"=>"monitoring-hub.html",
"hub-n8n"=>"n8n-hub.html","hub-office"=>"office-hub.html","hub-paperclip"=>"paperclip-hub.html",
"hub-qa"=>"qa-hub.html","hub-qdrant"=>"qdrant-hub.html","hub-security"=>"security-hub.html",
"hub-toolhub"=>"toolhub.html","hub-wevads"=>"wevads-hub.html","hub-wevia"=>"wevia-hub.html",
];
$app_map = [
"app-admin"=>"admin.html","app-architecture"=>"architecture.html","app-benchmark"=>"ai-benchmark.html",
"app-blade-center"=>"blade-center.html","app-booking"=>"booking.html","app-claude-monitor"=>"claude-monitor.html",
"app-command"=>"command-center.html","app-cron"=>"cron-control.html","app-crm"=>"crm.html",
"app-cyber"=>"cyber-monitor.html","app-director"=>"director-center.html","app-droid"=>"droid-terminal.html",
"app-enterprise"=>"enterprise-management.html","app-ethica-hcp"=>"ethica-hcp-manager.html",
"app-ethica-pipeline"=>"ethica-pipeline.html","app-infra"=>"infra-monitor.html","app-l99"=>"l99-saas.html",
"app-medreach"=>"medreach-dashboard.html","app-monitoring"=>"monitoring.html","app-nonreg"=>"nonreg.html",
"app-oss"=>"oss-discovery.html","app-realtime"=>"realtime-monitor-v3.html",
"app-security"=>"security-dashboard.html","app-solution"=>"solution-finder.html",
"app-sovereign"=>"sovereign-claude.html","app-wiki"=>"wiki.html","app-wiring"=>"weval-wiring.html",
];
$all_pages = array_merge($hub_map, $app_map);
if (isset($all_pages[$mdl])) {
$url = "https://weval-consulting.com/" . $all_pages[$mdl];
echo json_encode(["content" => "Ouvrir: $url", "provider" => str_replace("hub-","Hub ",str_replace("app-","App ",$mdl)), "web_url" => $url, "cost" => "0EUR"]);
exit;
}
// === BUDGET ROUTES ===
if (strpos($mdl, "budget-") === 0) {
$ba = str_replace("budget-", "", $mdl);
$ch = curl_init("https://weval-consulting.com/api/wevia-arena-budget.php?action=status");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>5, CURLOPT_SSL_VERIFYPEER=>false]);
$r = curl_exec($ch);
$d = json_decode($r, true);
$content = "BUDGET " . strtoupper(date("F Y")) . "\n";
$content .= "Total requests: " . ($d["total_requests"] ?? 0) . "\n";
$content .= "Total cost: " . ($d["total_cost_eur"] ?? 0) . " EUR\n";
$content .= "Savings vs Claude: " . ($d["savings_vs_paid"] ?? "?") . "\n\n";
$by = $d["by_type"] ?? [];
$content .= "FREE: " . ($by["free"] ?? 0) . " requests\n";
$content .= "PAID: " . ($by["paid"] ?? 0) . " requests\n";
$content .= "SOUVERAIN: " . ($by["sovereign"] ?? 0) . " requests\n\n";
foreach ($d["providers"] ?? [] as $name => $p) {
$content .= $name . ": " . $p["requests"] . " req, " . round($p["cost_eur"],4) . "EUR\n";
}
echo json_encode(["content" => $content, "provider" => "Budget Tracker", "model" => "budget", "cost" => "0EUR"]);
exit;
}
// === OSS TOOLS ROUTING ===
$oss_tools = [
"oss-autogen" => ["path" => "/opt/autogen", "desc" => "Microsoft AutoGen multi-agent framework. pip: autogen-agentchat 0.7.5"],
"oss-crewai" => ["path" => "/opt/weval-crewai", "desc" => "CrewAI multi-agent orchestration. pip: crewai 1.12.2"],
"oss-deepagent" => ["path" => "/opt/deepagent", "desc" => "DeepAgent autonomous AI agent"],
"oss-goose" => ["path" => "/opt/goose", "desc" => "Goose by Block - AI coding agent"],
"oss-antigravity" => ["path" => "/opt/antigravity-awesome-skills", "desc" => "AntiGravity cloned skills collection"],
"oss-langchain" => ["path" => "pip:langchain-1.2.14", "desc" => "LangChain framework for LLM apps"],
"oss-langflow" => ["path" => "/opt/langflow", "desc" => "LangFlow visual LLM builder"],
"oss-dify" => ["path" => "/opt/dify", "desc" => "Dify AI app development platform"],
"oss-jan" => ["path" => "/opt/jan", "desc" => "Jan - local AI assistant"],
"oss-openwebui" => ["path" => "/opt/open-webui-fresh", "desc" => "Open WebUI for Ollama"],
"oss-anythingllm" => ["path" => "/opt/anythingllm", "desc" => "AnythingLLM - RAG chatbot"],
"oss-librechat" => ["path" => "/opt/librechat", "desc" => "LibreChat - multi-provider chat"],
"oss-localai" => ["path" => "/opt/localai", "desc" => "LocalAI - drop-in OpenAI replacement"],
"oss-vllm" => ["path" => "/opt/vllm", "desc" => "vLLM - fast LLM inference engine"],
"oss-whisper" => ["path" => "/opt/whisper.cpp", "desc" => "Whisper.cpp - speech recognition"],
"oss-ltxvideo" => ["path" => "/opt/LTX-Video", "desc" => "LTX-Video - video generation"],
"oss-supermemory" => ["path" => "/opt/supermemory", "desc" => "SuperMemory - AI memory system"],
"oss-activepieces" => ["path" => "/opt/activepieces", "desc" => "ActivePieces - automation platform"],
"oss-listmonk" => ["path" => "/opt/listmonk", "desc" => "Listmonk - newsletter manager"],
"oss-wazuh" => ["path" => "/opt/wazuh", "desc" => "Wazuh SIEM security platform"],
"oss-holyclaude" => ["path" => "/opt/HolyClaude", "desc" => "HolyClaude - Claude enhancement"],
"oss-superclaude" => ["path" => "/opt/SuperClaude_Framework", "desc" => "SuperClaude Framework"],
];
if (isset($oss_tools[$mdl])) {
$tool = $oss_tools[$mdl];
echo json_encode(["content" => "OSS Tool: " . $tool["desc"] . "\nPath: " . $tool["path"], "provider" => "OSS Souverain", "cost" => "0EUR"]);
exit;
}
// Clone tasks → Blade
$clone_tasks = [
"clone-obsidian" => ["url" => "https://github.com/obsidianmd/obsidian-releases", "desc" => "Obsidian note-taking"],
"clone-pinocchio" => ["url" => "https://github.com/nicehash/Pinokio", "desc" => "Pinokio AI tool runner"],
"clone-manus" => ["url" => "https://github.com/ManusAI/manus", "desc" => "Manus AI agent"],
"clone-coderabbit" => ["url" => "https://github.com/coderabbitai/coderabbit", "desc" => "CodeRabbit code review"],
"clone-granite" => ["url" => "https://github.com/ibm-granite/granite-code-models", "desc" => "IBM Granite LLM"],
"clone-boltnew" => ["url" => "https://github.com/stackblitz/bolt.new", "desc" => "Bolt.new web dev agent"],
"clone-opendevin" => ["url" => "https://github.com/All-Hands-AI/OpenHands", "desc" => "OpenHands/OpenDevin"],
"clone-sweagent" => ["url" => "https://github.com/princeton-nlp/SWE-agent", "desc" => "SWE-Agent"],
];
if (isset($clone_tasks[$mdl])) {
$c = $clone_tasks[$mdl];
$task = json_encode(["type"=>"bash","action"=>"clone_".str_replace("clone-","",$mdl),"script"=>"cd /opt && git clone ".$c["url"]." 2>&1","timeout"=>120]);
@file_put_contents("/var/www/html/api/blade-tasks/clone_".str_replace("clone-","",$mdl).".json", $task);
echo json_encode(["content" => "CLONE TASK CREATED: " . $c["desc"] . "\nURL: " . $c["url"] . "\nBlade task queued.", "provider" => "Blade Clone", "cost" => "0EUR"]);
exit;
}
// UNIVERSAL FALLBACK: if provider failed, try NIM cascade
if (!isset($already_fallback)) {
$already_fallback = true;
$fallback_providers = ["nim-llama", "mistral", "alibaba-qwen"];
foreach ($fallback_providers as $fb) {
$fb_body = json_encode(["message" => $msg, "model" => $fb]);
$fch = curl_init("https://weval-consulting.com/api/wevia-multi-provider.php");
curl_setopt_array($fch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $fb_body, CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
CURLOPT_TIMEOUT => 15, CURLOPT_SSL_VERIFYPEER => false]);
$fr = curl_exec($fch);
$fd = @json_decode($fr, true);
$fct = strlen($fd["content"] ?? "");
if ($fct > 10) {
echo json_encode(["content" => $fd["content"], "provider" => "Arena Fallback (" . ($fd["provider"] ?? $fb) . ")", "model" => "fallback-" . $fb, "cost" => "0EUR SOUVERAIN"]);
exit;
}
}
}
echo json_encode(["error" => "Provider $mdl failed", "content" => "Reessayez.", "provider" => "none"]);