Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0490892e31 | ||
|
|
b86f18f85f |
2
.env
Normal file
2
.env
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
OPENAI_API_KEY=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
|
||||||
|
OPENAI_MODEL=gpt-4o
|
||||||
2
.env.example
Normal file
2
.env.example
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
OPENAI_API_KEY=
|
||||||
|
OPENAI_MODEL=gpt-4o-mini
|
||||||
92
api/chat.php
Normal file
92
api/chat.php
Normal file
@ -0,0 +1,92 @@
|
|||||||
|
<?php
|
||||||
|
ini_set('display_errors', 1);
|
||||||
|
ini_set('display_startup_errors', 1);
|
||||||
|
error_reporting(E_ALL);
|
||||||
|
|
||||||
|
session_start();
|
||||||
|
|
||||||
|
$logFile = __DIR__ . '/error.log';
|
||||||
|
// Clear the log file for each request to ensure we're only seeing the latest error.
|
||||||
|
file_put_contents($logFile, "");
|
||||||
|
|
||||||
|
// This is the top-level error handler.
|
||||||
|
// It will catch any exception that isn't caught elsewhere.
|
||||||
|
set_exception_handler(function($exception) use ($logFile) {
|
||||||
|
http_response_code(500);
|
||||||
|
$error = [
|
||||||
|
'error' => 'An unexpected error occurred.',
|
||||||
|
'message' => $exception->getMessage(),
|
||||||
|
'file' => $exception->getFile(),
|
||||||
|
'line' => $exception->getLine(),
|
||||||
|
];
|
||||||
|
file_put_contents($logFile, json_encode($error, JSON_PRETTY_PRINT));
|
||||||
|
// We must output valid JSON, otherwise the frontend will get a syntax error.
|
||||||
|
echo json_encode($error);
|
||||||
|
});
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../lib/config.php';
|
||||||
|
require_once __DIR__ . '/../lib/OpenAIService.php';
|
||||||
|
require_once __DIR__ . '/../db/config.php';
|
||||||
|
|
||||||
|
// The main try-catch block for the application logic.
|
||||||
|
try {
|
||||||
|
|
||||||
|
// Check if it's a POST request
|
||||||
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||||
|
http_response_code(405); // Method Not Allowed
|
||||||
|
throw new Exception('Only POST requests are allowed.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the user's message from the request body
|
||||||
|
$json_data = file_get_contents('php://input');
|
||||||
|
$data = json_decode($json_data);
|
||||||
|
$user_message = $data->message ?? '';
|
||||||
|
|
||||||
|
if (empty($user_message)) {
|
||||||
|
http_response_code(400); // Bad Request
|
||||||
|
throw new Exception('Message is required.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Database Interaction ---
|
||||||
|
$pdo = db();
|
||||||
|
if (empty($_SESSION['chat_session_id'])) {
|
||||||
|
$_SESSION['chat_session_id'] = bin2hex(random_bytes(16));
|
||||||
|
}
|
||||||
|
$chat_session_id = $_SESSION['chat_session_id'];
|
||||||
|
|
||||||
|
// Log the user's message
|
||||||
|
$stmt = $pdo->prepare("INSERT INTO chat_log (session_id, sender, message) VALUES (?, ?, ?)");
|
||||||
|
$stmt->execute([$chat_session_id, 'user', $user_message]);
|
||||||
|
|
||||||
|
// --- OpenAI API Call ---
|
||||||
|
$bot_response_data = OpenAIService::getCompletion($user_message);
|
||||||
|
|
||||||
|
if (isset($bot_response_data['error'])) {
|
||||||
|
throw new Exception('OpenAI API Error: ' . $bot_response_data['error']);
|
||||||
|
}
|
||||||
|
$bot_response = $bot_response_data['reply'];
|
||||||
|
|
||||||
|
// Log the bot's response
|
||||||
|
$stmt = $pdo->prepare("INSERT INTO chat_log (session_id, sender, message) VALUES (?, ?, ?)");
|
||||||
|
$stmt->execute([$chat_session_id, 'bot', $bot_response]);
|
||||||
|
|
||||||
|
// --- Send Response ---
|
||||||
|
header('Content-Type: application/json');
|
||||||
|
echo json_encode(['reply' => $bot_response]);
|
||||||
|
|
||||||
|
} catch (Throwable $e) {
|
||||||
|
// This will catch both Exceptions and Errors
|
||||||
|
http_response_code(500);
|
||||||
|
$errorDetails = [
|
||||||
|
'error' => 'Caught in main try-catch',
|
||||||
|
'message' => $e->getMessage(),
|
||||||
|
'file' => $e->getFile(),
|
||||||
|
'line' => $e->getLine(),
|
||||||
|
'trace' => $e->getTraceAsString()
|
||||||
|
];
|
||||||
|
file_put_contents($logFile, date('Y-m-d H:i:s') . " - " . json_encode($errorDetails, JSON_PRETTY_PRINT) . "
|
||||||
|
", FILE_APPEND);
|
||||||
|
// Ensure a JSON response is sent on error
|
||||||
|
header('Content-Type: application/json');
|
||||||
|
echo json_encode($errorDetails);
|
||||||
|
}
|
||||||
7
api/error.log
Normal file
7
api/error.log
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
2025-09-11 22:08:09 - {
|
||||||
|
"error": "Caught in main try-catch",
|
||||||
|
"message": "Only POST requests are allowed.",
|
||||||
|
"file": "\/home\/ubuntu\/executor\/workspace\/api\/chat.php",
|
||||||
|
"line": 37,
|
||||||
|
"trace": "#0 {main}"
|
||||||
|
}
|
||||||
93
assets/css/custom.css
Normal file
93
assets/css/custom.css
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
body {
|
||||||
|
font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||||
|
background-color: #F3F4F6;
|
||||||
|
margin: 0;
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-container {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 600px;
|
||||||
|
height: 100%;
|
||||||
|
max-height: 800px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
background-color: #FFFFFF;
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-header {
|
||||||
|
background: linear-gradient(90deg, #4F46E5, #6D28D9);
|
||||||
|
color: white;
|
||||||
|
padding: 16px;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-box {
|
||||||
|
flex-grow: 1;
|
||||||
|
padding: 16px;
|
||||||
|
overflow-y: auto;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-message {
|
||||||
|
padding: 10px 16px;
|
||||||
|
border-radius: 18px;
|
||||||
|
max-width: 75%;
|
||||||
|
word-wrap: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-message {
|
||||||
|
background-color: #4F46E5;
|
||||||
|
color: white;
|
||||||
|
align-self: flex-end;
|
||||||
|
border-bottom-right-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ai-message {
|
||||||
|
background-color: #E5E7EB;
|
||||||
|
color: #1F2937;
|
||||||
|
align-self: flex-start;
|
||||||
|
border-bottom-left-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-footer {
|
||||||
|
padding: 16px;
|
||||||
|
border-top: 1px solid #E5E7EB;
|
||||||
|
}
|
||||||
|
|
||||||
|
#chat-form {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#message-input {
|
||||||
|
flex-grow: 1;
|
||||||
|
border: 1px solid #D1D5DB;
|
||||||
|
padding: 12px;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
#chat-form button {
|
||||||
|
background-color: #4F46E5;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
padding: 12px 20px;
|
||||||
|
border-radius: 8px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 1rem;
|
||||||
|
transition: background-color 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
#chat-form button:hover {
|
||||||
|
background-color: #4338CA;
|
||||||
|
}
|
||||||
66
assets/js/main.js
Normal file
66
assets/js/main.js
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
const chatForm = document.getElementById('chat-form');
|
||||||
|
const messageInput = document.getElementById('message-input');
|
||||||
|
const chatBox = document.getElementById('chat-box');
|
||||||
|
|
||||||
|
// Load chat history on page load
|
||||||
|
function loadChatHistory() {
|
||||||
|
if (window.chatHistory && window.chatHistory.length > 0) {
|
||||||
|
window.chatHistory.forEach(item => {
|
||||||
|
appendMessage(item.message, item.sender);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
chatForm.addEventListener('submit', async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
const message = messageInput.value.trim();
|
||||||
|
if (!message) return;
|
||||||
|
|
||||||
|
appendMessage(message, 'user');
|
||||||
|
messageInput.value = '';
|
||||||
|
|
||||||
|
const typingIndicator = appendMessage('Typing...', 'ai');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/chat.php', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ message })
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Network response was not ok');
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
typingIndicator.remove();
|
||||||
|
|
||||||
|
if(data.error) {
|
||||||
|
appendMessage(data.error, 'ai');
|
||||||
|
} else {
|
||||||
|
appendMessage(data.reply, 'ai');
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
typingIndicator.remove();
|
||||||
|
appendMessage('Sorry, something went wrong.', 'ai');
|
||||||
|
console.error('Error:', error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function appendMessage(message, sender) {
|
||||||
|
const messageElement = document.createElement('div');
|
||||||
|
messageElement.classList.add('chat-message', `${sender}-message`);
|
||||||
|
messageElement.textContent = message;
|
||||||
|
chatBox.appendChild(messageElement);
|
||||||
|
chatBox.scrollTop = chatBox.scrollHeight;
|
||||||
|
return messageElement;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initial load
|
||||||
|
loadChatHistory();
|
||||||
|
});
|
||||||
BIN
assets/pasted-20250911-213644-13107a79.png
Normal file
BIN
assets/pasted-20250911-213644-13107a79.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 53 KiB |
@ -6,12 +6,35 @@ define('DB_USER', 'app_30855');
|
|||||||
define('DB_PASS', 'eee81949-37de-47f9-a26f-14ebc8402f7f');
|
define('DB_PASS', 'eee81949-37de-47f9-a26f-14ebc8402f7f');
|
||||||
|
|
||||||
function db() {
|
function db() {
|
||||||
static $pdo;
|
static $pdo;
|
||||||
if (!$pdo) {
|
if ($pdo) {
|
||||||
$pdo = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8mb4', DB_USER, DB_PASS, [
|
return $pdo;
|
||||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
}
|
||||||
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
|
||||||
]);
|
$dsn = 'mysql:host=' . DB_HOST . ';charset=utf8mb4';
|
||||||
}
|
$options = [
|
||||||
return $pdo;
|
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||||
}
|
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
||||||
|
];
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Try connecting to the database directly
|
||||||
|
$pdo = new PDO($dsn . ';dbname=' . DB_NAME, DB_USER, DB_PASS, $options);
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
// If the database doesn't exist, create it
|
||||||
|
if (strpos($e->getMessage(), 'Unknown database') !== false) {
|
||||||
|
try {
|
||||||
|
$tempPdo = new PDO($dsn, DB_USER, DB_PASS, $options);
|
||||||
|
$tempPdo->exec('CREATE DATABASE IF NOT EXISTS `' . DB_NAME . '`');
|
||||||
|
// Now, connect to the newly created database
|
||||||
|
$pdo = new PDO($dsn . ';dbname=' . DB_NAME, DB_USER, DB_PASS, $options);
|
||||||
|
} catch (PDOException $ce) {
|
||||||
|
throw new PDOException("Failed to create database and connect: " . $ce->getMessage());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new PDOException("Database connection failed: " . $e->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $pdo;
|
||||||
|
}
|
||||||
12
db/migrate.php
Normal file
12
db/migrate.php
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
<?php
|
||||||
|
require_once __DIR__ . '/config.php';
|
||||||
|
|
||||||
|
try {
|
||||||
|
$pdo = db();
|
||||||
|
$sql = file_get_contents(__DIR__ . '/migrations/001_create_chat_log_table.sql');
|
||||||
|
$pdo->exec($sql);
|
||||||
|
echo "Database migration successful! Table 'chat_log' is ready.\n";
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
die("Database migration failed: " . $e->getMessage() . "\n");
|
||||||
|
}
|
||||||
|
|
||||||
7
db/migrations/001_create_chat_log_table.sql
Normal file
7
db/migrations/001_create_chat_log_table.sql
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS `chat_log` (
|
||||||
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
`session_id` VARCHAR(255) NOT NULL,
|
||||||
|
`sender` VARCHAR(50) NOT NULL,
|
||||||
|
`message` TEXT NOT NULL,
|
||||||
|
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||||
161
index.php
161
index.php
@ -1,131 +1,48 @@
|
|||||||
<?php
|
<?php
|
||||||
declare(strict_types=1);
|
require_once __DIR__ . '/db/config.php';
|
||||||
@ini_set('display_errors', '1');
|
|
||||||
@error_reporting(E_ALL);
|
|
||||||
@date_default_timezone_set('UTC');
|
|
||||||
|
|
||||||
$phpVersion = PHP_VERSION;
|
session_start();
|
||||||
$now = date('Y-m-d H:i:s');
|
|
||||||
|
$chat_history = [];
|
||||||
|
if (!empty($_SESSION['session_id'])) {
|
||||||
|
try {
|
||||||
|
$pdo = db();
|
||||||
|
$stmt = $pdo->prepare("SELECT sender, message FROM chat_log WHERE session_id = ? ORDER BY created_at ASC");
|
||||||
|
$stmt->execute([$_SESSION['session_id']]);
|
||||||
|
$chat_history = $stmt->fetchAll();
|
||||||
|
} catch (PDOException $e) {
|
||||||
|
// Not critical if history fails to load, so we just log it.
|
||||||
|
error_log("Could not load chat history: " . $e->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
?>
|
?>
|
||||||
<!doctype html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8" />
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>New Style</title>
|
<title>Chat with AI</title>
|
||||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
<link rel="stylesheet" href="assets/css/custom.css?v=<?php echo time(); ?>">
|
||||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
||||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">
|
|
||||||
<style>
|
|
||||||
:root {
|
|
||||||
--bg-color-start: #6a11cb;
|
|
||||||
--bg-color-end: #2575fc;
|
|
||||||
--text-color: #ffffff;
|
|
||||||
--card-bg-color: rgba(255, 255, 255, 0.01);
|
|
||||||
--card-border-color: rgba(255, 255, 255, 0.1);
|
|
||||||
}
|
|
||||||
body {
|
|
||||||
margin: 0;
|
|
||||||
font-family: 'Inter', sans-serif;
|
|
||||||
background: linear-gradient(45deg, var(--bg-color-start), var(--bg-color-end));
|
|
||||||
color: var(--text-color);
|
|
||||||
display: flex;
|
|
||||||
justify-content: center;
|
|
||||||
align-items: center;
|
|
||||||
min-height: 100vh;
|
|
||||||
text-align: center;
|
|
||||||
overflow: hidden;
|
|
||||||
position: relative;
|
|
||||||
}
|
|
||||||
body::before {
|
|
||||||
content: '';
|
|
||||||
position: absolute;
|
|
||||||
top: 0;
|
|
||||||
left: 0;
|
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
|
||||||
background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><path d="M-10 10L110 10M10 -10L10 110" stroke-width="1" stroke="rgba(255,255,255,0.05)"/></svg>');
|
|
||||||
animation: bg-pan 20s linear infinite;
|
|
||||||
z-index: -1;
|
|
||||||
}
|
|
||||||
@keyframes bg-pan {
|
|
||||||
0% { background-position: 0% 0%; }
|
|
||||||
100% { background-position: 100% 100%; }
|
|
||||||
}
|
|
||||||
main {
|
|
||||||
padding: 2rem;
|
|
||||||
}
|
|
||||||
.card {
|
|
||||||
background: var(--card-bg-color);
|
|
||||||
border: 1px solid var(--card-border-color);
|
|
||||||
border-radius: 16px;
|
|
||||||
padding: 2rem;
|
|
||||||
backdrop-filter: blur(20px);
|
|
||||||
-webkit-backdrop-filter: blur(20px);
|
|
||||||
box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.1);
|
|
||||||
}
|
|
||||||
.loader {
|
|
||||||
margin: 1.25rem auto 1.25rem;
|
|
||||||
width: 48px;
|
|
||||||
height: 48px;
|
|
||||||
border: 3px solid rgba(255, 255, 255, 0.25);
|
|
||||||
border-top-color: #fff;
|
|
||||||
border-radius: 50%;
|
|
||||||
animation: spin 1s linear infinite;
|
|
||||||
}
|
|
||||||
@keyframes spin {
|
|
||||||
from { transform: rotate(0deg); }
|
|
||||||
to { transform: rotate(360deg); }
|
|
||||||
}
|
|
||||||
.hint {
|
|
||||||
opacity: 0.9;
|
|
||||||
}
|
|
||||||
.sr-only {
|
|
||||||
position: absolute;
|
|
||||||
width: 1px; height: 1px;
|
|
||||||
padding: 0; margin: -1px;
|
|
||||||
overflow: hidden;
|
|
||||||
clip: rect(0, 0, 0, 0);
|
|
||||||
white-space: nowrap; border: 0;
|
|
||||||
}
|
|
||||||
h1 {
|
|
||||||
font-size: 3rem;
|
|
||||||
font-weight: 700;
|
|
||||||
margin: 0 0 1rem;
|
|
||||||
letter-spacing: -1px;
|
|
||||||
}
|
|
||||||
p {
|
|
||||||
margin: 0.5rem 0;
|
|
||||||
font-size: 1.1rem;
|
|
||||||
}
|
|
||||||
code {
|
|
||||||
background: rgba(0,0,0,0.2);
|
|
||||||
padding: 2px 6px;
|
|
||||||
border-radius: 4px;
|
|
||||||
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
|
||||||
}
|
|
||||||
footer {
|
|
||||||
position: absolute;
|
|
||||||
bottom: 1rem;
|
|
||||||
font-size: 0.8rem;
|
|
||||||
opacity: 0.7;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<main>
|
<div class="chat-container">
|
||||||
<div class="card">
|
<div class="chat-header">
|
||||||
<h1>Analyzing your requirements and generating your website…</h1>
|
<h2>AI Chat</h2>
|
||||||
<div class="loader" role="status" aria-live="polite" aria-label="Applying initial changes">
|
</div>
|
||||||
<span class="sr-only">Loading…</span>
|
<div class="chat-box" id="chat-box">
|
||||||
</div>
|
<!-- Chat messages will be appended here -->
|
||||||
<p class="hint">Flatlogic AI is collecting your requirements and applying the first changes.</p>
|
</div>
|
||||||
<p class="hint">This page will update automatically as the plan is implemented.</p>
|
<div class="chat-footer">
|
||||||
<p>Runtime: PHP <code><?= htmlspecialchars($phpVersion) ?></code> — UTC <code><?= htmlspecialchars($now) ?></code></p>
|
<form id="chat-form">
|
||||||
|
<input type="text" id="message-input" placeholder="Type your message..." autocomplete="off">
|
||||||
|
<button type="submit">Send</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
|
||||||
<footer>
|
<script>
|
||||||
Page updated: <?= htmlspecialchars($now) ?> (UTC)
|
const chatHistory = <?php echo json_encode($chat_history); ?>;
|
||||||
</footer>
|
</script>
|
||||||
|
<script src="assets/js/main.js?v=<?php echo time(); ?>"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
79
lib/OpenAIService.php
Normal file
79
lib/OpenAIService.php
Normal file
@ -0,0 +1,79 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
class OpenAIService
|
||||||
|
{
|
||||||
|
private static $apiKey;
|
||||||
|
private static $model;
|
||||||
|
|
||||||
|
public static function init()
|
||||||
|
{
|
||||||
|
self::$apiKey = getenv('OPENAI_API_KEY');
|
||||||
|
self::$model = getenv('OPENAI_MODEL') ?: 'gpt-4o-mini';
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function getCompletion($message)
|
||||||
|
{
|
||||||
|
if (empty(self::$apiKey)) {
|
||||||
|
return ['error' => 'OpenAI API key is not configured.'];
|
||||||
|
}
|
||||||
|
|
||||||
|
$url = 'https://api.openai.com/v1/chat/completions';
|
||||||
|
|
||||||
|
$data = [
|
||||||
|
'model' => self::$model,
|
||||||
|
'messages' => [
|
||||||
|
['role' => 'system', 'content' => 'You are a helpful assistant.'],
|
||||||
|
['role' => 'user', 'content' => $message]
|
||||||
|
],
|
||||||
|
'max_tokens' => 150
|
||||||
|
];
|
||||||
|
|
||||||
|
$headers = [
|
||||||
|
'Content-Type: application/json',
|
||||||
|
'Authorization: Bearer ' . self::$apiKey
|
||||||
|
];
|
||||||
|
|
||||||
|
$options = [
|
||||||
|
'http' => [
|
||||||
|
'header' => implode("\r\n", $headers),
|
||||||
|
'method' => 'POST',
|
||||||
|
'content' => json_encode($data),
|
||||||
|
'ignore_errors' => true,
|
||||||
|
'timeout' => 30,
|
||||||
|
],
|
||||||
|
];
|
||||||
|
|
||||||
|
$context = stream_context_create($options);
|
||||||
|
$response = @file_get_contents($url, false, $context);
|
||||||
|
|
||||||
|
// Get HTTP status code from the response headers
|
||||||
|
$httpcode = 0;
|
||||||
|
if (isset($http_response_header[0])) {
|
||||||
|
preg_match('{HTTP/1\.\d (\d{3})}', $http_response_header[0], $matches);
|
||||||
|
if (isset($matches[1])) {
|
||||||
|
$httpcode = (int)$matches[1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($response === false) {
|
||||||
|
$error = error_get_last();
|
||||||
|
return ['error' => 'API call failed: ' . ($error['message'] ?? 'Unknown error')];
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($httpcode !== 200) {
|
||||||
|
return ['error' => 'API returned status ' . $httpcode . ': ' . $response];
|
||||||
|
}
|
||||||
|
|
||||||
|
$decodedResponse = json_decode($response, true);
|
||||||
|
|
||||||
|
if (isset($decodedResponse['choices'][0]['message']['content'])) {
|
||||||
|
return ['reply' => $decodedResponse['choices'][0]['message']['content']];
|
||||||
|
} elseif (isset($decodedResponse['error'])) {
|
||||||
|
return ['error' => $decodedResponse['error']['message']];
|
||||||
|
}
|
||||||
|
|
||||||
|
return ['error' => 'Unexpected API response format.'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
OpenAIService::init();
|
||||||
30
lib/config.php
Normal file
30
lib/config.php
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
function loadEnv($path)
|
||||||
|
{
|
||||||
|
if (!file_exists($path)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
||||||
|
foreach ($lines as $line) {
|
||||||
|
if (strpos(trim($line), '#') === 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
list($name, $value) = explode('=', $line, 2);
|
||||||
|
$name = trim($name);
|
||||||
|
$value = trim($value);
|
||||||
|
|
||||||
|
if (!array_key_exists($name, $_SERVER) && !array_key_exists($name, $_ENV)) {
|
||||||
|
putenv(sprintf('%s=%s', $name, $value));
|
||||||
|
$_ENV[$name] = $value;
|
||||||
|
$_SERVER[$name] = $value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load .env from the project root
|
||||||
|
$projectRoot = __DIR__ . '/..';
|
||||||
|
loadEnv($projectRoot . '/.env');
|
||||||
Loading…
x
Reference in New Issue
Block a user