Last active
September 3, 2024 18:33
-
-
Save kenzic/f0bd9e4fb3205427bb2c1f27821cc53f to your computer and use it in GitHub Desktop.
Playground to demo window.ai
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>window.ai playground: Updated 9/3/204</title> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
</head> | |
<body> | |
<div id="ui"> | |
<h1>Chat with Gemini Nano</h1> | |
<ul id="messages"></ul> | |
<input type="text" id="input" placeholder="Type something here"> | |
<button id="chat">Chat</button> | |
<button id="destory">Destory Sesion</button> | |
</div> | |
<script> | |
let session = null; | |
// Chat with the Gemini Nano | |
document.getElementById('chat').addEventListener('click', async function () { | |
// grab the input value and reset input | |
const input = document.getElementById('input'); | |
const message = input.value; | |
input.value = ''; | |
// append user message to UI | |
appendMessage('User', message); | |
// prompt the message to the AI | |
const response = await session.prompt(message); | |
// append AI response to the UI | |
appendMessage('AI', response); | |
}); | |
// Destory the session | |
document.getElementById('destory').addEventListener('click', async function () { | |
if (session) { | |
await session.destroy(); | |
// session = null; | |
alert('Session destroyed'); | |
} | |
}); | |
// Create a new session on document ready | |
document.addEventListener('DOMContentLoaded', async function () { | |
// Check if window.ai is available to create text session | |
if (!session && (await window.ai?.assistant.capabilities())?.available !== 'readily') { | |
alert('window.ai is not available in your browser') | |
} else { | |
// create a new session | |
session = await window.ai.assistant.create(); | |
} | |
}); | |
// create UI for message | |
function createMessage(role, message) { | |
const li = document.createElement('li'); | |
li.textContent = `${role}: ${message}`; | |
return li; | |
} | |
// append message to the UI | |
function appendMessage(role, message) { | |
const messages = document.getElementById('messages'); | |
messages.appendChild(createMessage(role, message)); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment