<?php
/*
Get OPENAI_API_KEY
here (accessToken): https://chat.openai.com/api/auth/session
or here (API key): https://platform.openai.com/account/api-keys
*/
define('OPENAI_API_KEY', '');
$prompt = "인생이란 무엇인가요?";
$url = "https://api.openai.com/v1/chat/completions";
$data = array(
"model" => "gpt-3.5-turbo",
"messages" => array(
array(
"role" => "user",
"content" => $prompt
)
),
"max_tokens" => 3000,
"temperature" => 0.5,
);
$data_string = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
'Authorization: Bearer ' . OPENAI_API_KEY,
"Content-Length: " . strlen($data_string))
);
$response = curl_exec($ch);
curl_close($ch);
$json_data = json_decode($response, true);
$model = $json_data['model'];
$content = $json_data['choices'][0]['message']['content'];
echo $model;
echo "<br>";
echo "<br>";
echo $content;
?>
<?php
/*
https://github.com/alexz006/ChatGPT-Example
Get OPENAI_API_KEY
here (accessToken): https://chat.openai.com/api/auth/session
or here (API key): https://platform.openai.com/account/api-keys
*/
define('OPENAI_API_KEY', '');
// var_dump ( $response );
set_time_limit(120);
$message = "사람의 마음에 대하여 논하세요";
$replay = openai_api($message);
echo $replay['message'] . "<br>";
function openai_api($message){
$url = "https://api.openai.com/v1/engines/davinci/completions";
$headers = [
'Content-Type: application/json',
'Authorization: Bearer ' . OPENAI_API_KEY
];
$data = [
"prompt" => $message,
'max_tokens' => 2049,
"temperature" => 1,
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (curl_errno($ch)) {
$return = [
'error' => ['msg'=>'<span style="color:red">' . curl_error($ch) . '</span>']
];
curl_close($ch);
return $return;
}
curl_close($ch);
$arr = json_decode($response, 1);
$return = [
'message' => ''
];
if(!empty($arr['error'])){
$return['message'] = '<span style="color:red">' . trim($arr['error']['message']) . '</span>';
}
elseif(!empty($arr['choices'])){
$return['message'] = trim($arr['choices'][0]['text']);
}
return $return;
}
?>