### Example response from Shaped AI rank endpoint Source: https://docs.shaped.ai/docs/overview/quickstart This is an example JSON response from the Shaped AI rank endpoint. It contains two parallel arrays: 'ids' with item identifiers and 'scores' indicating the relevance confidence for each item. This data can be used to understand and present personalized rankings. ```json { "ids":[ "427010", "182094", "332874", "827918", "403528" ], "scores":[ 0.9, 0.8, 0.7, 0.3, 0.2 ] } ``` -------------------------------- ### Use Shaped Rank Endpoint (Python) Source: https://docs.shaped.ai/docs/overview/install-sdk Illustrates how to leverage the Shaped SDK's Rank endpoint in Python for obtaining item recommendations. Examples include basic retrieval, including metadata, applying filters, and configuring advanced inference settings. ```python from shaped import ShapedClient client = ShapedClient(api_key="your_api_key") # Get recommended items for a user. recommendations = client.rank( model_name="your_model_name", user_id="user_id", ) # Get metadata for recommended items. recommendations = client.rank( model_name="your_model_name", user_id="user_id", return_metadata=True, ) # Get items with certain features. recommendations = client.rank( model_name="your_model_name", user_id="user_id", filter_predicate="category = 'sports' AND price < 100", ) # Advanced: Custom Inference Configuration Settings. recommendations = client.rank( model_name="your_model_name", user_id="user_id", config=shaped.InferenceConfig( exploration_factor=0.1, diversity_factor=0.1, diversity_attributes=["category", "brand"], retreieval_k=100, retriever_k_override=shaped.RetrieverTopKOverride( knn=300, chronological=100, popular=100, trending=300, random=0, cold_start=300, ) limit=10, ) ) ``` -------------------------------- ### Verify Shaped SDK Installation (JavaScript) Source: https://docs.shaped.ai/docs/overview/install-sdk Verifies the successful installation of the Shaped SDK client for JavaScript by listing the installed package. This command helps confirm that the SDK is ready for use in your project. ```bash npm list @shaped.ai/client ``` -------------------------------- ### Use Shaped Rank Endpoint (JavaScript) Source: https://docs.shaped.ai/docs/overview/install-sdk Demonstrates how to use the Shaped SDK's Rank endpoint in JavaScript to get item recommendations. It covers basic usage, returning metadata, filtering items by predicates, and advanced custom inference configurations. ```javascript const {rank} = require("@shaped.ai/client").Client('your_api_key') // Get item recommendations for a user. recommendations = rank({ model_name: "your_model_name", user_id: "user_id", }) // Get metadata for recommended items. recommendations = rank({ model_name: "your_model_name", user_id: "user_id", return_metadata: true, }) // Get items with certain features. recommendations = rank({ model_name: "your_model_name", user_id: "user_id", filter_predicate: "category = 'sports' AND price < 100", }) // Advanced: Custom Inference Configuration Settings. recommendations = rank({ model_name: "your_model_name", user_id: "user_id", config: { exploration_factor: 0.1, diversity_factor: 0.1, limit: 10, retriever_k_override: { knn: 300, chronological: 100, popular: 100, trending: 300, random: 0, cold_start: 300, } } }) ``` -------------------------------- ### Verify Shaped SDK Installation (Python) Source: https://docs.shaped.ai/docs/overview/install-sdk Confirms the correct installation of the Shaped SDK for Python by displaying information about the installed 'shaped' package. This is a crucial step before using the SDK's functionalities. ```bash pip show shaped ``` -------------------------------- ### Download Sample Movie Ratings Dataset Source: https://docs.shaped.ai/docs/overview/quickstart This command downloads a sample movie ratings dataset (ml-100k.zip) from files.grouplens.org using wget. The '--no-check-certificate' flag is used to bypass SSL certificate verification, which might be necessary in some environments. ```bash wget http://files.grouplens.org/datasets/movielens/ml-100k.zip --no-check-certificate ``` -------------------------------- ### Define and Create Model using YAML Configuration Source: https://docs.shaped.ai/docs/overview/quickstart This process involves two steps: first, defining the model configuration in a YAML file (e.g., movie_recommendation_model.yaml) specifying model name, connectors, and SQL fetch statements; second, creating the model in Shaped using the CLI command with the path to the YAML file. ```yaml model: name: movie_recommendations connectors: - type: Dataset id: movielens_ratings name: movielens_ratings fetch: events: | SELECT user_id, item_id, timestamp AS created_at, CASE WHEN rating >= 4 THEN 1 ELSE 0 END AS label FROM movielens_ratings ``` ```bash shaped create-model --file movie_recommendation_model.yaml ``` -------------------------------- ### Use Shaped Retrieve Endpoint (Python) Source: https://docs.shaped.ai/docs/overview/install-sdk Demonstrates using the Shaped SDK's Retrieve endpoint in Python for fetching items based on user ID, text queries, or filtered criteria. It also includes examples for advanced custom inference configuration. ```python from shaped import ShapedClient client = ShapedClient(api_key="your_api_key") # Retrieve items for a user. retrieved_items = client.retrieve( model_name="your_model_name", user_id="user_id", ) # Retrieve items with certain features. retrieved_items = client.retrieve( model_name="your_model_name", user_id="user_id", filter_predicate="category = 'sports' AND price < 100", ) # Retrieve items using a text query. retrieved_items = client.retrieve( model_name="your_model_name", user_id="user_id", query="brown cardigans and sweaters", ) # Advanced: Custom Inference Configuration Settings. retrieved_items = client.retrieve( model_name="your_model_name", user_id="user_id", config=shaped.InferenceConfig( limit=10, retriever_k_override=shaped.RetrieverTopKOverride( knn=300, chronological=100, popular=100, trending=300, random=0, cold_start=300, ) ) ) ``` -------------------------------- ### Install Shaped SDK for JavaScript Source: https://docs.shaped.ai/docs/overview/install-sdk Installs the Shaped SDK client for JavaScript using npm. This is the first step to integrate Shaped's services into your Node.js applications. No specific dependencies are mentioned beyond npm. ```bash npm install @shaped.ai/client ``` -------------------------------- ### Initialize Shaped Client and Rank Recommendations (Python) Source: https://docs.shaped.ai/docs/feature_types/categoricals Initializes the Shaped client and calls the rank API to get personalized recommendations for a user. It then iterates through the response metadata to print item details. This requires the 'shaped' library to be installed. ```python from shaped import Shaped # Initialize the Shaped client client = Shaped() response = client.rank( model_name='category_recs_platform', user_id='USER_XYZ', limit=10 ) for item in response.metadata: print(f"- {item['title']} (Category: {item['category']}, Brand: {item['brand']})") ``` -------------------------------- ### Create Dataset from Local TSV File Source: https://docs.shaped.ai/docs/overview/quickstart This CLI command creates a new dataset in Shaped by ingesting data from a local TSV file. Specify the dataset name ('--name'), the path to the file ('--path'), and the file type ('--type'). The example uses 'u.data' as the input file. ```bash shaped create-dataset-from-uri --name movielens_ratings --path u.data --type tsv ``` -------------------------------- ### Install Shaped and PyYAML for Model Schema Source: https://docs.shaped.ai/docs/tutorials/goodbooks Installs the 'shaped' library for using the Shaped CLI and 'pyyaml' for creating model schema files. These are essential first steps for setting up the recommendation model. ```python ! pip install shaped ! pip install pyyaml ``` -------------------------------- ### Install Shaped SDK for Python Source: https://docs.shaped.ai/docs/overview/install-sdk Installs the Shaped SDK for Python using pip. This package provides the necessary tools to interact with Shaped's Model Inference APIs in Python projects. Ensure pip is available and updated. ```bash pip install shaped ``` -------------------------------- ### CLI Example: List Models Source: https://docs.shaped.ai/docs/api This command-line interface example shows how to list all created models using the Shaped AI CLI tool. ```bash $ shaped list-models ``` -------------------------------- ### Install Shaped CLI using pipx Source: https://docs.shaped.ai/docs/overview/installing-shaped-cli Installs the Shaped CLI using pipx, a tool for installing Python applications in isolated environments. This can help avoid package conflicts. ```bash pipx install shaped ``` -------------------------------- ### Install Shaped CLI using pip Source: https://docs.shaped.ai/docs/overview/installing-shaped-cli Installs the Shaped CLI package from PyPI. Ensure you have Python 3.8-3.11 and pip installed. For dependency management, consider using a Python virtual environment. ```bash pip install shaped ``` -------------------------------- ### CLI Example Source: https://docs.shaped.ai/docs/use_cases/user_interest_ranking Example demonstrating how to use the Shaped CLI to call the Rank API with user features. ```APIDOC ```bash user_features = { "country": "US", "interests": ["technology", "travel", "food"], "language": "en" } shaped rank --model-name my_recommendation_model \ --user-features "$user_features" ``` ``` -------------------------------- ### YAML Model Configuration Example Source: https://docs.shaped.ai/docs/model_creation/overview This snippet shows a basic example of a Shaped model configuration file in YAML format. It defines model parameters such as name, description, training schedule, and inference configurations like exploration and diversity factors. It also includes placeholders for data fetching using SQL. ```yaml model: name: for_you_feed_v1 description: "Recommend items to show in the for you feed" pagination_store_ttl: 0 # Seconds. train_schedule: "@once" inference_config: exploration_factor: 0, diversity_factor: 0, boosting_factor: 0, diversity_attributes: - category_field retrieval_k: 0 retriever_k_override: knn: 0, chronological: 0, toplist: 0, trending: 0, random: 0, cold_start: 0 limit: 0 connectors: - id: connector1 name: connector1 type: Dataset fetch: events: | ... users: | .. items: | ... global_filters: | ... personal_filters: | ... ``` -------------------------------- ### Model Status Response Example Source: https://docs.shaped.ai/docs/tutorials/rent-the-runway An example JSON response from the 'list-models' or 'view-model' endpoint, indicating the status of a recommendation model. The status progresses through stages like SCHEDULING, FETCHING, TUNING, TRAINING, DEPLOYING, and finally ACTIVE. ```json [ "models": { "created_at": "2023-03-18T19:17:51 UTC", "model_name": "rent_runway_recommendations", "model_uri": "https://api.prod.shaped.ai/v1/models/rent_runway_recommendations", "status": "FETCHING" } ] ``` -------------------------------- ### Install Pandas for Data Handling Source: https://docs.shaped.ai/docs/tutorials/goodbooks Installs the 'pandas' library, which is used for viewing and editing the sample dataset. Pandas is a fundamental tool for data manipulation in Python. ```python ! pip install pandas ``` -------------------------------- ### Download and Unzip RentTheRunway Dataset Source: https://docs.shaped.ai/docs/tutorials/rent-the-runway Downloads the RentTheRunway dataset from a public URL and then unzips the downloaded gzipped file. This prepares the raw dataset for preprocessing. ```bash wget https://mcauleylab.ucsd.edu/public_datasets/data/renttherunway/renttherunway_final_data.json.gz --no-check-certificate gunzip renttherunway_final_data.json.gz ``` -------------------------------- ### Initialize Shaped Client Source: https://docs.shaped.ai/docs/overview/installing-shaped-cli Initializes the Shaped client by providing your API key. Replace with the key obtained from your Shaped Dashboard. This command sets up the CLI for subsequent operations. ```bash shaped init --api-key ``` -------------------------------- ### Rank Items (GET Request Example) Source: https://docs.shaped.ai/docs/api This example shows a convenience GET request to the rank endpoint. It's suitable for fetching ranked items based on user ID and optional metadata, simplifying common ranking use cases. ```http GET /v1/models/{model_name}/rank?user_id=user_123&return_metadata=true HTTP/1.1 Host: api.shaped.ai x-api-key: YOUR_API_KEY ``` -------------------------------- ### Initialize Shaped CLI with API Key Source: https://docs.shaped.ai/docs/tutorials/steam_review Initializes the Shaped client by authenticating with your API key. Obtain an API key from the Shaped platform before running this command. ```bash shaped init --api-key ``` -------------------------------- ### Rank Items (POST Request Example) Source: https://docs.shaped.ai/docs/api This example demonstrates how to make a POST request to the rank endpoint to get personalized recommendations or trending items. It requires the model name and can optionally include user ID, item IDs, or other parameters for customization. ```http POST /v1/models/{model_name}/rank HTTP/1.1 Host: api.shaped.ai Content-Type: application/json x-api-key: YOUR_API_KEY { "user_id": "user_123", "limit": 10 } ``` -------------------------------- ### Define Shaped Model for Cold Start Recommendations (YAML) Source: https://docs.shaped.ai/docs/use_cases/user_cold_start This YAML configuration defines a Shaped model named 'discovery_engine_v1'. It specifies connectors for user metadata, item metadata, and user interactions. The 'fetch' section outlines SQL queries to retrieve data from these datasets, including user details, item attributes, and interaction events. ```yaml model: name: discovery_engine_v1 connectors: - type: Dataset name: user_metadata id: users - type: Dataset name: item_metadata id: items - type: Dataset name: user_interactions id: interactions fetch: users: | SELECT user_id, country, device_type FROM users items: | SELECT item_id, title, description, category, tags brand, image_url, product_url, publish_date FROM items events: | SELECT user_id, item_id, timestamp AS created_at, event_type FROM interactions ``` -------------------------------- ### Example Redshift Dataset Configuration for Shaped Source: https://docs.shaped.ai/docs/connectors/redshift A YAML configuration file example for creating a Redshift dataset in Shaped. This configuration specifies connection details like host, port, user, password, and database, along with table and schema information for data synchronization. It also includes optional fields for advanced configuration. ```yaml name: your_redshift_dataset schema_type: REDSHIFT table: movies user: your_user password: pAssw0rd1! host: my-redshift-db.xxxxxxx.us-east-2.rds.amazonaws.com port: 5439 database: movielens database_schema: public replication_key: updated_at ``` -------------------------------- ### Initialize Shaped Client with API Key Source: https://docs.shaped.ai/docs/tutorials/goodbooks Initializes the Shaped CLI using an API key, which can be fetched from an environment variable or directly provided. This step connects the CLI to the Shaped service. ```python import os SHAPED_API_KEY = os.getenv('TEST_SHAPED_API_KEY', '') ``` ```bash ! shaped init --api-key $SHAPED_API_KEY ``` -------------------------------- ### Get Recommendations with Shaped Rank API (Python) Source: https://docs.shaped.ai/docs/feature_types/timestamps Initializes the Shaped client and calls the 'rank' API to retrieve recommendations. It then iterates through the response metadata to print item titles and their publication dates. This function requires the 'shaped' library to be installed. ```python from shaped import Shaped # Initialize the Shaped client shaped_client = Shaped() response = shaped_client.rank( model_name='temporal_recs_platform', user_id='USER_1', limit=10 ) for item in response.metadata: print(f"- {item['title']} (Published At: {item['published_at']})") ``` -------------------------------- ### Retrieve Endpoint Source: https://docs.shaped.ai/docs/overview/install-sdk The Retrieve endpoint returns relevant item_ids for a given text query or user query. It's suitable when filtering, scoring, and ordering stages are not required, potentially reducing latency and complexity. ```APIDOC ## POST /retrieve ### Description Returns relevant item_ids for the given text_query or user query. Useful for search-like functionality without full ranking. ### Method POST ### Endpoint /retrieve ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **model_name** (string) - Required - The name of the model to use for retrieval. - **user_id** (string) - Required - The ID of the user for whom to retrieve items. - **query** (string) - Optional - A text query to retrieve items based on textual relevance. - **filter_predicate** (string) - Optional - A predicate string to filter items based on their features (e.g., "category = 'electronics'"). - **config** (object) - Optional - Advanced inference configuration settings. - **limit** (integer) - Optional - The maximum number of items to retrieve. - **retriever_k_override** (object) - Optional - Overrides for retriever K values. - **knn** (integer) - Optional. - **chronological** (integer) - Optional. - **popular** (integer) - Optional. - **trending** (integer) - Optional. - **random** (integer) - Optional. - **cold_start** (integer) - Optional. ### Request Example ```json { "model_name": "your_model_name", "user_id": "user_id", "query": "blue jeans", "filter_predicate": "price < 50", "config": { "limit": 5 } } ``` ### Response #### Success Response (200) - **item_ids** (array of strings) - A list of relevant item IDs. #### Response Example ```json { "item_ids": ["itemA", "itemB", "itemC"] } ``` ``` -------------------------------- ### Initialize Shaped Client and Rank Recommendations (JavaScript) Source: https://docs.shaped.ai/docs/feature_types/categoricals Initializes the Shaped client using Node.js and calls the rank API to retrieve recommendations. It then logs the recommended items to the console. This requires the '@shaped/shaped' package to be installed. ```javascript const { Shaped } = require('@shaped/shaped'); // Initialize the Shaped client const client = new Shaped(); const response = await client.rank({ modelName: 'category_recs_platform', userId: 'USER_XYZ', limit: 10 }); console.log("Recommended Items:"); response.metadata.forEach(item => { console.log(`- ${item.title} (Category: ${item.category}, Brand: ${item.brand})`); }); ``` -------------------------------- ### Rank Endpoint Source: https://docs.shaped.ai/docs/overview/install-sdk The Rank endpoint returns a list of relevant item_ids for a given request context, ordered from most to least relevant. It supports various options including returning metadata, filtering by features, and advanced inference configuration. ```APIDOC ## POST /rank ### Description Returns a list of relevant item_ids (from most-relevant to least) for the given request context. ### Method POST ### Endpoint /rank ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **model_name** (string) - Required - The name of the model to use for ranking. - **user_id** (string) - Required - The ID of the user for whom to get recommendations. - **return_metadata** (boolean) - Optional - If true, includes metadata for recommended items. - **filter_predicate** (string) - Optional - A predicate string to filter items based on their features (e.g., "category = 'sports' AND price < 100"). - **config** (object) - Optional - Advanced inference configuration settings. - **exploration_factor** (number) - Optional - Controls exploration. - **diversity_factor** (number) - Optional - Controls diversity. - **diversity_attributes** (array of strings) - Optional - Attributes to consider for diversity. - **limit** (integer) - Optional - The maximum number of recommendations to return. - **retriever_k_override** (object) - Optional - Overrides for retriever K values. - **knn** (integer) - Optional. - **chronological** (integer) - Optional. - **popular** (integer) - Optional. - **trending** (integer) - Optional. - **random** (integer) - Optional. - **cold_start** (integer) - Optional. ### Request Example ```json { "model_name": "your_model_name", "user_id": "user_id", "return_metadata": true, "filter_predicate": "category = 'sports'", "config": { "limit": 10, "exploration_factor": 0.1 } } ``` ### Response #### Success Response (200) - **item_ids** (array of strings) - A list of relevant item IDs. - **metadata** (object) - Optional - Metadata for the recommended items if `return_metadata` is true. #### Response Example ```json { "item_ids": ["item1", "item2", "item3"], "metadata": { "item1": {"name": "Product A", "price": 50}, "item2": {"name": "Product B", "price": 75} } } ``` ``` -------------------------------- ### Create Model Source: https://docs.shaped.ai/docs/tutorials/amazon This section details how to create a new Shaped model using a configuration file and the CLI command. ```APIDOC ## Create your Shaped model This endpoint allows you to create a new Shaped model. You will need a YAML configuration file that defines the model's name, interaction expiration, data connectors, and data fetching logic. ### Method `POST` (via CLI) ### Endpoint N/A (CLI command) ### Parameters #### Request Body (via YAML file) - **model.name** (string) - Required - The name of the model. - **model.interaction_expiration_days** (integer) - Required - The number of days interactions are stored. - **connectors** (array) - Required - List of data connectors (e.g., Datasets). - **type** (string) - Required - Type of connector (e.g., `Dataset`). - **name** (string) - Required - Name of the connector. - **id** (string) - Required - ID of the connector. - **fetch.events** (string) - Required - SQL query to fetch event data. - **fetch.items** (string) - Required - SQL query to fetch item metadata. ### Request Example ```yaml --- model: name: amazon_beauty_product_recommendations interaction_expiration_days: 22000 connectors: - type: Dataset name: amazon_beauty_products id: amazon_beauty_products - type: Dataset name: amazon_beauty_ratings id: amazon_beauty_ratings fetch: events: | SELECT CASE WHEN overall >= 4 THEN 1 ELSE 0 END as label, asin AS item_id, reviewerID AS user_id, unixReviewTime AS created_at, summary, verified, FROM amazon_beauty_ratings items: | SELECT asin AS item_id, title, TRY_CAST(TRIM(price, '$') AS DOUBLE) AS price, brand, FROM amazon_beauty_products ``` ### CLI Command ```bash shaped create-model --file amazon_beauty_product_recommendation.yaml ``` ### Response Upon successful execution, the CLI will indicate model creation has started. The model status can be inspected using `shaped list-models` or the 'View Model' endpoint. ``` -------------------------------- ### Get Recommendations with Shaped JavaScript API Source: https://docs.shaped.ai/docs/feature_types/language This JavaScript code illustrates how to retrieve recommendations using the Shaped client. It mirrors the Python example by showing how to make requests for both the default language model and a model configured with a multilingual Hugging Face model. Error handling is included for robustness. ```javascript const { Shaped } = require('@shaped/shaped'); // Initialize the Shaped client const shapedClient = new Shaped(); // Get recommendations using the default language model async function getRecommendations() { try { const responseAuto = await shapedClient.rank({ modelName: 'auto_language_recs', userId: 'USER_1', limit: 10 }); console.log('Recommendations using default language model:', responseAuto); const responseHF = await shapedClient.rank({ modelName: 'multilingual_recs_hf', userId: 'USER_2', limit: 10 }); console.log('Recommendations using multilingual HF model:', responseHF); } catch (error) { console.error('Error fetching recommendations:', error); } } getRecommendations(); ``` -------------------------------- ### Fetch Recommendations with Shaped Rank API (CLI) Source: https://docs.shaped.ai/docs/use_cases/user_cold_start This command-line interface example shows how to use the Shaped CLI to fetch recommendations. It specifies the model name, provides session interactions and user features as JSON strings, and sets a limit for the number of recommendations returned. ```bash shaped rank \ --model-name discovery_engine_v1 \ --interactions '[{"item_id": "ITEM_ABC"}, {"item_id": "ITEM_XYZ"}]' \ --user-features '{"country": "CA"}' \ --limit 10 ``` -------------------------------- ### Rank with User Features via CLI Source: https://docs.shaped.ai/docs/use_cases/user_interest_ranking This command-line interface example demonstrates how to rank items using user features with the Shaped AI CLI. It requires the `shaped` package to be installed. User features are passed as a JSON string to the `--user-features` argument. ```bash user_features = { "country": "US", "interests": ["technology", "travel", "food"], "language": "en" } shaped rank --model-name my_recommendation_model \ --user-features "$user_features" ``` -------------------------------- ### Create and Monitor Shaped Model (CLI) Source: https://docs.shaped.ai/docs/use_cases/item_cold_start Commands to create a Shaped AI model using a YAML configuration file and to monitor its training status. Ensures the model is ready for use before proceeding. ```bash shaped create-model --file item_cold_start_model.yaml shaped view-model --model-name product_discovery_v2 # Wait for ACTIVE ``` -------------------------------- ### Create and Monitor Location Model (Shaped CLI) Source: https://docs.shaped.ai/docs/feature_types/locations Demonstrates the command-line interface commands for creating and monitoring a Shaped AI model. 'shaped create-model' initiates the model setup, and 'shaped view-model' allows monitoring its status until it becomes 'ACTIVE'. ```bash shaped create-model --file location_model.yaml # Monitor the model until it reaches the ACTIVE state shaped view-model --model-name location_recs_platform ``` -------------------------------- ### Configure BigQuery Datasets with YAML for Shaped AI Source: https://docs.shaped.ai/docs/model_creation/training-data Define dataset configurations for BigQuery tables using YAML files. These files specify the dataset name, schema type, table path, relevant columns, a datetime key for incremental ingestion, and a start datetime. This allows Shaped to ingest and process your data efficiently. ```yaml name: items schema_type: BIGQUERY table: "`bq-project`.shaped.`data`" columns: ["item_id", "created_at", "updated_at", "price"] datetime_key: "updated_at" start_datetime: "2020-01-01T00:00:00Z" ``` ```yaml name: items_categories schema_type: BIGQUERY table: "`bq-project`.shaped.`data`" columns: ["item_id", "created_at", "updated_at", "category", "deleted"] datetime_key: "updated_at" start_datetime: "2020-01-01T00:00:00Z" ``` -------------------------------- ### Create Shaped Model using CLI Source: https://docs.shaped.ai/docs/tutorials/amazon This command initiates the creation of a Shaped model by referencing a YAML configuration file. Ensure the specified YAML file exists and is correctly formatted. ```bash shaped create-model --file amazon_beauty_product_recommendation.yaml ``` -------------------------------- ### Python Client Example Source: https://docs.shaped.ai/docs/use_cases/user_interest_ranking Example demonstrating how to use the Shaped Python client to call the Rank API with user features. ```APIDOC ```python import shaped api_key = 'your_api_key' client = shaped.Client(api_key=api_key) user_features = { "country": "US", "interests": ["technology", "travel", "food"], "language": "en" } results = client.rank( model_name='for_you_feed_v1', user_features=user_features, limit=5, ) print(results) ``` ``` -------------------------------- ### Download and Extract Goodbooks-10k Dataset Source: https://docs.shaped.ai/docs/tutorials/goodbooks Downloads and extracts the Goodbooks-10k dataset from provided URLs. It uses 'wget' for downloading and 'zipfile' for extraction, saving the data into a specified directory. ```python import zipfile import os def download_and_extract_dataset(url, destination_directory): print(f"Downloading dataset from {url}...") os.makedirs(destination_directory, exist_ok=True) zip_file_path = os.path.join(destination_directory, os.path.basename(url)) # Download the ZIP file !wget $url --no-check-certificate -P $destination_directory # Extract the contents of the ZIP file with zipfile.ZipFile(zip_file_path, 'r') as zip_ref: zip_ref.extractall(destination_directory) # Directory name for storing datasets DIR_NAME = "notebook_assets" # Download and extract each dataset datasets = [ ("https://github.com/zygmuntz/goodbooks-10k/releases/download/v1.0/ratings.zip", DIR_NAME), ("https://github.com/zygmuntz/goodbooks-10k/releases/download/v1.0/books.zip", DIR_NAME) ] for dataset_url, destination_dir in datasets: download_and_extract_dataset(dataset_url, destination_dir) ``` -------------------------------- ### Fetch Recommendations with Shaped API (Python) Source: https://docs.shaped.ai/docs/feature_types/numericals Initializes the Shaped client and fetches recommendations using a numerically-enhanced model. It then iterates through the response to print recommended items, displaying their title, price, rating, and view count. This method requires the 'shaped' library to be installed. ```python from shaped import Shaped # Initialize the Shaped client shaped_client = Shaped() # Get recommendations using the numerically-enhanced model response = shaped_client.rank( model_name='numerical_recs_model', user_id='USER_1', limit=10 ) # Print the recommendations if response and response.metadata: print("Recommended Items:") for item in response.metadata: print(f"- {item['title']} (Price: {item['price']}, Rating: {item['average_rating']}, Views: {item['view_count']})") else: print("No recommendations found.") ```