JSONの構造を指定する
OpenAI APIのレスポンスで返されるJSONの構造を指定する方法を学びます。
ファイルの用意
Section titled “ファイルの用意”次のように index.html、style.css、main.js の3つのファイルを作成してください。
./works└── specify-json-structure ├── index.html ├── style.css └── main.jsStructured Outputs機能を使って、AIが返すレスポンスのJSON構造を指定します。これにより、常に一貫したデータ構造で結果を受け取ることができます。
この例では、ユーザーが入力した説明に基づいて、架空の人物のプロフィール(名前、年齢、出身地、好きなもの)を生成します。
このセクションでは、3段階に分けて実装します:
- 第1段階: UIの実装 - APIキーなしでUIの動作確認
- 第2段階: 普通のAPI呼び出し - JSON構造を指定しないAPI呼び出し
- 第3段階: JSON構造指定 - Structured Outputsでデータ構造を保証
第1段階: UIの実装
Section titled “第1段階: UIの実装”まず、OpenAI APIを使わずにUIの基本構造を作ります。
1. HTMLファイルを作成する
Section titled “1. HTMLファイルを作成する”index.html を作成する
Section titled “index.html を作成する”1<html>2 <head>3 <title>JSONの構造を指定する</title>4 <link rel="stylesheet" href="./style.css" />5 </head>6 <body>7 <h1>JSONの構造を指定する</h1>8 <div>9 <input type="text" id="descriptionInput" placeholder="どんな人がいいか入力してください" />10 <button id="generateButton">生成</button>11 </div>12 <div id="result">13 <h2>生成されたプロフィール</h2>14 <p>名前: <span id="name">-</span></p>15 <p>年齢: <span id="age">-</span></p>16 <p>出身地: <span id="hometown">-</span></p>17 <p>好きなもの: <span id="favorites">-</span></p>18 </div>19 <script src="./main.js"></script>20 </body>21</html>HTMLの構成要素
Section titled “HTMLの構成要素”input#descriptionInput: プロフィールの説明を入力button#generateButton: プロフィール生成ボタンspan#name,span#age,span#hometown,span#favorites: 生成されたプロフィール情報を表示
2. CSSファイルを作成する
Section titled “2. CSSファイルを作成する”style.css を作成する
Section titled “style.css を作成する”1input[type="text"] {2 width: 300px;3 padding: 8px;4 font-size: 14px;5}6
7button {8 padding: 8px 16px;9 font-size: 14px;10 cursor: pointer;11}3. JavaScriptファイルを作成する
Section titled “3. JavaScriptファイルを作成する”main.js を作成する
Section titled “main.js を作成する”1const descriptionInput = document.getElementById('descriptionInput');2const generateButton = document.getElementById('generateButton');3const nameElement = document.getElementById('name');4const ageElement = document.getElementById('age');5const hometownElement = document.getElementById('hometown');6const favoritesElement = document.getElementById('favorites');7
8function showResult(profile) {9 nameElement.textContent = profile.name;10 ageElement.textContent = profile.age;11 hometownElement.textContent = profile.hometown;12 favoritesElement.textContent = profile.favorites.join(', ');13}14
15generateButton.addEventListener('click', () => {16 // 仮のプロフィールデータ17 const fakeProfile = {18 name: '仮太郎',19 age: 25,20 hometown: '東京都',21 favorites: ['読書', '映画', '旅行']22 };23
24 showResult(fakeProfile);25});コードの説明
Section titled “コードの説明”- DOM要素の取得: 入力欄、ボタン、結果表示エリアを取得
- showResult関数: プロフィールデータを画面に表示する関数
- イベントリスナー: 仮のプロフィールデータを表示(まだAPIは呼び出していない)
ブラウザでHTMLファイルを開き、以下を確認します:
- 入力欄とボタンが表示される
- 「生成」ボタンをクリックすると、仮のプロフィールが表示される
第2段階: 普通のAPI呼び出し
Section titled “第2段階: 普通のAPI呼び出し”第1段階で作成したUIに、OpenAI APIを統合します。ただし、まだJSON構造は指定しません。
1. HTMLファイル
Section titled “1. HTMLファイル”HTMLは第1段階と同じです(変更なし)。
2. JavaScriptファイルを更新する
Section titled “2. JavaScriptファイルを更新する”main.js を変更する
Section titled “main.js を変更する”1const OPENAI_API_KEY = 'YOUR_API_KEY_HERE';2
13const descriptionInput = document.getElementById('descriptionInput');24const generateButton = document.getElementById('generateButton');35const nameElement = document.getElementById('name');1214 favoritesElement.textContent = profile.favorites.join(', ');1315}1416
15generateButton.addEventListener('click', () => {16 // 仮のプロフィールデータ17 const fakeProfile = {18 name: '仮太郎',19 age: 25,20 hometown: '東京都',21 favorites: ['読書', '映画', '旅行']22 };17generateButton.addEventListener('click', async () => {18 const description = descriptionInput.value || 'ランダムな人';2319
24 showResult(fakeProfile);20 const response = await fetch('https://api.openai.com/v1/chat/completions', {21 method: 'POST',22 headers: {23 'Content-Type': 'application/json',24 'Authorization': `Bearer ${OPENAI_API_KEY}`25 },26 body: JSON.stringify({27 model: 'gpt-6-luna',28 messages: [29 {30 role: 'user',31 content: `${description}のプロフィール(名前、年齢、出身地、好きなもの)をJSON形式で生成してください`32 }33 ]34 })35 });36
37 const data = await response.json();38 const aiMessage = data.choices[0].message.content;39
40 // JSONっぽい文字列をパースする(エラーが起きる可能性あり)41 const result = JSON.parse(aiMessage);42
43 showResult(result);2544});第1段階からの変更点
Section titled “第1段階からの変更点”- APIキーの追加:
OPENAI_API_KEY定数を追加 - fetch APIでリクエスト送信: OpenAI APIを呼び出す
- プロンプトの工夫: 「JSON形式で生成してください」と指示
- レスポンスのパース:
JSON.parse()で文字列をJSONに変換
この段階の問題点
Section titled “この段階の問題点”JSON構造が保証されない問題があります:
- AIが必ずしもパース可能なJSONを返すとは限らない
- フィールド名が異なる場合がある(
namevs名前) - 必須フィールドが欠けている場合がある
- 余計な説明文が含まれている場合がある
これらの問題を解決するのが、次の第3段階です。
OPENAI_API_KEYを実際のAPIキーに置き換える- ブラウザでHTMLファイルを開く
- 入力欄に説明を入力(例: “明るくて元気な人”)
- 「生成」ボタンをクリック
- プロフィールが表示されることを確認(エラーが出る可能性もあり)
第3段階: JSON構造指定
Section titled “第3段階: JSON構造指定”第2段階のコードに、Structured Outputs機能を追加して、確実に決まった構造のJSONを取得します。
1. HTMLファイル
Section titled “1. HTMLファイル”HTMLは第1段階と同じです(変更なし)。
2. JavaScriptファイルを更新する
Section titled “2. JavaScriptファイルを更新する”main.js を変更する
Section titled “main.js を変更する”2828 messages: [2929 {3030 role: 'user',31 content: `${description}のプロフィール(名前、年齢、出身地、好きなもの)をJSON形式で生成してください`31 content: `${description}のプロフィールを生成してください`3232 }33 ]33 ],34 response_format: {35 type: 'json_schema',36 json_schema: {37 name: 'person_profile',38 strict: true,39 schema: {40 type: 'object',41 properties: {42 name: {43 type: 'string',44 description: '名前'45 },46 age: {47 type: 'number',48 description: '年齢'49 },50 hometown: {51 type: 'string',52 description: '出身地'53 },54 favorites: {55 type: 'array',56 description: '好きなもののリスト',57 items: {58 type: 'string'59 }60 }61 },62 required: ['name', 'age', 'hometown', 'favorites'],63 additionalProperties: false64 }65 }66 }3467 })3568 });3669
3770 const data = await response.json();38 const aiMessage = data.choices[0].message.content;71 const result = JSON.parse(data.choices[0].message.content);3972
40 // JSONっぽい文字列をパースする(エラーが起きる可能性あり)41 const result = JSON.parse(aiMessage);42
4373 showResult(result);4474});第2段階からの変更点
Section titled “第2段階からの変更点”- response_formatの追加: JSON構造を指定する新しいパラメータ
- プロンプトの簡略化: 「JSON形式で」という指示が不要になった
JSON構造の指定 (Structured Outputs)
Section titled “JSON構造の指定 (Structured Outputs)”response_formatパラメータで、レスポンスのJSON構造を厳密に指定します:
response_format: { type: 'json_schema', json_schema: { name: 'person_profile', strict: true, schema: { type: 'object', properties: { name: { type: 'string', description: '名前' }, age: { type: 'number', description: '年齢' }, hometown: { type: 'string', description: '出身地' }, favorites: { type: 'array', description: '好きなもののリスト', items: { type: 'string' } } }, required: ['name', 'age', 'hometown', 'favorites'], additionalProperties: false } }}主要なフィールド:
type: 'json_schema': Structured Outputsを使用name: スキーマの名前(任意)strict: true: 厳密なスキーマ検証を有効化schema: JSONスキーマの定義type: 'object': オブジェクト型properties: 各フィールドの型と説明required: 必須フィールドのリストadditionalProperties: false: 定義外のフィールドを禁止
レスポンスの処理
Section titled “レスポンスの処理”AIからの返答は必ず指定した構造になります:
const result = JSON.parse(data.choices[0].message.content);返答例:
{ "name": "田中太郎", "age": 28, "hometown": "東京都", "favorites": ["読書", "映画鑑賞", "旅行"]}OPENAI_API_KEYを実際のAPIキーに置き換える- ブラウザでHTMLファイルを開く
- 入力欄に説明を入力(例: “明るくて元気な人”)
- 「生成」ボタンをクリック
- 構造化されたプロフィールが確実に表示されることを確認
Structured Outputsのメリット
Section titled “Structured Outputsのメリット”- 一貫性: 常に同じ構造のデータが返される
- 型安全性: 数値、文字列、配列などの型が保証される
- エラー削減: パース失敗やフィールド欠落がない
- 開発効率: レスポンス処理のコードがシンプルになる
- プロンプト簡略化: 「JSON形式で」などの指示が不要
この節を終えたときのディレクトリ
Section titled “この節を終えたときのディレクトリ”specify-json-structure
<html> <head> <title>JSONの構造を指定する</title> <link rel="stylesheet" href="./style.css" /> </head> <body> <h1>JSONの構造を指定する</h1> <div> <input type="text" id="descriptionInput" placeholder="どんな人がいいか入力してください" /> <button id="generateButton">生成</button> </div> <div id="result"> <h2>生成されたプロフィール</h2> <p>名前: <span id="name">-</span></p> <p>年齢: <span id="age">-</span></p> <p>出身地: <span id="hometown">-</span></p> <p>好きなもの: <span id="favorites">-</span></p> </div> <script src="./main.js"></script> </body></html>const OPENAI_API_KEY = 'YOUR_API_KEY_HERE';
const descriptionInput = document.getElementById('descriptionInput');const generateButton = document.getElementById('generateButton');const nameElement = document.getElementById('name');const ageElement = document.getElementById('age');const hometownElement = document.getElementById('hometown');const favoritesElement = document.getElementById('favorites');
function showResult(profile) { nameElement.textContent = profile.name; ageElement.textContent = profile.age; hometownElement.textContent = profile.hometown; favoritesElement.textContent = profile.favorites.join(', ');}
generateButton.addEventListener('click', async () => { const description = descriptionInput.value || 'ランダムな人';
const response = await fetch('https://api.openai.com/v1/chat/completions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${OPENAI_API_KEY}` }, body: JSON.stringify({ model: 'gpt-6-luna', messages: [ { role: 'user', content: `${description}のプロフィールを生成してください` } ], response_format: { type: 'json_schema', json_schema: { name: 'person_profile', strict: true, schema: { type: 'object', properties: { name: { type: 'string', description: '名前' }, age: { type: 'number', description: '年齢' }, hometown: { type: 'string', description: '出身地' }, favorites: { type: 'array', description: '好きなもののリスト', items: { type: 'string' } } }, required: ['name', 'age', 'hometown', 'favorites'], additionalProperties: false } } } }) });
const data = await response.json(); const result = JSON.parse(data.choices[0].message.content);
showResult(result);});input[type="text"] { width: 300px; padding: 8px; font-size: 14px;}
button { padding: 8px 16px; font-size: 14px; cursor: pointer;}