Skip to content

Instantly share code, notes, and snippets.

@kenzic
Created July 17, 2024 17:20
Show Gist options
  • Save kenzic/f0bd9e4fb3205427bb2c1f27821cc53f to your computer and use it in GitHub Desktop.
Save kenzic/f0bd9e4fb3205427bb2c1f27821cc53f to your computer and use it in GitHub Desktop.
Playground to demo window.ai
<html>
<head>
<meta charset="utf-8">
<title>window.ai playground</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?.canCreateTextSession()) {
alert('window.ai is not available in your browser')
}
// create a new session
session = await window.ai.createTextSession();
});
// 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