Code viewer for World: Colour Palette Generator w...

// Cloned by Ronan Lynch on 17 Nov 2024 from World "Chat with GPT model" by Starter user 
// Please leave this clone trail here.


const cohereURL = "https://api.cohere.ai/v1/generate";           // can POST to this 3rd party URL
const themodel = "command";       
const openaiURL = "https://api.openai.com/v1/chat/completions";  
const openaiModel = "gpt-4o";

// default API key and prompt:

var apikey = "CG4CmzzW6R9GYDr7OewEbU5kovJrAlTxnL7usGLP";
let openaiKey = null;
var theprompt = "hello";
 
document.write ( `

<style>

  .background{
    text-align: center;
    background-color: #861c8a;
    min-height: 2500px;
  }
  .intro{
    background-color: #01c8a1;
    width:700px;
    margin-left:600px;
  }
  #colorPicker {
    background-color: none;
    outline: none;
    border: none;
    height: 40px;
    width: 80px;
    cursor: pointer;
  }       
  #box {
    outline: none;
    border: 2px solid #333;
    border-radius: 50px;
    height: 40px;
    width: 100px;
    padding: 0 10px;
  }
</style>
<div class="background">

<div class="intro">
<h1> Colour Palette Generator </h1>

<pre>
</pre>

<h3> Enter API key </h3>

This page uses the cohere api and Openai api to generate colour palettes. Both of these api's require api keys.<br>
<br>
Cohere does not seem very strict on the keys so the key has been hardcoded into this world. Openai is strict however so you will need to enter your own key below.<br>
<br>
Then you can enter a colour and you will receive two colour palettes below based on your colour. 1 from Cohere and 1 from OpenAI<br>
<br>
FUN FACT: The colours used in this world were actually generated by Cohere.
<br>
<p>

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

</div>

<pre>
</pre>

<div style="position: absolute; width:200px; background-color:#ffffff;  border: 1px solid black; top: 505px; left: 820px; padding: 20px; text-align:center">
<h1>Colour Picker</h1>
    <div class="main">
        <!-- To select the color -->
        Color Picker: <input type="color" 
            id="colorPicker" value="#6a5acd">

        <!-- To display hex code of the color -->
        Hex Code: <input type="text" id="box">
    </div>
</div>
<div style="width:660px; background-color:#7a35c4;  border: 1px solid black; margin-left:600px;; padding: 20px; text-align:center">
<h3> Enter a colour (ex. #123456 or blue) </h3>
<INPUT style="width:180px; text-align:center" id=me value="#123456" >
<button onclick="sendchat(); sendOpen();"     class=ab-normbutton > Send </button> 
</div>

<div style="position: absolute; width:5vw; background-color:#ffffff;  border: 1px solid black; top: 505px; left: 650px; padding: 20px; text-align:center">
<h3> Cohere's Palette </h3>
<div id=them > </div>
</div>

<div style="position: absolute; width:5vw; background-color:#ffffff;  border: 1px solid black; top: 505px; left: 1100px; padding: 20px; text-align:center">
<h3> OpenAI's Palette </h3>
<div id=open > </div>
</div>

<pre>

</pre>
</div>
` );



// Enter will also send chat:

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

// --- Send my line of text ----------------------------------------------------------------

function sendchat()
{
  $("#them").html ( "" );
  const aprompt = document.getElementById('me').value;
  const theprompt = "Generate a colour palette of hex values based around the colour" + aprompt+ ". Don't include any text, just a list of hex codes, seperated by spaces. Include the hash symbol for each one also.";
  const options = {
    method: 'POST',
    headers: {
      accept: 'application/json',
      'content-type': 'application/json',
      authorization: 'Bearer ' + apikey
    },
    body: JSON.stringify({
      truncate: 'END',
      return_likelihoods: 'NONE',
      prompt: theprompt
    })
  };
  
   fetch(cohereURL, options)
    .then(response => response.json())
    .then(response => {
     const text = response.generations[0].text; 
     console.log(response);
     const words = text.split(" ");
     for (var i = 1; i < words.length; i++) {
         console.log(words[i][0]);
         if(words[i][0] != '#'){
             break;
         } else{
           var div = document.createElement("div");
           div.style.width = "100px";
           div.style.height = "100px";
           div.style.background = words[i];
           div.style.border = "1px solid black";
           div.style.align = "center";
           div.innerHTML = words[i];
           document.getElementById("them").appendChild(div);
         }
     }
});
}
 
function setkey() {
    // Get the key from the input field and trim whitespace
    const keyInput = jQuery("input#apikey").val().trim();

    if (!keyInput) {
        alert("Please enter a valid API key.");
        return;
    }

    // Store the key in memory only
    openaiKey = keyInput;
    
    console.log("API key set:", openaiKey);

    // Update the UI to indicate the key has been set
    $("#enterkey").html("<b>API key has been set.</b>");
}

function sendOpen() {
    $("#open").html ( "" );
    const aPrompt = $("#me").val().trim();

    if (!aPrompt) {
        $("#open").html("<font color=red><b>Please enter a message before sending.</b></font>");
        return;
    }

    if (!openaiKey) {
        $("#open").html("<font color=red><b>Enter API key to be able to chat.</b></font>");
        return;
    }

    console.log("Using API Key:", openaiKey); // Debugging the API key
    const userPrompt = "Generate a colour palette of hex values based around the colour" + aPrompt + ". Don't include any text, just a list of hex codes, seperated by spaces. Include the hash symbol for each one also.";

    const requestData = {
        model: openaiModel, // Ensure `openaiModel` is defined
        temperature: 0.7,
        messages: [{ role: "user", content: userPrompt }]
    };

    const requestString = JSON.stringify(requestData);

    console.log("Request Data:", requestData); // Debugging the request payload

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

    console.log("Authorization Header:", "Bearer " + openaiKey); // Debugging the Authorization header

    $.ajax({
        type: "POST",
        url: openaiURL, // Ensure `openaiURL` is set to the correct endpoint
        data: requestString,
        dataType: "json",
        success: function (data, rc) {
            handleSuccess(data, rc);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.error("AJAX Error:", jqXHR.responseText); // Debugging the error response
            handleError();
        }
    });
}


// Global variable for debugging API responses
let debugData = null;

// Success handler for API responses
function handleSuccess(data, rc) {
    debugData = data; // Store response for debugging
    const out = data?.choices?.[0]?.message?.content || "No response from the API.";
    console.log(out);
    const words = out.split(" ");
    console.log(words);
     for (var i = 1; i < words.length; i++) {
         if(words[i][0] != '#'){
             break;
         } else{
           var div = document.createElement("div");
           div.style.width = "100px";
           div.style.height = "100px";
           div.style.background = words[i];
           div.style.border = "1px solid black";
           div.style.align = "center";
           div.innerHTML = words[i];
           document.getElementById("open").appendChild(div);
         }
     }

}

// Error handler for failed API requests
function handleError() {
    if (!openaiKey) {
        $("#open").html("<font color=red><b>Enter API key to be able to chat.</b></font>");
    } else {
        $("#open").html("<font color=red><b>An unknown error occurred. Please try again.</b></font>");
    }
}
 

function myColor() {
        // Get the value return by color picker
        var color = document.getElementById('colorPicker').value;
        // Set the color as background
        document.body.style.backgroundColor = color;
            // Take the hex code
        document.getElementById('box').value = color;
}
// When user clicks over color picker,
// myColor() function is called
document.getElementById('colorPicker')
.addEventListener('input', myColor);