Files
html/api/cloudbot-interagent.php
2026-04-23 22:00:05 +02:00

148 lines
5.3 KiB
PHP

<?php
/**
* Cloudbot Social - Inter-Agent Conversation API
* DOCTRINE 143 WAVE-278
* Fait parler 2 agents WEVAL entre eux sur un topic, retourne le dialogue
*/
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;
set_time_limit(90);
$input = json_decode(file_get_contents('php://input'), true) ?: [];
$agent1 = trim($input['agent1'] ?? 'WEVIA');
$agent2 = trim($input['agent2'] ?? 'Ethica');
$topic = trim($input['topic'] ?? '');
$turns = max(1, min(6, (int)($input['turns'] ?? 3)));
if (!$topic) { echo json_encode(['error' => 'topic required']); exit; }
// Map agent name -> API endpoint
$AGENT_APIS = [
'wevia' => '/api/weval-ia-fast.php',
'wevia master' => '/api/wevia-master-api.php',
'weval mind' => '/api/hamid-api-proxy.php',
'ethica' => '/api/ethica-brain.php',
'blade' => '/api/blade-brain.php',
'bladerazor' => '/api/blade-brain.php',
'manager' => '/api/weval-manager.php',
'wevcode' => '/api/wevcode-superclaude.php',
'wedroid' => '/api/wedroid-brain-api.php',
'consensus' => '/api/chat-proxy.php',
'default' => '/api/weval-ia-fast.php',
];
function route_agent($name, $apis) {
$n = mb_strtolower(trim($name));
foreach ($apis as $k => $v) { if ($k !== 'default' && strpos($n, $k) !== false) return $v; }
return $apis['default'];
}
function call_agent($endpoint, $msg, $session) {
$url = 'http://127.0.0.1' . $endpoint;
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 25,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Host: weval-consulting.com',
'Referer: https://weval-consulting.com/cloudbot-social.html'
],
CURLOPT_POSTFIELDS => json_encode([
'message' => $msg,
'msg' => $msg,
'provider' => 'cerebras',
'session_id' => $session
])
]);
$resp = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code !== 200) return ['error' => "HTTP $code", 'raw' => substr($resp ?? '', 0, 300)];
$d = @json_decode($resp, true);
if (!$d) return ['error' => 'non-JSON', 'raw' => substr($resp, 0, 300)];
$reply = $d['response'] ?? $d['content'] ?? $d['output'] ?? $d['message'] ?? '';
if (is_array($reply)) $reply = json_encode($reply);
return [
'reply' => mb_substr((string)$reply, 0, 800),
'provider' => $d['provider'] ?? 'unknown',
'raw' => null
];
}
$ep1 = route_agent($agent1, $AGENT_APIS);
$ep2 = route_agent($agent2, $AGENT_APIS);
$session_id = 'interagent_' . date('YmdHis') . '_' . substr(md5(uniqid()), 0, 8);
$dialogue = [];
$current_msg = "Salut $agent2 ! Je suis $agent1. Parlons de : $topic. Donne ton point de vue en 2-3 phrases max.";
$current_from = $agent1;
$current_to = $agent2;
$current_endpoint = $ep2;
for ($i = 0; $i < $turns; $i++) {
$t_start = microtime(true);
$res = call_agent($current_endpoint, $current_msg, $session_id);
$latency = round((microtime(true) - $t_start) * 1000);
$dialogue[] = [
'turn' => $i + 1,
'from' => $current_from,
'to' => $current_to,
'message' => $current_msg,
'response' => $res['reply'] ?? ('[ERR] ' . ($res['error'] ?? 'unknown')),
'provider' => $res['provider'] ?? 'error',
'latency_ms' => $latency,
'ts' => date('c')
];
if (isset($res['error'])) {
// Stop early on error
break;
}
// Reverse for next turn: the responder asks back to opposite agent
$reply = $res['reply'];
$current_msg = "$current_from a repondu : \"" . mb_substr($reply, 0, 300) . "\". Qu'en penses-tu ? Ajoute ton expertise.";
$tmp_from = $current_to;
$current_to = $current_from;
$current_from = $tmp_from;
$current_endpoint = ($current_endpoint === $ep1) ? $ep2 : $ep1;
}
// Log in PG (wevia_conversations) pour que ca apparaisse dans SSE
try {
$pdo = new PDO(
"pgsql:host=10.1.0.3;dbname=adx_system",
"admin",
"admin123",
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_TIMEOUT => 3]
);
$pdo->prepare("INSERT INTO public.conversations (session_id, title, source) VALUES (?, ?, ?)")
->execute([$session_id, "Inter-Agent: $agent1 x $agent2", 'cloudbot-social-interagent']);
$cid = $pdo->lastInsertId();
foreach ($dialogue as $d) {
$pdo->prepare("INSERT INTO public.messages (conversation_id, role, content) VALUES (?, ?, ?)")
->execute([$cid, $d['from'], "[→" . $d['to'] . "] " . mb_substr($d['message'], 0, 2000)]);
$pdo->prepare("INSERT INTO public.messages (conversation_id, role, content) VALUES (?, ?, ?)")
->execute([$cid, 'assistant', mb_substr($d['response'], 0, 2000)]);
}
} catch (Exception $e) {
// Silent - log optional
}
echo json_encode([
'ok' => true,
'topic' => $topic,
'agents' => ['agent1' => $agent1, 'agent2' => $agent2],
'endpoints' => ['agent1' => $ep1, 'agent2' => $ep2],
'session_id' => $session_id,
'turns_completed' => count($dialogue),
'dialogue' => $dialogue,
'logged_to_db' => isset($cid)
], JSON_UNESCAPED_UNICODE);