embed static method

Future<Float32List> embed(
  1. String text
)

Convert text to an embedding vector.

The inference runs entirely on the background worker isolate so this call never blocks the UI thread. The returned Float32List is transferred across the isolate boundary without copying via TransferableTypedData; downstream FFI consumers (rag_engine_flutter) also expect Float32List, so no further conversion is performed.

Implementation

static Future<Float32List> embed(String text) async {
  final sendPort = _workerSendPort;
  if (sendPort == null) {
    if (_disposed) {
      throw StateError(
        'EmbeddingService was disposed before the embedding '
        'started.',
      );
    }
    throw Exception("EmbeddingService not initialized. Call init() first.");
  }

  final replyPort = ReceivePort();
  final reply = Completer<Object?>();
  _pendingReplies[replyPort] = reply;
  replyPort.listen((message) {
    if (!reply.isCompleted) reply.complete(message);
  });
  final Object? result;
  try {
    sendPort.send({
      'cmd': 'embed',
      'text': text,
      'debugMode': debugMode,
      'replyPort': replyPort.sendPort,
    });
    result = await reply.future;
  } finally {
    _pendingReplies.remove(replyPort);
    replyPort.close();
  }

  if (result is Map && result['error'] != null) {
    throw Exception(result['error']);
  }

  final embedding = (result as TransferableTypedData)
      .materialize()
      .asFloat32List();
  _dimensionState.validateAndRemember(embedding.length);
  return embedding;
}