40 lines
1.2 KiB
PHP
40 lines
1.2 KiB
PHP
<?php
|
|
|
|
require_once __DIR__ . '/whatsapp_api.php'; // untuk dapatkan OPENAI_API_KEY
|
|
|
|
class Gpt_Ai_Api {
|
|
|
|
/**
|
|
* Memanggil OpenAI Chat Completions
|
|
* @param array $payload Array sesuai format OpenAI API
|
|
* @return string Respon AI atau pesan error
|
|
*/
|
|
public function call_openai(array $payload): string {
|
|
$ch = curl_init("https://api.openai.com/v1/chat/completions");
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
|
"Content-Type: application/json",
|
|
"Authorization: " . "Bearer " . OPENAI_API_KEY
|
|
]);
|
|
curl_setopt($ch, CURLOPT_POST, true);
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
|
|
$response = curl_exec($ch);
|
|
|
|
if ($response === false) {
|
|
$error_msg = curl_error($ch);
|
|
curl_close($ch);
|
|
return "⚠️ Gagal menghubungi AI: $error_msg";
|
|
}
|
|
|
|
curl_close($ch);
|
|
|
|
$data = json_decode($response, true);
|
|
if (json_last_error() !== JSON_ERROR_NONE) {
|
|
return "⚠️ Respon AI tidak valid JSON.";
|
|
}
|
|
|
|
return $data['choices'][0]['message']['content'] ?? "⚠️ Tidak ada respon dari AI.";
|
|
}
|
|
|
|
}
|