Code viewer for World: Practical 2 - Hello World
// Define API URL and model
const openaiURL = "https://api.openai.com/v1/chat/completions";
const themodel = "gpt-3.5-turbo"; // Example model

// Global variable for API key
var apikey = "";

// Apply basic styling
$('body').css({ "margin": "20px", "padding": "20px" });

// HTML content using document.write
document.write(`
    <h1>Simple OpenAI API Example</h1>
    <div>
        Enter API key: 
        <input style='width:25vw;' maxlength='2000' id="apikey" placeholder="Enter your API key here">
        <button onclick='setApiKey();'>Set API key</button>
    </div>
    <div>
        <h3>Enter a "prompt"</h3>
        <input style='width:50vw;' id="user-input" placeholder="Enter your prompt here">
        <button onclick="sendRequest();">Send</button>
    </div>
    <div>
        <h3>GPT replies</h3>
        <div id="response"></div>
    </div>
`);

// Function to set API key
function setApiKey() {
    apikey = $("#apikey").val().trim();
    if (apikey) {
        $("#apikey").hide(); // Hide the input field
        $("#set-api-key-button").hide(); // Hide the set button
        $("#api-key-label").hide(); // Hide the label
        $("#reset-api-key").show(); // Show the reset button
        $("#api-key-set-message").show(); // Show the "API key has been set" message
        console.log("API Key has been set!");
        console.log("Current prompt: ", promptForAi);
    } else {
        showCustomAlert("Please enter an API key.");
    }
}

// Function to send request to OpenAI
function sendRequest() {
    if (!apikey) {
        alert("Please set the API key first.");
        return;
    }

    const theprompt = document.getElementById('user-input').value;

    var thedata = {
        "model": themodel,
        "temperature": 0.7,
        "messages": [{ "role": "user", "content": theprompt }]
    };

    $.ajax({
        type: "POST",
        url: openaiURL,
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + apikey
        },
        data: JSON.stringify(thedata),
        dataType: "json",
        success: function(data) {
            var answer = data.choices[0].message.content;
            document.getElementById('response').innerText = answer;
        },
        error: function() {
            var errorMsg = "Error: Unable to fetch response. Please check your API key and network connection.";
            document.getElementById('response').innerText = errorMsg;
        }
    });
}