createEmbeddingModel method
Future<EmbeddingModel>
createEmbeddingModel({
- String? modelPath,
- String? tokenizerPath,
- PreferredBackend? preferredBackend,
override
Creates and returns a new EmbeddingModel instance.
Modern API: If paths are not provided, uses the active embedding model set via
FlutterGemma.installEmbeddingModel()
or modelManager.setActiveModel()
.
Legacy API: Provide explicit paths for backward compatibility.
modelPath
— path to the embedding model file (optional if active model set).
tokenizerPath
— path to the tokenizer file (optional if active model set).
preferredBackend
— backend preference (e.g., CPU, GPU).
Implementation
@override
Future<EmbeddingModel> createEmbeddingModel({
String? modelPath,
String? tokenizerPath,
PreferredBackend? preferredBackend,
}) async {
if (_initEmbeddingCompleter case Completer<EmbeddingModel> completer) {
return completer.future;
}
final completer = _initEmbeddingCompleter = Completer<EmbeddingModel>();
// Modern API: Use active embedding model if paths not provided
if (modelPath == null || tokenizerPath == null) {
final manager = _unifiedManager;
final activeModel = manager.activeEmbeddingModel;
// No active embedding model - user must set one first
if (activeModel == null) {
completer.completeError(
Exception('No active embedding model set. Use `FlutterGemma.installEmbeddingModel()` or `modelManager.setActiveModel()` to set a model first'),
);
return completer.future;
}
// Verify the active model is still installed
final isModelInstalled = await manager.isModelInstalled(activeModel);
if (!isModelInstalled) {
completer.completeError(
Exception('Active embedding model is no longer installed. Use the `modelManager` to load the model first'),
);
return completer.future;
}
// Get the actual model file paths through unified system
final modelFilePaths = await manager.getModelFilePaths(activeModel);
if (modelFilePaths == null || modelFilePaths.isEmpty) {
completer.completeError(
Exception('Embedding model file paths not found. Use the `modelManager` to load the model first'),
);
return completer.future;
}
// Extract model and tokenizer paths from spec
modelPath = modelFilePaths[PreferencesKeys.embeddingModelFile];
tokenizerPath = modelFilePaths[PreferencesKeys.embeddingTokenizerFile];
if (modelPath == null || tokenizerPath == null) {
completer.completeError(
Exception('Could not find model or tokenizer path in active embedding model'),
);
return completer.future;
}
debugPrint('Using active embedding model: $modelPath, tokenizer: $tokenizerPath');
}
try {
await _platformService.createEmbeddingModel(
modelPath: modelPath,
tokenizerPath: tokenizerPath,
preferredBackend: preferredBackend,
);
final model = _initializedEmbeddingModel = MobileEmbeddingModel(
onClose: () {
_initializedEmbeddingModel = null;
_initEmbeddingCompleter = null;
},
);
completer.complete(model);
return model;
} catch (e, st) {
completer.completeError(e, st);
Error.throwWithStackTrace(e, st);
}
}