Code viewer for World: OpenAI demo
// talk to ChatGPT API
// adapted from:
//  https://platform.openai.com/docs/api-reference/making-requests


// the main UI issue is how to get the API key into the call:

var  apikey = "";


// the other UI issue is how to collect queries to send to ChatGPT 

var thestring = "when did henry vii die";



 


const openaiURL = "https://api.openai.com/v1/chat/completions";

  // can POST to this 3rd party URL
  

// 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": "gpt-3.5-turbo",
     "temperature": 0.7,
     "messages": [{
         "role": "user", 
         "content": thestring
        }] 
   };
   
   
// 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 )
 {
//     document.write (data + " " + rc); 
     a = data;
     var answer = a["choices"][0].message.content;
     document.write ( answer );
 }
 
 function errorfn()
 {
     if ( apikey == "" ) document.write ("Edit code and enter API key");
     else document.write ( "Unknown error." ); 
 }