JavaScript code to make API calls to ChatGPT in a webserver

PHOTO EMBED

Fri Apr 07 2023 23:48:00 GMT+0000 (Coordinated Universal Time)

Saved by @snh345 #javascript

function fetchStuff(prompt){


  updateChat(messages, "user", prompt);
  
  var to_send = [];
  // tres 4/6 iterate through messages array and only load relevant samples
  foreach (message in messages) {
    if (message["user"] == socket.id || message["user"] == "all") {
      to_send.push(message);
    }
  }
  
  fetch("https://api.openai.com/v1/chat/completions", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: "Bearer sk-(your key goes here)",
  },

  body: JSON.stringify({
    "model": "gpt-3.5-turbo",
    // tres 4/6 updated to send to_send
    "messages": to_send
  }),

})

  .then((response) => response.json())
  .then((data) => {
    let answer = data.choices[0].message.content;
    updateChat(messages, "assistant",data.choices[0].message.content);
    console.log(answer);
    io.sockets.emit('gpt-response', {
      message: "\n" + answer})
      console.log(messages)
  })
  .catch((error) => console.error(error));

} 
content_copyCOPY

Works pretty well, but you also need the function updateChat(), which appends a JSON array with the messages you pass into and receive from GPT.