Chat GPT-4o

$apiKey = ‘xxx’;
$url = “https://api.openai.com/v1/chat/completions”;
$seach_text = filter_input(INPUT_POST, ‘seach_text’, FILTER_DEFAULT);
$data = [
“model” => “chatgpt-4o-latest”,
“messages” => [
[“role” => “system”, “content” => “あなたはPHPの開発者です、正確な情報を提供するAIです。すべての回答は日本語で行ってください。”],
[“role” => “user”, “content” => $seach_text]
],
“temperature” => 0.2,
“top_p” => 0.5,
“max_tokens” => 1500
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
“Authorization: Bearer $apiKey “,
“Content-Type: application/json”
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

$response = curl_exec($ch);
curl_close($ch);

$response_data = json_decode($response, true);

//echo “response_data<pre>” ;
//print_r($response_data) ;
//echo “</pre>” ;

// `choices` から `content` を取り出す
if (isset($response_data[“choices”][0][“message”][“content”])) {
//$ai_response = $response_data[“choices”][0][“message”][“content”];
$answer = $response_data[“choices”][0][“message”][“content”];
$answer = nl2br($answer);
//echo “AIの回答: ” . $ai_response;
} else {
//echo “エラー: `choices` から応答を取得できませんでした。”;
}

echo <<<EOD
<!DOCTYPE html>

<html lang=”ja”>
<head>
<meta charset=”utf-8″>
<title>GPTアプリ</title>
</head>
<body>
<div style=”margin:50px;”>
<h1>php-ChatGPT</h1>
<h3>test-1</h3>
<form action=”test-1.php” method=”post”>
<div>
<input name=”seach_text” value=”{$seach_text}” $type=”text” style=”width:80%;padding:8px;” placeholder=”何が知りたいですか?” size=”150″>
<button style=”width:80px;padding:6px;”>検 索</button>
</div>
</form>
<div>
<p>【検索結果】</p>
<p>{$answer}</p>
</div>
</div>
</body>
</html>
EOD;

Previous article

OpenAIのモデルと、GPT