2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【ChatGPT】fetchでAPIを利用する方法

Last updated at Posted at 2023-04-08

ChatGPTはPythonライブラリやNode.jsライブラリを使用する方法もあるが、エンドポイントへ直接POSTリクエストを送っても使用できる。

下記コードをそれぞれ、適当なフォルダに置いて、index.htmlをブラウザで開く。

HTML

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>タイトル</title>
    <link rel="stylesheet" href="styles.css">
    <script src="main.js" defer></script>
</head>
<body>
    <h1>ChatGPTをfetchでリクエストする方法</h1>
    <form id="input-form" method="POST">
        <label for="input_text">適当に入力してください</label>
        <input type="text" id="input_text" name="input_text">
        <button type="submit">リクエスト</button>
    </form>
    <div id="output">
        <p id="generated-sentence"></p>
    </div>
</body>
</html>

CSS

styles.css
h1 {
    text-align: center;
}

form {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20px;
}
input[type="text"], button {
    transition: all 0.3s ease;
  }

  input[type="text"]:focus, button:hover {
    transform: scale(1.05);
  }
input {
    font-size: 16px;
    padding: 5px 10px;
    margin-bottom: 10px;
}

button {
    font-size: 16px;
    padding: 5px 10px;
    background-color: #4fc3f7;
    color: #fff;
    border: none;
    cursor: pointer;
    transition: background-color 0.3s;
}

button:hover {
    background-color: #039be5;
}

#output {
    display: flex;
    flex-direction: column;
    align-items: center;
}

Javascript

main.js
window.onload = function() {
    const form = document.getElementById("input-form");
    const output = document.getElementById("generated-sentence");
    const apiKey = '***************************************';
    const endpoint = 'https://api.openai.com/v1/chat/completions';

    form.addEventListener("submit", async (event) => {
        event.preventDefault();
        const input = document.getElementById("input_text").value;
        fetch(endpoint, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${apiKey}`
                },
                body: JSON.stringify({
                    messages: [{"role": "system", "content": "これは何ですか?"},
                    {"role": "system", "content": "日本語で答えてください"},
                    {"role": "user", "content": input}],
                    model: "gpt-3.5-turbo",
                    max_tokens: 500,
                    temperature: 1,
                    n: 1,
                    stop: '###'
                })
            })
            .then(response => response.json())
            .then(data => {
                const text = data.choices[0].message.content;
                output.textContent = text;
            })
            .catch(error => console.error(error));
    });
};

まとめ

今回は、CharGPT APIをfetchでエンドポイントへリクエストを送ることで使用する方法を紹介した。

2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?