Last active
June 30, 2024 02:38
-
-
Save prabhjotSL/ac5c1b616dfc3bc4b981c0c335380a9d to your computer and use it in GitHub Desktop.
Generate Text in Browser using Chrome's Built in AI
This file contains hidden or 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
async function generateStreamingText(prompt) { | |
const canCreate = await window.ai.canCreateTextSession(); | |
if (canCreate !== "no") { | |
const session = await window.ai.createTextSession(); | |
// Prompt the model and stream the result: | |
const stream = session.promptStreaming(prompt); | |
let result = ''; | |
let previousLength = 0; | |
for await (const chunk of stream) { | |
const newContent = chunk.slice(previousLength); | |
console.log(newContent); | |
previousLength = chunk.length; | |
result += newContent; | |
} | |
return result; | |
} else { | |
return null | |
} | |
} | |
async function generateText(prompt) { | |
const canCreate = await window.ai.canCreateTextSession(); | |
if (canCreate !== "no") { | |
const session = await window.ai.createTextSession(); | |
// Prompt the model and wait for the whole result to come back. | |
const result = await session.prompt(prompt); | |
return result | |
} else { | |
return null | |
} | |
} | |
(async () => { | |
let resultStreaming = await generateStreamingText("Write an email to my customer telling them about the benefits of using Automations for their shopify store.") | |
console.log("Streaming final result:"); | |
console.log(resultStreaming); | |
let result = await generateText("What is combinatorial innovation? Describe as a poem.") | |
console.log("One off generation:"); | |
console.log(result); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment