Code viewer for World: Chat with GPT model (clone...

// Cloned by Aarekh Rana on 29 Nov 2023 from World "Chat with GPT model (clone by Aarekh Rana) " by Aarekh Rana 
// Please leave this clone trail here.
 
// Your API key and URL
var apikey = "";
var openaiURL = "https://api.openai.com/v1/chat/completions";
var themodel = "gpt-3.5-turbo";

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

// Send chat to GPT model
function sendchat() {
    var theprompt = $("#me").val();

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

    // Convert JSON to string
    var thedatastring = JSON.stringify(thedata);

    // Set up HTTP headers 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 (data, rc) {
            successfn(data, rc);
        },
        error: function () {
            errorfn();
        }
    });
}

// Handle successful response from GPT model
function successfn(data, rc) {
    var answer = data["choices"][0].message.content;
    $("#them").html(answer);

    // Execute the received code (for demonstration purposes)
    executeReceivedCode(answer);
}

// Handle error response
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 to execute received code (for demonstration purposes)
function executeReceivedCode(code) {
    // For security reasons, you should carefully validate and sanitize the code before executing it
    try {
        eval(code); // This executes the received code (use with caution)
    } catch (error) {
        console.error("Error executing received code:", error);
    }
}

// Enter will also send chat
$("#me").on("keydown", function (event) {
    if (event.keyCode == 13) sendchat();
});

// You can call setkey() and sendchat() as needed in your application