0
# AI-Powered Recommendations
1
2
Machine learning-based prediction and recommendation services for personalized customer experiences. The Prediction and Model Services provide intelligent product recommendations, model management, and ML model training capabilities powered by Google's retail AI.
3
4
## Capabilities
5
6
### Prediction Service
7
8
AI-powered recommendations and predictions based on user behavior and product catalog.
9
10
```python { .api }
11
class PredictionServiceClient:
12
def predict(self, request: PredictRequest) -> PredictResponse:
13
"""
14
Gets personalized product recommendations using trained ML models.
15
16
Args:
17
request: Prediction parameters including placement, user context, and model settings
18
19
Returns:
20
PredictResponse: Recommended products with scores and metadata
21
22
Raises:
23
InvalidArgument: If prediction parameters are invalid
24
NotFound: If placement or model not found
25
"""
26
```
27
28
### Model Management
29
30
Comprehensive ML model lifecycle management including creation, training, and deployment.
31
32
```python { .api }
33
class ModelServiceClient:
34
def create_model(self, request: CreateModelRequest) -> Operation:
35
"""
36
Creates a new recommendation model (long-running operation).
37
38
Args:
39
request: Model configuration including type, training parameters, and data requirements
40
41
Returns:
42
Operation: Resolves to Model when training completes
43
"""
44
45
def get_model(self, request: GetModelRequest) -> Model:
46
"""
47
Retrieves model information and training status.
48
49
Args:
50
request: Contains model resource name
51
52
Returns:
53
Model: Model configuration, status, and performance metrics
54
"""
55
56
def list_models(self, request: ListModelsRequest) -> ListModelsResponse:
57
"""
58
Lists all models in a catalog with filtering and pagination.
59
60
Args:
61
request: Contains parent catalog and optional filtering parameters
62
63
Returns:
64
ListModelsResponse: List of models with pagination support
65
"""
66
67
def update_model(self, request: UpdateModelRequest) -> Model:
68
"""
69
Updates an existing model's configuration.
70
71
Args:
72
request: Contains model updates and field mask
73
74
Returns:
75
Model: Updated model information
76
"""
77
78
def delete_model(self, request: DeleteModelRequest) -> None:
79
"""
80
Deletes a model and stops serving predictions.
81
82
Args:
83
request: Contains model resource name
84
"""
85
86
def pause_model(self, request: PauseModelRequest) -> Model:
87
"""
88
Pauses model serving without deleting the model.
89
90
Args:
91
request: Contains model resource name
92
93
Returns:
94
Model: Updated model with paused status
95
"""
96
97
def resume_model(self, request: ResumeModelRequest) -> Model:
98
"""
99
Resumes a paused model for serving predictions.
100
101
Args:
102
request: Contains model resource name
103
104
Returns:
105
Model: Updated model with active status
106
"""
107
108
def tune_model(self, request: TuneModelRequest) -> Operation:
109
"""
110
Fine-tunes an existing model with new data (long-running operation).
111
112
Args:
113
request: Contains model name and tuning parameters
114
115
Returns:
116
Operation: Resolves to TuneModelResponse when tuning completes
117
"""
118
119
class PredictionServiceAsyncClient:
120
async def predict(self, request: PredictRequest) -> PredictResponse:
121
"""Async version of predict."""
122
123
class ModelServiceAsyncClient:
124
async def create_model(self, request: CreateModelRequest) -> Operation:
125
"""Async version of create_model."""
126
127
async def get_model(self, request: GetModelRequest) -> Model:
128
"""Async version of get_model."""
129
130
async def list_models(self, request: ListModelsRequest) -> ListModelsResponse:
131
"""Async version of list_models."""
132
133
async def update_model(self, request: UpdateModelRequest) -> Model:
134
"""Async version of update_model."""
135
136
async def delete_model(self, request: DeleteModelRequest) -> None:
137
"""Async version of delete_model."""
138
139
async def pause_model(self, request: PauseModelRequest) -> Model:
140
"""Async version of pause_model."""
141
142
async def resume_model(self, request: ResumeModelRequest) -> Model:
143
"""Async version of resume_model."""
144
145
async def tune_model(self, request: TuneModelRequest) -> Operation:
146
"""Async version of tune_model."""
147
```
148
149
## Data Types
150
151
### Prediction Request and Response
152
153
Configuration for getting personalized recommendations and the resulting predictions.
154
155
```python { .api }
156
class PredictRequest:
157
placement: str # Placement resource name (required)
158
user_event: UserEvent # User context and current session information
159
page_size: int # Maximum predictions to return (default: 100, max: 1000)
160
page_token: str # Token for pagination
161
filter: str # Filter expression for recommended products
162
validate_only: bool # Validate request without serving predictions
163
params: Dict[str, Value] # Additional model parameters
164
labels: Dict[str, str] # Custom labels for analytics
165
166
class PredictResponse:
167
results: List[PredictResponsePredictionResult] # Prediction results
168
attribution_token: str # Token for attributing user actions
169
missing_ids: List[str] # Product IDs that couldn't be recommended
170
dry_run: bool # Whether this was a validation-only request
171
metadata: List[PredictResponsePredictionResult] # Additional metadata
172
173
class PredictResponsePredictionResult:
174
id: str # Recommended product ID
175
metadata: Dict[str, Value] # Prediction metadata and scores
176
```
177
178
### Model Configuration
179
180
Comprehensive model definition with training parameters and performance metrics.
181
182
```python { .api }
183
class Model:
184
name: str # Model resource name (read-only)
185
display_name: str # Human-readable model name
186
training_state: ModelTrainingState # TRAINING, PAUSED, READY
187
serving_state: ModelServingState # INACTIVE, ACTIVE, TUNED
188
create_time: Timestamp # Model creation time (read-only)
189
update_time: Timestamp # Last update time (read-only)
190
type: str # Model type (recommended-for-you, others-you-may-like, etc.)
191
optimization_objective: str # CTR, CVR, REVENUE_PER_ORDER
192
periodic_tuning_state: ModelPeriodicTuningState # Automatic retraining settings
193
last_tune_time: Timestamp # Last tuning/training time
194
tuning_operation: str # Current tuning operation name
195
data_state: ModelDataState # Data requirements satisfaction
196
filtering_option: RecommendationsFilteringOption # Filtering behavior
197
serving_config_lists: List[ModelServingConfigList] # Associated serving configurations
198
model_features_config: ModelModelFeaturesConfig # Feature configuration
199
200
class ModelServingConfigList:
201
serving_config_ids: List[str] # IDs of serving configurations using this model
202
203
class ModelModelFeaturesConfig:
204
frequently_bought_together_config: ModelFrequentlyBoughtTogetherFeaturesConfig # FBT feature settings
205
```
206
207
### Model Training States and Metadata
208
209
Training status, performance metrics, and operational metadata.
210
211
```python { .api }
212
class ModelTrainingState(Enum):
213
TRAINING_STATE_UNSPECIFIED = 0
214
PAUSED = 1 # Training paused, can be resumed
215
TRAINING = 2 # Currently training
216
217
class ModelServingState(Enum):
218
SERVING_STATE_UNSPECIFIED = 0
219
INACTIVE = 1 # Not serving predictions
220
ACTIVE = 2 # Actively serving predictions
221
TUNED = 3 # Recently tuned, ready for serving
222
223
class ModelDataState(Enum):
224
DATA_STATE_UNSPECIFIED = 0
225
DATA_OK = 1 # Sufficient data for training
226
DATA_ERROR = 2 # Insufficient or invalid data
227
228
class ModelPeriodicTuningState(Enum):
229
PERIODIC_TUNING_STATE_UNSPECIFIED = 0
230
PERIODIC_TUNING_DISABLED = 1 # No automatic retraining
231
ALL_TUNING_DISABLED = 2 # All tuning disabled
232
PERIODIC_TUNING_ENABLED = 3 # Automatic retraining enabled
233
```
234
235
### Request Types
236
237
Model management operation requests with comprehensive configuration options.
238
239
```python { .api }
240
class CreateModelRequest:
241
parent: str # Catalog resource name (required)
242
model: Model # Model configuration (required)
243
dry_run: bool # Validate request without creating model
244
245
class GetModelRequest:
246
name: str # Model resource name (required)
247
248
class ListModelsRequest:
249
parent: str # Catalog resource name (required)
250
page_size: int # Maximum models to return
251
page_token: str # Token for pagination
252
253
class UpdateModelRequest:
254
model: Model # Model with updates (required)
255
update_mask: FieldMask # Fields to update
256
257
class DeleteModelRequest:
258
name: str # Model resource name (required)
259
260
class PauseModelRequest:
261
name: str # Model resource name (required)
262
263
class ResumeModelRequest:
264
name: str # Model resource name (required)
265
266
class TuneModelRequest:
267
name: str # Model resource name (required)
268
269
class TuneModelResponse:
270
# Response contains tuning results and performance metrics
271
```
272
273
### Model Types and Optimization
274
275
Different recommendation model types and optimization objectives.
276
277
```python { .api }
278
# Model Types (specified in Model.type field)
279
MODEL_TYPE_RECOMMENDED_FOR_YOU = "recommended-for-you" # Personalized recommendations
280
MODEL_TYPE_OTHERS_YOU_MAY_LIKE = "others-you-may-like" # Similar item recommendations
281
MODEL_TYPE_FREQUENTLY_BOUGHT_TOGETHER = "frequently-bought-together" # Bundle recommendations
282
MODEL_TYPE_PAGE_OPTIMIZATION = "page-optimization" # Page-level optimization
283
MODEL_TYPE_SIMILAR_ITEMS = "similar-items" # Content-based similarity
284
MODEL_TYPE_BUY_IT_AGAIN = "buy-it-again" # Repurchase recommendations
285
MODEL_TYPE_ON_SALE_ITEMS = "on-sale-items" # Promotional item recommendations
286
287
# Optimization Objectives
288
OPTIMIZATION_OBJECTIVE_REVENUE_PER_ORDER = "revenue-per-order" # Maximize revenue
289
OPTIMIZATION_OBJECTIVE_CVR = "cvr" # Maximize conversion rate
290
OPTIMIZATION_OBJECTIVE_CTR = "ctr" # Maximize click-through rate
291
```
292
293
## Usage Examples
294
295
### Getting Product Recommendations
296
297
```python
298
from google.cloud import retail
299
300
client = retail.PredictionServiceClient()
301
302
# Get personalized recommendations for a user
303
user_event = retail.UserEvent(
304
event_type="page-view",
305
visitor_id="visitor-123",
306
user_info=retail.UserInfo(
307
user_id="user-456",
308
ip_address="192.168.1.100"
309
),
310
product_details=[
311
retail.ProductDetail(
312
product=retail.Product(id="viewed-product-123"),
313
quantity=1
314
)
315
]
316
)
317
318
request = retail.PredictRequest(
319
placement="projects/my-project/locations/global/catalogs/default_catalog/placements/product_detail_page_recommended_for_you",
320
user_event=user_event,
321
page_size=10,
322
filter='(categories: ANY("Electronics"))'
323
)
324
325
response = client.predict(request=request)
326
327
print(f"Recommendations for user:")
328
for result in response.results:
329
print(f"- Product ID: {result.id}")
330
if 'score' in result.metadata:
331
print(f" Confidence Score: {result.metadata['score'].number_value:.3f}")
332
```
333
334
### Creating a Recommendation Model
335
336
```python
337
model_client = retail.ModelServiceClient()
338
339
# Create a new recommendation model
340
model = retail.Model(
341
display_name="Homepage Recommendations Model",
342
type="recommended-for-you",
343
optimization_objective="revenue-per-order",
344
filtering_option=retail.RecommendationsFilteringOption.RECOMMENDATIONS_FILTERING_ENABLED,
345
periodic_tuning_state=retail.Model.PeriodicTuningState.PERIODIC_TUNING_ENABLED
346
)
347
348
request = retail.CreateModelRequest(
349
parent="projects/my-project/locations/global/catalogs/default_catalog",
350
model=model
351
)
352
353
# This is a long-running operation
354
operation = model_client.create_model(request=request)
355
print(f"Model creation operation: {operation.name}")
356
357
# Wait for model training to complete (this can take several hours)
358
print("Waiting for model training to complete...")
359
trained_model = operation.result()
360
print(f"Model created: {trained_model.name}")
361
print(f"Training state: {trained_model.training_state}")
362
print(f"Serving state: {trained_model.serving_state}")
363
```
364
365
### Managing Model Lifecycle
366
367
```python
368
# List all models in catalog
369
request = retail.ListModelsRequest(
370
parent="projects/my-project/locations/global/catalogs/default_catalog",
371
page_size=20
372
)
373
374
response = model_client.list_models(request=request)
375
376
print("Available models:")
377
for model in response.models:
378
print(f"- {model.display_name}")
379
print(f" Name: {model.name}")
380
print(f" Type: {model.type}")
381
print(f" Training State: {model.training_state}")
382
print(f" Serving State: {model.serving_state}")
383
print(f" Last Tune Time: {model.last_tune_time}")
384
print()
385
386
# Get detailed model information
387
model_name = "projects/my-project/locations/global/catalogs/default_catalog/models/model-123"
388
request = retail.GetModelRequest(name=model_name)
389
model = model_client.get_model(request=request)
390
391
print(f"Model Details:")
392
print(f"Display Name: {model.display_name}")
393
print(f"Optimization Objective: {model.optimization_objective}")
394
print(f"Data State: {model.data_state}")
395
print(f"Filtering Option: {model.filtering_option}")
396
397
# Pause model serving
398
if model.serving_state == retail.Model.ServingState.ACTIVE:
399
pause_request = retail.PauseModelRequest(name=model_name)
400
paused_model = model_client.pause_model(request=pause_request)
401
print(f"Model paused. New serving state: {paused_model.serving_state}")
402
403
# Resume model serving
404
if model.serving_state == retail.Model.ServingState.INACTIVE:
405
resume_request = retail.ResumeModelRequest(name=model_name)
406
resumed_model = model_client.resume_model(request=resume_request)
407
print(f"Model resumed. New serving state: {resumed_model.serving_state}")
408
```
409
410
### Model Tuning and Retraining
411
412
```python
413
# Fine-tune an existing model with recent data
414
tune_request = retail.TuneModelRequest(
415
name="projects/my-project/locations/global/catalogs/default_catalog/models/model-123"
416
)
417
418
# This is a long-running operation
419
tune_operation = model_client.tune_model(request=tune_request)
420
print(f"Model tuning operation: {tune_operation.name}")
421
422
# Monitor tuning progress
423
print("Waiting for model tuning to complete...")
424
tune_result = tune_operation.result()
425
print(f"Model tuning completed: {tune_result}")
426
427
# Check updated model status
428
updated_model = model_client.get_model(
429
request=retail.GetModelRequest(
430
name="projects/my-project/locations/global/catalogs/default_catalog/models/model-123"
431
)
432
)
433
print(f"Updated serving state: {updated_model.serving_state}")
434
print(f"Last tune time: {updated_model.last_tune_time}")
435
```
436
437
### Advanced Prediction Configuration
438
439
```python
440
# Get recommendations with advanced filtering and custom parameters
441
user_event = retail.UserEvent(
442
event_type="add-to-cart",
443
visitor_id="visitor-123",
444
user_info=retail.UserInfo(
445
user_id="user-456",
446
ip_address="192.168.1.100",
447
user_agent="Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X)"
448
),
449
product_details=[
450
retail.ProductDetail(
451
product=retail.Product(id="cart-product-456"),
452
quantity=2
453
)
454
],
455
purchase_transaction=retail.PurchaseTransaction(
456
id="txn-789",
457
revenue=199.98,
458
tax=16.00,
459
cost=150.00,
460
currency_code="USD"
461
)
462
)
463
464
request = retail.PredictRequest(
465
placement="projects/my-project/locations/global/catalogs/default_catalog/placements/shopping_cart_frequently_bought_together",
466
user_event=user_event,
467
page_size=5,
468
filter='(price_info.price: [10, 500]) AND (availability: "IN_STOCK")',
469
params={
470
'returnProduct': {'bool_value': True},
471
'strictFiltering': {'bool_value': True}
472
},
473
labels={
474
'page_type': 'shopping_cart',
475
'ab_test_group': 'treatment_a'
476
}
477
)
478
479
response = client.predict(request=request)
480
481
print("Frequently bought together recommendations:")
482
for result in response.results:
483
print(f"- Product ID: {result.id}")
484
# Extract custom metadata
485
for key, value in result.metadata.items():
486
print(f" {key}: {value}")
487
```