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.
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
<!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>
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;
async function getOpenAIChatCompletions() {const apiKey = "this-is-a-fake-chatgpt-api-key";let text = document.getElementById("dialog").value;// remove any * in texttext = text.replace(/\*/g, '');const lines = text.split('\n');// delete empty items in lines arrayfor (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 button = document.querySelector("#btn");button.addEventListener("click", () => {getOpenAIChatCompletions();});
role: usercontent: How about in 2019? Which team won and where was it played?