recombee-api-client


Namerecombee-api-client JSON
Version 4.1.0 PyPI version JSON
download
home_pagehttps://github.com/Recombee/python-api-client
SummaryClient for Recombee recommendation API
upload_time2023-01-10 16:46:11
maintainer
docs_urlNone
authorRecombee
requires_python>=3.4
licenseMIT
keywords recommendation engine as a service
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            *****************
RecombeeApiClient
*****************

A Python 3 client for easy use of the `Recombee <https://www.recombee.com/>`_  recommendation API.

If you don't have an account at Recombee yet, you can create a free account `here <https://www.recombee.com/>`_.

Documentation of the API can be found at `docs.recombee.com <https://docs.recombee.com/>`_.

=============
Installation
=============

Install the client with pip:

.. code-block:: bash

    $ pip install recombee-api-client

========
Examples
========

-------------
Basic example
-------------

.. code-block:: python

    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
---------------------

.. code-block:: python

    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:

.. code-block:: python

  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



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/Recombee/python-api-client",
    "name": "recombee-api-client",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.4",
    "maintainer_email": "",
    "keywords": "recommendation engine as a service",
    "author": "Recombee",
    "author_email": "ondrej.fiedler@recombee.com",
    "download_url": "https://files.pythonhosted.org/packages/13/2b/4d34b3169f948ac2ec51da1d535d7f165cd8182e25370facc9298282f725/recombee-api-client-4.1.0.tar.gz",
    "platform": null,
    "description": "*****************\nRecombeeApiClient\n*****************\n\nA Python 3 client for easy use of the `Recombee <https://www.recombee.com/>`_  recommendation API.\n\nIf you don't have an account at Recombee yet, you can create a free account `here <https://www.recombee.com/>`_.\n\nDocumentation of the API can be found at `docs.recombee.com <https://docs.recombee.com/>`_.\n\n=============\nInstallation\n=============\n\nInstall the client with pip:\n\n.. code-block:: bash\n\n    $ pip install recombee-api-client\n\n========\nExamples\n========\n\n-------------\nBasic example\n-------------\n\n.. code-block:: python\n\n    from recombee_api_client.api_client import RecombeeClient, Region\n    from recombee_api_client.exceptions import APIException\n    from recombee_api_client.api_requests import *\n    import random\n\n    client = RecombeeClient('--my-database-id--', '--db-private-token--', region=Region.US_WEST)\n\n    #Generate some random purchases of items by users\n    PROBABILITY_PURCHASED = 0.1\n    NUM = 100\n    purchase_requests = []\n\n    for user_id in [\"user-%s\" % i for i in range(NUM) ]:\n      for item_id in [\"item-%s\" % i for i in range(NUM) ]:\n        if random.random() < PROBABILITY_PURCHASED:\n\n          request = AddPurchase(user_id, item_id, cascade_create=True)\n          purchase_requests.append(request)\n\n    try:\n        # Send the data to Recombee, use Batch for faster processing of larger data\n        print('Send purchases')\n        client.send(Batch(purchase_requests))\n\n        # Get recommendations for user 'user-25'\n        response = client.send(RecommendItemsToUser('user-25', 5))\n        print(\"Recommended items: %s\" % response)\n\n        # User scrolled down - get next 3 recommended items\n        response = client.send(RecommendNextItems(response['recommId'], 3))\n        print(\"Next recommended items: %s\" % response)\n\n    except APIException as e:\n        print(e)\n\n\n\n---------------------\nUsing property values\n---------------------\n\n.. code-block:: python\n\n    from recombee_api_client.api_client import RecombeeClient, Region\n    from recombee_api_client.api_requests import AddItemProperty, SetItemValues, AddPurchase\n    from recombee_api_client.api_requests import RecommendItemsToItem, SearchItems, Batch, ResetDatabase\n    import random\n\n    NUM = 100\n    PROBABILITY_PURCHASED = 0.1\n\n    client = RecombeeClient('--my-database-id--', '--db-private-token--', region=Region.AP_SE)\n\n    # Clear the entire database\n    client.send(ResetDatabase())\n\n    # We will use computers as items in this example\n    # Computers have four properties \n    #   - price (floating point number)\n    #   - number of processor cores (integer number)\n    #   - description (string)\n    #   - image (url of computer's photo)\n\n    # Add properties of items\n    client.send(AddItemProperty('price', 'double'))\n    client.send(AddItemProperty('num-cores', 'int'))\n    client.send(AddItemProperty('description', 'string'))\n    client.send(AddItemProperty('image', 'image'))\n\n    # Prepare requests for setting a catalog of computers\n    requests = [SetItemValues(\n        \"computer-%s\" % i, #itemId\n        #values:\n        { \n          'price': random.uniform(500, 2000),\n          'num-cores': random.randrange(1,9),\n          'description': 'Great computer',\n          'image': 'http://examplesite.com/products/computer-%s.jpg' % i\n        },\n        cascade_create=True   # Use cascadeCreate for creating item\n                              # with given itemId if it doesn't exist\n      ) for i in range(NUM)]\n\n\n    # Send catalog to the recommender system\n    client.send(Batch(requests))\n\n    # Prepare some purchases of items by users\n    requests = []\n    items = [\"computer-%s\" % i for i in range(NUM)]\n    users = [\"user-%s\" % i for i in range(NUM)]\n\n    for item_id in items:\n        #Use cascadeCreate to create unexisting users\n        purchasing_users = [user_id for user_id in users if random.random() < PROBABILITY_PURCHASED]\n        requests += [AddPurchase(user_id, item_id, cascade_create=True) for user_id in purchasing_users]\n\n    # Send purchases to the recommender system\n    client.send(Batch(requests))\n\n    # Get 5 recommendations for user-42, who is currently viewing computer-6\n    # Recommend only computers that have at least 3 cores\n    recommended = client.send(\n        RecommendItemsToItem('computer-6', 'user-42', 5, filter=\"'num-cores'>=3\")\n    )\n    print(\"Recommended items with at least 3 processor cores: %s\" % recommended)\n\n    # Recommend only items that are more expensive then currently viewed item (up-sell)\n    recommended = client.send(\n        RecommendItemsToItem('computer-6', 'user-42', 5, filter=\"'price' > context_item[\\\"price\\\"]\")\n    )\n    print(\"Recommended up-sell items: %s\" % recommended)\n\n    # Filters, boosters and other settings can be also set in the Admin UI (admin.recombee.com)\n    # when scenario is specified\n    recommended = client.send(\n      RecommendItemsToItem('computer-6', 'user-42', 5, scenario='product_detail')\n      )\n\n    # Perform personalized full-text search with a user's search query (e.g. 'computers').\n    matches = client.send(SearchItems('user-42', 'computers', 5, scenario='search_top'))\n    print(\"Matched items: %s\" % matches)\n\n------------------\nException handling\n------------------\n\nFor 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.\n\nWe 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.\n\nExample:\n\n.. code-block:: python\n\n  from recombee_api_client.exceptions import *\n\n  try:\n    recommended = client.send(\n        RecommendItemsToItem('computer-6', 'user-42', 5, filter=\"'price' > context_item[\\\"price\\\"]\")\n    )\n  except ResponseException as e:\n    #Handle errorneous request => use fallback\n  except ApiTimeoutException as e:\n    #Handle timeout => use fallback\n  except APIException as e:\n    #APIException is parent of both ResponseException and ApiTimeoutException\n\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Client for Recombee recommendation API",
    "version": "4.1.0",
    "split_keywords": [
        "recommendation",
        "engine",
        "as",
        "a",
        "service"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "620b836267b7fc907b075f5272605c440e2f6d6e0da0b0a02b3d854c0f7ace23",
                "md5": "0de9a7daa86f5ae5c48091de582ae94a",
                "sha256": "fdde38e4223933a9dac7984113406f89ebd63c5ddf67ace58cfd775a95c22173"
            },
            "downloads": -1,
            "filename": "recombee_api_client-4.1.0-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "0de9a7daa86f5ae5c48091de582ae94a",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": ">=3.4",
            "size": 170065,
            "upload_time": "2023-01-10T16:46:08",
            "upload_time_iso_8601": "2023-01-10T16:46:08.856990Z",
            "url": "https://files.pythonhosted.org/packages/62/0b/836267b7fc907b075f5272605c440e2f6d6e0da0b0a02b3d854c0f7ace23/recombee_api_client-4.1.0-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "132b4d34b3169f948ac2ec51da1d535d7f165cd8182e25370facc9298282f725",
                "md5": "864900d8d3ad202c584921f615eee3ee",
                "sha256": "16055afd91bd4dd9d7bd285ee0bf6e727c638c0c819b65b7e3b8be339dfba605"
            },
            "downloads": -1,
            "filename": "recombee-api-client-4.1.0.tar.gz",
            "has_sig": false,
            "md5_digest": "864900d8d3ad202c584921f615eee3ee",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.4",
            "size": 44935,
            "upload_time": "2023-01-10T16:46:11",
            "upload_time_iso_8601": "2023-01-10T16:46:11.880037Z",
            "url": "https://files.pythonhosted.org/packages/13/2b/4d34b3169f948ac2ec51da1d535d7f165cd8182e25370facc9298282f725/recombee-api-client-4.1.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-01-10 16:46:11",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "Recombee",
    "github_project": "python-api-client",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "recombee-api-client"
}
        
Elapsed time: 0.03079s