Skip to content

Instantly share code, notes, and snippets.

@simonw
Last active July 13, 2023 04:53
Show Gist options
  • Save simonw/2e59cd48d706cd94f5d30a963836f45d to your computer and use it in GitHub Desktop.
Save simonw/2e59cd48d706cd94f5d30a963836f45d to your computer and use it in GitHub Desktop.
JavaScript function to explain selected text on the page using GPT 3.5
(function() {
const OPENAI_API_KEY = 'sk-...';
let selectedText = window.getSelection().toString().trim();
if (selectedText.length > 0) {
let body = JSON.stringify({
model: 'gpt-3.5-turbo',
messages: [{role: 'system', content: 'explain this succinctly' },{ role: 'user', content: selectedText }]
});
fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${OPENAI_API_KEY}`
},
body: body
})
.then(response => response.json())
.then(data => {
let responseBox = document.createElement('div');
responseBox.style.width = '300px';
responseBox.style.backgroundColor = 'white';
responseBox.style.padding = '5px';
responseBox.style.border = '1px solid black';
responseBox.style.position = 'fixed';
responseBox.style.top = '10px';
responseBox.style.right = '10px';
let closeButton = document.createElement('button');
closeButton.innerHTML = 'X';
closeButton.onclick = () => { document.body.removeChild(responseBox); };
responseBox.appendChild(document.createTextNode(data.choices[0].message.content));
responseBox.appendChild(closeButton);
document.body.appendChild(responseBox);
});
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment