Code viewer for World: GPT Short Story Teller (by...

// Cloned by Jakub on 21 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 

var charDetails = [];

var temp = 1.0;

var story = ""

var flag = 0 //used to determine wether the user likes the introduction and wants to expand the story or not

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


 
document.write ( `

<h1> Make your own short story with GPT3.5 </h1>

Based on World:
<a href='https://ancientbrain.com/world.php?world=2850716357'>Chat with GPT model</a>.
<br> 
Write a short story
  <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>

The crucial thing is you need an    "API key" to talk to OpenAI. <br>
Register for free and get your API key (Its only free for a month it expires after and needs to be topped up !)
<a href='https://platform.openai.com/account/api-keys'>here</a>.
<br>
You enter your API key below and then chat away.
Then communications to OpenAI come from your IP address using your API key. 
<br>
<p>

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

<pre>

</pre>

    <div style="width:20vw; background-color:#fffccc;  border: 1px solid black; margin:20; padding: 20px; float: right;">
    <h3> Story Details </h3>
    <h4 id=genre></h4>
    <h4 id=name></h4>
    <h4 id=year></h4>
    <h4 id=setting></h4>
    </div>

<div style="width:90vw; background-color:white;  border: 3px solid black; margin:20; padding: 15px;">
<h3> Enter a exactly 4 parameters seperated by spaces: Genre, Name, Year, Setting. For your story.</h3>
<hr>
<h3>Press send once a response is given, press expand once expand returns press finish to tie up your story</h3>
<INPUT style="width:50vw;" id=me value="Thriller Joe 1999 Mars" >
<button onclick="sendchat();"     class=ab-normbutton > Send </button> 
<hr>
<h4>Set the AI temperature, between 0.5 and 1.0, higher the temperature the more outlandish the story can be.</h4>
<INPUT style="width:20vw;" id=temp>
<button onclick="changetemp();"     class=ab-normbutton > Change </button>
</div>





<button onclick="sendchat();"     class=ab-normbutton> Expand </button> <button onclick="sendchat();"     class=ab-normbutton> Finish </button> <button onclick="reset();"     class=ab-normbutton> Reset </button> <p>Press reset before generating a new story</p>
<div style="width:60vw; background-color:#fffccc;  border: 1px solid black; margin:20; padding: 20px;">
<h3> Your short story</h3>
<div id=them > </div>
</div>


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

` );


function setkey()          
{
	apikey =  jQuery("input#apikey").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 reset(){
    flag = 0;
    story = "";
}

function changetemp(){
    temp = parseFloat(jQuery("input#temp").val());
    console.log(temp);
}

function sendchat()
{
  if (flag === 0) {
  theprompt = $("#me").val();
  charDetails = theprompt.split(" ");
  $("#genre").html ( charDetails[0] );
  $("#name").html ( charDetails[1] );
  $("#year").html ( charDetails[2] );
  $("#setting").html ( charDetails[3] );
  theprompt = "Write a start to a story " +charDetails[0] + " about " +charDetails[1]+" in the year " +charDetails[2]+ " in " +charDetails[3]+ " max 75 words ";
  //console.log(theprompt);
  //console.log(temp);
  }
  if(flag ===1){
      theprompt = "Write the main body of a story of maximum 300 words that starts like this:" + story;
      //console.log(theprompt);
  }
  if(flag >= 2){
      theprompt = "Write a maximum 100 word ending to this story:" + story;
  }
  flag +=1;
  
  
// construct request as JSON
// "Lowering temperature means it will take fewer risks, and completions will be more accurate and deterministic. Increasing temperature will result in more diverse completions."

var thedata = {
     "model": themodel,
     "temperature": temp,
     "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;
     story += answer;
     console.log(story)
     $("#them").html ( story );
 }
 
 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>" ); 
 }