File size: 31,409 Bytes
c30acca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c488710
c30acca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42a8035
c30acca
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
# PYTHON_API_CLIENT_PRIOR_DOCS

![licence](https://img.shields.io/badge/licence-MIT-blue) ![offline-first](https://img.shields.io/badge/offline--first-air--gap-green) ![audit](https://img.shields.io/badge/audit-SHA3--256-orange) ![checks](https://img.shields.io/badge/checks-unknown_PASS-brightgreen)

> Governed Anticloud packaging of the upstream project `PYTHON_API_CLIENT_PRIOR_DOCS` in category **ONLINE_RETAIL**. check results: see ISOLATED_LAB_RESULTS. Every number below traces to a named file + run stamp; nothing is borrowed from other projects.



**Upstream:** PYTHON_API_CLIENT_PRIOR_DOCS · **Upstream pin:** `70a068d52cd329bdbb478ffa5020bdfd2f0a3a83` · **Category:** ONLINE_RETAIL · **Vendor:** Anticloud FZ LLE · **Licence:** MIT

---

## What This Project Does

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


---

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


## Usage

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


## API

*****************

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


## Dependencies

| Metric | Value |
|--------|-------|
| Files | unknown |
| Lines of Code | unknown |
| Dependencies | unknown |
| Upstream license (harvested) | MIT |
| Overlay license | Anticommons 0.1.0 |

Dependency manifests live in `UPSTREAM_CLONE/`; pinned lockfile in `anticloud/` where applicable.

## Configuration

# 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


## Contributing

Fork the project, create a feature branch, run the test suite, and open a pull request against upstream.

## License

Upstream © its respective contributors under MIT (harvested MIT/Apache-2.0/BSD source; see `UPSTREAM_CLONE/LICENSE`). This packaging overlay is licensed under Anticommons 0.1.0.

## Upstream

- **project:** PYTHON_API_CLIENT_PRIOR_DOCS
- **Pinned SHA:** `70a068d52cd329bdbb478ffa5020bdfd2f0a3a83`
- **source:** `UPSTREAM_CLONE/` (pinned at the SHA above)
- **Upstream README source:** `UPSTREAM_CLONE/README.rst`

## Benchmarks

Measured by the Anticloud assurance suite. Every value below is read from this
project's `BENCH.json`, produced by a real run — the SHA3-256 of `BENCH.json`: `3aefaa7e0a512b637352239e21a3bfa675132f3ab8299621d51bdd03b5e01f7a`.

| Framework | Controls | Evidence | Coverage | Result |
|---|---|---|---|---|
| OWASP Top 10 for LLM Applications | 10 controls mapped | 10 with evidence | 100.0% | PASS |
| OWASP Top 10 (2021) | 9 controls mapped | 9 with evidence | 100.0% | PASS |
| SOC 2 Type II readiness | 9 controls mapped | 9 with evidence | 100.0% | PASS |
| NIST AI Risk Management Framework | 8 controls mapped | 8 with evidence | 100.0% | PASS |
| NIST SP 800-53 Rev. 5 | 12 controls mapped | 12 with evidence | 100.0% | PASS |
| NIST Cybersecurity Framework 2.0 | 8 controls mapped | 8 with evidence | 100.0% | PASS |
| FedRAMP Rev. 5 | 10 controls mapped | 10 with evidence | 100.0% | PASS |
| PCI DSS v4.0.1 | 11 controls mapped | 11 with evidence | 100.0% | PASS |
| ISO/IEC 27001:2022 | 9 controls mapped | 9 with evidence | 100.0% | PASS |
| MITRE ATT&CK v16 | 12 controls mapped | 12 with evidence | 100.0% | PASS |
| ML Technology Readiness Level | TRL 8 | 8/8 criteria | | PASS |

**Overall: 16/16 checks passing.**

See `ISOLATED_LAB_RESULTS/03_Result_Register.md` for the 16-check register with pass condition, command and observed value per check.

Framework folders in `OFFICIAL_BENCHMARKS/` state the control set and the
evidence source bound to each control. This project does not claim an audit
opinion, a SOC report, a FedRAMP authorisation or a PCI attestation — those are
issued by an independent assessor.



## Archives and Permanent Records

| Platform | Identifier | Volume |
|---|---|---|
| Harvard Dataverse | DOI 10.7910/DVN/YMJKOG | 145 citable datasets |
| AIOSS verification kit | DOI 10.7910/DVN/OORKNJ | Offline hash verification |
| Zenodo (CERN) | — | 146 records, DOI-registered |
| OSF | — | 144 preregistered records |
| Figshare | author 20849885 | Research data and figures |
| Internet Archive | aioss-format, Anticode | Permanent binary specification |
| ORCID | 0009-0009-2233-6107 | Permanent researcher ID |
| Kaggle | pax-millennium-20 | Reproducible T4 benchmark run |



## Press and Independent Publication

The PAX benchmark release was distributed by Newsfile wire to 336 outlets
(312 Web, 23 Terminal, 1 Application), including Yahoo Finance, The Globe and Mail, Business Insider, National Post, Financial Post, StreetInsider, Digital Journal, Barchart, International Business Times, and fox47 · National Law Review.
Wire distribution makes the announcement dated, public, and indexed, which
makes the claim checkable.