// Cloned by Anand on 1 Dec 2023 from World "AI_APIs" by Anand
// Please leave this clone trail here.
// Cloned by Anand on 26 Nov 2023 from World "Chat with GPT model" by Starter user
// Please leave this clone trail here.
//Practical 2 :
//Use an AI API to achieve a function:
//2 worlds - Hello world to introduce the API and one where API is used heavily .
//Pick top 2 news article and TL;DR those.
const openaiURL = "https://api.openai.com/v1/chat/completions"; // can POST to this 3rd party URL
const openai_moderations_URL = "https://api.openai.com/v1/moderations";
const themodel = "gpt-3.5-turbo"; // the OpenAI model we are going to talk to
var apikey = "";
// default API key and prompt:
var topic = "hello";
var final_str;
var gpt_temperature = 0.2;
var content_moderation_failed = 0;
var content_moderation_reasons = [];
// default body is margin 0 and padding 0
// give it more whitespace:
$('body').css( "margin", "100px" );
$('body').css( "padding", "100px" );
$('body').css( "background-color", "red");
$('body').css( "box-sizing", "border-box" );
$('body').css( "list-style", "none" );
$('InfoDiv').css ("font-family", "Arial");
document.write ( `
<h1> Hello GPT </h1>
<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>
<div class="InfoDiv" style="width:60vw; background-color:pink; border: 1px solid black; margin:20; padding: 20px;">
Who are you ?:
<select id="Gender", name = "Gender" required>
<option value="Man" selected>Man</option>
<option value="Woman">Woman</option>
<option value="Non-Binary">Non-Binary</option>
</select>
<hr>
How old are you :
<input type=number style='width:5vw;' maxlength='2' NAME="Age" id="EnterAge" required>
<hr>
Pick some interests <br>
<input class="interestCheckbox" type="checkbox" id="interest1" name="Biking" >
<label for="interest1"> Biking </label>
<input class="interestCheckbox" type="checkbox" id="interest2" name="Hiking" >
<label for="interest2"> Hiking </label>
<input class="interestCheckbox" type="checkbox" id="interest3" name="Road Trips" >
<label for="interest3"> Road Trips </label>
<input class="interestCheckbox" type="checkbox" id="interest4" name="Bouldering" >
<label for="interest4"> Bouldering </label>
<input class="interestCheckbox" type="checkbox" id="interest5" name="Skiing" >
<label for="interest5"> Skiing </label>
<input class="interestCheckbox" type="checkbox" id="interest6" name="wine tasting" >
<label for="interest6"> Wine tasting </label>
<input class="interestCheckbox" type="checkbox" id="interest7" name="dancing" >
<label for="interest7"> Dancing </label>
<input class="interestCheckbox" type="checkbox" id="interest8" name="watching movies" >
<label for="interest8"> Watching Movies </label><br>
<pre>
</pre>
<hr>
Qurkiness level : sets temperature for GPT : The sampling temperature, between 0 and 1.
Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.
If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit..
<div class="slidecontainer">
<input type="range" min="0" max="100" value="25" class="slider" id="myRange">
<p>Quirkiness Index: <span id="demo"></span></p>
</div>
<hr>
<br>
<hr>
<button onclick='setInterests();' class=ab-normbutton >Submit</button>
<pre>
</pre>
<hr>
<div id=ur_query > </div>
<hr>
<pre>
</pre>
</div>
<div style="width:60vw; background-color:#ffffff; border: 1px solid black; margin:20; padding: 20px;">
<h3> GPT replies </h3>
<div id=them > </div>
</div>
<pre>
</pre>
` );
function setInterests() {
my_gender = jQuery("select#Gender").val();
my_age = jQuery("input#EnterAge").val();
final_str = `Hello, I'm a : ${my_age} year old ${my_gender}. Few of my hobbies : :`;
var my_interests = [];
var checkedValue = null;
var inputElements = document.getElementsByClassName('interestCheckbox');
for(var i=0; inputElements[i]; ++i){
var j = 0;
if(inputElements[i].checked){
my_interests[j] = inputElements[i].name;
final_str = final_str.concat(my_interests[j], ", ");
console.log("Interests : " + my_interests[j])
j = j+1;
}
}
if(my_interests.length === 0) {
}
check_content_moderation(final_str);
console.log("done with loop");
if(content_moderation_failed == 1) {
var info = "<font color=red><b> Content moderation failed - your inputs possibly contain language indicating : ";
for(var i=0; i<content_moderation_reasons.length; i++) {
info = info.concat(content_moderation_reasons[i], " ");
}
info = info.concat("</b></font>")
console.log("content moderation failed, info = " + info);
$("#content_moderation").html ( info );
} else {
final_str = final_str.concat(" Can you introduce yourself ? ");
console.log(final_str);
sendchat();
}
}
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('newstopic').onkeydown = function(event) { if (event.keyCode == 13) sendchat(); };
var slider = document.getElementById("myRange");
var m_output = document.getElementById("demo");
m_output.innerHTML = slider.value;
slider.oninput = function() {
gpt_temperature = mapRange(this.value, 0, 100, 0.1, 0.8);
m_output.innerHTML = this.value;
console.log("gpt-temp = " + gpt_temperature);
}
function mapRange(value, inMin, inMax, outMin, outMax) {
return ((value - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;
}
// --- Send my line of text ----------------------------------------------------------------
function sendchat()
{
let gpt_query = final_str
console.log(gpt_query);
$("#ur_query").html ( gpt_query );
var thedata = {
"model": themodel,
"temperature": gpt_temperature,
"messages": [{
"role": "user",
"content": gpt_query
}]
};
// then as string representing that JSON:
var thedatastring = JSON.stringify ( thedata );
$.ajaxSetup({
headers:
{
"Content-Type": "application/json",
"Authorization": "Bearer " + apikey
}
});
console.log(thedatastring);
//First check for moderation of input data - make sure there's no offensive things in there
$.ajax({
type: "POST",
url: openaiURL,
data: thedatastring,
dataType: "json",
success: function ( d, rc ) { successfn ( d, rc ); },
error: function() { errorfn (); }
});
//Send in the second token to actually generate a prompt.
}
// global variable to examine return data in console
var a;
function check_content_moderation (data) {
var moderation_data = {
"input": data
} ;
var moderation_str = JSON.stringify(moderation_data);
console.log("moderation input = : " + moderation_str);
$.ajaxSetup({
headers:
{
"Content-Type": "application/json",
"Authorization": "Bearer " + apikey
}
});
$.ajax({
type: "POST",
url: openai_moderations_URL,
async: false,
data: moderation_str,
dataType: "json",
success: function ( d, rc ) { mod_successfn ( d, rc ); },
error: function() { errorfn (); }
});
// _callback();
}
function mod_successfn(data, rc) {
a = data;
console.log("moderation success : " + a["results"][0].flagged);
if(a["results"][0].flagged === true ) {
content_moderation_failed = 1;
var obj = a["results"][0].categories;
for (var key in obj) {
if(obj[key] === true) {
content_moderation_reasons.push(key);
}
console.log("moderation content : " + key + " : " + obj[key] + "content_mod = " + content_moderation_failed);
}
}
}
function mod_errorfn(data, rc) {
console.log("something went wrong with moderation API ");
}
function successfn ( data, rc )
{
a = data;
var answer = a["choices"][0].message.content;
$("#them").html ( answer );
}
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>" );
}