PHPでChatGPT APIを使う方法

PHP

PHPでChatGPT APIを使う方法についてメモしておきます。

準備

自分のAPIキーを取得します。

使用例

モデルは「gpt-4o」としています。

$question = "次の文章を形態素解析してください。「私は猫です。」";
$answer = get_chatgpt($question);

print $question;
print $answer;

function get_chatgpt($question){
  $apiKey = "{自分のAPIキー}";
  $endpoint = "https://api.openai.com/v1/chat/completions";
  $headers = array(
    "Content-Type: application/json",
    "Authorization: Bearer " . $apiKey
  );
  $data = array(
    "model" => "gpt-4o",
    "messages" => [
      [
        "role" => "user",
        "content" => $question
      ]
    ]
  );

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $endpoint);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  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);

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

  $result = json_decode($response, true);
  $answer = $result["choices"][0]["message"]["content"];
  return $answer;
}

コメント

タイトルとURLをコピーしました