createWebEngine function

Future<Engine> createWebEngine(
  1. EngineConfig config, {
  2. JSAny? model,
  3. ToolCallReader toolCallsOf = nativeToolCalls,
  4. @visibleForTesting LiteRtLmPageLock? pageLock,
})

Engine.create, with model — a ReadableStream<Uint8Array> or a Blob — in place of EngineConfig.modelPath when given, such as a model file read from the page's own storage. EngineConfig.modelPath then only names it in the log.

toolCallsOf reads the tool calls of a reply stopped mid-turn, which the rebuilt conversation replays as calls, as natively (createEngineWithBundle). The default reads the calls the runtime converted.

Implementation

Future<Engine> createWebEngine(
  EngineConfig config, {
  JSAny? model,
  ToolCallReader toolCallsOf = nativeToolCalls,
  @visibleForTesting LiteRtLmPageLock? pageLock,
}) async {
  _refuseOnWeb(config);
  final constructor = await _awaitRuntime();
  // Said before the create: an older runtime fails it ("Unsupported backend:
  // 2" on 0.18.0), and the reason is the version.
  noteOtherWebRuntimeVersion();
  final settings = JSObject()..['model'] = model ?? config.modelPath.toJS;
  settings['backend'] = _webBackendValue(config.backend).toJS;
  if (config.visionBackend case final vision?) {
    settings['visionBackend'] = _webBackendValue(vision).toJS;
  }
  if (config.audioBackend case final audio?) {
    settings['audioBackend'] = _webBackendValue(audio).toJS;
  }
  final executor = JSObject();
  // A GPU_ARTISAN model (Gemma 4's web exports) reserves its images' space
  // per conversation up front: with none reserved the first image fails
  // ("Media embedding cache was not set.", 0.19.0, measured 2026-11-23). As
  // natively, unset is 1 with a vision encoder.
  if (config.maxNumImages ?? (config.visionBackend == null ? null : 1)
      case final images?) {
    executor['maxNumImages'] = images.toJS;
  }
  if (config.maxNumTokens case final tokens?) {
    executor['maxNumTokens'] = tokens.toJS;
  }
  if (config.backend case CpuBackend(:final threadCount?)) {
    if (threadCount < 1) {
      throw ArgumentError.value(
        threadCount,
        'threadCount',
        'must be 1 or more',
      );
    }
    executor['backendConfig'] = JSObject()
      ..['number_of_threads'] = threadCount.toJS;
  }
  if (_hasKeys(executor)) {
    settings['mainExecutorSettings'] = executor;
  }
  final lock = pageLock ?? liteRtLmPageLock;
  runtimeLog(
    '[litertlm_dart/web] Engine.create({model: '
    '${model == null ? config.modelPath : '<stream: ${config.modelPath}>'}})',
  );
  final took = Stopwatch()..start();
  // Streams the model into the page's WebAssembly module, which the
  // EmbeddingGemma 2 engine shares: see page_lock.dart.
  final JsLiteRtLmEngine js;
  try {
    js = await lock.run(
      () => (constructor as JsLiteRtLmEngine)
          .callMethod<JSPromise<JsLiteRtLmEngine>>('create'.toJS, settings)
          .toDart,
    );
  } on LiteRtLmPagePoisonedError {
    rethrow;
  } catch (e) {
    final message = '$e';
    final others = liteRtLmWebFetchedVersions()
      ..remove(liteRtLmWebRuntimeVersion);
    throw LiteRtLmEngineCreateException(
      others.isEmpty
          ? '$liteRtLmWebRuntime could not create the engine for '
                '${config.modelPath} on ${config.backend}: $message'
          : 'The page\'s @litert-lm/core ${others.join(', ')} could not create '
                'the engine for ${config.modelPath} on ${config.backend}: '
                '$message. This release runs on $liteRtLmWebRuntimeVersion: '
                'import $liteRtLmWebModuleUrl in the page\'s module script.',
      nativeMessage: message,
    );
  }
  runtimeLog(
    '[litertlm_dart/web] Engine.create: ${took.elapsedMilliseconds} ms',
  );
  final resolved = js.settings;
  final resolvedBackend = resolved?['backend'];
  final resolvedExecutor = resolved?['mainExecutorSettings'];
  final tokens = resolvedExecutor.isA<JSObject>()
      ? (resolvedExecutor as JSObject)['maxNumTokens']
      : null;
  final Backend backend;
  try {
    backend = switch (resolvedBackend.isA<JSNumber>()
        ? (resolvedBackend as JSNumber).toDartInt
        : null) {
      liteRtLmWebBackendCpu => const Backend.cpu(),
      liteRtLmWebBackendGpu ||
      liteRtLmWebBackendGpuArtisan => const Backend.gpu(),
      final other => throw StateError(
        other == null
            ? '$liteRtLmWebRuntime reported no backend for the engine '
                  '(settings.backend), so this release cannot say where it '
                  'runs.'
            : '$liteRtLmWebRuntime resolved the engine to backend $other, '
                  'which this release does not know.',
      ),
    };
  } catch (_) {
    // Nobody else holds the engine: free it before refusing it.
    try {
      await awaitIfThenable(js.delete());
    } catch (e) {
      noteWebDeleteFailure('An engine', e);
    }
    rethrow;
  }
  // An encoder asked for: where the runtime put it, or why that is unknown.
  final reasons = <String>[];
  Backend? encoder(String medium, Backend? asked) {
    if (asked == null) return null;
    final value = resolved?['${medium}Backend'];
    if (!value.isA<JSNumber>()) {
      reasons.add(
        'without its $medium encoder (settings.${medium}Backend not '
        'reported): the model may have none',
      );
      return null;
    }
    final code = (value as JSNumber).toDartInt;
    return switch (code) {
      liteRtLmWebBackendCpu => const Backend.cpu(),
      liteRtLmWebBackendGpu ||
      liteRtLmWebBackendGpuArtisan => const Backend.gpu(),
      _ => () {
        reasons.add(
          'with its $medium encoder on backend $code, which this release '
          'does not know',
        );
        return null;
      }(),
    };
  }

  final vision = encoder('vision', config.visionBackend);
  final audio = encoder('audio', config.audioBackend);
  if (reasons.isNotEmpty) {
    // Asked for, not loaded where this release can tell: a message with
    // that medium would fail later.
    try {
      await awaitIfThenable(js.delete());
    } catch (e) {
      noteWebDeleteFailure('An engine', e);
    }
    throw LiteRtLmEngineCreateException(
      '$liteRtLmWebRuntime created the engine for ${config.modelPath} '
      '${reasons.join(', and ')}.',
    );
  }
  return Engine._(
    js,
    backend: backend,
    visionBackend: vision,
    audioBackend: audio,
    maxNumImages: vision == null ? null : (config.maxNumImages ?? 1),
    maxNumTokens: tokens.isA<JSNumber>()
        ? (tokens as JSNumber).toDartInt
        : (config.maxNumTokens ?? 0),
    pageLock: lock,
    toolCallsOf: toolCallsOf,
  );
}