File size: 6,654 Bytes
f0f26c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
<?php
/**
 * RAG Integration for Chat - PHP Integration Layer
 * Connects PHP backend with Python RAG API (powered by NVIDIA Mistral)
 * 
 * This file provides functions to:
 * 1. Fetch products from database
 * 2. Call the RAG API
 * 3. Format and return responses to the frontend
 * 
 * The RAG API uses:
 * - Sentence-Transformers for semantic search
 * - FAISS for vector similarity
 * - NVIDIA Mistral models for intelligent recommendations
 */

// Configuration
define('RAG_API_URL', getenv('RAG_API_URL') ?: 'http://localhost:8004');
define('RAG_ENDPOINT', '/search-products');

/**
 * Fetch products from database
 * Customize this function based on your database schema
 * 
 * @param mysqli $conn Database connection
 * @param string $category Optional category filter
 * @param int $limit Max products to fetch
 * @return array Array of product objects
 */
function get_products_for_rag($conn, $category = null, $limit = 50) {
    $query = "SELECT id, name, description, price, category, brand, image_path, rating 
              FROM products 
              WHERE status = 'active'";
    
    if ($category) {
        $category = $conn->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' => []
    ]);
}
?>