Code viewer for World: OpenAI summarise text
// MH edit
// moved to top
var API_KEY =   "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";



document.write (`

<h1> Practical 2 - Simple Hello World </h1>
<p style="color:red">
Run Test 1 first as it gets file_id that is needed by the Test 2.
</p>

<p>
--------------------------------------------------------------------------------
</p>
<p> <strong>
Test 1 - uploading document successfully (pdf,txt):
</strong></p>

<form action="https://api.openai.com/v1/files" method="post" enctype="multipart/form-data">
  <input name="file" type="file" multiple>
  <input name="purpose" id="purpose" type="hidden" value="assistants">
  <button type="submit">Upload</button>
</form>

</p>
<p id=file_id>
</p>

<p>
--------------------------------------------------------------------------------
</p>


<p> <strong>
Test 2 - communicating with assistants API:
</strong></p>

<p>
Section for error messages (if any).
</p>
<p id=output_p0>
</p>
<p>
    <button type="submit" onclick="call_apis()">Call APIs</button>
</p>
</p>
<p>
Button click calls API's in a blocking way. One click is enough and it takes 20-40seconds to execute. Blocking behaviour is fixed in the full aplication.
</p>

<p>
--------------------------------------------------------------------------------
</p>
<p>
Some information bits from AI API:
</p>
<p id=output_p1>
</p>

<p id=output_p2>
</p>

<p id=output_p3>
</p>

<p id=output_p4>
</p>

<p>
--------------------------------------------------------------------------------
</p>
<p>
Status of the assistants run:
</p>
<p id=output_p5>
</p>

<p>
--------------------------------------------------------------------------------
</p>
<p>
Message response from AI:
</p>
<p id=output_p6>
</p>


`);


var assistant_id = "";
var thread_id = "";
var run_id = "";
var response = "";
var file_id = "";

//------------------------------------------------------------------------------
// --- Handling file uploads
const form = document.querySelector('form');
form.addEventListener('submit', handle_submit);

function handle_submit(event) {
  event.preventDefault();
  
  const url = 'https://api.openai.com/v1/files';
  const formData = new FormData(form);


  const fetchOptions = {
    method: 'post',
    headers: {
        "Authorization": "Bearer " + API_KEY,
        "OpenAI-Beta": "assistants=v1"
    },
    body: formData
  };

  fetch(url, fetchOptions).then(response => response.json()).then(confirm_upload);
}

function confirm_upload(json_data)
{
    console.log(json_data);
    file_id = json_data['id'];
    console.log(file_id);
    $("#file_id").html ("File uploaded sucessfully: " + file_id);
}

//------------------------------------------------------------------------------

function create_assistant(API_KEY)
{
    // 1. build a request as JSON
    var request_json = {
        "instructions": "You are a assignment marking and grading assistant. You will support lecturer by reviewing and evaluating student submissions.",
        "name": "Assignment Marking Assistant",
        "file_ids": [file_id],
        "tools": [{"type": "retrieval"}],
        "model": "gpt-4-1106-preview"
       };
    
    // 2. convert JSON to string
    var request_string = JSON.stringify(request_json);   
       
    // 3. set up HTTP headers
    $.ajaxSetup({
        headers:
        {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + API_KEY,
            "OpenAI-Beta": "assistants=v1"
        }
    });
    
    
    // 4. perform POST request
    $.ajax({
        type: "POST",
        async: false, // force sync execution
        url: "https://api.openai.com/v1/assistants",
        data: request_string,
        dataType: "json",
        
        success: function(d, rc) {
            //console.log(d);
            assistant_id = d['id'];
            $("#output_p1").html (assistant_id);
        },
        
        error: function(d, rc){
            //console.log(d)
            if ( API_KEY === "" )  $("#output_p0").html ( "<font color=red><b> Enter API key to be able to chat. </b></font>" );
            else                   $("#output_p0").html ( "<font color=red><b> Unknown error. </b></font>" ); 
        }
    });
}

function create_thread(API_KEY)
{
    // 1. request string - empty
    var request_string = "";   
       
    // 2. set up HTTP headers
    $.ajaxSetup({
        headers:
        {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + API_KEY,
            "OpenAI-Beta": "assistants=v1"
        }
    });
    
    
    // 3. perform POST request
    $.ajax({
        type: "POST",
        async: false, // force sync execution
        url: "https://api.openai.com/v1/threads",
        data: request_string,
        dataType: "json",
        
        success: function(d, rc) {
            //console.log(d);
            window.thread_id = d['id'];
            $("#output_p2").html (thread_id);
            update_thread_id(thread_id);
        },
        
        error: function(d, rc){
            //console.log(d)
            if ( API_KEY === "" )  $("#output_p0").html ( "<font color=red><b> Enter API key to be able to chat. </b></font>" );
            else                   $("#output_p0").html ( "<font color=red><b> Unknown error. </b></font>" ); 
        }
    });
}

function update_thread_id(thread_id)
{
    thread_id = thread_id;
}


function add_message(API_KEY, thread_id, message)
{
    // 1. build a request as JSON
    var request_json = {
        "role": "user",
        "file_ids": [file_id],
        "content": message
       };
    
    // 2. convert JSON to string
    var request_string = JSON.stringify(request_json);   
       
    // 3. set up HTTP headers
    $.ajaxSetup({
        headers:
        {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + API_KEY,
            "OpenAI-Beta": "assistants=v1"
        }
    });
    
    // 4. perform POST request
    $.ajax({
        type: "POST",
        async: false, // force sync execution
        url: `https://api.openai.com/v1/threads/${thread_id}/messages`,
        data: request_string,
        dataType: "json",
        
        success: function(d, rc) {
            //console.log(d);
            //assistant_id = d['id'];
            //$("#output_p3").html (assistant_id);
        },
        
        error: function(d, rc){
            console.log(d)
            if ( API_KEY === "" )  $("#output_p0").html ( "<font color=red><b> Enter API key to be able to chat. </b></font>" );
            else                   $("#output_p0").html ( "<font color=red><b> Unknown error. </b></font>" ); 
        }
    });
    
}

function run_assistant(API_KEY, thread_id)
{
    // 1. build a request as JSON
    var request_json = {
        "assistant_id": assistant_id
       };
    
    // 2. convert JSON to string
    var request_string = JSON.stringify(request_json);   
       
    // 3. set up HTTP headers
    $.ajaxSetup({
        headers:
        {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + API_KEY,
            "OpenAI-Beta": "assistants=v1"
        }
    });
    
    // 4. perform POST request
    $.ajax({
        type: "POST",
        async: false, // force sync execution
        url: `https://api.openai.com/v1/threads/${thread_id}/runs`,
        data: request_string,
        dataType: "json",
        
        success: function(d, rc) {
            console.log(d);
            run_id = d['id'];
            $("#output_p4").html (run_id);
        },
        
        error: function(d, rc){
            console.log(d)
            if ( API_KEY === "" )  $("#output_p0").html ( "<font color=red><b> Enter API key to be able to chat. </b></font>" );
            else                   $("#output_p0").html ( "<font color=red><b> Unknown error. </b></font>" ); 
        }
    });

}


function is_run_complete(API_KEY, thread_id, run_id)
{
    var status = "unknown";
    
    // 1. empty string
    var request_string = "";   
       
    // 2. set up HTTP headers
    $.ajaxSetup({
        headers:
        {
            "Authorization": "Bearer " + API_KEY,
            "OpenAI-Beta": "assistants=v1"
        }
    });
    
    // 3. perform GET request
    $.ajax({
        type: "GET",
        async: false, // force sync execution
        url: `https://api.openai.com/v1/threads/${thread_id}/runs/${run_id}`,
        data: request_string,
        dataType: "json",
        
        success: function(d, rc) {
            console.log(d);
            status = d['status'];
            $("#output_p5").html (status);
        },
        
        error: function(d, rc){
            console.log(d)
            if ( API_KEY === "" )  $("#output_p0").html ( "<font color=red><b> Enter API key to be able to chat. </b></font>" );
            else                   $("#output_p0").html ( "<font color=red><b> Unknown error. </b></font>" ); 
        }
    });
    
    if (status == "completed")
    {
        return true;
    } else {
        return false;
    }
    
}

function get_response(API_KEY, thread_id)
{
     // 1. empty body
    var request_string = "";   
       
    // 2. set up HTTP headers
    $.ajaxSetup({
        headers:
        {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + API_KEY,
            "OpenAI-Beta": "assistants=v1"
        }
    });
    
    // 3. perform POST request
    $.ajax({
        type: "GET",
        async: false, // force sync execution
        url: `https://api.openai.com/v1/threads/${thread_id}/messages`,
        data: request_string,
        dataType: "json",
        
        success: function(d, rc) {
            console.log(d);
            response = d['data'][0]['content'][0].text.value;
            $("#output_p6").html (response);
        },
        
        error: function(d, rc){
            console.log(d)
            if ( API_KEY === "" )  $("#output_p4").html ( "<font color=red><b> Enter API key to be able to chat. </b></font>" );
            else                   $("#output_p4").html ( "<font color=red><b> Unknown error. </b></font>" ); 
        }
    });
}


function call_apis()
{
    // Step 1: Create an Assistant
    create_assistant(API_KEY);
    
    // Step 2: Create a Thread
    create_thread(API_KEY);
    
    // Step 3: Add a Message to a Thread
    var message = "Please summarise this file in 5 bulletpoints. Wrap each bullet point with html paragraph tags. Mark most important keywords in red html colour tags. Lastly, evaluate how well written document is.";
    add_message(API_KEY, thread_id, message);
    
    // Step 4: Run the Assistant
    run_assistant(API_KEY, thread_id);
    
    // Step 5: Check the Run status and Step 6: Get the Assistant's Response
    var run_interval = setInterval(waiting_for_run, 1000);
    function waiting_for_run() 
    {
        if (is_run_complete(API_KEY, thread_id, run_id))
        {
            get_response(API_KEY, thread_id);
            clearInterval(run_interval);
        }
    }
}