LiteRT-LM 웹 API

브라우저의 JavaScript 및 TypeScript 용 LiteRT-LM 웹 API입니다. 이것은 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
  }
}