Files
wevia-brain/modules/api-wrapper.php
2026-04-12 23:01:36 +02:00

140 lines
5.1 KiB
PHP
Executable File

<?php
/**
* ╔══════════════════════════════════════════════════════════╗
* ║ WEVIA OPUS — Unified API Wrapper ║
* ║ Single endpoint for all brain capabilities ║
* ║ GET /api-wrapper.php?action=... ║
* ║ POST /api-wrapper.php (JSON body) ║
* ╚══════════════════════════════════════════════════════════╝
*/
error_reporting(0);
header("Content-Type: application/json; charset=utf-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") exit;
require_once __DIR__ . '/opus-orchestrator.php';
$input = json_decode(file_get_contents("php://input"), true) ?: [];
$action = $input['action'] ?? $_GET['action'] ?? 'chat';
$orchestrator = new OpusOrchestrator([
'ollama_url' => 'http://127.0.0.1:11434',
'db_host' => '127.0.0.1',
'db_name' => 'wevia_db',
'db_user' => 'postgres'
]);
switch ($action) {
case 'chat':
$message = $input['message'] ?? '';
if (!$message) die(json_encode(['error' => 'Empty message']));
$result = $orchestrator->process($message, [
'session_id' => $input['session'] ?? 'api',
'capability' => $input['capability'] ?? 'normal',
'model' => $input['model'] ?? null,
'temperature' => $input['temperature'] ?? 0.7,
'max_tokens' => $input['max_tokens'] ?? 4096
]);
echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
break;
case 'models':
// List available Ollama models
$ch = curl_init('http://127.0.0.1:11434/api/tags');
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 5]);
$raw = curl_exec($ch);
curl_close($ch);
$data = json_decode($raw, true);
$models = [];
foreach (($data['models'] ?? []) as $m) {
$models[] = [
'name' => $m['name'],
'size_gb' => round($m['size'] / 1e9, 1),
'modified' => $m['modified_at'] ?? ''
];
}
echo json_encode(['models' => $models, 'count' => count($models)]);
break;
case 'kb_stats':
try {
$pdo = new PDO("pgsql:host=127.0.0.1;dbname=wevia_db", "postgres", "");
$rag = new RAGEngine($pdo);
echo json_encode($rag->getStats());
} catch (\Exception $e) {
echo json_encode(['error' => $e->getMessage()]);
}
break;
case 'kb_ingest':
$text = $input['text'] ?? '';
$source = $input['source'] ?? 'api';
$category = $input['category'] ?? 'general';
if (!$text) die(json_encode(['error' => 'Empty text']));
try {
$pdo = new PDO("pgsql:host=127.0.0.1;dbname=wevia_db", "postgres", "");
$rag = new RAGEngine($pdo);
$chunks = $rag->ingest($text, $source, $category);
echo json_encode(['success' => true, 'chunks_created' => $chunks]);
} catch (\Exception $e) {
echo json_encode(['error' => $e->getMessage()]);
}
break;
case 'health':
$checks = [];
// Ollama
$ch = curl_init('http://127.0.0.1:11434/api/tags');
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 3]);
$raw = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$checks['ollama'] = $code === 200;
// GPU
$gpu = trim(shell_exec("nvidia-smi --query-gpu=memory.used,memory.total --format=csv,noheader 2>/dev/null"));
$checks['gpu'] = !empty($gpu);
$checks['gpu_info'] = $gpu;
// DB
try {
$pdo = new PDO("pgsql:host=127.0.0.1;dbname=wevia_db", "postgres", "");
$checks['database'] = true;
} catch (\Exception $e) {
$checks['database'] = false;
}
// Disk
$disk = trim(shell_exec("df -h / | tail -1 | awk '{print \$5}'"));
$checks['disk_usage'] = $disk;
$checks['brain_modules'] = count(glob(__DIR__ . '/*.php'));
$checks['kb_files'] = count(glob(__DIR__ . '/../knowledge/*.json'));
echo json_encode([
'status' => 'operational',
'checks' => $checks,
'timestamp' => date('c')
], JSON_PRETTY_PRINT);
break;
case 'metrics':
echo json_encode($orchestrator->getMetrics());
break;
default:
echo json_encode([
'error' => 'Unknown action',
'available' => ['chat', 'models', 'kb_stats', 'kb_ingest', 'health', 'metrics']
]);
}