Code viewer for World: OpenAI API
const apiURL = "https://open-ai21.p.rapidapi.com/conversationgpt35"; // API endpoint
let apiKey = ""; // Placeholder for the API key
let chatHistory = []; // To track the chat history

// Initialize the UI dynamically
function initializeUI() {
  const body = document.body;
  body.style.margin = "20px";
  body.style.padding = "20px";

  body.innerHTML = `
    <h1> Chat with OpenAI GPT-3.5 </h1>

    <div id="enterkey">
      Enter API key: 
      <input style="width:25vw;" maxlength="2000" id="apikey" value="">  
      <button onclick="setApiKey();" style="padding:10px; background-color:#4CAF50; color:white; border:none; cursor:pointer; border-radius:5px;">Set API Key</button>
    </div>

    <div style="margin-top:20px;">
      <h3> Enter a "prompt" </h3>
      <input style="width:50vw;" id="userPrompt" placeholder="Type your message here">
      <button onclick="sendMessage();" style="padding:10px; background-color:#4CAF50; color:white; border:none; cursor:pointer; border-radius:5px;">Send</button> 
    </div>

    <div style="margin-top:20px; background-color:#f9f9f9; padding:15px; border:1px solid #ccc; border-radius:5px;">
      <h3> AI Replies </h3>
      <div id="response"> </div>
    </div>
    
    <p style="margin-top:20px; color:#555;"> 
      <i> Note: AI responses may not always be accurate. Evaluate content critically. </i>
    </p>
  `;
}

// Set the API key
function setApiKey() {
  apiKey = document.getElementById("apikey").value.trim();
  if (apiKey) {
    document.getElementById("enterkey").innerHTML = "<b> API key has been set. </b>";
  } else {
    alert("Please enter a valid API key.");
  }
}

// Display messages in the response area
function displayMessage(content) {
  const responseDiv = document.getElementById("response");
  responseDiv.innerHTML = `<b>AI:</b> ${content}`;
}

// Send a message to the OpenAI API
function sendMessage() {
  const userMessage = document.getElementById("userPrompt").value.trim();

  if (!apiKey) {
    displayMessage("Error: Please set your API key first.");
    return;
  }

  if (!userMessage) {
    displayMessage("Error: Please enter a prompt to send.");
    return;
  }

  // Add user message to chat history
  chatHistory.push({ role: "user", content: userMessage });

  // Prepare request payload
  const data = JSON.stringify({
    messages: chatHistory,
    web_access: false,
    system_prompt: '',
    temperature: 0.9,
    top_k: 5,
    top_p: 0.9,
    max_tokens: 256
  });

  // Set HTTP headers and make the request
  fetch(apiURL, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-RapidAPI-Key": apiKey,
      "X-RapidAPI-Host": "open-ai21.p.rapidapi.com"
    },
    body: data
  })
    .then(response => {
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      return response.json();
    })
    .then(responseData => {
      // Display the result from the API response
      const botMessage = responseData.result || "No response from the server.";
      
      // Add bot response to chat history
      chatHistory.push({ role: "assistant", content: botMessage });

      // Display the bot's response
      displayMessage(botMessage);
    })
    .catch(error => {
      console.error("Error:", error);
      displayMessage("An error occurred while fetching the response.");
    });
}

// Add Enter key functionality
document.addEventListener("keydown", function (event) {
  if (event.target.id === "userPrompt" && event.key === "Enter") {
    sendMessage();
  }
});

// Initialize the UI
initializeUI();