// JavaScript code to write HTML content
const openaiURL = "https://api.openai.com/v1/completions";
const themodel = "text-davinci-003";
var apikey = "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";
$('body').css("margin", "20px");
$('body').css("padding", "20px");
document.write(`
<h1>AI Response Generator with Adjustable Temperature</h1>
<p>Adjust the temperature and see how it affects the AI's response.</p>
<div id="enterkey">
Enter API key:
<input style='width:25vw;' id="apikey" value=''>
<button onclick='setApiKey();'>Set API key</button>
</div>
<div style="margin-top: 20px;">
<label for="temperature">Temperature:</label>
<input type="range" id="temperature" min="0" max="1" step="0.1" value="0.5">
<span id="temperatureValue">0.5</span>
</div>
<div style="margin-top: 20px;">
<textarea id="prompt" placeholder="Enter your prompt here" style="width:50vw; height:100px;"></textarea>
<button onclick="generateResponse();">Generate Response</button>
</div>
<div id="aiResponse" style="background-color:#f0f0f0; border: 1px solid black; padding: 15px; width:60vw;"></div>
`);
function setApiKey() {
apikey = $("#apikey").val().trim();
$("#enterkey").html(apikey ? "<b>API key has been set.</b>" : "<b>Please enter an API key.</b>");
}
function generateResponse() {
var userPrompt = $("#prompt").val();
var temperature = $("#temperature").val();
if (!apikey) {
$("#aiResponse").text("API key is not set.");
return;
}
var data = {
model: themodel,
prompt: userPrompt,
temperature: parseFloat(temperature),
max_tokens: 150
};
$.ajax({
type: "POST",
url: openaiURL,
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + apikey
},
data: JSON.stringify(data),
dataType: "json",
success: function(response) {
$("#aiResponse").text(response.choices[0].text);
},
error: function(jqXHR) {
var errorMsg = jqXHR.responseJSON && jqXHR.responseJSON.error && jqXHR.responseJSON.error.message;
$("#aiResponse").text("Error occurred: " + (errorMsg || "Unknown error"));
}
});
}
$("#temperature").on("input", function() {
$("#temperatureValue").text($(this).val());
});