real_escape_string($category); $query .= " AND category = '$category'"; } $query .= " LIMIT $limit"; $result = $conn->query($query); if (!$result) { error_log("Database error in get_products_for_rag: " . $conn->error); return []; } $products = []; while ($row = $result->fetch_assoc()) { $products[] = [ 'id' => (int)$row['id'], 'name' => $row['name'], 'description' => $row['description'], 'price' => (float)$row['price'], 'category' => $row['category'], 'brand' => $row['brand'] ?? null, 'image_path' => $row['image_path'] ?? null, 'rating' => $row['rating'] ?? null, ]; } return $products; } /** * Call the RAG API for product recommendations * * @param string $query User's natural language query * @param array $products Array of product objects * @param int $top_k Number of top recommendations to return * @return array|false Response from RAG API or false on error */ function call_rag_api($query, $products, $top_k = 5) { if (!$query || empty($products)) { error_log("RAG API error: Empty query or products"); return false; } // Prepare payload $payload = [ 'query' => $query, 'products' => $products, 'top_k' => $top_k ]; // Make POST request to RAG API $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, RAG_API_URL . RAG_ENDPOINT); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload)); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Accept: application/json' ]); curl_setopt($ch, CURLOPT_TIMEOUT, 30); $response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curl_error = curl_error($ch); curl_close($ch); // Handle curl errors if ($curl_error) { error_log("RAG API curl error: $curl_error"); return false; } // Handle HTTP errors if ($http_code !== 200) { error_log("RAG API HTTP error: $http_code - $response"); return false; } // Parse and return response $data = json_decode($response, true); if (!$data) { error_log("RAG API response parse error: " . json_last_error_msg()); return false; } return $data; } /** * Check if RAG API is healthy * * @return bool True if API is responsive */ function check_rag_health() { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, RAG_API_URL . '/health'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return $http_code === 200; } /** * Main function: Get AI recommendations for user query * This is the primary function to call from your chat endpoint * * @param mysqli $conn Database connection * @param string $user_query User's question/query * @param string $category Optional product category to search in * @return array Response containing message and products */ function get_rag_recommendations($conn, $user_query, $category = null) { // Check RAG API health if (!check_rag_health()) { error_log("RAG API is not available"); return [ 'success' => false, 'message' => 'Recommendation service temporarily unavailable', 'products' => [] ]; } // Fetch products from database $products = get_products_for_rag($conn, $category, 50); if (empty($products)) { return [ 'success' => false, 'message' => 'No products available for recommendation', 'products' => [] ]; } // Call RAG API $rag_response = call_rag_api($user_query, $products, 5); if (!$rag_response) { error_log("Failed to get RAG recommendations"); return [ 'success' => false, 'message' => 'Failed to generate recommendations', 'products' => [] ]; } return [ 'success' => true, 'message' => $rag_response['message'] ?? 'No message', 'products' => $rag_response['products'] ?? [], 'timestamp' => $rag_response['timestamp'] ?? date('c') ]; } // ── Example Usage (if this file is called directly) ────────────────────────── if ($_SERVER['REQUEST_METHOD'] === 'POST' && php_sapi_name() !== 'cli') { header('Content-Type: application/json'); $input = json_decode(file_get_contents('php://input'), true); $query = $input['query'] ?? ''; if (!$query) { http_response_code(400); echo json_encode(['error' => 'Query is required']); exit; } // Include your database connection // require_once 'db.php'; // Uncomment below when integrated with your system: // $result = get_rag_recommendations($conn, $query); // echo json_encode($result); // For now, return example response echo json_encode([ 'success' => true, 'message' => 'RAG API integration ready. Call get_rag_recommendations($conn, $query) from your chat handler.', 'products' => [] ]); } ?>