Code viewer for World: Aarekh Rana (AI_Practical_...
const openaiURL = "https://api.openai.com/v1/chat/completions"; // can POST to this 3rd party URL
const themodel = "gpt-3.5-turbo"; // the OpenAI model we are going to talk to


// default API key and prompt:
    var apikey = "";
    var theprompt = "hello";
    var apiKeyValid = false;

    // default body is margin 0 and padding 0 give it more whitespace:
    $('body').css("margin", "20px");
    $('body').css("padding", "20px");

//  Set API key

    function setkey() {
    apikey = $("#apikey").val().trim();

    if (!apikey) {
        $("#enterkey").html("<h3>Please enter a valid API key</h3><button onclick='resetApiKey();' class='ab-normbutton'>TRY WITH NEW API KEY</button>");
        apiKeyValid = false; // Set the flag to false
        return;
    }

    $.ajaxSetup({
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + apikey
        }
    });

    $.ajax({
        type: "POST",
        url: openaiURL,
        data: JSON.stringify({
            model: themodel,
            messages: [
                {
                    role: 'system',
                    content: 'You are a helpful assistant.'
                }
            ]
        }),
        dataType: "json",
        success: function (response) {
            console.log('Choices array:', response.choices);
            successKeyResponse(response);
        },
        error: function (xhr, status, error) {
            let errorResponse = JSON.parse(xhr.responseText);
            handleApiKeyResponse({ status: xhr.status, errorMessage: errorResponse.message });
        }
    });
}
    
    const threeScript = document.createElement('script');
    threeScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js';
    document.head.appendChild(threeScript);
    
    
    function successKeyResponse(response){
            $("#enterkey").empty()
            $("#enterkey").append("<b><p>Great! You are using a valid API key</p></b><button onclick='resetApiKey();' class='ab-normbutton'>TRY WITH NEW API KEY</button>");
            apiKeyValid = true;
        
    }
    
    
    function handleApiKeyResponse(response) {
        
        // Print response status in the box
        // $("#enterkey").html("<h3>Response Status: " + response.status + "</h3>");
    
         if (response.status === 401) {
            // Unauthorized (incorrect API key)
            $("#enterkey").empty()
            $("#enterkey").append("<b><p>Incorrect API Key. Please enter a valid API key</p></b><button onclick='resetApiKey();' class='ab-normbutton'>TRY WITH NEW API KEY</button>");
        } else {
            // Display generic error message
            $("#enterkey").empty()
            let errorMessage = response.errorMessage || "Unknown error";
            $("#enterkey").append("<b><p>Error: " + errorMessage + "</p></b><button onclick='resetApiKey();' class='ab-normbutton'>TRY WITH NEW API KEY</button>");
        }
}


    function resetApiKey() {
        // Reset the UI to allow entering a new API key
        $("#enterkey").html(`
            <h3>Please Enter The Valid API Key To Enjoy My Services</h3>
            <input style='width:25vw;' maxlength='2000' NAME="apikey" id="apikey" VALUE=''>
            <button onclick='setkey();' class="ab-normbutton">Submit</button>
        `);
}


document.write(`
    <style>
    
        <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>

        body {
            font-family: 'Arial', sans-serif;
            background-image: url('https://media.giphy.com/media/dq2Q82fsF19c4pNQDL/giphy.gif');
            background-size: cover;
            background-repeat: no-repeat;
            color: #333;
            margin: 0;
            padding: 0;
        }

        h1 {
            font-size: 72px;
            background: -webkit-linear-gradient(red, grey, black);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            text-align: center;
            margin-bottom: 20px;
        }

        .container {
            width: 60vw;
            margin: 20px;
            padding: 20px;
            border: 1px solid #ccc;
            background-color: rgba(255, 255, 255, 0.5); /* Adjust the alpha value for transparency */
            border-radius: 5px;
            margin-bottom: 10px;
            position: relative;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        input,
        button {
            margin-right: 10px;
        }

        #loading {
            display: none;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

        #outputContainer {
            margin-top: 10px;
            background-color: rgba(233, 236, 239, 0.5); /* Transparent background for outputContainer */
        }

        .button-container {
            margin-top: 10px;
            text-align: center;
        }

        #output {
            margin-top: 10px;
            background-color: rgba(233, 236, 239, 0.5); /* Transparent background for output */
        }

        .loader {
            border: 8px solid #f3f3f3;
            border-top: 8px solid #3498db;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
            display: inline-block;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        #credits {
            text-align: center;
            margin-top: 20px;
            color: #777;
        }

        #credits a {
            color: #007bff;
            text-decoration: none;
        }

        #credits a:hover {
            text-decoration: underline;
        }

        #current-time {
            position: fixed;
            top: 10px;
            right: 10px;
            font-size: 14px;
            color: #fff;
            z-index: 9999;
            background-color: rgba(0, 0, 0, 0.5); /* Add a semi-transparent background */
            padding: 5px;
            border-radius: 5px;
        }

        #current-day-date {
            position: fixed;
            top: 40px;
            right: 10px;
            font-size: 14px;
            color: #fff;
            z-index: 9999;
            background-color: rgba(0, 0, 0, 0.5);
            padding: 5px;
            border-radius: 5px;
        }

        #location-info {
            position: fixed;
            top: 70px;
            right: 10px;
            font-size: 14px;
            color: #fff;
            z-index: 9999;
            background-color: rgba(0, 0, 0, 0.5);
            padding: 5px;
            border-radius: 5px;
        }

    </style>

    <h1>Welcome to RanaGPT</h1>

    <div style="text-align: center">
        Running World:
        <a href='https://ancientbrain.com/world.php?world=2850716357' style="color: #007bff;">RanaGPT: The Second AI Practical WORLD 2</a>.
        <br> 
        Chat with
        <a href="https://platform.openai.com/docs/models/overview" style="color: #007bff;">GPT 3.5</a>
        using the
        <a href="https://en.wikipedia.org/wiki/OpenAI" style="color: #007bff;">OpenAI</a> API.
        <br> 
        This is the model
        <a href="https://en.wikipedia.org/wiki/ChatGPT" style="color: #007bff;">About ChatGPT</a>
        <a href="https://chat.openai.com" style="color: #007bff;">,Learn ChatGPT</a>
        uses.
        <br>
        Access Code
        <a href="https://ancientbrain.com/edit.world.php?world=8787097348" style="color: #007bff;">Here.</a>
    </div>

    <pre></pre>
    
    <div id="current-time"></div>
    <div id="current-time"></div>
    <div id="current-day-date"></div>
    <div id="location-info"></div>

    <div id="enterkey" class="container" style="background-color: rgba(233, 236, 239, 0.5);">
        <h3>Please Enter The Valid API Key To Enjoy My Services</h3>
        <input style='width:25vw;' maxlength='2000' NAME="apikey" id="apikey" VALUE=''>
        <button onclick='setkey();' class="ab-normbutton">Submit</button>
    </div>

    <pre></pre>

    <div class="container" style="background-color: rgba(233, 236, 239, 0.5);">
        <h3>Ask Me Anything...</h3>
        <p>If you want to draw something please ask me to find a code in jquery.</p>
        <p>Example: Give me a code to generate 5 circles using three.js liabrary in jquery.</p>
        <p>To find your images please scroll down the website.</p>
        <p>Don't worry if you haven't get your results in the first time, sometimes it needs to run more than one time to get desired results.
        <input style="width:50vw;" id="me" value="which planet has life other than Earth?" >
        <button onclick="sendchat();" class="ab-normbutton"> Send </button>
        <span id="loading" class="loader"></span>

        <!-- Temperature Adjustment Scale -->
        <div style="position: absolute; top: 20px; right: -400px; text-align: center;">
        <h4>Adjust Temperature</h4>
        <input type="range" min="0.1" max="1" step="0.1" value="0.7" id="temperatureRange" style="width: 150px;" list="temperatureList">
        <datalist id="temperatureList">
            <option value="0.1">
            <option value="0.2">
            <option value="0.3">
            <option value="0.4">
            <option value="0.5">
            <option value="0.6">
            <option value="0.7">
            <option value="0.8">
            <option value="0.9">
            <option value="1.0">
        </datalist>
        <p id="temperatureValue">By Default Temperature: 0.7</p>
        <p style="font-size: 12px;">Adjust the temperature for more specific or diverse results.</p>
    </div>
    </div>

    <div id="outputContainer" class="container" style="background-color: rgba(233, 236, 239, 0.5);">
        <h3>Here You Go!!</h3>
        <div id="output" class="button-container"></div>
        <div class="button-container">
            <button onclick="clearOutputs();" class="ab-normbutton"> Clear </button>
        </div>
    </div>

    <p> <i> Be warned that GPT replies are often completely inaccurate. <br>
        All LLM systems <a href="https://www.google.com/search?q=llm+hallucination" style="color: #007bff;"> "hallucinate"</a>.
        It is how they work. </i> </p>

    <div id="credits">
        Credits:
        <br>
        <a href="https://ancientbrain.com/" target="_blank"><img src="https://ancientbrain.com/images/logo.earth.png" alt="AncientBrain Logo" style="height: 30px;"></a>
        <a href="https://ancientbrain.com/" target="_blank">AncientBrain.com</a> /
        <a href="https://giphy.com/" target="_blank"><img src="https://giphy.com/static/img/giphy-be-animated-logo.gif" alt="Giphy Logo" style="height: 30px;"></a>
        <a href="https://giphy.com/" target="_blank">Giphy</a>/
        <a href="https://www.youtube.com/watch?v=wDtjBb4ZJwA" target="_blank"><img src="https://media.giphy.com/media/SVTPWzQWPCUKfji4fp/giphy.gif" alt="Youtube Logo" style="height: 30px;"></a>
        <a href="https://www.youtube.com/watch?v=wDtjBb4ZJwA" target="_blank">Youtube_Codevolution</a>
    </div>
`);


// Function to update the current time, day, date, country, and city.
    function updateInfo() {
        // Update the current time
        var now = new Date();
        var hours = now.getHours().toString().padStart(2, '0');
        var minutes = now.getMinutes().toString().padStart(2, '0');
        var seconds = now.getSeconds().toString().padStart(2, '0');
        var currentTimeString = hours + ':' + minutes + ':' + seconds;
    
        // Update the content of the element with id "current-time"
        document.getElementById('current-time').innerText = 'Current Time: ' + currentTimeString;
    
        // Update the content of the element with id "current-day-date"
        var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
        var day = days[now.getDay()];
        var date = now.getDate();
        var month = now.getMonth() + 1; // Month is zero-based
        var year = now.getFullYear();
        var currentDayDateString = day + ', ' + date + '/' + month + '/' + year;
    
        document.getElementById('current-day-date').innerText = currentDayDateString;
    
        
        // Get country and city
        $.ajax({
            url: 'https://ipapi.co/json/',
            dataType: 'json',
            success: function (data) {
                // Update the content of the element with id "location-info"
                var city = data.city;
                var country = data.country_name;
                document.getElementById('location-info').innerText = 'Location: ' + city + ', ' + country;
            },
            error: function () {
                // Handle error if location information cannot be retrieved
                document.getElementById('location-info').innerText = 'Location information not available';
            }
        });
}

// Initial update
    updateInfo();

// Update every minute (adjust the interval as needed)
    setInterval(updateInfo, 60000);


    function sendchat() {
    // Clear the GPT replies section
    $("#output").html("");
    $("#loading").show();

    theprompt = $("#me").val();

    // Check if the API key is valid
    if (isApiKeyValid()) {
        var thedata = {
            "model": themodel,
            "temperature": parseFloat($("#temperatureRange").val()),
            "messages": [{
                "role": "user",
                "content": theprompt
            }]
        };

        var thedatastring = JSON.stringify(thedata);

        $.ajaxSetup({
            headers: {
                "Content-Type": "application/json",
                "Authorization": "Bearer " + apikey
            }
        });

        $.ajax({
            type: "POST",
            url: openaiURL,
            data: thedatastring,
            dataType: "json",
            success: function (data, rc) {
                successfn(data, rc);
                executeReceivedCode(data.choices[0].message.content);
            },
            error: function () {
                errorfn();
            }
        });
    } 
    else {
        // Display an error message when the API key is not valid
        $("#output").html("<font color=red><b> Please enter a valid API key. </b></font>");
        $("#loading").hide();
    }
}


    function isApiKeyValid() {
        
        return apiKeyValid; // Replace with your actual variable or condition
}
    
    
    var a;
    
    function successfn(data, rc) {
        a = data;
        var answer = a.choices[0].message.content;
    
        // Display the output between the lines
        $("#output").html(answer);
        $("#loading").hide();
    
        // Log successful response to the console for debugging
        // console.log("Successful Response:", data);
    
        executeReceivedCode(answer);
}
    
    function errorfn(xhr, status, error) {
        if (apikey == "") {
            $("#output").html("<font color=red><b> Enter API key to be able to chat. </b></font>");
        } else {
            $("#output").html("<font color=red><b> Unknown error. </b></font>");
        }
    
        // Log error response to the console for debugging
        console.error("Error Response:", xhr.responseText);
    
        $("#loading").hide();
}
    
    
    function executeReceivedCode(code) {
        try {
            
            eval(code);
        } 
        catch (error) {
            
        }
}
    
    function clearOutputs() {
        $("#output").html("");
        $("canvas").remove();
}