ChatRAG / rag_integration.php
Binayak Panigrahi
Add application file
f0f26c7
<?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' => []
]);
}
?>