LoginSignup
3
2

More than 1 year has passed since last update.

ChatGPTにJavaScriptからアクセスする

Posted at

はじめに

なぜか、ChatGPTにJavaScriptからアクセスするコードは
普通に検索しても得られないのですが、なんとかこれで動くようですのでお試しください

参考にしたコード

「ChatGPTにJavaScriptでAPIにアクセスする方法」でChatGPTに質問して得られたコード→古くてエラー
「example」の「json」のコード等

コード

index.html
<!doctype html>
<html>
<meta charset="utf-8">
<script>
const apiKey = "APIキー";

// APIエンドポイントを設定します
const endpoint = "https://api.openai.com/v1/completions";

// リクエストデータを設定します
const requestData = {
	"model": "text-davinci-003",
    prompt: "CM動画を閲覧してどのように感じられましたか?",
	"temperature": 0,
	"max_tokens": 450,
	"top_p": 1.0,
	"frequency_penalty": 0.0,
	"presence_penalty": 0.0
};

// リクエストヘッダーを設定します
const requestHeaders = {
    "Content-Type": "application/json",
	"OpenAI-Organization": "org-mEa6WWqeF4GNLJ6KojVd1OOY",
    "Authorization": `Bearer ${apiKey}`
};

// APIにPOSTリクエストを送信します
fetch(endpoint, {
    method: "POST",
    headers: requestHeaders,
    body: JSON.stringify(requestData)
})
.then(response => response.json())
.then(data => {
//    console.log(data.choices[0].text);
	  alert(data.choices[0].text);
})
.catch(error => {
    console.error(error);
});
</script>
</html>
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2