80 lines
2.3 KiB
PHP
80 lines
2.3 KiB
PHP
<?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();
|