document.write(`
<h1>My Web Page</h1>
<div id=enterAPIkey>
Enter API key:
<input type="text" id="apikey" value="">
<button onclick="setKey()">Set API Key</button>
</div>
<h2> Say Hello to your game host! </h2>
<p> Greet your game show host below! </p>
<input id=prompt value="hello!">
<button onclick=getChatCompletion()>Send</button>
<div id="response">
<div>
`);
let apiKey = "";
function setKey() {
apiKey = document.getElementById('apikey').value;
console.log('API Key set:', apiKey);
$("#enterAPIkey").html ("<b> API key has been set! </b>")
}
async function getChatCompletion() {
if (!apiKey) {
console.log('API Key is not set');
return;
}
const prompt = document.getElementById('prompt').value;
const data = {
model: "gpt-3.5-turbo",
messages: [
{ "role": "system", "content": "You are a game show host." },
{ "role": "user", "content": prompt }
]
};
try {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error(`Error: ${response.status}`);
}
const result = await response.json();
$("#response").html(result["choices"][0].message.content);
} catch (error) {
console.error('Failed to fetch from OpenAI:', error);
}
}