【WordPress PHP】ChatGPTのJSONモードを扱ってみる

AI搭載のアプリケーションを作るとなるとJSON形式で生成させるのがかなり重要になると思うので、メモ

  • プロンプトに必ず「JSON」という文字を含めること

  • $response_format = array('type' => 'json_object');で指定すること

  • 文字列で返ってくるのでjson_decodeすること

$messages[] = array('role' => 'assistant', 'content' => "日本語で回答してください。");
$response_format = array('type' => 'json_object');
$prompt = "以下の情報を基に、Googleが認識できるQ&A構造化データ(JSON形式)を生成してください。";
$messages[] = array('role' => 'user', 'content' => $prompt);

$params = json_encode(
	array(
		'model' => "gpt-4-turbo",
		'messages' => $messages,
		'response_format' => $response_format
	)
);
$curl = curl_init('https://api.openai.com/v1/chat/completions');

$options = array(
       CURLOPT_POST => true,
       CURLOPT_HTTPHEADER => $header,
       CURLOPT_POSTFIELDS => $params,
       CURLOPT_RETURNTRANSFER => true,
       CURLOPT_BINARYTRANSFER => true,
   );
    
curl_setopt_array($curl,$options);
$response = curl_exec($curl);

$httpcode = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
if (200 == $httpcode) {
	$json_array = json_decode($response, true);
	if (isset($json_array['choices'][0]['message']['content'])) {
		$return_value = $json_array['choices'][0]['message']['content'];
	}
}else{
		$return_value = "エラー";
}

return $return_value;


$response = json_decode($response, true);
$posts_data[] = [
			'1' => $response["1"],
			'2' => $response["2"],
			'3' => $response["3"],
		];

ここから先は

0字
この記事のみ ¥ 300

メンバーシップ加入で、全ての記事が閲覧できます。