LiteRT-LM Web API

瀏覽器中 JavaScript 和 TypeScript 適用的 LiteRT-LM 網頁 API。這是初期預先發布版,支援在 WebGPU 中執行的文字輸入 / 輸出。

支援的機型

LiteRT-LM JS API 目前僅支援部分與網頁相容的模型。 我們正努力擴大支援範圍,將一般 .litertlm 模型檔案納入其中,但目前僅支援下列模型:

簡介

以下是使用 JavaScript API 建構的 REPL 即時通訊應用程式範例:

<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>

開始使用

LiteRT-LM 以 npm 套件形式提供。您可以從 npm 安裝最新版本,或直接從 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';

初始化引擎

Engine 是 API 的進入點。可處理模型載入、工作階段建立和資源管理作業。不再需要模型時,請記得 delete 引擎來釋放資源。

注意:初始化引擎可能需要幾秒鐘才能載入模型。

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();

建立對話

引擎初始化完成後,請建立 Conversation 例項。您可以提供 ConversationConfig 來自訂其行為。

const conversation = await engine.createConversation({
  preface: {
    messages: [
      {role: 'system', content: 'You are a helpful assistant'}
    ]
  }
});

conversation.sendMessage({
  role: 'user',
  content: 'Write a poem',
});

可傳送訊息

你可以選擇是否要串流播放影片,然後傳送訊息。

非串流範例

// 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: '...'});

串流範例

// 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);
    }
  }
}

取消生成

您可以針對 Conversation 執行個體呼叫 cancel(),明確取消進行中的生成作業:

// Cancel any ongoing generation
conversation.cancel();

如果正在串流處理回覆,提早結束 for await...of 迴圈 (例如使用 break),系統也會自動取消正在進行的生成作業:

for await (const chunk of stream) {
  if (shouldStop()) {
    break; // Cancels the stream and underlying generation
  }
}