Code viewer for World: Advance world: Graphic gen...
const threeScript = document.createElement('script');
threeScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js';
document.head.appendChild(threeScript);

const openaiURL = "https://api.openai.com/v1/chat/completions";
const themodel = "gpt-3.5-turbo";
var apikey = "";
var theprompt = "hello";

$('body').css("margin", "20px");
$('body').css("padding", "20px");

document.write(`
    <h1>Graphic Generator</h1>
    <p>Welcome to the Graphic Generator program! Please enter your API key and let us know what type of graphic you'd like to generate.</p>

    <div id=enterkey>
        <label for="apikey">Enter API key:</label>
        <input style='width:25vw;' maxlength='2000' NAME="apikey" id="apikey" VALUE=''>  
        <button onclick='setkey();' class=ab-normbutton >Set API key</button>
    </div>

    <div style="width:60vw; background-color:white;  border: 1px solid black; margin:20; padding: 20px;">
        <h3>What type of graphic would you like?</h3>
        <label for="graphicType">Graphic Type:</label>
        <input style="width:40vw;" id="graphicType" value="Generate JavaScript code using three.js and jQuery to create a scene with shapes positioned in a way, it looks like a tree.">
        <button onclick="generateGraphic();" class=ab-normbutton >Generate Graphic</button> 
    </div>

    <div style="width:60vw; background-color:#ffffcc;  border: 1px solid black; margin:20; padding: 20px;">
        <h3>GPT replies</h3>
        <div id=them> </div>
    </div>

    <div style="width:60vw; background-color:#ccffcc;  border: 1px solid black; margin:20; padding: 20px; position: relative;">
        <h3>Temperature Slider</h3>
        <input type="range" min="0" max="1" step="0.1" value="0.7" id="temperatureSlider" style="width: 50%;" oninput="updateTemperatureValue(this.value)">
        <span id="temperatureValue">0.7</span>
    </div>

    <button onclick="clearScreen();" class=ab-normbutton >Clear Screen</button>
    <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"> "hallucinate"</a>.
    It is how they work.</i></p>

    <pre></pre>

    <div id="drawing-section" style="width: 60vw; height: 300px; background-color: #ccffff; border: 1px solid black; margin: 20; padding: 20px; overflow: hidden;">
        <h3>Generated Graphic</h3>
        <!-- Display the generated graphic here -->
    </div>
`);

function setkey() {
    apikey = jQuery("input#apikey").val();
    apikey = apikey.trim();
    $("#enterkey").html("<b> API key has been set. </b>");
}

document.getElementById('graphicType').onkeydown = function (event) { if (event.keyCode == 13) generateGraphic(); };

function generateGraphic() {
    var graphicType = $("#graphicType").val();
    theprompt = `Generate a ${graphicType} graphic`;

    var thedata = {
        "model": themodel,
        "temperature": parseFloat(temperatureValue),
        "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 (d, rc) { successfn(d, rc); },
        error: function () { errorfn(); }
    });
}

var a;

function successfn(data, rc) {
    a = data;
    var answer = a["choices"][0].message.content;
    $("#them").html("<p>" + answer + "</p>");

    runReceivedCode(answer);
}

function errorfn() {
    if (apikey == "") $("#them").html("<font color=red><b> Enter API key to be able to chat. </b></font>");
    else $("#them").html("<font color=red><b> Unknown error. </b></font>");
}

function clearScreen() {
    $("#them").html("");
    $("#drawing-section").html(""); // Clear the drawing section
}

var temperatureValue = 0.7;

function updateTemperatureValue(value) {
    temperatureValue = parseFloat(value).toFixed(1);
    $("#temperatureValue").text(temperatureValue);
}

function runReceivedCode(code) {
    try {
        var scriptRegex = /<script>([\s\S]*?)<\/script>/gi;
        var match;
        var extractedCode = '';

        // Extract the content of the first <script> block
        if ((match = scriptRegex.exec(code)) !== null) {
            extractedCode = match[1];
        }

        if (extractedCode) {
            eval(extractedCode);
        } else {
            console.error("No executable JavaScript found in the response.");
        }
    } catch (error) {
        console.error("Error executing received code:", error);
    }
}