Friday, June 9, 2023

Using ChatGPT Chat Completion API with pure JavaScript

 In this tutorial you will create a very simple JavaScript web page that interacts with ChatGPT.

Get an API key from openai.com

Visit https://openai.com and create an account. The login page looks like this:


Click on your profile and select “View API keys”. On the next page, click on the “+ Create new secret key” button.


Give your key a name, then click on “Generate secret key”.


An API key is generated. You must save this key somewhere because this is your only chance to view it as it cannot be viewed again. Click on the copy button and paste it is a safe place.


Creating a simple JavaScript app

We will create a very simple Chat Completion application that we can ask questions to and it will use the smarts of ChatGPT to provide us with answers. We will ground the chat so that it discusses topics related to the National Basketball Association (NBA).

Create a folder named ChatCompletionJS. Inside of that folder, create an HTML file named chatgpt-chat-completion_nba.html. Using a text editor, add the following HTML code to chatgpt-chat-completion_nba.html:

<!DOCTYPE html>
<html lang="en">
  <head>
     <title>ChatGPT with JavaScript (NBA)</title>
  </head>
  <body>
    <div>
      <h1>ChatGPT with JavaScript (NBA)</h1>
      <textarea id="dialog" cols="100" rows="30"></textarea>
      <br />
      <button id="btn">Call Completion</button>
    </div>
    <script>
    </script>
  </body>
</html>

The page will look like this when viewed in your favorite browser:



We have a simple textarea and a button

Let’s add some JavaScript code that will ground our discussion on the topic of the NBA. Add this code inside the <script> . . . </script> tags:

const messages = [
  { role: "system", content: "You are a helpful assistant." },
  { role: "user", content: "Who won the NBA in 2020?" },
  {
    role: "assistant",
    content: "The Los Angeles Lakers won the NBA in 2020.",
  },
  { role: "user", content: "Where was it played?" },
];

let defaultMessage = "";
messages.forEach((item) => {
  defaultMessage += `role: ${item.role}\ncontent: ${item.content}\n\n`;
});

document.getElementById("dialog").value = defaultMessage;

The above code basically takes the contents of the messages array and neatly places it inside the HTML textarea. Your page now looks like this:


As you can see, we are asking ChatGPT to let us know where the NBA finals in 2020 were held. Let’s add some code to work with ChatGPT that sends data to it and obtains a reply. Add the following JavaScript getOpenAIChatCompletions() function right under the opening <script> tag:

async function getOpenAIChatCompletions() {
  const apiKey = "this-is-a-fake-chatgpt-api-key";

  let text = document.getElementById("dialog").value;

  // remove any * in text
  text = text.replace(/\*/g, '');

  const lines = text.split('\n');

  // delete empty items in lines array
  for (let i = 0; i < lines.length; i++) {
    if (lines[i] === '') {
      lines.splice(i, 1);
    }
  }

  const result = [];

  for (let i = 0; i < lines.length; i += 2) {
    if (lines[i] === '') {
      continue;
    }
    const role = lines[i].split(': ')[1];
    const content = lines[i+1].split(': ')[1];
    result.push({ role, content });
  }

  console.log(result);

  fetch("https://api.openai.com/v1/chat/completions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${apiKey}`,
    },
    body: JSON.stringify({
      max_tokens: 50,
      n: 1,
      stop: "\n",
      model: "gpt-3.5-turbo",
      temperature: 0.5,
      messages: result,
    }),
  })
    .then((response) => response.json())
    .then((data) => {
      const message = data.choices[0].message;
      const content = message.content;
      const role = message.role;

      const dialog = `role: ${role}\ncontent: ${content}`;

      document.getElementById("dialog").value += "*" + dialog + "*";
    });
}

Remember to replace the value of apiKey with the API key that you copied from https://openai.com.

The above code passes on the content of our textarea to ChatGPT, then obtains a reply. Data is sent as a JSON array that looks like this:


Finally, add the following event handler code for the button that calls the getOpenAIChatCompletions() function:

const button = document.querySelector("#btn");
button.addEventListener("click", () => {
  getOpenAIChatCompletions();
});

Our sample application is complete. View the latest version of your page and click on the “Call Completion button. You will receive a response that looks like this:


The response from ChatGPT is surrounded by *. This tells us that the NBA finals were played in Orlando. Let’s ask about what happened a year earlier in 2019 by posing this additional text:

role: user
content: How about in 2019? Which team won and where was it played?

Our page now looks like this:


Click on the “Call Completion” button. 



We are told that the 2019 NBA champions were the Toronto Raptors.

You can see from this very simple tutorial that it is quite easy to incorporate ChaGPT in your JavaScript applications.

The complete code is given below:

<!DOCTYPE html>
<html lang="en">
  <head>
     <title>ChatGPT with JavaScript (NBA)</title>
  </head>
  <body>
    <div>
      <h1>ChatGPT with JavaScript (NBA)</h1>
      <textarea id="dialog" cols="100" rows="30"></textarea>
      <br />
      <button id="btn">Call Completion</button>
    </div>
    <script>
      async function getOpenAIChatCompletions() {
        const apiKey = "this-is-a-fake-chatgpt-api-key";

        let text = document.getElementById("dialog").value;

        // remove any * in text
        text = text.replace(/\*/g, '');

        const lines = text.split('\n');

        // delete empty items in lines array
        for (let i = 0; i < lines.length; i++) {
          if (lines[i] === '') {
            lines.splice(i, 1);
          }
        }

        const result = [];

        for (let i = 0; i < lines.length; i += 2) {
          if (lines[i] === '') {
            continue;
          }
          const role = lines[i].split(': ')[1];
          const content = lines[i+1].split(': ')[1];
          result.push({ role, content });
        }

        console.log(result);

        fetch("https://api.openai.com/v1/chat/completions", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${apiKey}`,
          },
          body: JSON.stringify({
            max_tokens: 50,
            n: 1,
            stop: "\n",
            model: "gpt-3.5-turbo",
            temperature: 0.5,
            messages: result,
          }),
        })
          .then((response) => response.json())
          .then((data) => {
            const message = data.choices[0].message;
            const content = message.content;
            const role = message.role;

            const dialog = `role: ${role}\ncontent: ${content}`;

            document.getElementById("dialog").value += "*" + dialog + "*";
          });
      }

      const messages = [
        { role: "system", content: "You are a helpful assistant." },
        { role: "user", content: "Who won the NBA in 2020?" },
        {
          role: "assistant",
          content: "The Los Angeles Lakers won the NBA in 2020.",
        },
        { role: "user", content: "Where was it played?" },
      ];

      let defaultMessage = "";
      messages.forEach((item) => {
        defaultMessage += `role: ${item.role}\ncontent: ${item.content}\n\n`;
      });

      //console.log(defaultMessage);
      document.getElementById("dialog").value = defaultMessage;

      const button = document.querySelector("#btn");
      button.addEventListener("click", () => {
        getOpenAIChatCompletions();
      });

    </script>
  </body>
</html>

If you click on the Examples tab on the ChatGPT page you can find many examples that you can look into to explore other things that you can do.


The sky is the limit with regards to what is possible.


No comments:

Post a Comment