Code viewer for World: CA318 Assignment - Hello W...
// Function to initiate the world.
function startWorld() {
    // This function is called when the world starts.
    callOpenAI();
}

// Function to make a call to the OpenAI API.
function callOpenAI() {
    var xhr = new XMLHttpRequest(); // Creating a new XMLHttpRequest object.
    xhr.open("POST", "https://api.openai.com/v1/chat/completions", true); // Setting up the request as a POST to the OpenAI API endpoint.

    // Setting the required HTTP headers for the OpenAI API request.
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader("Authorization", "Bearer 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"); // Replace with your actual API key.

    // Function to handle the state changes of the request.
    xhr.onreadystatechange = function () {
        // Check if the request is completed (readyState == 4) and was successful (status == 200).
        if (xhr.readyState == 4 && xhr.status == 200) {
            var response = JSON.parse(xhr.responseText); // Parsing the JSON response from the API.
            displayResponse(response.choices[0].message.content); // Displaying the response on the webpage.
        }
    }

    // Data to be sent in the API request, defining the model and message content.
    var data = {
        model: "gpt-3.5-turbo",
        messages: [{
            role: "user",
            content: "Hello, world!"
        }]
    };

    xhr.send(JSON.stringify(data)); // Sending the request with the JSON data.
}

// Function to display the response on the webpage.
function displayResponse(response) {
    document.write(`
        <h1>Response from OpenAI</h1>
        <p>${response}</p>
    `); // Using template literals to insert the response in HTML format.
}

startWorld(); // Initiating the world by calling startWorld function.