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

// Cloned by Reeve Barreto on 17 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

// default API key and prompt:

let API_BASE_URL = "https://api.openai.com/v1/";
var apikey = "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";

let character_1 = "";
let character_2 = "";
let scene = ""

let story = {}

let loader = document.getElementById("loader")

// default body is margin 0 and padding 0 
// give it more whitespace:

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

document.write ( `
<style>
.loader {
    display: none;
    position: relative;
    top:50%;
    left:50%;
    width: 48px;
    height: 48px;
    border: 5px solid #000;
    border-bottom-color: transparent;
    border-radius: 50%;
    box-sizing: border-box;
    animation: rotation 1s linear infinite;
}

@keyframes rotation {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
} 
</style>

<span class="loader"></span>

<h1> Chat with GPT model </h1>

Running World:
<a href='https://ancientbrain.com/world.php?world=2850716357'>Chat with GPT model</a>.
<br> 
Chat with
  <A HREF="https://platform.openai.com/docs/models/overview">GPT 3.5</A>
 using the 
<A HREF="https://en.wikipedia.org/wiki/OpenAI">OpenAI    </A>  API.
 <br> 
 This is the model
   <A HREF="https://en.wikipedia.org/wiki/ChatGPT">ChatGPT</A>   uses.

<pre>

</pre>

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

<pre></pre>

<div style="width:60vw; background-color:white;  border: 1px solid black; margin:20; padding: 20px;">
<h3> Enter a "prompt" </h3>
<input style="margin-top: 10px; width:100%; padding: 5px 20px;" id="character_1" placeholder="who is character 1" >
<input style="margin-top: 10px; width:100%; padding: 5px 20px;" id="character_2" placeholder="who is character 2" >
<input style="margin-top: 10px; width:100%; padding: 5px 20px;" id="scene" placeholder="what scene?" >
<button onclick="sendchat();" style="display: block; padding: 5px 20px; margin-top: 10px" class=ab-normbutton > Send </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>
` );

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

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

async function sendchat() {
    character_1 = $("#character_1").val();
    character_2 = $("#character_2").val();
    scene = $("#scene").val();
    
    const prompt = `characters: ${character_1} & ${character_2}. scene: ${scene}`;
  
    // construct request as JSON
    let the_input = {
         "model": "gpt-3.5-turbo",
         "temperature": 0.7,
         "messages": [
            {
                "role": "system",
                "content": `You will be provided 2 characters and a scene. Give the characters funny names and create a comedic sketch with four sarcastic dialogues between them relevant to the scene. Provide a brief narration of the sketch (Max length: 3000 characters). Format the output in JSON as {sketch: [character: "", dialogue: ""], narration: ""}.`
            }, 
            {
                "role": "user", 
                "content": prompt
            }
        ] 
    };
    
    let image_input_1 = {
        "model": "dall-e-2",
        "prompt": `a picture of ${character_1}`,
        "n": 1,
        "size": "256x256"
    }
    
    let image_input_2 = {
        "model": "dall-e-2",
        "prompt": `a picture of ${character_2}`,
        "n": 1,
        "size": "256x256"
    }
    
    let the_input_string = JSON.stringify ( the_input );
    let the_image_string_1 = JSON.stringify ( image_input_1 );
    let the_image_string_2 = JSON.stringify ( image_input_2 );
    
    try {
        $.ajaxSetup({
           headers:
           {
                "Content-Type": "application/json",
                "Authorization": "Bearer " + apikey  
           }
        });
        
        $("#them").html(`
            <p style="font-weight>
                Sending request!
            </p>
        `)
        
        let res_1 = await $.ajax({
            type: "POST",
            url: API_BASE_URL + "chat/completions",
            data: the_input_string,
            dataType: "json",
        });
        
        let res_2 = await $.ajax({
            type: "POST",
            url: API_BASE_URL + "images/generations",
            data: the_image_string_1,
            dataType: "json",
        });
        
        let res_3 = await $.ajax({
            type: "POST",
            url: API_BASE_URL + "images/generations",
            data: the_image_string_2,
            dataType: "json",
        });
        
        const { sketch, narration } = JSON.parse(res_1["choices"][0].message.content);
        
        // const audio_input = {
        //     "model": "tts-1",
        //     "input": narration,
        //     "voice": "alloy"
        // }
        // const the_audio_string = JSON.stringify(audio_input);
        
        // let res_4 = await $.ajax({
        //     type: "POST",
        //     url: API_BASE_URL + "audio/speech",
        //     data: the_audio_string,
        // })
        
        story = {
            sketch,
            narration,
            character_1_img: res_2.data[0].url, 
            character_2_img: res_3.data[0].url,
            // audio: res_4
        };
        
        $("#them").html(`
            <p style="font-weight: bold">
                ${story.narration}
            </p>
        `)
        
        for (let i=0; i < story.sketch.length; i++) {
            $("#them").append(`
                <div style="display: flex; align-items: center; padding: 1rem; margin: 1rem;">
                    <img src=${i % 2 == 0 ? story.character_1_img : story.character_2_img} width="64px" height="64px" style="border-radius: 20rem">
                    <div style="display:flex; padding: 0.5rem;">
                        <p style="font-weight: bold">${story.sketch[i].character}: </p>
                        <p>${story.sketch[i].dialogue}</p>
                    </div>
                </div>
            `);
        }
        
        // $("#them").append(`
        //     <audio controls autoplay>
        //         <source src=${story.audio} type="audio/mpeg">
        //     </audio>
        // `)
        
    } catch (error) {
        console.log(error);
        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>" ); 
    }
}