File: /var/www/html/laravel/public/gpt.php
<?php
$params = json_decode(file_get_contents('php://input'), true);
header('Content-Type: application/json');
$input = '';
$status = 'success';
$temperature = 0;
$max_tokens = 4096;
$input = '';
$data = [];
$messages = [];
$apiKey = $params['key'];
$headers = [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey,
];
if (!empty(trim($params['prompt']))) {
$messages = [['role' => 'system', 'content' => $params['prompt']]];
}
if (!empty($params['messages'])) {
foreach ($params['messages'] as $message) {
$messages[] = ['role' => 'user', 'content' => $message['user']];
$messages[] = ['role' => 'assistant', 'content' => $message['assistant']];
}
}
if (!empty($params['input'])) {
$input = $params['input'];
$messages[] = ['role' => 'user', 'content' => $input];
}
if (!empty($params['temperature'])) {
$temperature = $params['temperature'];
}
if (!empty($params['max_tokens'])) {
$max_tokens = $params['max_tokens'];
}
$url = 'https://api.openai.com/v1/chat/completions';
$data = array_merge($data, [
'model' => $params['model'],
'messages' => $messages,
]);
if (substr_count($params['model'], '-4')) {
$data = array_merge($data, [
'max_tokens' => $max_tokens,
'temperature' => $temperature,
]);
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 300);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
$result = curl_error($ch);
}
curl_close($ch);
echo $result;