or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-features.mdai-recommendations.mdanalytics-export.mdcatalog-config.mdindex.mdproduct-management.mdsearch-discovery.mduser-events.md
tile.json

tessl/pypi-google-cloud-retail

Python client library for Google Cloud Retail API enabling end-to-end personalized recommendation systems

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/google-cloud-retail@2.5.x

To install, run

npx @tessl/cli install tessl/pypi-google-cloud-retail@2.5.0

index.mddocs/

Google Cloud Retail

Python client library for Google Cloud Retail API that enables customers to build end-to-end personalized recommendation systems without requiring high-level expertise in machine learning or recommendation systems. The library provides comprehensive tools for product catalog management, search functionality, AI-powered recommendations, user event tracking, and analytics.

Package Information

  • Package Name: google-cloud-retail
  • Language: Python
  • Installation: pip install google-cloud-retail

Core Imports

import google.cloud.retail

For stable API (recommended for production):

from google.cloud import retail

For specific API versions:

from google.cloud import retail_v2
from google.cloud import retail_v2alpha  # Alpha features
from google.cloud import retail_v2beta   # Beta features

For async clients (optimal for async frameworks like FastAPI, asyncio applications):

from google.cloud.retail import ProductServiceAsyncClient
from google.cloud.retail import SearchServiceAsyncClient
from google.cloud.retail import UserEventServiceAsyncClient
# All service clients have corresponding async variants

Basic Usage

from google.cloud import retail

# Initialize a product service client
client = retail.ProductServiceClient()

# Create a product
project_id = "your-project-id"
location = "global"
catalog = "default_catalog"
branch = "default_branch"

parent = f"projects/{project_id}/locations/{location}/catalogs/{catalog}/branches/{branch}"

product = retail.Product(
    id="product-123",
    title="Example Product",
    categories=["Electronics", "Computers"],
    price_info=retail.PriceInfo(
        price=299.99,
        currency_code="USD"
    )
)

request = retail.CreateProductRequest(
    parent=parent,
    product=product,
    product_id=product.id
)

created_product = client.create_product(request=request)
print(f"Created product: {created_product.name}")

# Search for products
search_client = retail.SearchServiceClient()
search_request = retail.SearchRequest(
    placement=f"projects/{project_id}/locations/{location}/catalogs/{catalog}/placements/search",
    query="computers",
    page_size=10
)

search_response = search_client.search(request=search_request)
for result in search_response.results:
    print(f"Found product: {result.product.title}")

Async Usage

import asyncio
from google.cloud.retail import ProductServiceAsyncClient

async def manage_products_async():
    # Initialize async client
    async_client = ProductServiceAsyncClient()
    
    # Create product asynchronously
    project_id = "your-project-id"
    location = "global"
    catalog = "default_catalog"
    branch = "default_branch"
    
    parent = f"projects/{project_id}/locations/{location}/catalogs/{catalog}/branches/{branch}"
    
    product = retail.Product(
        id="async-product-123",
        title="Async Example Product",
        categories=["Electronics"],
        price_info=retail.PriceInfo(price=199.99, currency_code="USD")
    )
    
    request = retail.CreateProductRequest(
        parent=parent,
        product=product,
        product_id=product.id
    )
    
    # Await async operation
    created_product = await async_client.create_product(request=request)
    print(f"Async created product: {created_product.name}")
    
    # Close the async client
    await async_client.close()

# Run async function
# asyncio.run(manage_products_async())

Architecture

The Google Cloud Retail API is organized around several core concepts:

  • Projects: Top-level containers for all retail resources
  • Catalogs: Collections of products within a project location
  • Branches: Separate product data environments (e.g., staging, production)
  • Products: Individual items in your catalog with attributes, pricing, and availability
  • User Events: Customer interactions (views, purchases, add-to-cart) used for recommendations
  • Models: Machine learning models for personalized recommendations
  • Serving Configs: Configuration for search and recommendation serving

The library supports three API versions with different stability levels:

  • v2: Production-stable core functionality
  • v2beta: Beta features with broader testing
  • v2alpha: Experimental features under active development

Capabilities

Product Management

Core product catalog operations including creating, updating, and managing product information, inventory, and fulfillment details.

class ProductServiceClient:
    def create_product(self, request: CreateProductRequest) -> Product: ...
    def get_product(self, request: GetProductRequest) -> Product: ...
    def list_products(self, request: ListProductsRequest) -> ListProductsResponse: ...
    def update_product(self, request: UpdateProductRequest) -> Product: ...
    def delete_product(self, request: DeleteProductRequest) -> None: ...
    def set_inventory(self, request: SetInventoryRequest) -> Operation: ...
    def import_products(self, request: ImportProductsRequest) -> Operation: ...

class ProductServiceAsyncClient:
    async def create_product(self, request: CreateProductRequest) -> Product: ...
    async def get_product(self, request: GetProductRequest) -> Product: ...
    async def list_products(self, request: ListProductsRequest) -> ListProductsResponse: ...
    async def update_product(self, request: UpdateProductRequest) -> Product: ...
    async def delete_product(self, request: DeleteProductRequest) -> None: ...
    async def set_inventory(self, request: SetInventoryRequest) -> Operation: ...
    async def import_products(self, request: ImportProductsRequest) -> Operation: ...

Product Management

Search and Discovery

Search functionality with filtering, faceting, ranking, and query auto-completion capabilities.

class SearchServiceClient:
    def search(self, request: SearchRequest) -> SearchResponse: ...

class CompletionServiceClient:
    def complete_query(self, request: CompleteQueryRequest) -> CompleteQueryResponse: ...

Search and Discovery

AI-Powered Recommendations

Machine learning-based prediction and recommendation services for personalized customer experiences.

class PredictionServiceClient:
    def predict(self, request: PredictRequest) -> PredictResponse: ...

class ModelServiceClient:
    def create_model(self, request: CreateModelRequest) -> Operation: ...
    def tune_model(self, request: TuneModelRequest) -> Operation: ...
    def get_model(self, request: GetModelRequest) -> Model: ...

AI-Powered Recommendations

User Event Tracking

Collection and management of user interaction events that power recommendation algorithms and analytics.

class UserEventServiceClient:
    def write_user_event(self, request: WriteUserEventRequest) -> UserEvent: ...
    def collect_user_event(self, request: CollectUserEventRequest) -> HttpBody: ...
    def import_user_events(self, request: ImportUserEventsRequest) -> Operation: ...

User Event Tracking

Catalog Configuration

Management of catalog settings, attributes, branches, and completion configurations.

class CatalogServiceClient:
    def list_catalogs(self, request: ListCatalogsRequest) -> ListCatalogsResponse: ...
    def update_catalog(self, request: UpdateCatalogRequest) -> Catalog: ...
    def get_completion_config(self, request: GetCompletionConfigRequest) -> CompletionConfig: ...
    def add_catalog_attribute(self, request: AddCatalogAttributeRequest) -> AttributesConfig: ...

Catalog Configuration

Analytics and Export

Analytics data export and metrics collection for business intelligence and reporting.

class AnalyticsServiceClient:
    def export_analytics_metrics(self, request: ExportAnalyticsMetricsRequest) -> Operation: ...

Analytics and Export

Advanced Features

Enhanced capabilities including business rules, serving configurations, and generative AI features.

class ControlServiceClient:
    def create_control(self, request: CreateControlRequest) -> Control: ...
    def list_controls(self, request: ListControlsRequest) -> ListControlsResponse: ...

class ServingConfigServiceClient:
    def create_serving_config(self, request: CreateServingConfigRequest) -> ServingConfig: ...
    def add_control(self, request: AddControlRequest) -> ServingConfig: ...

class GenerativeQuestionServiceClient:
    def update_generative_questions_feature_config(self, request: UpdateGenerativeQuestionsFeatureConfigRequest) -> GenerativeQuestionsFeatureConfig: ...

Advanced Features

Common Data Types

# Core product entity
class Product:
    id: str
    title: str
    categories: List[str]
    price_info: PriceInfo
    availability: ProductAvailability
    attributes: Dict[str, CustomAttribute]

# User interaction event
class UserEvent:
    event_type: str
    visitor_id: str
    product_details: List[ProductDetail]
    purchase_transaction: PurchaseTransaction

# Pricing information
class PriceInfo:
    price: float
    currency_code: str
    cost: float
    price_effective_time: Timestamp

# Search request parameters
class SearchRequest:
    placement: str
    query: str
    visitor_id: str
    page_size: int
    filter: str
    facet_specs: List[FacetSpec]

Error Handling

All service methods may raise google.api_core.exceptions.GoogleAPIError and its subclasses. Common exceptions include:

  • NotFound: Resource not found
  • AlreadyExists: Resource already exists
  • InvalidArgument: Invalid request parameters
  • PermissionDenied: Insufficient permissions
  • ResourceExhausted: Quota exceeded
from google.api_core import exceptions

try:
    product = client.get_product(request=request)
except exceptions.NotFound:
    print("Product not found")
except exceptions.InvalidArgument as e:
    print(f"Invalid request: {e}")