OpenAI API を呼び出す
ブラウザから直接OpenAI APIを呼び出す基本的な実装を学びます。
ファイルの用意
Section titled “ファイルの用意”次のように index.html と main.js の2つのファイルを作成してください。
./works└── call-openai-api ├── index.html └── main.jsOpenAI APIのChat Completions エンドポイントを使って、ユーザーが入力したテキストメッセージを送信し、AIからの応答を画面に表示するシンプルなチャットインターフェースを作成します。
このセクションでは、2段階に分けて実装します:
- 第1段階: UIの実装 - APIキーなしでUIの動作確認
- 第2段階: OpenAI API統合 - 実際のAPIを呼び出す
第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>OpenAI API を呼び出す</title>4 </head>5 <body>6 <h1>OpenAI API を呼び出す</h1>7 <textarea id="messageInput"></textarea>8 <button id="sendButton">送信</button>9 <div id="result"></div>10 <script src="./main.js"></script>11 </body>12</html>HTMLの構成要素
Section titled “HTMLの構成要素”textarea#messageInput: ユーザーがメッセージを入力するエリアbutton#sendButton: メッセージを送信するボタンdiv#result: ユーザーとAIのメッセージを表示するエリア
2. JavaScriptファイルを作成する
Section titled “2. JavaScriptファイルを作成する”main.js を作成する
Section titled “main.js を作成する”1const messageInput = document.getElementById('messageInput');2const sendButton = document.getElementById('sendButton');3const resultText = document.getElementById('result');4
5function appendResult(text) {6 const p = document.createElement('p');7 p.textContent = text;8 resultText.appendChild(p);9}10
11sendButton.addEventListener('click', async () => {12 const userMessage = messageInput.value;13 appendResult('あなた:' + userMessage);14
15 const aiMessage = "仮のメッセージ"16 appendResult('AI:' + aiMessage);17});コードの説明
Section titled “コードの説明”- DOM要素の取得: テキストエリア、ボタン、結果表示エリアを取得
- appendResult関数: 結果エリアに新しいメッセージを追加する関数
- イベントリスナー:
- ユーザーの入力を取得して表示
- 仮のAIメッセージを表示(まだAPIは呼び出していない)
ブラウザでHTMLファイルを開き、以下を確認します:
- テキストエリアに文字を入力できる
- 送信ボタンをクリックすると、入力したメッセージが表示される
- 仮のAIメッセージ「仮のメッセージ」が表示される
第2段階: OpenAI API統合
Section titled “第2段階: OpenAI API統合”第1段階で作成したUIに、実際のOpenAI APIを統合します。
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 messageInput = document.getElementById('messageInput');24const sendButton = document.getElementById('sendButton');35const resultText = document.getElementById('result');1214 const userMessage = messageInput.value;1315 appendResult('あなた:' + userMessage);1416
15 const aiMessage = "仮のメッセージ"17 const response = await fetch('https://api.openai.com/v1/chat/completions', {18 method: 'POST',19 headers: {20 'Content-Type': 'application/json',21 'Authorization': `Bearer ${OPENAI_API_KEY}`22 },23 body: JSON.stringify({24 model: 'gpt-6-luna',25 messages: [26 {27 role: 'user',28 content: userMessage29 }30 ]31 })32 });33
34 const data = await response.json();35 const aiMessage = data.choices[0].message.content;1636 appendResult('AI:' + aiMessage);1737});第1段階からの変更点
Section titled “第1段階からの変更点”- APIキーの追加:
OPENAI_API_KEY定数を追加 - fetch APIでリクエスト送信:
- エンドポイント:
https://api.openai.com/v1/chat/completions - メソッド: POST
- AuthorizationヘッダーにAPIキーを設定
- エンドポイント:
- リクエストボディ:
model: 使用するモデル(gpt-6-luna)messages: ユーザーが入力したメッセージを送信
- レスポンスの処理: 仮のメッセージの代わりに、APIからの実際の返答を表示
OPENAI_API_KEYを実際のAPIキーに置き換える- ブラウザでHTMLファイルを開く
- テキストエリアにメッセージを入力して送信
- AIからの実際の返答が表示されることを確認
この節を終えたときのディレクトリ
Section titled “この節を終えたときのディレクトリ”call-openai-api
<html> <head> <title>OpenAI API を呼び出す</title> </head> <body> <h1>OpenAI API を呼び出す</h1> <textarea id="messageInput"></textarea> <button id="sendButton">送信</button> <div id="result"></div> <script src="./main.js"></script> </body></html>const OPENAI_API_KEY = 'YOUR_API_KEY_HERE';
const messageInput = document.getElementById('messageInput');const sendButton = document.getElementById('sendButton');const resultText = document.getElementById('result');
function appendResult(text) { const p = document.createElement('p'); p.textContent = text; resultText.appendChild(p);}
sendButton.addEventListener('click', async () => { const userMessage = messageInput.value; appendResult('あなた:' + userMessage);
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: userMessage } ] }) });
const data = await response.json(); const aiMessage = data.choices[0].message.content; appendResult('AI:' + aiMessage);});