Skip to content

Chat GPT in JavaScript | Basic

The Chat GPT application can be built using JavaScript and HTML, with CSS for styling. JavaSript is used for the Fetch API or XMLHttpRequest to make requests to the OpenAI API and receive responses from the chatbot.

Chat GPT in JavaScript example

Simple example code user input and sending it to the OpenAI API for processing and displaying the chatbot’s response in the output field for the user to see.

First, get Oepn API key form here: https://platform.openai.com/account/api-keys, Repalce in JS YOUR_API_KEY.

HTML

<!DOCTYPE html>
<html>
<head>
    <title>Chat GPT</title>
    <script src="ChatGPT.js?v=12"></script>
    <link rel="stylesheet" type="text/css" href="chat.css">
</head>
<body>

    <div id="idContainer">
        <textarea id="txtOutput" rows="10" style="margin-top: 10px; width: 100%;" 
         placeholder="Output"></textarea>

        <div>
            <button type="button" onclick="Send()" id="btnSend">Send</button>
           
        </div>

        <textarea id="txtMsg" rows="5" wrap="soft" style="width: 98%; 
         margin-left: 3px; margin-top: 6px" placeholder="Input Text"></textarea>

        <div id="idText"></div>
    </div>

</body>
</html>

JS file “chat.js”

function Send() {

    var selLang = "en-US"

    var sQuestion = txtMsg.value;
    if (sQuestion == "") {
        alert("Type in your question!");
        txtMsg.focus();
        return;
    }

    var oHttp = new XMLHttpRequest();
    oHttp.open("POST", "https://api.openai.com/v1/completions");
    oHttp.setRequestHeader("Accept", "application/json");
    oHttp.setRequestHeader("Content-Type", "application/json");
    oHttp.setRequestHeader("Authorization", "Bearer " + "YOUR_API_KEY")

    oHttp.onreadystatechange = function () {
        if (oHttp.readyState === 4) {
            //console.log(oHttp.status);
            var oJson = {}
            if (txtOutput.value != "") txtOutput.value += "\n";

            try {
                oJson = JSON.parse(oHttp.responseText);
            } catch (ex) {
                txtOutput.value += "Error: " + ex.message
            }

            if (oJson.error && oJson.error.message) {
                txtOutput.value += "Error: " + oJson.error.message;
            } else if (oJson.choices && oJson.choices[0].text) {
                var s = oJson.choices[0].text;

                if (selLang.value != "en-US") {
                    var a = s.split("?\n");
                    if (a.length == 2) {
                        s = a[1];
                    }
                }

                if (s == "") s = "No response";
                txtOutput.value += "Chat GPT: " + s;
                TextToSpeech(s);
            }            
        }
    };

    var sModel = "text-davinci-003";
    var iMaxTokens = 2048;
    var sUserId = "1";
    var dTemperature = 0.5;    

    var data = {
        model: sModel,
        prompt: sQuestion,
        max_tokens: iMaxTokens,
        user: sUserId,
        temperature:  dTemperature,
        frequency_penalty: 0.0, //Number between -2.0 and 2.0  
                                //Positive values decrease the model's likelihood 
                                //to repeat the same line verbatim.
        presence_penalty: 0.0,  //Number between -2.0 and 2.0. 
                                //Positive values increase the model's likelihood 
                                //to talk about new topics.
        stop: ["#", ";"]        //Up to 4 sequences where the API will stop 
                                //generating further tokens. The returned text 
                                //will not contain the stop sequence.
    }

    oHttp.send(JSON.stringify(data));

    if (txtOutput.value != "") txtOutput.value += "\n";
    txtOutput.value += "Me: " + sQuestion;
    txtMsg.value = "";
}

CSS file “chat.css”

#idContainer {
  background-color: #f2f2f2;
  padding: 20px;
}

#txtOutput {
  font-size: 16px;
  border: none;
  background-color: #fff;
  margin-bottom: 10px;
}

#txtMsg {
  font-size: 16px;
  border: none;
  background-color: #fff;
  margin-bottom: 10px;
}

#btnSend {
  background-color: #4CAF50;
  color: white;
  padding: 12px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

#btnSend:hover {
  background-color: #3e8e41;
}

Output:

Chat GPT in JavaScript Basic

This is the basic code for Chat GPT integration with JavaScript, HTML, and CSS, do comment if you have any input on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

3 thoughts on “Chat GPT in JavaScript | Basic”

  1. Dear Sir,
    Need your help,
    after integrate this with my website when i ask current year it will give me 2020 except 2023,
    can you plz help me resolve this issue.
    thanks in advance

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading