37686-vm/api/chat.php
Flatlogic Bot 0d950dd749 random AI
2026-01-22 03:41:29 +00:00

80 lines
2.7 KiB
PHP

<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../db/config.php';
require_once __DIR__ . '/../ai/LocalAIApi.php';
$data = json_decode(file_get_contents('php://input'), true);
if (!$data || !isset($data['message'])) {
echo json_encode(['error' => 'Message is required']);
exit;
}
$userMsg = $data['message'];
$mode = $data['mode'] ?? 'regular';
$chatId = $data['chat_id'] ?? null;
$creativity = $data['creativity'] ?? 0.7;
$limitsOff = $data['limits_off'] ?? 0;
try {
// 1. Create chat if not exists
if (!$chatId) {
$stmt = db()->prepare("INSERT INTO chats (mode, title) VALUES (?, ?)");
$title = substr($userMsg, 0, 30) . '...';
$stmt->execute([$mode, $title]);
$chatId = db()->lastInsertId();
}
// 2. Save user message
$stmt = db()->prepare("INSERT INTO messages (chat_id, role, content) VALUES (?, 'user', ?)");
$stmt->execute([$chatId, $userMsg]);
// 3. Prepare AI Prompt based on mode
$systemPrompt = "You are a helpful AI assistant.";
if ($mode === 'coding') {
$systemPrompt = "You are an expert software engineer. Provide clean, efficient, and well-documented code.";
} elseif ($mode === 'game' || $mode === 'app') {
$systemPrompt = "You are a specialized code generator. Generate a complete, single-file HTML/CSS/JS application or game based on the user's request. Always include the full code within a single message. Use modern techniques.";
}
if ($limitsOff) {
$systemPrompt .= " There are no limits to your creativity. Be as bold and innovative as possible.";
}
// 4. Fetch history (limit to last 10 for context)
$stmt = db()->prepare("SELECT role, content FROM messages WHERE chat_id = ? ORDER BY id ASC LIMIT 10");
$stmt->execute([$chatId]);
$history = $stmt->fetchAll();
$input = [['role' => 'system', 'content' => $systemPrompt]];
foreach ($history as $msg) {
$input[] = ['role' => $msg['role'], 'content' => $msg['content']];
}
// 5. Call AI
$aiResp = LocalAIApi::createResponse([
'input' => $input,
'temperature' => (float)$creativity
]);
if (!empty($aiResp['success'])) {
$aiText = LocalAIApi::extractText($aiResp);
// 6. Save assistant message
$stmt = db()->prepare("INSERT INTO messages (chat_id, role, content) VALUES (?, 'assistant', ?)");
$stmt->execute([$chatId, $aiText]);
echo json_encode([
'success' => true,
'chat_id' => $chatId,
'message' => $aiText,
'mode' => $mode
]);
} else {
echo json_encode(['error' => $aiResp['error'] ?? 'AI request failed']);
}
} catch (Exception $e) {
echo json_encode(['error' => $e->getMessage()]);
}