Skip to content

Instantly share code, notes, and snippets.

@lukecarbis
Last active March 22, 2023 15:26
Show Gist options
  • Save lukecarbis/68042385b653fb0cfaac9a60fbcba060 to your computer and use it in GitHub Desktop.
Save lukecarbis/68042385b653fb0cfaac9a60fbcba060 to your computer and use it in GitHub Desktop.
An HTML widget that asks the GPT-3.5 model for a short poem about the current time.
<script>
const url = "https://api.openai.com/v1/chat/completions";
const apiKey = "YOUR OpenAI API KEY GOES HERE";
fetchPoem();
setInterval(runCodeOnMinute, 1000);
function fetchPoem() {
const xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "Bearer " + apiKey);
xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
const result = JSON.parse(this.responseText);
const poem = result.choices[0].message.content.trim();
const formattedPoem = poem.replace(/\n/g, '<br />');
document.getElementById('time-poem').innerHTML = formattedPoem;
}
}
xhr.send(getRequestData());
}
function runCodeOnMinute() {
const date = new Date();
if (date.getSeconds() === 0) {
fetchPoem();
}
}
function getCurrentTime() {
const now = new Date();
const hours = now.getHours();
const minutes = now.getMinutes();
const amPm = hours >= 12 ? 'PM' : 'AM';
const formattedHours = hours % 12 || 12;
const formattedMinutes = minutes < 10 ? '0' + minutes : minutes;
const formattedTime = formattedHours + ':' + formattedMinutes + ' ' + amPm;
return formattedTime;
}
function getRequestData() {
const currentTime = getCurrentTime();
return JSON.stringify({
"messages": [{"role":"system", "content":`It's ${currentTime}`}, {"role":"user", "content":"Write a 4 line rhyming poem in the style of William Blake. The poem can be about anything except the passing of time, and it MUST include the current time in the format HH:MM."}],
"model": "gpt-3.5-turbo",
"temperature": 0.7,
"max_tokens": 256,
"top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0
});
}
</script>
<p id="time-poem"></p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment