Files
html/api/wevia-webchat-direct.php
2026-04-16 05:14:43 +02:00

157 lines
7.5 KiB
PHP

<?php
// WEVIA WebChat Direct API — bypass Playwright, use native APIs
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;
$input = json_decode(file_get_contents("php://input"), true) ?: [];
$service = $input['service'] ?? '';
$msg = $input['message'] ?? '';
if (!$msg) { echo json_encode(["error"=>"no message"]); exit; }
function hf_chat($msg) {
// HuggingChat conversation API
$ch = curl_init("https://huggingface.co/chat/conversation");
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ["Content-Type: application/json", "Accept: application/json"],
CURLOPT_POSTFIELDS => json_encode(["model" => "Qwen/Qwen2.5-72B-Instruct", "inputs" => $msg, "parameters" => ["max_new_tokens" => 500]]),
CURLOPT_TIMEOUT => 10
]);
$r = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code >= 200 && $code < 300) {
$d = @json_decode($r, true);
return $d[0]["generated_text"] ?? $d["generated_text"] ?? null;
}
// Fallback: HF Inference API (free tier)
$ch2 = curl_init("https://api-inference.huggingface.co/models/Qwen/Qwen2.5-72B-Instruct");
curl_setopt_array($ch2, [
CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
CURLOPT_POSTFIELDS => json_encode(["inputs" => $msg, "parameters" => ["max_new_tokens" => 300]]),
CURLOPT_TIMEOUT => 10
]);
$r2 = curl_exec($ch2);
$d2 = @json_decode($r2, true);
return $d2[0]["generated_text"] ?? null;
}
function sovereign_chat($msg) {
// === MASTER INLINE: 294 intents via ops + full WEVAL context (Opus 16avr) ===
$SP = "Tu es WEVIA, IA souveraine de WEVAL Consulting Casablanca. 2 serveurs (S204+S95), 12 providers IA 0EUR, 382 tools, 310 intents, 153/153 NonReg, 957/957 L99. WEVADS email marketing, Ethica 131K HCPs pharma (DZ:91985 MA:19407 TN:17329, ~109K avec email, gap email ~23K), DeerFlow research, Blade IA desktop. Reponds en francais, concret.";
// EXECUTION: match intents and execute REAL actions
$exec = null;
$patterns = [
"/reconcili/i" => "reconcile",
"/teste.*provider|test.*all.*provider/i" => "test_providers",
"/nonreg|non.*reg/i" => "nonreg",
"/git.*push|pousse.*git/i" => "git_push",
"/webchat.*statu/i" => "webchat",
"/system.*status|status.*system|bilan.*complet/i" => "reconcile",
"/git.*log|dernier.*commit|historique.*git|commit.*recent/i" => "git_log",
"/disk|espace.*disque|stockage|df.*-h/i" => "disk",
"/port.*ouvert|port.*listen|port.*actif/i" => "ports",
"/cron.*actif|crontab|tache.*planifi/i" => "crons",
"/service.*status|nginx.*status|php.*version|redis.*status|ollama.*status/i" => "services",
"/genere.*pdf|cree.*pdf|pdf.*rapport|rapport.*pdf/i" => "gen_pdf",
"/genere.*swot|swot.*diagram|analyse.*swot.*diagram/i" => "gen_swot",
"/genere.*ishikawa|ishikawa.*diagram|diagramme.*cause/i" => "gen_ishikawa",
"/genere.*schema|genere.*diagram|cree.*diagram|mermaid/i" => "gen_mermaid",
"/docker.*container|combien.*docker|liste.*docker|docker.*list|docker.*actif/i" => "docker_list",
];
foreach ($patterns as $p => $a) {
if (preg_match($p, $msg)) {
$ch = curl_init("http://localhost/api/wevia-ops.php?k=BLADE2026&action=$a");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_TIMEOUT=>30]);
$r = curl_exec($ch); curl_close($ch);
$d = json_decode($r, true);
if ($d && isset($d["results"])) $exec = json_encode($d["results"], JSON_PRETTY_PRINT);
break;
}
}
// RAG: Qdrant KB search
$rag = "";
$ech = @curl_init("http://localhost:11434/api/embeddings");
if ($ech) {
curl_setopt_array($ech, [CURLOPT_POST=>true,CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>2,
CURLOPT_HTTPHEADER=>["Content-Type: application/json"],
CURLOPT_POSTFIELDS=>json_encode(["model"=>"nomic-embed-text","prompt"=>$msg])]);
$er = @json_decode(curl_exec($ech),true); curl_close($ech);
if (isset($er["embedding"])) {
$qch = @curl_init("http://localhost:6333/collections/wevia_kb/points/search");
curl_setopt_array($qch,[CURLOPT_POST=>true,CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>2,
CURLOPT_HTTPHEADER=>["Content-Type: application/json"],
CURLOPT_POSTFIELDS=>json_encode(["vector"=>$er["embedding"],"limit"=>3,"with_payload"=>true])]);
$qr = @json_decode(curl_exec($qch),true); curl_close($qch);
foreach(($qr["result"]??[]) as $h) { $t=$h["payload"]["text"]??$h["payload"]["content"]??""; if($t) $rag.=substr($t,0,400)."\n"; }
}
}
// Build enhanced prompt
$sys = $SP;
if ($rag) $sys .= "\n\nCONTEXTE KB:\n" . $rag;
if ($exec) $sys .= "\n\nRESULTAT EXECUTION REELLE:\n" . $exec . "\n\nPresente ces resultats reels clairement. Ce sont des donnees live du serveur.";
// LLM cascade
$msgs = [["role"=>"system","content"=>$sys],["role"=>"user","content"=>$msg]];
$provs = [
["url"=>"https://api.cerebras.ai/v1/chat/completions","key"=>"csk-fyccfew4yw2rxnvfkemrrp42pmxrf85v9pmheh3xd9e6cvvy","model"=>"llama-4-scout-17b-16e-instruct"],
["url"=>"https://api.groq.com/openai/v1/chat/completions","key"=>"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","model"=>"llama-3.1-8b-instant"],
];
foreach($provs as $p) {
$ch=curl_init($p["url"]);
curl_setopt_array($ch,[CURLOPT_POST=>true,CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>10,
CURLOPT_HTTPHEADER=>["Content-Type: application/json","Authorization: Bearer ".$p["key"]],
CURLOPT_POSTFIELDS=>json_encode(["model"=>$p["model"],"messages"=>$msgs,"max_tokens"=>800])]);
$r=curl_exec($ch);$d=@json_decode($r,true);
$text=$d["choices"][0]["message"]["content"]??null;
if($text) return $text;
}
if ($exec) return "Execution reussie:\n".$exec;
return null;
}
// Route by service
$content = null;
$provider = "WebChat-Direct-" . $service;
// DeepSeek Arena model aliases (Opus 16avr)
if ($service === "deepseek-web" || $service === "deepseek-web-think" || $service === "deepseek-web-search") {
$service = "deepseek";
}
switch ($service) {
case 'huggingchat':
$content = hf_chat($msg);
if ($content) $provider = "HuggingChat Direct API";
break;
// All others: try Playwright first (port 8902, 5s), then sovereign
default:
$ch = curl_init("http://127.0.0.1:8902/chat");
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_POST=>true,
CURLOPT_POSTFIELDS=>json_encode(["service"=>$service, "message"=>$msg]),
CURLOPT_HTTPHEADER=>["Content-Type: application/json"], CURLOPT_TIMEOUT=>2]);
$r = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code === 200) {
$d = @json_decode($r, true);
if (!empty($d["content"])) { $content = $d["content"]; $provider = "WebChat-Playwright-" . $service; }
}
break;
}
// Sovereign fallback
if (!$content) {
$content = sovereign_chat($msg);
$provider = "Web+" . $service . " (sovereign)";
}
echo json_encode([
"content" => $content ?: "Service $service indisponible",
"provider" => $provider,
"cost" => "0EUR ILLIMITE",
"service" => $service
], JSON_UNESCAPED_UNICODE);