Skip to main content

Client for Recombee recommendation API

Project description

A Python 3 client for easy use of the Recombee recommendation API.

If you don’t have an account at Recombee yet, you can create a free account here.

Documentation of the API can be found at docs.recombee.com.

Installation

Install the client with pip:

$ pip install recombee-api-client

Examples

Basic example

from recombee_api_client.api_client import RecombeeClient, Region
from recombee_api_client.exceptions import APIException
from recombee_api_client.api_requests import *
import random

client = RecombeeClient('--my-database-id--', '--db-private-token--', region=Region.US_WEST)

#Generate some random purchases of items by users
PROBABILITY_PURCHASED = 0.1
NUM = 100
purchase_requests = []

for user_id in ["user-%s" % i for i in range(NUM) ]:
  for item_id in ["item-%s" % i for i in range(NUM) ]:
    if random.random() < PROBABILITY_PURCHASED:

      request = AddPurchase(user_id, item_id, cascade_create=True)
      purchase_requests.append(request)

try:
    # Send the data to Recombee, use Batch for faster processing of larger data
    print('Send purchases')
    client.send(Batch(purchase_requests))

    # Get recommendations for user 'user-25'
    response = client.send(RecommendItemsToUser('user-25', 5))
    print("Recommended items: %s" % response)

    # User scrolled down - get next 3 recommended items
    response = client.send(RecommendNextItems(response['recommId'], 3))
    print("Next recommended items: %s" % response)

except APIException as e:
    print(e)

Using property values

from recombee_api_client.api_client import RecombeeClient, Region
from recombee_api_client.api_requests import AddItemProperty, SetItemValues, AddPurchase
from recombee_api_client.api_requests import RecommendItemsToItem, SearchItems, Batch, ResetDatabase
import random

NUM = 100
PROBABILITY_PURCHASED = 0.1

client = RecombeeClient('--my-database-id--', '--db-private-token--', region=Region.AP_SE)

# Clear the entire database
client.send(ResetDatabase())

# We will use computers as items in this example
# Computers have four properties
#   - price (floating point number)
#   - number of processor cores (integer number)
#   - description (string)
#   - image (url of computer's photo)

# Add properties of items
client.send(AddItemProperty('price', 'double'))
client.send(AddItemProperty('num-cores', 'int'))
client.send(AddItemProperty('description', 'string'))
client.send(AddItemProperty('image', 'image'))

# Prepare requests for setting a catalog of computers
requests = [SetItemValues(
    "computer-%s" % i, #itemId
    #values:
    {
      'price': random.uniform(500, 2000),
      'num-cores': random.randrange(1,9),
      'description': 'Great computer',
      'image': 'http://examplesite.com/products/computer-%s.jpg' % i
    },
    cascade_create=True   # Use cascadeCreate for creating item
                          # with given itemId if it doesn't exist
  ) for i in range(NUM)]


# Send catalog to the recommender system
client.send(Batch(requests))

# Prepare some purchases of items by users
requests = []
items = ["computer-%s" % i for i in range(NUM)]
users = ["user-%s" % i for i in range(NUM)]

for item_id in items:
    #Use cascadeCreate to create unexisting users
    purchasing_users = [user_id for user_id in users if random.random() < PROBABILITY_PURCHASED]
    requests += [AddPurchase(user_id, item_id, cascade_create=True) for user_id in purchasing_users]

# Send purchases to the recommender system
client.send(Batch(requests))

# Get 5 recommendations for user-42, who is currently viewing computer-6
# Recommend only computers that have at least 3 cores
recommended = client.send(
    RecommendItemsToItem('computer-6', 'user-42', 5, filter="'num-cores'>=3")
)
print("Recommended items with at least 3 processor cores: %s" % recommended)

# Recommend only items that are more expensive then currently viewed item (up-sell)
recommended = client.send(
    RecommendItemsToItem('computer-6', 'user-42', 5, filter="'price' > context_item[\"price\"]")
)
print("Recommended up-sell items: %s" % recommended)

# Filters, boosters and other settings can be also set in the Admin UI (admin.recombee.com)
# when scenario is specified
recommended = client.send(
  RecommendItemsToItem('computer-6', 'user-42', 5, scenario='product_detail')
  )

# Perform personalized full-text search with a user's search query (e.g. 'computers').
matches = client.send(SearchItems('user-42', 'computers', 5, scenario='search_top'))
print("Matched items: %s" % matches)

Exception handling

For the sake of brevity, the above examples omit exception handling. However, various exceptions can occur while processing request, for example because of adding an already existing item, submitting interaction of nonexistent user or because of timeout.

We are doing our best to provide the fastest and most reliable service, but production-level applications must implement a fallback solution since errors can always happen. The fallback might be, for example, showing the most popular items from the current category, or not displaying recommendations at all.

Example:

from recombee_api_client.exceptions import *

try:
  recommended = client.send(
      RecommendItemsToItem('computer-6', 'user-42', 5, filter="'price' > context_item[\"price\"]")
  )
except ResponseException as e:
  #Handle errorneous request => use fallback
except ApiTimeoutException as e:
  #Handle timeout => use fallback
except APIException as e:
  #APIException is parent of both ResponseException and ApiTimeoutException

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

recombee-api-client-5.0.2.tar.gz (31.3 kB view details)

Uploaded Source

Built Distribution

recombee_api_client-5.0.2-py2.py3-none-any.whl (93.3 kB view details)

Uploaded Python 2Python 3

File details

Details for the file recombee-api-client-5.0.2.tar.gz.

File metadata

  • Download URL: recombee-api-client-5.0.2.tar.gz
  • Upload date:
  • Size: 31.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.9

File hashes

Hashes for recombee-api-client-5.0.2.tar.gz
Algorithm Hash digest
SHA256 9b31f2224c843bd2c97e84e3554c499f192ba746f643af73c00f5c3d7786583e
MD5 fdb6b80d73a5f2f717b7e164802e927d
BLAKE2b-256 d28f6b528139a860fe400bbd4b12d9367d5d45a836bcbc9e2ed7e22c420570b6

See more details on using hashes here.

File details

Details for the file recombee_api_client-5.0.2-py2.py3-none-any.whl.

File metadata

File hashes

Hashes for recombee_api_client-5.0.2-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 61d5d9f5d281caaf0ada6c9d185a96d32f69d0016d9840cfe7e1e6df1029ba39
MD5 26ba5247707f0a015f40dd6eb0b54592
BLAKE2b-256 fbd0a84a41772a19f79170db2eb380803f80d66fe890fcf588461df308986390

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page