loadModel static method

Future<void> loadModel(
  1. String modelId
)

Load a model by ID

Finds the model in the registry, gets its local path, and loads it via the appropriate backend (LlamaCpp, ONNX, etc.)

Implementation

static Future<void> loadModel(String modelId) async {
  if (!_isInitialized) {
    throw SDKError.notInitialized();
  }

  final logger = SDKLogger('RunAnywhere.LoadModel');
  logger.info('Loading model: $modelId');
  final startTime = DateTime.now().millisecondsSinceEpoch;

  // Emit load started event
  EventBus.shared.publish(SDKModelEvent.loadStarted(modelId: modelId));

  try {
    // Find the model in available models
    final models = await availableModels();
    final model = models.where((m) => m.id == modelId).firstOrNull;

    if (model == null) {
      throw SDKError.modelNotFound('Model not found: $modelId');
    }

    // Check if model has a local path (downloaded)
    if (model.localPath == null) {
      throw SDKError.modelNotDownloaded(
        'Model is not downloaded. Call downloadModel() first.',
      );
    }

    // Resolve the actual model file path (matches Swift resolveModelFilePath)
    // For LlamaCpp: finds the .gguf file in the model folder
    // For ONNX: returns the model directory
    final resolvedPath =
        await DartBridge.modelPaths.resolveModelFilePath(model);
    if (resolvedPath == null) {
      throw SDKError.modelNotFound(
          'Could not resolve model file path for: $modelId');
    }
    logger.info('Resolved model path: $resolvedPath');

    // Unload any existing model first via the bridge
    if (DartBridge.llm.isLoaded) {
      logger.debug('Unloading previous model');
      DartBridge.llm.unload();
    }

    // Load model directly via DartBridgeLLM (mirrors Swift CppBridge.LLM pattern)
    // The C++ layer handles finding the right backend via the service registry
    logger.debug('Loading model via C++ bridge: $resolvedPath');
    await DartBridge.llm.loadModel(resolvedPath, modelId, model.name);

    // Verify the model loaded successfully
    if (!DartBridge.llm.isLoaded) {
      throw SDKError.modelLoadFailed(
        modelId,
        'LLM model failed to load - model may not be compatible',
      );
    }

    final loadTimeMs = DateTime.now().millisecondsSinceEpoch - startTime;
    logger.info(
        'Model loaded successfully: ${model.name} (isLoaded=${DartBridge.llm.isLoaded})');

    // Track model load success
    TelemetryService.shared.trackModelLoad(
      modelId: modelId,
      modelType: 'llm',
      success: true,
      loadTimeMs: loadTimeMs,
    );

    // Emit load completed event
    EventBus.shared.publish(SDKModelEvent.loadCompleted(modelId: modelId));
  } catch (e) {
    logger.error('Failed to load model: $e');

    // Track model load failure
    TelemetryService.shared.trackModelLoad(
      modelId: modelId,
      modelType: 'llm',
      success: false,
    );
    TelemetryService.shared.trackError(
      errorCode: 'model_load_failed',
      errorMessage: e.toString(),
      context: {'model_id': modelId},
    );

    // Emit load failed event
    EventBus.shared.publish(SDKModelEvent.loadFailed(
      modelId: modelId,
      error: e.toString(),
    ));

    rethrow;
  }
}