or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

app-management.mdauthentication.mdfirestore.mdfunctions.mdindex.mdmachine-learning.mdmessaging.mdproject-management.mdrealtime-database.mdremote-config.mdstorage.mdtenant-management.md

machine-learning.mddocs/

0

# Machine Learning

1

2

Firebase ML model management for deploying and managing custom machine learning models in Firebase projects. Supports model lifecycle management including creation, publishing, and version control.

3

4

## Capabilities

5

6

### Model Management

7

8

Create, update, retrieve, and manage ML models in Firebase projects with comprehensive model lifecycle support.

9

10

```python { .api }

11

def create_model(model, app=None):

12

"""

13

Create a new ML model in Firebase.

14

15

Args:

16

model: Model instance with model configuration

17

app: Firebase app instance (optional)

18

19

Returns:

20

Model: Created model instance with Firebase-assigned ID

21

"""

22

23

def update_model(model, app=None):

24

"""

25

Update an existing ML model.

26

27

Args:

28

model: Model instance with updated configuration

29

app: Firebase app instance (optional)

30

31

Returns:

32

Model: Updated model instance

33

"""

34

35

def get_model(model_id, app=None):

36

"""

37

Get an ML model by ID.

38

39

Args:

40

model_id: Model ID string

41

app: Firebase app instance (optional)

42

43

Returns:

44

Model: Model instance for the given ID

45

46

Raises:

47

NotFoundError: If the model doesn't exist

48

"""

49

50

def delete_model(model_id, app=None):

51

"""

52

Delete an ML model from Firebase.

53

54

Args:

55

model_id: Model ID string to delete

56

app: Firebase app instance (optional)

57

58

Raises:

59

NotFoundError: If the model doesn't exist

60

"""

61

```

62

63

### Model Listing

64

65

List and paginate through ML models in the Firebase project with filtering options.

66

67

```python { .api }

68

def list_models(list_filter=None, page_size=None, page_token=None, app=None):

69

"""

70

List ML models in the project.

71

72

Args:

73

list_filter: Filter string for model selection (optional)

74

page_size: Maximum number of models to return (optional)

75

page_token: Token for pagination (optional)

76

app: Firebase app instance (optional)

77

78

Returns:

79

ListModelsPage: Page of model results with pagination info

80

"""

81

```

82

83

### Model Publishing

84

85

Publish and unpublish models to control their availability for client applications.

86

87

```python { .api }

88

def publish_model(model_id, app=None):

89

"""

90

Publish an ML model to make it available to client apps.

91

92

Args:

93

model_id: Model ID string to publish

94

app: Firebase app instance (optional)

95

96

Returns:

97

Model: Published model instance

98

99

Raises:

100

NotFoundError: If the model doesn't exist

101

"""

102

103

def unpublish_model(model_id, app=None):

104

"""

105

Unpublish an ML model to make it unavailable to client apps.

106

107

Args:

108

model_id: Model ID string to unpublish

109

app: Firebase app instance (optional)

110

111

Returns:

112

Model: Unpublished model instance

113

114

Raises:

115

NotFoundError: If the model doesn't exist

116

"""

117

```

118

119

## Model Configuration

120

121

### Model Class

122

123

```python { .api }

124

class Model:

125

"""Represents a Firebase ML model."""

126

127

def __init__(self, display_name=None, tags=None, model_format=None):

128

"""

129

Initialize a model.

130

131

Args:

132

display_name: Human-readable model name (optional)

133

tags: List of tags for model organization (optional)

134

model_format: ModelFormat instance specifying model type (optional)

135

"""

136

137

@property

138

def model_id(self):

139

"""The Firebase-assigned model ID."""

140

141

@property

142

def display_name(self):

143

"""The human-readable model name."""

144

145

@property

146

def tags(self):

147

"""List of tags associated with the model."""

148

149

@property

150

def model_format(self):

151

"""The model format specification."""

152

153

@property

154

def state(self):

155

"""The current state of the model."""

156

157

@property

158

def create_time(self):

159

"""When the model was created."""

160

161

@property

162

def update_time(self):

163

"""When the model was last updated."""

164

165

@property

166

def validation_error(self):

167

"""Validation error message if model is invalid."""

168

169

@property

170

def etag(self):

171

"""Entity tag for optimistic locking."""

172

173

class ListModelsPage:

174

"""Page of model results with pagination support."""

175

176

@property

177

def models(self):

178

"""List of Model instances in this page."""

179

180

@property

181

def next_page_token(self):

182

"""Token for the next page (None if no more pages)."""

183

184

@property

185

def has_next_page(self):

186

"""Whether there are more pages available."""

187

188

def get_next_page(self):

189

"""Get the next page of results."""

190

```

191

192

### Model Formats

193

194

```python { .api }

195

class TFLiteFormat:

196

"""TensorFlow Lite model format."""

197

198

def __init__(self, model_source):

199

"""

200

Initialize TFLite format specification.

201

202

Args:

203

model_source: TFLiteSource instance specifying model location

204

"""

205

206

class TFLiteGCSModelSource:

207

"""TensorFlow Lite model stored in Google Cloud Storage."""

208

209

def __init__(self, gcs_tflite_uri):

210

"""

211

Initialize GCS model source.

212

213

Args:

214

gcs_tflite_uri: GCS URI to the .tflite model file

215

"""

216

217

class TFLiteAutoMLSource:

218

"""TensorFlow Lite model from AutoML."""

219

220

def __init__(self, automl_model):

221

"""

222

Initialize AutoML model source.

223

224

Args:

225

automl_model: AutoML model resource name

226

"""

227

```

228

229

## Usage Examples

230

231

### Creating and Publishing a Model

232

233

```python

234

from firebase_admin import ml

235

236

# Create a TensorFlow Lite model from Cloud Storage

237

model_source = ml.TFLiteGCSModelSource('gs://my-bucket/model.tflite')

238

model_format = ml.TFLiteFormat(model_source=model_source)

239

240

# Create model with configuration

241

model = ml.Model(

242

display_name='Image Classification Model',

243

tags=['image', 'classification', 'v1.0'],

244

model_format=model_format

245

)

246

247

# Create the model in Firebase

248

created_model = ml.create_model(model)

249

print(f'Created model: {created_model.model_id}')

250

251

# Publish the model to make it available to client apps

252

published_model = ml.publish_model(created_model.model_id)

253

print(f'Published model: {published_model.model_id}')

254

```

255

256

### Managing Existing Models

257

258

```python

259

# Get a specific model

260

model = ml.get_model('model_123')

261

print(f'Model: {model.display_name}')

262

print(f'State: {model.state}')

263

print(f'Tags: {model.tags}')

264

265

# Update model metadata

266

model.display_name = 'Updated Classification Model'

267

model.tags = ['image', 'classification', 'v1.1', 'production']

268

269

updated_model = ml.update_model(model)

270

print(f'Updated model: {updated_model.display_name}')

271

272

# Unpublish model (make unavailable to clients)

273

unpublished_model = ml.unpublish_model(model.model_id)

274

print(f'Unpublished model state: {unpublished_model.state}')

275

```

276

277

### Listing and Filtering Models

278

279

```python

280

# List all models

281

models_page = ml.list_models()

282

for model in models_page.models:

283

print(f'Model: {model.display_name} (ID: {model.model_id})')

284

285

# List with pagination

286

models_page = ml.list_models(page_size=10)

287

while models_page:

288

for model in models_page.models:

289

print(f'Model: {model.display_name}')

290

291

if models_page.has_next_page:

292

models_page = models_page.get_next_page()

293

else:

294

break

295

296

# Filter models by tags or other criteria

297

filtered_models = ml.list_models(list_filter='tags:production')

298

for model in filtered_models.models:

299

print(f'Production model: {model.display_name}')

300

```

301

302

### AutoML Integration

303

304

```python

305

# Create model from AutoML

306

automl_source = ml.TFLiteAutoMLSource(

307

automl_model='projects/my-project/locations/us-central1/models/my-automl-model'

308

)

309

automl_format = ml.TFLiteFormat(model_source=automl_source)

310

311

automl_model = ml.Model(

312

display_name='AutoML Classification Model',

313

tags=['automl', 'classification'],

314

model_format=automl_format

315

)

316

317

created_automl_model = ml.create_model(automl_model)

318

print(f'Created AutoML model: {created_automl_model.model_id}')

319

```

320

321

### Model Validation and Error Handling

322

323

```python

324

from firebase_admin.exceptions import NotFoundError, InvalidArgumentError

325

326

try:

327

# Attempt to get a model

328

model = ml.get_model('nonexistent_model')

329

except NotFoundError:

330

print('Model not found')

331

332

try:

333

# Create model with invalid configuration

334

invalid_model = ml.Model(

335

display_name='', # Empty display name might be invalid

336

model_format=None # Missing model format

337

)

338

ml.create_model(invalid_model)

339

except InvalidArgumentError as e:

340

print(f'Invalid model configuration: {e}')

341

342

# Check for validation errors after creation

343

model = ml.get_model('model_123')

344

if model.validation_error:

345

print(f'Model validation error: {model.validation_error}')

346

```

347

348

### Model State Management

349

350

```python

351

# Check model state before operations

352

model = ml.get_model('model_123')

353

354

if model.state == 'PUBLISHED':

355

print('Model is published and available to clients')

356

elif model.state == 'UNPUBLISHED':

357

print('Model exists but is not available to clients')

358

elif model.state == 'INVALID':

359

print(f'Model is invalid: {model.validation_error}')

360

361

# Conditional publishing based on state

362

if model.state == 'UNPUBLISHED':

363

published_model = ml.publish_model(model.model_id)

364

print(f'Model published: {published_model.state}')

365

```

366

367

### Batch Model Operations

368

369

```python

370

# Batch create multiple models

371

models_to_create = [

372

{

373

'display_name': 'Model A',

374

'gcs_uri': 'gs://my-bucket/model_a.tflite',

375

'tags': ['experimental', 'version_a']

376

},

377

{

378

'display_name': 'Model B',

379

'gcs_uri': 'gs://my-bucket/model_b.tflite',

380

'tags': ['experimental', 'version_b']

381

}

382

]

383

384

created_model_ids = []

385

for model_config in models_to_create:

386

source = ml.TFLiteGCSModelSource(model_config['gcs_uri'])

387

format_spec = ml.TFLiteFormat(model_source=source)

388

389

model = ml.Model(

390

display_name=model_config['display_name'],

391

tags=model_config['tags'],

392

model_format=format_spec

393

)

394

395

created_model = ml.create_model(model)

396

created_model_ids.append(created_model.model_id)

397

398

print(f'Created {len(created_model_ids)} models')

399

400

# Batch publish models

401

for model_id in created_model_ids:

402

ml.publish_model(model_id)

403

print(f'Published model: {model_id}')

404

```

405

406

## Client Integration

407

408

Models created and published through the Admin SDK become available to client applications:

409

410

### iOS Client Usage

411

412

```swift

413

// iOS client code to download and use the model

414

let conditions = ModelDownloadConditions(

415

allowsCellularAccess: false,

416

allowsBackgroundDownloading: true

417

)

418

419

let downloadProgress = ModelManager.modelManager().download(

420

remoteModel,

421

conditions: conditions

422

)

423

```

424

425

### Android Client Usage

426

427

```java

428

// Android client code to download and use the model

429

FirebaseModelDownloader.getInstance()

430

.getModel("model_123", DownloadType.LOCAL_MODEL, conditions)

431

.addOnSuccessListener(model -> {

432

// Use the downloaded model

433

File modelFile = model.getFile();

434

});

435

```

436

437

## Best Practices

438

439

### Model Management

440

441

- **Version Control**: Use tags to track model versions

442

- **Testing Pipeline**: Test models before publishing

443

- **Rollback Strategy**: Keep previous versions available

444

- **Performance Monitoring**: Monitor model performance in production

445

446

### Security and Access Control

447

448

- **IAM Permissions**: Use appropriate IAM roles for model management

449

- **Model Validation**: Validate models before deployment

450

- **Access Logging**: Monitor model access and usage

451

- **Secure Storage**: Store model files securely in Cloud Storage

452

453

### Performance Optimization

454

455

- **Model Size**: Optimize model size for mobile deployment

456

- **Caching Strategy**: Implement appropriate client-side caching

457

- **Progressive Updates**: Update models incrementally when possible

458

- **Resource Management**: Consider device capabilities for model deployment

459

460

## Types

461

462

```python { .api }

463

class Model:

464

"""Represents a Firebase ML model."""

465

466

@property

467

def model_id(self):

468

"""The Firebase-assigned model ID."""

469

470

@property

471

def display_name(self):

472

"""The human-readable model name."""

473

474

@property

475

def tags(self):

476

"""List of tags associated with the model."""

477

478

@property

479

def model_format(self):

480

"""The model format specification."""

481

482

@property

483

def state(self):

484

"""The current state of the model (PUBLISHED, UNPUBLISHED, INVALID)."""

485

486

@property

487

def create_time(self):

488

"""When the model was created."""

489

490

@property

491

def update_time(self):

492

"""When the model was last updated."""

493

494

class ListModelsPage:

495

"""Page of model results with pagination support."""

496

497

@property

498

def models(self):

499

"""List of Model instances in this page."""

500

501

@property

502

def next_page_token(self):

503

"""Token for the next page."""

504

505

def get_next_page(self):

506

"""Get the next page of results."""

507

508

class TFLiteFormat:

509

"""TensorFlow Lite model format specification."""

510

511

class TFLiteGCSModelSource:

512

"""TensorFlow Lite model stored in Google Cloud Storage."""

513

514

class TFLiteAutoMLSource:

515

"""TensorFlow Lite model from AutoML."""

516

```