generateEmbeddings static method
Generate embeddings for multiple texts (batch processing).
texts - List of texts to embed
Returns List<List<double>> - List of embedding vectors
Throws Exception if not initialized or generation fails
Implementation
static Future<List<List<double>>> generateEmbeddings(List<String> texts) async {
if (!isInitialized()) {
throw StateError('LiteRT embeddings not initialized. Call initialize() first.');
}
if (texts.isEmpty) {
throw ArgumentError('texts must not be empty');
}
for (final text in texts) {
if (text.trim().isEmpty) {
throw ArgumentError('All texts must not be empty');
}
}
try {
// Convert Dart List<String> to JS Array
final jsTexts = texts.map((t) => t.toJS).toList().toJS;
// Call JS function and get array of Float32Arrays
final jsResult = await _generateEmbeddingsJS(jsTexts).toDart;
// Convert JS array of Float32Arrays to Dart List<List<double>>
final jsArrays = jsResult as JSFloat32Arrays;
final result = <List<double>>[];
for (int i = 0; i < jsArrays.arrayLength; i++) {
final jsEmbedding = jsArrays.getAt(i);
final embeddingLength = jsEmbedding.length.toDartInt;
final embedding = List<double>.filled(embeddingLength, 0.0);
for (int j = 0; j < embeddingLength; j++) {
embedding[j] = jsEmbedding[j.toJS].toDartDouble;
}
result.add(embedding);
}
return result;
} catch (e) {
throw Exception('Failed to generate embeddings: $e');
}
}