File: /home/panomity.de/public_html/ai/index.php
<?php
session_start();
define("OPENAI_API_KEY", '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');
define("ASSISTANT_ID", 'asst_v3SM9xDJmeTLspw1HkzY8YPC');
function sendOpenAIRequest($endpoint, $payload) {
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.openai.com/v1/" . $endpoint,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_HTTPHEADER => [
"Content-Type: application/json",
"Authorization: Bearer " . OPENAI_API_KEY,
"OpenAI-Beta: assistants=v1" // Add this line
],
]);
$response = curl_exec($curl);
curl_close($curl);
return json_decode($response, true);
}
function handleFileUpload() {
if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['error'] == 0) {
$uploadedFile = $_FILES['uploaded_file'];
$basePath = 'uploads/'; // Ensure this directory exists and is writable
$filePath = $basePath . basename($uploadedFile['name']);
if (move_uploaded_file($uploadedFile['tmp_name'], $filePath)) {
return $filePath;
}
}
return null;
}
function encodeFileForAPI($filePath) {
if (file_exists($filePath)) {
$fileData = file_get_contents($filePath);
return base64_encode($fileData);
}
return null;
}
function createThread($content, $file = null) {
$payload = [
"messages" => [
["role" => "user", "content" => $content]
]
];
if ($file !== null) {
$encodedFile = encodeFileForAPI($file);
// Include the encoded file in the payload as required by the API
}
$response = sendOpenAIRequest("threads", $payload);
$_SESSION['thread_id'] = $response['id'];
return $response;
}
function createMessage($content, $file = null) {
$threadId = $_SESSION['thread_id'] ?? null;
if ($threadId === null) {
throw new Exception("Thread ID is not available.");
}
$payload = [
"role" => "user",
"content" => $content,
];
if ($file !== null) {
$encodedFile = encodeFileForAPI($file);
// Include the encoded file in the payload as required by the API
}
return sendOpenAIRequest("threads/".$threadId."/messages", $payload);
}
function renderWebInterface() {
echo '<form action="" method="post" enctype="multipart/form-data">';
echo 'Message: <input type="text" name="user_input"><br>';
echo 'Upload file: <input type="file" name="uploaded_file"><br>';
echo '<input type="submit" value="Submit">';
echo '</form>';
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$userInput = $_POST['user_input'] ?? '';
$filePath = handleFileUpload();
if (!isset($_SESSION['thread_id'])) {
$response = createThread($userInput, $filePath);
} else {
$response = createMessage($userInput, $filePath);
}
// Display the response or handle it as needed
echo '<pre>';
print_r($response);
echo '</pre>';
}
renderWebInterface();
?>