36584-vm/api/index.php
2025-12-02 14:17:38 +00:00

61 lines
2.2 KiB
PHP

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header('Content-Type: application/json');
require_once __DIR__ . '/../ai/LocalAIApi.php';
require_once __DIR__ . '/../includes/pexels.php';
$requestBody = file_get_contents('php://input');
$data = json_decode($requestBody, true);
$query = $data['query'] ?? '';
if (empty($query)) {
echo json_encode(['error' => 'Query is empty']);
exit;
}
$resp = LocalAIApi::createResponse(
[
'input' => [
['role' => 'system', 'content' => 'You are a travel agent specializing in Poland. The user is looking for: ' . $query . '. Provide a travel suggestion with a title and a description. Your response must be in JSON format, like this: {"title": "...", "description": "..."}'],
['role' => 'user', 'content' => $query],
],
]
);
if (!empty($resp['success'])) {
$text = LocalAIApi::extractText($resp);
$aiResponse = json_decode($text, true);
if (json_last_error() !== JSON_ERROR_NONE) {
// If the response is not a valid JSON, we try to extract the title and description manually
// This is a fallback mechanism
$title = "AI Generated Response";
$description = $text;
} else {
$title = $aiResponse['title'] ?? 'AI Generated Response';
$description = $aiResponse['description'] ?? 'No description available.';
}
$pexelsUrl = 'https://api.pexels.com/v1/search?query=' . urlencode($title) . '&orientation=landscape&per_page=1&page=1';
$pexelsData = pexels_get($pexelsUrl);
$imageUrl = 'https://images.pexels.com/photos/1699030/pexels-photo-1699030.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1'; // Default image
if ($pexelsData && !empty($pexelsData['photos'])) {
$photo = $pexelsData['photos'][0];
$imageUrl = $photo['src']['large2x'] ?? ($photo['src']['large'] ?? $photo['src']['original']);
}
echo json_encode([
'title' => $title,
'description' => $description,
'image' => $imageUrl
]);
} else {
error_log('AI error: ' . ($resp['error'] ?? 'unknown'));
echo json_encode(['error' => 'Failed to get AI response']);
}