A API da Web do LiteRT-LM para JavaScript e TypeScript no navegador. Esta é uma prévia que oferece suporte à execução de texto de entrada / saída na WebGPU.
Modelos compatíveis
No momento, a API JavaScript LiteRT-LM oferece suporte a um conjunto limitado de modelos compatíveis com a Web.
Estamos trabalhando para expandir isso e incluir arquivos de modelo .litertlm gerais, mas, por enquanto, os seguintes modelos são compatíveis:
gemma-4-E2B-it-web.litertlmde litert-community/gemma-4-E2B-it-litert-lmgemma-4-E4B-it-web.litertlmde litert-community/gemma-4-E4B-it-litert-lm
Introdução
Confira um exemplo de app de chat REPL criado com a API JavaScript:
<div id="out" style="white-space: pre-wrap; font-family: monospace;"></div>
<input id="in" onkeydown="if(event.key === 'Enter') repl(this)">
<script type="module">
import { Engine } from 'https://cdn.jsdelivr.net/npm/@litert-lm/core/+esm';
const engine = await Engine.create({
// Load the Gemma 4 E2B model
model: 'https://huggingface.co/litert-community/gemma-4-E2B-it-litert-lm/resolve/main/gemma-4-E2B-it-web.litertlm'
// Or use the E4B model by swapping in this line
// model: 'https://huggingface.co/litert-community/gemma-4-E4B-it-litert-lm/resolve/main/gemma-4-E4B-it-web.litertlm'
});
const chat = await engine.createConversation();
window.repl = async (el) => {
const text = el.value;
el.value = ''; // Clear immediately
out.append(`\n>>> ${text}\nAI: `);
for await (const chunk of chat.sendMessageStreaming(text)) {
out.append(chunk.content[0].text);
}
};
</script>
Primeiros passos
O LiteRT-LM está disponível como um pacote npm. Você pode instalar a versão mais recente do npm ou importar diretamente de uma CDN:
# From npm
npm i --save @litert-lm/core
# From a CDN (in your JavaScript file)
import * as litertlm from 'https://cdn.jsdelivr.net/npm/@litert-lm/core/+esm';
Inicializar o mecanismo
O Engine é o ponto de entrada da API. Ele processa o carregamento de modelos, a criação de sessões e o gerenciamento de recursos. Não se esqueça de delete o mecanismo para liberar
recursos quando o modelo não for mais necessário.
Observação:a inicialização do mecanismo pode levar alguns segundos para carregar o modelo.
import {Engine, EngineSettings} from '@litert-lm/core';
const engineSettings = {
model: 'url/path/to/model.litertlm', // or a ReadableStream, or a Blob
// You can configure context length and other settings here
mainExecutorSettings: {
maxNumTokens: 8192,
},
} satisfies EngineSettings;
const engine = await Engine.create(engineSettings);
// ... Use the engine to create a conversation ...
// Delete the engine when done.
await engine.delete();
Criar uma conversa
Depois que o mecanismo for inicializado, crie uma instância Conversation. Você pode
fornecer um ConversationConfig para personalizar o comportamento dele.
const conversation = await engine.createConversation({
preface: {
messages: [
{role: 'system', content: 'You are a helpful assistant'}
]
}
});
conversation.sendMessage({
role: 'user',
content: 'Write a poem',
});
Enviar mensagens
Você pode enviar mensagens com ou sem streaming.
Exemplo de não streaming
// Simple string input
let response = await conversation.sendMessage("What is the capital of France?");
console.log(response.content[0].text);
// Or with full message structure
response = await conversation.sendMessage({role: 'user', content: '...'});
Exemplo de streaming
// sendMessageStreaming returns a ReadableStream of response chunks
const stream = conversation.sendMessageStreaming('Tell me a long story.');
for await (const chunk of stream) {
// Chunks are Records containing pieces of the response
for (const item of chunk.content) {
if (item.type === 'text') {
console.log(item.text);
}
}
}
Cancelar geração
Você pode cancelar uma geração em andamento explicitamente chamando cancel() na instância de
Conversation:
// Cancel any ongoing generation
conversation.cancel();
Se você estiver transmitindo a resposta, sair do loop for await...of antes do tempo (como
com break) também vai cancelar automaticamente a geração em andamento:
for await (const chunk of stream) {
if (shouldStop()) {
break; // Cancels the stream and underlying generation
}
}