Code viewer for World: Kaushalendra_23274426_ca68...

// Cloned by Kaushal on 19 Nov 2023 from World "Chat with GPT model" by Starter user 
// Please leave this clone trail here.

// Credit:Following tutorials help me in implementing this.
// https://platform.openai.com/docs/models
// https://platform.openai.com/docs/tutorials/meeting-minutes 
// https://medium.com/muthoni-wanyoike/implementing-text-summarization-using-openais-gpt-3-api-dcd6be4f6933
// https://www.freecodecamp.org/news/how-to-build-a-chatbot-with-openai-chatgpt-nodejs-and-react/
// https://www.daily.co/blog/how-to-automatically-summarize-a-video-meeting-with-openai-next-js-and-dailys-video-apis/



// talk to OpenAI GPT model (ChatGPT)
// adapted from:
//  https://platform.openai.com/docs/api-reference/making-requests

// OpenAI API for text generation  
const openaiURL = "https://api.openai.com/v1/chat/completions";           // can POST to this 3rd party URL

// A set of models that improve on GPT-3.5 and can understand as well as generate natural language or code
// https://platform.openai.com/docs/models/overview 
const themodel = "gpt-3.5-turbo";
    
// 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" );

var chatTranscript= 'Chat Summary. Chat Date: ' +  new Date().toLocaleString() +'\nLocation: Online \n\nAttendees:\n- User\n- Chat Assitant \n\n This is summary of chat with user\n\n';

 
document.write ( `

<h1> Meeting Summary Generator with OpenAI APIs </h1>

<div>
This world is using OpenAI APIs to generate meeting summary. 
In this sample implementation, we are collecting are passing chat data to API and getting summary of discussion.
Another option to test this is to provide summary of chat in relevant text box and click "Generate Summary".
</div>

<pre></pre>

<div>
In real work, this solution can be used to generate meeting minutes from recording. 
Example, it can integrate with Zoom or Team chat, and can send final summary with action items to the users.
This will reduce the effort required in capturing meeting minutes.
</div>

<pre>

</pre>

<h3> Enter API key </h3>

<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: 100%; overflow-y: scroll;">
    <div style="width: 50%; min-height: 80%; float: left; background: lightgreen;">
        <h2> Chat With Assitant <h2>
        
        <div style="width:90%; background-color:white;  border: 1px solid black; margin:20; padding: 20px;">
            <h3> Enter a "prompt" </h3>
            <INPUT style="width:90%;" id=me value="when did henry vii die?" >
            <button onclick="sendchat();"     class=ab-normbutton > Send </button> 
        </div>
        
        <div style="width:90%; background-color:#ffffcc;  border: 1px solid black; margin:20; padding: 20px;">
            <h3> GPT replies </h3>
            <div id=them > </div>
        </div>
        
        <div style="width:90%; background-color:white;  border: 1px solid black; margin:20; padding: 20px;">
            <h3> Click here to Generate Final Summary" </h3>
            <button onclick="generateSummaryFromChat();"     class=ab-normbutton > Generate Summary </button> 
        </div>
        
        
    </div>
    
    <div style="margin-left: 50%; min-height: 80%; background: lightgray;">
        <h2> OR Provide Transcript to generate summary <h2>
        
        <div style="width:90%; background-color:white;  border: 1px solid black; margin:20; padding: 20px;">
            <h3> Provide transcript" </h3>
            <textarea style="width:90%; min-height: 30%" id="transcriptText">Meeting Date: December 1st, 2023\nMeeting Time: 2:00 PM\nLocation: Online \n\nAttendees:\n- Paul\n- Tom\n- Jerry \n\nMeeting called to discuss project launch plan at 2:05 PM\n\n1. Paul: \"hi folks as per project plan we are planning to launch new FooBar website on 31 Jan 2024.\" \n Paul: \"This meeting is to review current status and launch plan, lets take 30 mins to review the plan and then we will start discussion.\"\n\n2. \n- Tom: \"Plan looks good and it appears we have done all testing.\"\n- Jerry \"Agreed. Have we done stress test and beta user testing.\"\n- Paul : \"No we have not done stress testing however it’s in plan. Beta testing is not part of plan.\"\n- Tom: \"Let’s finish stress test by 31 December 2023 and launch the website for beta testing before production launch on 31st January 2024..\"\n- Paul: \"Noted, we will finish stress test by 31st Dec 2023 and will do beta testing in January 2024.\n- Jerry: \"Lets meet again on 15 January to review the updated results \"\n\nMeeting adjourned at 3:00 PM. Next meeting scheduled for January 15th, 2024 at 2:00 PM.'</textarea>
        </div>
        
        <div style="width:90%; background-color:white;  border: 1px solid black; margin:20; padding: 20px;">
            <h3> Click here to Generate Final Summary" </h3>
            <button onclick="generateSummaryFromTranscript();"     class=ab-normbutton > Generate Summary </button> 
        </div>
    </div>
</div>

<pre>

</pre>

<div style="width: 100%; overflow-y: scroll;">
    <div style="width:60vw; background-color:lightblue;  border: 1px solid black; margin:20; padding: 20px;">
            <h3> Meeting Summary: </h3>
            <pre></pre>
            <div id=summary > ......summary of discussion....</div>
    </div>
    <div style="width:60vw; background-color:lightblue;  border: 1px solid black; margin:20; padding: 20px;">
            <h3> Meeting Action Items: </h3>
            <pre></pre>
            <div id=actionitems > ......action items....</div>
    </div>
</div>



<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 sendchat()
{
  theprompt = $("#me").val();
  chatTranscript += 'User: \"' + theprompt + '\" \n';
  
// 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": 0.7,
     "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(e)         { errorfn (e); }
 });
 
}


 
 // global variable to examine return data in console 
 var a;
 
 function successfn ( data, rc )
 {
     a = data;
     var answer = a["choices"][0].message.content;
     chatTranscript += 'Chat Assitant: \"' + answer + '\" \n';
     $("#them").html ("User : " + theprompt);
     $("#them").html ("Assitant : " + answer);
 }
 
 function errorfn(e)
 {
     if ( apikey == "" )    $("#them").html ( "<font color=red><b> Enter API key to be able to chat. </b></font>" );
     else                   $("#them").html (e.responseText); 
 }
 
 function clearChat() {
     $("#them").html (""); 
     chatTranscript= 'Chat Summary. Chat Date: ' +  new Date().toLocaleString() +'\nLocation: Online \n\nAttendees:\n- User\n- Chat Assitant \n\n This is summary of chat with user\n\n';

 }
 
 function generateSummaryFromChat() {
    chatTranscript += 'Chat concluded at ' + new Date().toLocaleString();
    generateSummary(chatTranscript, function () { clearChat();} );
    $("#actionitems").text("Action items not applicable for chat summary.")
 }

 function generateSummaryFromTranscript() {
    var data = $("#transcriptText").text();
    //var data = 'Meeting Date: December 1st, 2023\nMeeting Time: 2:00 PM\nLocation: Online \n\nAttendees:\n- Paul\n- Tom\n- Jerry \n\nMeeting called to discuss project launch plan at 2:05 PM\n\n1. Paul: \"hi folks as per project plan we are planning to launch new FooBar website on 31 Jan 2024.\" \n Paul: \"This meeting is to review current status and launch plan, lets take 30 mins to review the plan and then we will start discussion.\"\n\n2. \n- Tom: \"Plan looks good and it appears we have done all testing.\"\n- Jerry \"Agreed. Have we done stress test and beta user testing.\"\n- Paul : \"No we have not done stress testing however it’s in plan. Beta testing is not part of plan.\"\n- Tom: \"Let’s finish stress test by 31 December 2023 and launch the website for beta testing before production launch on 31st January 2024..\"\n- Paul: \"Noted, we will finish stress test by 31st Dec 2023 and will do beta testing in January 2024.\n- Jerry: \"Lets meet again on 15 January to review the updated results \"\n\nMeeting adjourned at 3:00 PM. Next meeting scheduled for January 15th, 2024 at 2:00 PM.';
    generateSummary(data);
    generateActionItems(data);
 }
 
 function generateSummary(chatData, additionFn) {
    var requestData = {
     "model": themodel,     
     "temperature": 0.5,
     "max_tokens": 1024,
     "frequency_penalty": 0,
     "presence_penalty": 0,
     "messages": [
            {
                "role": "system",
                "content": "You are a highly skilled AI trained in language comprehension and summarization. I would like you to read the following text and summarize it into a concise abstract paragraph. Aim to retain the most important points, providing a coherent and readable summary that could help a person understand the main points of the discussion without needing to read the entire text. Please avoid unnecessary details or tangential points."
            },
            {
                "role": "user",
                "content": chatData
            }
        ]
   };

    $.ajaxSetup({
        headers:
        {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + apikey  
        }
    });
    
    $.ajax({
        type: "POST",
        url: openaiURL,
        dataType: "json", 
        data: JSON.stringify(requestData),
        success: function(response) {
            $("#summary").html(response['choices'][0]['message']['content'])
            console.log(response['choices'][0]['message']['content']);
            if (!!additionFn) 
               additionFn();
        },
        error: function(error) {
            $("#summary").html(error.responseText);
            console.log(error);
        }
    });
 }
 
 function generateActionItems(inputData) {
   var requestData = {
     "model": themodel,
     "temperature": 0.5,
     "max_tokens": 1024,
     "frequency_penalty": 0,
     "presence_penalty": 0,
     "messages": [
            {
                "role": "system",
                "content": "You are an AI expert in analyzing conversations and extracting action items. Please review the text and identify any tasks, assignments, or actions that were agreed upon or mentioned as needing to be done. These could be tasks assigned to specific individuals, or general actions that the group has decided to take. Please list these action items clearly and concisely."
            },
            {
                "role": "user",
                "content": inputData
            }
        ]
   };

    $.ajaxSetup({
        headers:
        {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + apikey  
        }
    });
    
    $.ajax({
        type: "POST",
        url: openaiURL,
        dataType: "json", 
        data: JSON.stringify(requestData),
        success: function(response) {
            $("#actionitems").html(response['choices'][0]['message']['content'])
            console.log(response['choices'][0]['message']['content']);
        },
        error: function(error) {
            $("#actionitems").html(error.responseText)
            console.log(error);
        }
    });
 }