LiteRT-LM Web API

LiteRT-LM 的 Web API,适用于浏览器中的 JavaScript 和 TypeScript。这是一个早期预览版,支持在 WebGPU 中运行的文本输入 / 文本输出。

简介

下面是一个使用 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({ model: '/path/to/model.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
} 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
  }
}