ask the AI course advisor // JSON body: {messages: [{role: 'user'|'assistant', content: string}, ...]} // (the whole conversation so far; the last entry is the question) // Response: {answer, recommended: [{folder_id, order, reason, course}], // courses: {"412": {folder_id, name}, ...} (the "#412" mentions // in `answer`, resolved so the browser can link them), // from_ine: [{catalog_id, name, difficulty, vendor, url, reason}], // missing_prerequisites: [...], degraded, // usage: {prompt_tokens, cache_hit_tokens, completion_tokens, // reasoning_tokens, remaining_today}} // 503 when the advisor is switched off, 429 past the daily cap, // 502 when the AI service could not answer. require_once __DIR__ . '/../includes/auth.php'; require_once __DIR__ . '/../includes/advisor.php'; header('Content-Type: application/json'); $userId = requireLoginApi(); if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['error' => 'Method not allowed']); exit; } $data = json_decode(file_get_contents('php://input'), true) ?: []; verifyCsrfApi($data); if (!aiEnabled()) { http_response_code(503); echo json_encode(['error' => 'The course advisor is switched off on this install.', 'advisor' => false]); exit; } try { $messages = advisorNormalizeMessages($data['messages'] ?? null); } catch (InvalidArgumentException $e) { http_response_code(400); echo json_encode(['error' => $e->getMessage()]); exit; } $limit = advisorLimit(); $used = advisorUsedToday($userId); if ($used >= $limit) { http_response_code(429); echo json_encode([ 'error' => "You have used today's $limit advisor question" . ($limit === 1 ? '' : 's') . ' — the count resets over the next 24 hours.', 'remaining_today' => 0, ]); exit; } $requestId = advisorRecordUse($userId); set_time_limit(120); try { $result = advisorAsk($userId, $messages); } catch (AiRejected | AiUnavailable | AiBadReply $e) { http_response_code(502); echo json_encode(['error' => $e->getMessage()]); exit; } advisorMarkOk($requestId, $result['usage'], $result['model']); $result['usage']['remaining_today'] = max(0, $limit - $used - 1); unset($result['model']); echo json_encode($result);