36427-vm/api/chat.php
Flatlogic Bot 2f8a204b48 123
2025-11-28 12:21:10 +00:00

76 lines
2.7 KiB
PHP

<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../ai/LocalAIApi.php';
require_once __DIR__ . '/../includes/pexels.php';
$action = $_POST['action'] ?? 'chat';
if ($action === 'chat') {
$day = $_POST['day'] ?? 'good';
$profession = $_POST['profession'] ?? 'programmer';
// 1. Generate content with AI using a JSON-structured prompt
$prompt = <<<PROMPT
A user had a "{$day}" day at their job as a "{$profession}".
Please generate a response in JSON format with two keys:
1. "wish": A short, funny, and cheerful weekend wish for them.
2. "meme_keyword": A single, simple, SFW (safe for work) keyword for a funny meme image related to their situation.
Example:
{
"wish": "Your code fought bravely, now let your weekend be bug-free! Enjoy the break!",
"meme_keyword": "relaxing cat"
}
PROMPT;
$aiResponse = LocalAIApi::createResponse([
'input' => [
['role' => 'system', 'content' => 'You are a cheerful and witty assistant who provides funny weekend wishes and suggests meme keywords in a structured JSON format.'],
['role' => 'user', 'content' => $prompt],
],
]);
$generatedText = "I'm a bit tired, but I wish you a fantastic weekend! Let's talk more on Monday.";
$memeKeyword = 'cat'; // Default keyword
if (!empty($aiResponse['success'])) {
$jsonOutput = LocalAIApi::decodeJsonFromResponse($aiResponse);
if ($jsonOutput && isset($jsonOutput['wish']) && isset($jsonOutput['meme_keyword'])) {
$generatedText = $jsonOutput['wish'];
$memeKeyword = $jsonOutput['meme_keyword'];
} else {
$generatedText = LocalAIApi::extractText($aiResponse); // Fallback to raw text
}
}
// 2. Fetch a meme image using the keyword
$memeData = null;
$pexelsUrl = 'https://api.pexels.com/v1/search?query=' . urlencode($memeKeyword) . '&orientation=portrait&per_page=1&page=1';
$pexelsData = pexels_get($pexelsUrl);
if ($pexelsData && !empty($pexelsData['photos'])) {
$photo = $pexelsData['photos'][0];
$src = $photo['src']['large'] ?? $photo['src']['original'];
$memeData = [
'src' => $src,
'photographer' => $photo['photographer']
];
} else {
// Fallback image
$memeData = [
'src' => 'https://images.pexels.com/photos/1741205/pexels-photo-1741205.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
'photographer' => 'Pexels'
];
}
echo json_encode([
'success' => true,
'message' => $generatedText,
'meme' => $memeData
]);
exit;
}
echo json_encode(['success' => false, 'error' => 'Invalid action.']);