Code viewer for World: New World trial 1 AI api
// Cloned by Aarekh Rana on 22 Nov 2023 from World "Chat with GPT model" by Starter user 
// Please leave this clone trail here.

// talk to OpenAI GPT model (ChatGPT)
// adapted from: https://platform.openai.com/docs/api-reference/making-requests

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";

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

// Enhanced UI - HTML Structure
document.write(`
    <div class="container">
        <h1 class="header">Chat with GPT model</h1>
        <div class="api-key-section">
            <h3>Enter API key</h3>
            <input type="text" id="apikey" placeholder="Enter your API key">
            <button onclick="setkey();" class="set-api-btn">Set API Key</button>
        </div>

        <div class="chat-section">
            <h3>Enter a Prompt</h3>
            <input type="text" id="me" placeholder="Type your prompt here">
            <button onclick="sendchat();" class="send-btn">Send</button>
        </div>

        <div class="response-section">
            <h3>GPT Replies</h3>
            <div id="them"></div>
        </div>

        <button onclick="clearScreen();" class="clear-btn">Clear Screen</button>

        <div class="drawing-section" id="drawing-section">
            <h3>Drawing Section</h3>
            <!-- Add your drawing elements here -->
        </div>
    </div>
`);

// Your existing JavaScript functions (setkey, sendchat, successfn, errorfn, clearScreen, runReceivedCode) go here.


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

// Enter will also send chat:
document.getElementById('me').onkeydown = function (event) { if (event.keyCode == 13) sendchat(); };

// --- Send my line of text ----------------------------------------------------------------
function sendchat() {
    theprompt = $("#me").val();

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

    // then as string representing that JSON:
    var thedatastring = JSON.stringify(thedata);

    // HTTP headers must be set up with API key: 
    $.ajaxSetup({
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + apikey
        }
    });

    // POST to 3rd party URL: 
    $.ajax({
        type: "POST",
        url: openaiURL,
        data: thedatastring,
        dataType: "json",
        success: function (d, rc) { successfn(d, rc); },
        error: function () { errorfn(); }
    });
}

// global variable to examine return data in console 
var a;

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

    // Run the code received from GPT and display the result in the drawing section
    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
}

function runReceivedCode(code) {
    // Implement the logic to run the received code and display the result in the drawing section
    // For example, you can use eval() to execute the code
    try {
        eval(code);
    } catch (error) {
        console.error("Error executing received code:", error);
    }
}