chat-gpt’s diary

ChatGPTでAIと会話した結果を残してます。

ChatGPTのAPIをPHP5で実行したいので、サンプルをください。

申し訳ありませんが、現在の日付である2023年4月3日には、PHP5は非推奨であり、サポートされていません。PHP5は、2014年以来、セキュリティアップデートを受け取っていません。

推奨される最新バージョンのPHPを使用することをお勧めします。

ChatGPT APIを実行するためのサンプルコードは以下の通りです。

<?php

// ChatGPT APIのエンドポイントURL
$endpoint = 'https://api.openai.com/v1/engines/davinci-codex/completions';

// APIキー
$api_key = 'your_api_key_here';

// リクエストボディ
$data = array(
    'prompt' => 'Hello, ',
    'max_tokens' => 50,
    'temperature' => 0.5,
    'n' => 1,
    'stop' => '.'
);

// リクエストヘッダー
$headers = array(
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key,
);

// cURLを初期化
$ch = curl_init();

// cURLオプションを設定
curl_setopt($ch, CURLOPT_URL, $endpoint);
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);

// APIリクエストを実行
$response = curl_exec($ch);

// cURLリソースを閉じる
curl_close($ch);

// レスポンスを出力
echo $response;

このコードを使用するには、以下の手順に従ってください。

  1. OpenAIのWebサイトでAPIキーを取得します。
  2. 上記のコードの your_api_key_here を、取得したAPIキーに置き換えます。
  3. PHPを実行するサーバーに、cURLがインストールされていることを確認します。
  4. コードを実行します。

古かったので、現行のAPIに合わせて少し修正

<?php

// ChatGPT APIのエンドポイントURL
$endpoint = 'https://api.openai.com/v1/chat/completions';

// APIキー
$api_key = 'your_api_key_here';

// リクエストボディ
$messages = array(
    array("role"=> "system", "content" => "愛とは何ですか?")
);
$data = array(
    "model" => "gpt-3.5-turbo",
    "messages" => $messages
);

// リクエストヘッダー
$headers = array(
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key,
);

// cURLを初期化
$ch = curl_init();

// cURLオプションを設定
curl_setopt($ch, CURLOPT_URL, $endpoint);
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);

// APIリクエストを実行
$response = curl_exec($ch);

// cURLリソースを閉じる
curl_close($ch);

// レスポンスを出力
var_dump($response);

実行

string(780) "{"id":"chatcmpl-71FMJ52Mco3A99AeFeCQ2bTEGk8Qx","object":"chat.completion","created":1680531723,"model":"gpt-3.5-turbo-0301","usage":{"prompt_tokens":16,"completion_tokens":185,"total_tokens":201},"choices":[{"message":{"role":"assistant","content":"人々が他人に対して持つ深い感情の一つであり、同情、思いやり、尊敬、慈愛、自己犠牲などが含まれます。愛は一般的に、親子、夫婦、友情、家族、コミュニティなどの関係性に基づいて存在し、暖かく、信頼できる、幸せな感情をもたらします。愛は時に痛みや喜びをもたらすことがありますが、その本質は深いつながりと相手を大切に思う気持ちにあります。"},"finish_reason":"stop","index":0}]}