recapi 0.4.9__tar.gz → 0.4.11__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {recapi-0.4.9 → recapi-0.4.11}/PKG-INFO +58 -14
- recapi-0.4.9/recapi.egg-info/PKG-INFO → recapi-0.4.11/README.md +44 -23
- {recapi-0.4.9 → recapi-0.4.11}/pyproject.toml +13 -1
- {recapi-0.4.9 → recapi-0.4.11}/recapi/async_client.py +9 -2
- {recapi-0.4.9 → recapi-0.4.11}/recapi/client.py +158 -51
- recapi-0.4.11/recapi/py.typed +0 -0
- recapi-0.4.9/README.md → recapi-0.4.11/recapi.egg-info/PKG-INFO +67 -13
- {recapi-0.4.9 → recapi-0.4.11}/recapi.egg-info/SOURCES.txt +1 -0
- {recapi-0.4.9 → recapi-0.4.11}/tests/test_async_client.py +14 -1
- {recapi-0.4.9 → recapi-0.4.11}/tests/test_client_vectors.py +46 -1
- {recapi-0.4.9 → recapi-0.4.11}/LICENSE +0 -0
- {recapi-0.4.9 → recapi-0.4.11}/recapi/__init__.py +0 -0
- {recapi-0.4.9 → recapi-0.4.11}/recapi/history.py +0 -0
- {recapi-0.4.9 → recapi-0.4.11}/recapi.egg-info/dependency_links.txt +0 -0
- {recapi-0.4.9 → recapi-0.4.11}/recapi.egg-info/top_level.txt +0 -0
- {recapi-0.4.9 → recapi-0.4.11}/setup.cfg +0 -0
- {recapi-0.4.9 → recapi-0.4.11}/tests/test_client.py +0 -0
- {recapi-0.4.9 → recapi-0.4.11}/tests/test_history.py +0 -0
- {recapi-0.4.9 → recapi-0.4.11}/tests/test_stores.py +0 -0
|
@@ -1,8 +1,21 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: recapi
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.11
|
|
4
4
|
Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
|
|
5
5
|
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://recapi.io
|
|
7
|
+
Project-URL: Documentation, https://recapi.io/docs
|
|
8
|
+
Project-URL: Issues, https://recapi.io/contact
|
|
9
|
+
Keywords: recommendations,recommender,personalization,ecommerce,api-client
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
18
|
+
Classifier: Typing :: Typed
|
|
6
19
|
Requires-Python: >=3.11
|
|
7
20
|
Description-Content-Type: text/markdown
|
|
8
21
|
License-File: LICENSE
|
|
@@ -31,16 +44,15 @@ The library is on PyPI, with no dependencies: install it with pip, or add
|
|
|
31
44
|
pip install recapi
|
|
32
45
|
```
|
|
33
46
|
|
|
34
|
-
Production releases publish each version there
|
|
35
|
-
([docs/deployment.md](../../docs/deployment.md#publishing-the-libraries)).
|
|
47
|
+
Production releases publish each version there.
|
|
36
48
|
Your recapi API serves the same library, for servers that can't reach PyPI
|
|
37
49
|
(the dashboard's quick start shows the line with your API's address):
|
|
38
50
|
|
|
39
51
|
```sh
|
|
40
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
52
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.11-py3-none-any.whl
|
|
41
53
|
```
|
|
42
54
|
|
|
43
|
-
To work on the library itself, install it from a checkout of
|
|
55
|
+
To work on the library itself, install it from a checkout of recapi's repository
|
|
44
56
|
(`pip install ./sdk/python`).
|
|
45
57
|
|
|
46
58
|
## Quick start
|
|
@@ -65,8 +77,9 @@ client.track("item-42", "view", user_id="user-881")
|
|
|
65
77
|
# reached, this returns popular items instead (result.fallback is True), and an
|
|
66
78
|
# empty list if those fail too or the key is refused (hide the slot): no
|
|
67
79
|
# try/except.
|
|
68
|
-
# item.why says why it is listed, safe to show anyone
|
|
69
|
-
# codes
|
|
80
|
+
# item.why says why it is listed, safe to show anyone
|
|
81
|
+
# (https://recapi.io/docs/api#reason-codes): pick your own words, no label for
|
|
82
|
+
# codes you don't map.
|
|
70
83
|
LABELS = {
|
|
71
84
|
"for_you": "Picked for you",
|
|
72
85
|
"similar": "Similar items",
|
|
@@ -87,7 +100,7 @@ for item in result.items:
|
|
|
87
100
|
client.track("item-77", "view", user_id="user-881")
|
|
88
101
|
```
|
|
89
102
|
|
|
90
|
-
Levels follow the [recommended scale](
|
|
103
|
+
Levels follow the [recommended scale](https://recapi.io/docs/api#interaction-levels):
|
|
91
104
|
`"view"` (3), `"cart"` (5), `"purchase"` (10), or any integer from -10 to 10
|
|
92
105
|
(`track("article-9", 5, …)` for an article read to the end); 0 is an
|
|
93
106
|
impression. `"reject"` (-10) is an explicit "not interested": the item is never
|
|
@@ -99,6 +112,23 @@ itself: recapi stores the `anon_id` and the dashboard shows it. Call
|
|
|
99
112
|
items they were shown become the user's, so what they did before logging in
|
|
100
113
|
keeps counting.
|
|
101
114
|
|
|
115
|
+
### Several rows in one call
|
|
116
|
+
|
|
117
|
+
A page with several rows (similar items, then "for you") asks for them in one
|
|
118
|
+
call: the history is sent once and the call is billed as one recommendation.
|
|
119
|
+
You get one `Recommendations` per list, in order; a list holds none of the
|
|
120
|
+
items of the lists before it unless `allow_repeats=True`.
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
similar, for_you = client.recommend_lists(
|
|
124
|
+
[
|
|
125
|
+
{"placement": "product", "count": 4, "context_item_id": "item-42"},
|
|
126
|
+
{"placement": "for_you", "count": 8},
|
|
127
|
+
],
|
|
128
|
+
user_id="user-881",
|
|
129
|
+
)
|
|
130
|
+
```
|
|
131
|
+
|
|
102
132
|
## Where the history lives
|
|
103
133
|
|
|
104
134
|
By default each process keeps its users' state in memory (the 10,000 most
|
|
@@ -208,9 +238,10 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
208
238
|
| Method | What it does |
|
|
209
239
|
|---|---|
|
|
210
240
|
| `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. Raises `ValueError` for an invalid level or user, visitor or recommendation id. An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; `None` or no string at all too) drops the event with a log line: no exception, and the other events are sent as usual |
|
|
211
|
-
| `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](
|
|
241
|
+
| `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](https://recapi.io/docs/api#item-metadata)), None when it has none; `why` its [reason code](https://recapi.io/docs/api#reason-codes). The user's rejected items are added to `exclude`. At most 1.5 s; on a network error, timeout, 5xx or 429 it returns popular items (`fallback` True, no id), or no item when those fail too; on a 401 or 403 no item at once. A `context_item_id` the API would refuse (no string at all too) isn't sent: you get the same popular list and a log line, with no recommendation request. Any other failure (a bad request, a reply that isn't the API's) raises |
|
|
242
|
+
| `recommend_lists(lists, *, user_id=None, anon_id=None, exclude=None, allow_repeats=False)` | One `Recommendations` per list, in order, from one call billed as one recommendation. Each list is a dict of `recommend`'s list keywords (`placement`, `count`, `tags_any`, `tags_all`, `exclude`, `context_item_id`, `discovery`); `exclude` applies to every list. A list holds none of the items of the lists before it unless `allow_repeats`. Fails and falls back as `recommend` does, popular items asked list by list |
|
|
212
243
|
| `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user. On a network error, timeout, 5xx, 429, 401 or 403: an empty list and a log line. Other failures as in `recommend` |
|
|
213
|
-
| `upsert_items(items, *, merge=False)` | Creates or replaces items (dicts with the [item fields](
|
|
244
|
+
| `upsert_items(items, *, merge=False)` | Creates or replaces items (dicts with the [item fields](https://recapi.io/docs/api#put-v1itemsitem_id--secret-key)), 1,000 per request, with retries. Returns how many were stored. With `merge=True` only the fields an item has are sent and changed, the others keep their stored values (a tags-only sync keeps titles and metadata); to clear a field, replace the item or set it to `None`, which resets it to its default. Metadata merges key by key: the keys sent are set, the others kept, a key set to `None` is removed (`"metadata": {"old_price": None}`) and `"metadata": None` removes them all. A bad item doesn't keep the others out: once all are sent, `recapi.RejectedItemsError` (a `RecapiError`, code `invalid_request`) lists them in `rejected` as `(index, error)` pairs, with the count stored in `upserted` |
|
|
214
245
|
| `identify(anon_id, user_id)` | At login: merges the visitor's history and shown items into the user's, then deletes the visitor's entry. The user's first restore from recapi then leaves that visitor's browsing out, so it doesn't count twice |
|
|
215
246
|
| `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
|
|
216
247
|
| `flush()` / `close()` | Send queued events now; `close()` also stops the background sender |
|
|
@@ -235,6 +266,20 @@ alone. Each logs one warning, which never quotes the id. An empty or `None`
|
|
|
235
266
|
Background failures go to the `recapi` logger: refused events are dropped, a
|
|
236
267
|
batch that can succeed later is retried with backoff (up to 10,000 queued).
|
|
237
268
|
|
|
269
|
+
## Errors and troubleshooting
|
|
270
|
+
|
|
271
|
+
`recommend` never raises for an outage: it returns popular items, or an empty
|
|
272
|
+
list on a 401 or 403, and logs one warning to the `recapi` logger. A bad
|
|
273
|
+
request or a reply that isn't the API's raises `recapi.RecapiError` (`code`,
|
|
274
|
+
`status`, `retryable`); `upsert_items` raises `recapi.RejectedItemsError` for
|
|
275
|
+
the items the API refused.
|
|
276
|
+
|
|
277
|
+
- [Errors](https://recapi.io/docs/errors): each error code, its cause and fix.
|
|
278
|
+
- [Troubleshooting](https://recapi.io/docs/troubleshooting): no lists yet,
|
|
279
|
+
empty lists, only popular items, key errors.
|
|
280
|
+
|
|
281
|
+
## Development
|
|
282
|
+
|
|
238
283
|
The API builds the wheel from `recapi/*.py` and `pyproject.toml`, and pip
|
|
239
284
|
caches its URL for a year: a change there needs a new `version` in
|
|
240
285
|
`pyproject.toml` and `__version__` in `recapi/client.py`, and a new entry in
|
|
@@ -242,7 +287,6 @@ caches its URL for a year: a change there needs a new `version` in
|
|
|
242
287
|
An older version's URL then installs the new one, so the library's public
|
|
243
288
|
methods and their arguments only grow.
|
|
244
289
|
|
|
245
|
-
Tests: `cd sdk/python && python3 -m
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
HTTP server.
|
|
290
|
+
Tests, from a checkout of recapi's repository: `cd sdk/python && python3 -m
|
|
291
|
+
unittest discover -s tests`. They run recapi's shared test vectors (history
|
|
292
|
+
and client behaviour) against a local HTTP server.
|
|
@@ -1,13 +1,3 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: recapi
|
|
3
|
-
Version: 0.4.9
|
|
4
|
-
Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
|
|
5
|
-
License: MIT
|
|
6
|
-
Requires-Python: >=3.11
|
|
7
|
-
Description-Content-Type: text/markdown
|
|
8
|
-
License-File: LICENSE
|
|
9
|
-
Dynamic: license-file
|
|
10
|
-
|
|
11
1
|
# recapi for Python
|
|
12
2
|
|
|
13
3
|
Python client for the recapi recommendation API, for servers: Django,
|
|
@@ -31,16 +21,15 @@ The library is on PyPI, with no dependencies: install it with pip, or add
|
|
|
31
21
|
pip install recapi
|
|
32
22
|
```
|
|
33
23
|
|
|
34
|
-
Production releases publish each version there
|
|
35
|
-
([docs/deployment.md](../../docs/deployment.md#publishing-the-libraries)).
|
|
24
|
+
Production releases publish each version there.
|
|
36
25
|
Your recapi API serves the same library, for servers that can't reach PyPI
|
|
37
26
|
(the dashboard's quick start shows the line with your API's address):
|
|
38
27
|
|
|
39
28
|
```sh
|
|
40
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
29
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.11-py3-none-any.whl
|
|
41
30
|
```
|
|
42
31
|
|
|
43
|
-
To work on the library itself, install it from a checkout of
|
|
32
|
+
To work on the library itself, install it from a checkout of recapi's repository
|
|
44
33
|
(`pip install ./sdk/python`).
|
|
45
34
|
|
|
46
35
|
## Quick start
|
|
@@ -65,8 +54,9 @@ client.track("item-42", "view", user_id="user-881")
|
|
|
65
54
|
# reached, this returns popular items instead (result.fallback is True), and an
|
|
66
55
|
# empty list if those fail too or the key is refused (hide the slot): no
|
|
67
56
|
# try/except.
|
|
68
|
-
# item.why says why it is listed, safe to show anyone
|
|
69
|
-
# codes
|
|
57
|
+
# item.why says why it is listed, safe to show anyone
|
|
58
|
+
# (https://recapi.io/docs/api#reason-codes): pick your own words, no label for
|
|
59
|
+
# codes you don't map.
|
|
70
60
|
LABELS = {
|
|
71
61
|
"for_you": "Picked for you",
|
|
72
62
|
"similar": "Similar items",
|
|
@@ -87,7 +77,7 @@ for item in result.items:
|
|
|
87
77
|
client.track("item-77", "view", user_id="user-881")
|
|
88
78
|
```
|
|
89
79
|
|
|
90
|
-
Levels follow the [recommended scale](
|
|
80
|
+
Levels follow the [recommended scale](https://recapi.io/docs/api#interaction-levels):
|
|
91
81
|
`"view"` (3), `"cart"` (5), `"purchase"` (10), or any integer from -10 to 10
|
|
92
82
|
(`track("article-9", 5, …)` for an article read to the end); 0 is an
|
|
93
83
|
impression. `"reject"` (-10) is an explicit "not interested": the item is never
|
|
@@ -99,6 +89,23 @@ itself: recapi stores the `anon_id` and the dashboard shows it. Call
|
|
|
99
89
|
items they were shown become the user's, so what they did before logging in
|
|
100
90
|
keeps counting.
|
|
101
91
|
|
|
92
|
+
### Several rows in one call
|
|
93
|
+
|
|
94
|
+
A page with several rows (similar items, then "for you") asks for them in one
|
|
95
|
+
call: the history is sent once and the call is billed as one recommendation.
|
|
96
|
+
You get one `Recommendations` per list, in order; a list holds none of the
|
|
97
|
+
items of the lists before it unless `allow_repeats=True`.
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
similar, for_you = client.recommend_lists(
|
|
101
|
+
[
|
|
102
|
+
{"placement": "product", "count": 4, "context_item_id": "item-42"},
|
|
103
|
+
{"placement": "for_you", "count": 8},
|
|
104
|
+
],
|
|
105
|
+
user_id="user-881",
|
|
106
|
+
)
|
|
107
|
+
```
|
|
108
|
+
|
|
102
109
|
## Where the history lives
|
|
103
110
|
|
|
104
111
|
By default each process keeps its users' state in memory (the 10,000 most
|
|
@@ -208,9 +215,10 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
208
215
|
| Method | What it does |
|
|
209
216
|
|---|---|
|
|
210
217
|
| `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. Raises `ValueError` for an invalid level or user, visitor or recommendation id. An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; `None` or no string at all too) drops the event with a log line: no exception, and the other events are sent as usual |
|
|
211
|
-
| `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](
|
|
218
|
+
| `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](https://recapi.io/docs/api#item-metadata)), None when it has none; `why` its [reason code](https://recapi.io/docs/api#reason-codes). The user's rejected items are added to `exclude`. At most 1.5 s; on a network error, timeout, 5xx or 429 it returns popular items (`fallback` True, no id), or no item when those fail too; on a 401 or 403 no item at once. A `context_item_id` the API would refuse (no string at all too) isn't sent: you get the same popular list and a log line, with no recommendation request. Any other failure (a bad request, a reply that isn't the API's) raises |
|
|
219
|
+
| `recommend_lists(lists, *, user_id=None, anon_id=None, exclude=None, allow_repeats=False)` | One `Recommendations` per list, in order, from one call billed as one recommendation. Each list is a dict of `recommend`'s list keywords (`placement`, `count`, `tags_any`, `tags_all`, `exclude`, `context_item_id`, `discovery`); `exclude` applies to every list. A list holds none of the items of the lists before it unless `allow_repeats`. Fails and falls back as `recommend` does, popular items asked list by list |
|
|
212
220
|
| `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user. On a network error, timeout, 5xx, 429, 401 or 403: an empty list and a log line. Other failures as in `recommend` |
|
|
213
|
-
| `upsert_items(items, *, merge=False)` | Creates or replaces items (dicts with the [item fields](
|
|
221
|
+
| `upsert_items(items, *, merge=False)` | Creates or replaces items (dicts with the [item fields](https://recapi.io/docs/api#put-v1itemsitem_id--secret-key)), 1,000 per request, with retries. Returns how many were stored. With `merge=True` only the fields an item has are sent and changed, the others keep their stored values (a tags-only sync keeps titles and metadata); to clear a field, replace the item or set it to `None`, which resets it to its default. Metadata merges key by key: the keys sent are set, the others kept, a key set to `None` is removed (`"metadata": {"old_price": None}`) and `"metadata": None` removes them all. A bad item doesn't keep the others out: once all are sent, `recapi.RejectedItemsError` (a `RecapiError`, code `invalid_request`) lists them in `rejected` as `(index, error)` pairs, with the count stored in `upserted` |
|
|
214
222
|
| `identify(anon_id, user_id)` | At login: merges the visitor's history and shown items into the user's, then deletes the visitor's entry. The user's first restore from recapi then leaves that visitor's browsing out, so it doesn't count twice |
|
|
215
223
|
| `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
|
|
216
224
|
| `flush()` / `close()` | Send queued events now; `close()` also stops the background sender |
|
|
@@ -235,6 +243,20 @@ alone. Each logs one warning, which never quotes the id. An empty or `None`
|
|
|
235
243
|
Background failures go to the `recapi` logger: refused events are dropped, a
|
|
236
244
|
batch that can succeed later is retried with backoff (up to 10,000 queued).
|
|
237
245
|
|
|
246
|
+
## Errors and troubleshooting
|
|
247
|
+
|
|
248
|
+
`recommend` never raises for an outage: it returns popular items, or an empty
|
|
249
|
+
list on a 401 or 403, and logs one warning to the `recapi` logger. A bad
|
|
250
|
+
request or a reply that isn't the API's raises `recapi.RecapiError` (`code`,
|
|
251
|
+
`status`, `retryable`); `upsert_items` raises `recapi.RejectedItemsError` for
|
|
252
|
+
the items the API refused.
|
|
253
|
+
|
|
254
|
+
- [Errors](https://recapi.io/docs/errors): each error code, its cause and fix.
|
|
255
|
+
- [Troubleshooting](https://recapi.io/docs/troubleshooting): no lists yet,
|
|
256
|
+
empty lists, only popular items, key errors.
|
|
257
|
+
|
|
258
|
+
## Development
|
|
259
|
+
|
|
238
260
|
The API builds the wheel from `recapi/*.py` and `pyproject.toml`, and pip
|
|
239
261
|
caches its URL for a year: a change there needs a new `version` in
|
|
240
262
|
`pyproject.toml` and `__version__` in `recapi/client.py`, and a new entry in
|
|
@@ -242,7 +264,6 @@ caches its URL for a year: a change there needs a new `version` in
|
|
|
242
264
|
An older version's URL then installs the new one, so the library's public
|
|
243
265
|
methods and their arguments only grow.
|
|
244
266
|
|
|
245
|
-
Tests: `cd sdk/python && python3 -m
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
HTTP server.
|
|
267
|
+
Tests, from a checkout of recapi's repository: `cd sdk/python && python3 -m
|
|
268
|
+
unittest discover -s tests`. They run recapi's shared test vectors (history
|
|
269
|
+
and client behaviour) against a local HTTP server.
|
|
@@ -4,16 +4,28 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "recapi"
|
|
7
|
-
version = "0.4.
|
|
7
|
+
version = "0.4.11"
|
|
8
8
|
description = "Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
11
11
|
dependencies = []
|
|
12
12
|
license = { text = "MIT" }
|
|
13
|
+
keywords = ["recommendations", "recommender", "personalization", "ecommerce", "api-client"]
|
|
14
|
+
# One line each: the API builds its wheel with a line-by-line read of this table.
|
|
15
|
+
classifiers = ["Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Topic :: Internet :: WWW/HTTP", "Typing :: Typed"]
|
|
16
|
+
|
|
17
|
+
[project.urls]
|
|
18
|
+
Homepage = "https://recapi.io"
|
|
19
|
+
Documentation = "https://recapi.io/docs"
|
|
20
|
+
Issues = "https://recapi.io/contact"
|
|
13
21
|
|
|
14
22
|
[tool.setuptools]
|
|
15
23
|
packages = ["recapi"]
|
|
16
24
|
|
|
25
|
+
# py.typed tells mypy and pyright that the package carries its own types.
|
|
26
|
+
[tool.setuptools.package-data]
|
|
27
|
+
recapi = ["py.typed"]
|
|
28
|
+
|
|
17
29
|
[tool.ruff]
|
|
18
30
|
line-length = 100
|
|
19
31
|
target-version = "py311"
|
|
@@ -47,9 +47,16 @@ class AsyncClient:
|
|
|
47
47
|
|
|
48
48
|
async def recommend(self, **params: Any) -> Recommendations:
|
|
49
49
|
"""Personalised recommendations: :meth:`Client.recommend`, same keywords."""
|
|
50
|
+
return await self._within_deadline(self._client._recommend, **params)
|
|
51
|
+
|
|
52
|
+
async def recommend_lists(self, lists: Any, **params: Any) -> list[Recommendations]:
|
|
53
|
+
"""Several lists in one call: :meth:`Client.recommend_lists`, same arguments."""
|
|
54
|
+
return await self._within_deadline(self._client._recommend_lists, lists, **params)
|
|
55
|
+
|
|
56
|
+
async def _within_deadline(self, fn: Any, *args: Any, **params: Any) -> Any:
|
|
50
57
|
client = self._client
|
|
51
58
|
deadline = time.monotonic() + client._recommend_timeout
|
|
52
|
-
job = self._pool.submit(
|
|
59
|
+
job = self._pool.submit(fn, deadline, *args, **params)
|
|
53
60
|
result = asyncio.wrap_future(job)
|
|
54
61
|
try:
|
|
55
62
|
return await asyncio.wait_for(asyncio.shield(result), client._recommend_timeout)
|
|
@@ -61,7 +68,7 @@ class AsyncClient:
|
|
|
61
68
|
raise
|
|
62
69
|
# Every thread was still busy at the deadline: don't wait for one to
|
|
63
70
|
# serve the fallback. Past its deadline, the call asks only for popular items.
|
|
64
|
-
return await asyncio.to_thread(
|
|
71
|
+
return await asyncio.to_thread(fn, deadline, *args, **params)
|
|
65
72
|
|
|
66
73
|
async def track(self, item_id: str, level: int | str, **ids: str | None) -> None:
|
|
67
74
|
"""Record an interaction: :meth:`Client.track`."""
|
|
@@ -29,7 +29,7 @@ from typing import Any, Protocol
|
|
|
29
29
|
|
|
30
30
|
from .history import History, is_id
|
|
31
31
|
|
|
32
|
-
__version__ = "0.4.
|
|
32
|
+
__version__ = "0.4.11"
|
|
33
33
|
|
|
34
34
|
log = logging.getLogger("recapi")
|
|
35
35
|
Tags = Sequence[str] | None
|
|
@@ -196,6 +196,31 @@ class Recommendations:
|
|
|
196
196
|
items: list[Item]
|
|
197
197
|
|
|
198
198
|
|
|
199
|
+
@dataclass
|
|
200
|
+
class _Row:
|
|
201
|
+
"""One list of a call: recommend()'s own, or a row of recommend_lists()."""
|
|
202
|
+
|
|
203
|
+
placement: str | None = None
|
|
204
|
+
count: int = 0
|
|
205
|
+
tags_any: Tags = None
|
|
206
|
+
tags_all: Tags = None
|
|
207
|
+
exclude: Tags = None
|
|
208
|
+
context_item_id: str | None = None
|
|
209
|
+
discovery: float | None = None
|
|
210
|
+
|
|
211
|
+
def fields(self, exclude: list[str] | None) -> dict[str, Any]:
|
|
212
|
+
"""Return the row's request fields, None where unset."""
|
|
213
|
+
return {
|
|
214
|
+
"placement": self.placement,
|
|
215
|
+
"count": self.count or None,
|
|
216
|
+
"tags_any": _list(self.tags_any),
|
|
217
|
+
"tags_all": _list(self.tags_all),
|
|
218
|
+
"exclude": exclude,
|
|
219
|
+
"context_item_id": self.context_item_id,
|
|
220
|
+
"discovery": self.discovery,
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
|
|
199
224
|
class Store(Protocol):
|
|
200
225
|
"""Where per-user state lives: a Redis client, Django's cache, memcached...
|
|
201
226
|
|
|
@@ -648,6 +673,34 @@ class Client:
|
|
|
648
673
|
discovery=discovery,
|
|
649
674
|
)
|
|
650
675
|
|
|
676
|
+
def recommend_lists(
|
|
677
|
+
self,
|
|
678
|
+
lists: Sequence[Mapping[str, Any]],
|
|
679
|
+
*,
|
|
680
|
+
user_id: str | None = None,
|
|
681
|
+
anon_id: str | None = None,
|
|
682
|
+
exclude: Tags = None,
|
|
683
|
+
allow_repeats: bool = False,
|
|
684
|
+
) -> list[Recommendations]:
|
|
685
|
+
"""One list per entry of ``lists``, in order, from one call.
|
|
686
|
+
|
|
687
|
+
Each entry takes recommend()'s keywords for a list: ``placement``,
|
|
688
|
+
``count``, ``tags_any``, ``tags_all``, ``exclude`` (that list's own),
|
|
689
|
+
``context_item_id`` and ``discovery``. A page's rows send the history
|
|
690
|
+
once and are billed as one recommendation. A list holds none of the
|
|
691
|
+
items of the lists before it unless ``allow_repeats``. It fails and
|
|
692
|
+
falls back as recommend() does: each list then holds popular items,
|
|
693
|
+
asked list by list, and once popular fails the lists after it are empty.
|
|
694
|
+
"""
|
|
695
|
+
return self._recommend_lists(
|
|
696
|
+
time.monotonic() + self._recommend_timeout,
|
|
697
|
+
lists,
|
|
698
|
+
user_id=user_id,
|
|
699
|
+
anon_id=anon_id,
|
|
700
|
+
exclude=exclude,
|
|
701
|
+
allow_repeats=allow_repeats,
|
|
702
|
+
)
|
|
703
|
+
|
|
651
704
|
@property
|
|
652
705
|
def _recommend_timeout(self) -> float:
|
|
653
706
|
return min(self._timeout, RECOMMEND_TIMEOUT)
|
|
@@ -658,33 +711,69 @@ class Client:
|
|
|
658
711
|
*,
|
|
659
712
|
user_id: str | None = None,
|
|
660
713
|
anon_id: str | None = None,
|
|
661
|
-
count: int = 0,
|
|
662
|
-
placement: str | None = None,
|
|
663
|
-
tags_any: Tags = None,
|
|
664
|
-
tags_all: Tags = None,
|
|
665
714
|
exclude: Tags = None,
|
|
666
|
-
|
|
667
|
-
discovery: float | None = None,
|
|
715
|
+
**row: Any,
|
|
668
716
|
) -> Recommendations:
|
|
669
717
|
"""recommend() with its deadline as a ``time.monotonic()`` instant.
|
|
670
718
|
|
|
671
719
|
AsyncClient sets it at the ``await``: a call that waited for a thread
|
|
672
720
|
past it goes straight to the fallback.
|
|
673
721
|
"""
|
|
722
|
+
rows = [_Row(**row)]
|
|
723
|
+
return self._recommend_rows(
|
|
724
|
+
deadline, rows, user_id=user_id, anon_id=anon_id, shared=exclude
|
|
725
|
+
)[0]
|
|
726
|
+
|
|
727
|
+
def _recommend_lists(
|
|
728
|
+
self,
|
|
729
|
+
deadline: float,
|
|
730
|
+
lists: Sequence[Mapping[str, Any]],
|
|
731
|
+
*,
|
|
732
|
+
user_id: str | None = None,
|
|
733
|
+
anon_id: str | None = None,
|
|
734
|
+
exclude: Tags = None,
|
|
735
|
+
allow_repeats: bool = False,
|
|
736
|
+
) -> list[Recommendations]:
|
|
737
|
+
"""recommend_lists() with its deadline, as _recommend()."""
|
|
738
|
+
if not lists:
|
|
739
|
+
raise ValueError("at least one list is required")
|
|
740
|
+
rows = [_Row(**row) for row in lists]
|
|
741
|
+
return self._recommend_rows(
|
|
742
|
+
deadline,
|
|
743
|
+
rows,
|
|
744
|
+
user_id=user_id,
|
|
745
|
+
anon_id=anon_id,
|
|
746
|
+
shared=exclude,
|
|
747
|
+
repeats=allow_repeats,
|
|
748
|
+
several=True,
|
|
749
|
+
)
|
|
750
|
+
|
|
751
|
+
def _recommend_rows(
|
|
752
|
+
self,
|
|
753
|
+
deadline: float,
|
|
754
|
+
rows: list[_Row],
|
|
755
|
+
*,
|
|
756
|
+
user_id: str | None,
|
|
757
|
+
anon_id: str | None,
|
|
758
|
+
shared: Tags,
|
|
759
|
+
repeats: bool = False,
|
|
760
|
+
several: bool = False,
|
|
761
|
+
) -> list[Recommendations]:
|
|
762
|
+
"""Serve recommend() (one row) and recommend_lists(): ``shared`` is the call's exclude."""
|
|
674
763
|
key = self._key(user_id, anon_id)
|
|
675
764
|
t = _now_ms()
|
|
676
765
|
state = self._load(key) if key is not None else _UserState()
|
|
677
|
-
if not _usable_context(context_item_id)
|
|
766
|
+
unusable = next((r for r in rows if not _usable_context(r.context_item_id)), None)
|
|
767
|
+
if unusable is not None:
|
|
678
768
|
_, _, rejected = state.history.wire(t)
|
|
679
769
|
# The message never quotes the id: a visitor may have written it.
|
|
680
770
|
# No id goes on to the fallback: no item can have this one.
|
|
771
|
+
unusable.context_item_id = None
|
|
681
772
|
cause = RecapiError(
|
|
682
773
|
"invalid_request",
|
|
683
774
|
"context_item_id must be 1-256 bytes of UTF-8 without control characters",
|
|
684
775
|
)
|
|
685
|
-
return self.
|
|
686
|
-
cause, rejected, count=count, tags_any=tags_any, tags_all=tags_all, exclude=exclude
|
|
687
|
-
)
|
|
776
|
+
return self._fallbacks(cause, rows, _with_rejected(shared, rejected), repeats)
|
|
688
777
|
if (
|
|
689
778
|
user_id
|
|
690
779
|
and not state.restored
|
|
@@ -693,6 +782,15 @@ class Client:
|
|
|
693
782
|
):
|
|
694
783
|
state = self._restore(key, user_id, state, deadline, t)
|
|
695
784
|
history, recent, rejected = state.history.wire(t)
|
|
785
|
+
exclude = _with_rejected(shared, rejected)
|
|
786
|
+
if several:
|
|
787
|
+
fields = {
|
|
788
|
+
"placements": [_compact(r.fields(_with_rejected(r.exclude, []))) for r in rows],
|
|
789
|
+
"exclude": exclude,
|
|
790
|
+
"allow_repeats": repeats or None,
|
|
791
|
+
}
|
|
792
|
+
else:
|
|
793
|
+
fields = rows[0].fields(exclude)
|
|
696
794
|
try:
|
|
697
795
|
response = self._request(
|
|
698
796
|
"POST",
|
|
@@ -702,38 +800,33 @@ class Client:
|
|
|
702
800
|
{
|
|
703
801
|
"user_id": user_id,
|
|
704
802
|
"anon_id": anon_id,
|
|
705
|
-
|
|
706
|
-
"count": count or None,
|
|
707
|
-
"tags_any": _list(tags_any),
|
|
708
|
-
"tags_all": _list(tags_all),
|
|
709
|
-
"exclude": _with_rejected(exclude, rejected),
|
|
710
|
-
"context_item_id": context_item_id,
|
|
803
|
+
**fields,
|
|
711
804
|
"history": history,
|
|
712
805
|
"recent": recent,
|
|
713
|
-
"discovery": discovery,
|
|
714
806
|
}
|
|
715
807
|
),
|
|
716
808
|
)
|
|
717
|
-
|
|
809
|
+
replies = (
|
|
810
|
+
response.get("lists") if several and isinstance(response, dict) else [response]
|
|
811
|
+
)
|
|
812
|
+
if not isinstance(replies, list) or len(replies) != len(rows):
|
|
813
|
+
raise RecapiError("invalid_response", "malformed recommendations response")
|
|
814
|
+
lists = [
|
|
815
|
+
Recommendations(i, False, items)
|
|
816
|
+
for i, items in map(_parse_recommendations, replies)
|
|
817
|
+
]
|
|
718
818
|
except RecapiError as error:
|
|
719
819
|
if not error._spare_the_page:
|
|
720
820
|
raise
|
|
721
|
-
return self.
|
|
722
|
-
error,
|
|
723
|
-
rejected,
|
|
724
|
-
count=count,
|
|
725
|
-
tags_any=tags_any,
|
|
726
|
-
tags_all=tags_all,
|
|
727
|
-
exclude=exclude,
|
|
728
|
-
context_item_id=context_item_id,
|
|
729
|
-
)
|
|
821
|
+
return self._fallbacks(error, rows, exclude, repeats)
|
|
730
822
|
|
|
731
823
|
if key is not None:
|
|
732
824
|
with self._lock_for(key):
|
|
733
825
|
state = self._load(key)
|
|
734
|
-
for
|
|
735
|
-
|
|
736
|
-
|
|
826
|
+
for result in lists:
|
|
827
|
+
for item in result.items:
|
|
828
|
+
state.shown.pop(item.item_id, None)
|
|
829
|
+
state.shown[item.item_id] = [result.recommendation_id, t]
|
|
737
830
|
while len(state.shown) > MAX_SHOWN_ITEMS:
|
|
738
831
|
del state.shown[next(iter(state.shown))]
|
|
739
832
|
# Only trusted when we sent nothing; merged, never replacing
|
|
@@ -745,34 +838,48 @@ class Client:
|
|
|
745
838
|
state.history = state.history.merge_snapshot(History.from_snapshot(snapshot), t)
|
|
746
839
|
state.restored = True
|
|
747
840
|
self._save(key, state, t)
|
|
748
|
-
return
|
|
841
|
+
return lists
|
|
842
|
+
|
|
843
|
+
def _fallbacks(
|
|
844
|
+
self, error: RecapiError, rows: list[_Row], shared: list[str] | None, repeats: bool
|
|
845
|
+
) -> list[Recommendations]:
|
|
846
|
+
"""Popular items for each row of a failed call, a popular call per row.
|
|
847
|
+
|
|
848
|
+
``shared`` (with the rejected items) and the row's own exclude are
|
|
849
|
+
skipped, and so, unless ``repeats``, are the items of the rows before
|
|
850
|
+
it. Once popular fails, the rows after it are empty without asking.
|
|
851
|
+
"""
|
|
852
|
+
out: list[Recommendations] = []
|
|
853
|
+
shown: list[str] = []
|
|
854
|
+
failed = False
|
|
855
|
+
for row in rows:
|
|
856
|
+
if failed:
|
|
857
|
+
out.append(Recommendations(None, True, []))
|
|
858
|
+
continue
|
|
859
|
+
skip = {*(shared or ()), *(row.exclude or ()), *shown}
|
|
860
|
+
result, failed = self._fallback(error, skip, row)
|
|
861
|
+
out.append(result)
|
|
862
|
+
if not repeats:
|
|
863
|
+
shown += [item.item_id for item in result.items]
|
|
864
|
+
return out
|
|
749
865
|
|
|
750
866
|
def _fallback(
|
|
751
|
-
self,
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
*,
|
|
755
|
-
count: int,
|
|
756
|
-
tags_any: Tags,
|
|
757
|
-
tags_all: Tags,
|
|
758
|
-
exclude: Tags,
|
|
759
|
-
context_item_id: str | None = None,
|
|
760
|
-
) -> Recommendations:
|
|
761
|
-
"""What recommend() answers instead of a list of its own: popular items, or none."""
|
|
867
|
+
self, error: RecapiError, skip: set[str], row: _Row
|
|
868
|
+
) -> tuple[Recommendations, bool]:
|
|
869
|
+
"""What a row answers instead of a list of its own: popular items, or none (True)."""
|
|
762
870
|
if error._key_refused:
|
|
763
871
|
log.warning(
|
|
764
872
|
"recapi: recommendations refused, served no items: %s: %s", error.code, error
|
|
765
873
|
)
|
|
766
|
-
return Recommendations(None, True, [])
|
|
874
|
+
return Recommendations(None, True, []), True
|
|
767
875
|
# The requested length without the excluded items, so a few more
|
|
768
876
|
# are asked for. 0 is the recommendations default; popular refuses it.
|
|
769
|
-
n = count or DEFAULT_COUNT
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
skip.add(context_item_id)
|
|
877
|
+
n = row.count or DEFAULT_COUNT
|
|
878
|
+
if row.context_item_id is not None:
|
|
879
|
+
skip.add(row.context_item_id)
|
|
773
880
|
try:
|
|
774
881
|
popular = self._popular(
|
|
775
|
-
min(n + len(skip), MAX_COUNT), tags_any, tags_all, self._recommend_timeout
|
|
882
|
+
min(n + len(skip), MAX_COUNT), row.tags_any, row.tags_all, self._recommend_timeout
|
|
776
883
|
)
|
|
777
884
|
except RecapiError as fallback_error:
|
|
778
885
|
# recapi is down or the limit covers popular too. The README
|
|
@@ -784,12 +891,12 @@ class Client:
|
|
|
784
891
|
error,
|
|
785
892
|
fallback_error,
|
|
786
893
|
)
|
|
787
|
-
return Recommendations(None, True, [])
|
|
894
|
+
return Recommendations(None, True, []), True
|
|
788
895
|
log.warning(
|
|
789
896
|
"recapi: recommendations failed, served popular items: %s: %s", error.code, error
|
|
790
897
|
)
|
|
791
898
|
items = [item for item in popular if item.item_id not in skip][:n]
|
|
792
|
-
return Recommendations(None, True, items)
|
|
899
|
+
return Recommendations(None, True, items), False
|
|
793
900
|
|
|
794
901
|
def _restore(
|
|
795
902
|
self, key: str, user_id: str, state: _UserState, deadline: float, t: int
|
|
File without changes
|
|
@@ -1,3 +1,26 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: recapi
|
|
3
|
+
Version: 0.4.11
|
|
4
|
+
Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://recapi.io
|
|
7
|
+
Project-URL: Documentation, https://recapi.io/docs
|
|
8
|
+
Project-URL: Issues, https://recapi.io/contact
|
|
9
|
+
Keywords: recommendations,recommender,personalization,ecommerce,api-client
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.11
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
1
24
|
# recapi for Python
|
|
2
25
|
|
|
3
26
|
Python client for the recapi recommendation API, for servers: Django,
|
|
@@ -21,16 +44,15 @@ The library is on PyPI, with no dependencies: install it with pip, or add
|
|
|
21
44
|
pip install recapi
|
|
22
45
|
```
|
|
23
46
|
|
|
24
|
-
Production releases publish each version there
|
|
25
|
-
([docs/deployment.md](../../docs/deployment.md#publishing-the-libraries)).
|
|
47
|
+
Production releases publish each version there.
|
|
26
48
|
Your recapi API serves the same library, for servers that can't reach PyPI
|
|
27
49
|
(the dashboard's quick start shows the line with your API's address):
|
|
28
50
|
|
|
29
51
|
```sh
|
|
30
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
52
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.11-py3-none-any.whl
|
|
31
53
|
```
|
|
32
54
|
|
|
33
|
-
To work on the library itself, install it from a checkout of
|
|
55
|
+
To work on the library itself, install it from a checkout of recapi's repository
|
|
34
56
|
(`pip install ./sdk/python`).
|
|
35
57
|
|
|
36
58
|
## Quick start
|
|
@@ -55,8 +77,9 @@ client.track("item-42", "view", user_id="user-881")
|
|
|
55
77
|
# reached, this returns popular items instead (result.fallback is True), and an
|
|
56
78
|
# empty list if those fail too or the key is refused (hide the slot): no
|
|
57
79
|
# try/except.
|
|
58
|
-
# item.why says why it is listed, safe to show anyone
|
|
59
|
-
# codes
|
|
80
|
+
# item.why says why it is listed, safe to show anyone
|
|
81
|
+
# (https://recapi.io/docs/api#reason-codes): pick your own words, no label for
|
|
82
|
+
# codes you don't map.
|
|
60
83
|
LABELS = {
|
|
61
84
|
"for_you": "Picked for you",
|
|
62
85
|
"similar": "Similar items",
|
|
@@ -77,7 +100,7 @@ for item in result.items:
|
|
|
77
100
|
client.track("item-77", "view", user_id="user-881")
|
|
78
101
|
```
|
|
79
102
|
|
|
80
|
-
Levels follow the [recommended scale](
|
|
103
|
+
Levels follow the [recommended scale](https://recapi.io/docs/api#interaction-levels):
|
|
81
104
|
`"view"` (3), `"cart"` (5), `"purchase"` (10), or any integer from -10 to 10
|
|
82
105
|
(`track("article-9", 5, …)` for an article read to the end); 0 is an
|
|
83
106
|
impression. `"reject"` (-10) is an explicit "not interested": the item is never
|
|
@@ -89,6 +112,23 @@ itself: recapi stores the `anon_id` and the dashboard shows it. Call
|
|
|
89
112
|
items they were shown become the user's, so what they did before logging in
|
|
90
113
|
keeps counting.
|
|
91
114
|
|
|
115
|
+
### Several rows in one call
|
|
116
|
+
|
|
117
|
+
A page with several rows (similar items, then "for you") asks for them in one
|
|
118
|
+
call: the history is sent once and the call is billed as one recommendation.
|
|
119
|
+
You get one `Recommendations` per list, in order; a list holds none of the
|
|
120
|
+
items of the lists before it unless `allow_repeats=True`.
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
similar, for_you = client.recommend_lists(
|
|
124
|
+
[
|
|
125
|
+
{"placement": "product", "count": 4, "context_item_id": "item-42"},
|
|
126
|
+
{"placement": "for_you", "count": 8},
|
|
127
|
+
],
|
|
128
|
+
user_id="user-881",
|
|
129
|
+
)
|
|
130
|
+
```
|
|
131
|
+
|
|
92
132
|
## Where the history lives
|
|
93
133
|
|
|
94
134
|
By default each process keeps its users' state in memory (the 10,000 most
|
|
@@ -198,9 +238,10 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
198
238
|
| Method | What it does |
|
|
199
239
|
|---|---|
|
|
200
240
|
| `track(item_id, level, *, user_id=None, anon_id=None, recommendation_id=None)` | Updates the user's history at once and queues the event. `recommendation_id` overrides the automatic attribution. Raises `ValueError` for an invalid level or user, visitor or recommendation id. An `item_id` the API would refuse (1-256 bytes of UTF-8, no control character; `None` or no string at all too) drops the event with a log line: no exception, and the other events are sent as usual |
|
|
201
|
-
| `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](
|
|
241
|
+
| `recommend(*, user_id=None, anon_id=None, count=0, placement=None, tags_any=None, tags_all=None, exclude=None, context_item_id=None, discovery=None)` | Returns `Recommendations(recommendation_id, fallback, items)`, each item `Item(item_id, score, slot, metadata, why)`. `metadata` is the dict stored with the item ([Item metadata](https://recapi.io/docs/api#item-metadata)), None when it has none; `why` its [reason code](https://recapi.io/docs/api#reason-codes). The user's rejected items are added to `exclude`. At most 1.5 s; on a network error, timeout, 5xx or 429 it returns popular items (`fallback` True, no id), or no item when those fail too; on a 401 or 403 no item at once. A `context_item_id` the API would refuse (no string at all too) isn't sent: you get the same popular list and a log line, with no recommendation request. Any other failure (a bad request, a reply that isn't the API's) raises |
|
|
242
|
+
| `recommend_lists(lists, *, user_id=None, anon_id=None, exclude=None, allow_repeats=False)` | One `Recommendations` per list, in order, from one call billed as one recommendation. Each list is a dict of `recommend`'s list keywords (`placement`, `count`, `tags_any`, `tags_all`, `exclude`, `context_item_id`, `discovery`); `exclude` applies to every list. A list holds none of the items of the lists before it unless `allow_repeats`. Fails and falls back as `recommend` does, popular items asked list by list |
|
|
202
243
|
| `popular(*, count=10, tags_any=None, tags_all=None)` | Popular items (`Item`, metadata and `why` included), for pages without a user. On a network error, timeout, 5xx, 429, 401 or 403: an empty list and a log line. Other failures as in `recommend` |
|
|
203
|
-
| `upsert_items(items, *, merge=False)` | Creates or replaces items (dicts with the [item fields](
|
|
244
|
+
| `upsert_items(items, *, merge=False)` | Creates or replaces items (dicts with the [item fields](https://recapi.io/docs/api#put-v1itemsitem_id--secret-key)), 1,000 per request, with retries. Returns how many were stored. With `merge=True` only the fields an item has are sent and changed, the others keep their stored values (a tags-only sync keeps titles and metadata); to clear a field, replace the item or set it to `None`, which resets it to its default. Metadata merges key by key: the keys sent are set, the others kept, a key set to `None` is removed (`"metadata": {"old_price": None}`) and `"metadata": None` removes them all. A bad item doesn't keep the others out: once all are sent, `recapi.RejectedItemsError` (a `RecapiError`, code `invalid_request`) lists them in `rejected` as `(index, error)` pairs, with the count stored in `upserted` |
|
|
204
245
|
| `identify(anon_id, user_id)` | At login: merges the visitor's history and shown items into the user's, then deletes the visitor's entry. The user's first restore from recapi then leaves that visitor's browsing out, so it doesn't count twice |
|
|
205
246
|
| `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
|
|
206
247
|
| `flush()` / `close()` | Send queued events now; `close()` also stops the background sender |
|
|
@@ -225,6 +266,20 @@ alone. Each logs one warning, which never quotes the id. An empty or `None`
|
|
|
225
266
|
Background failures go to the `recapi` logger: refused events are dropped, a
|
|
226
267
|
batch that can succeed later is retried with backoff (up to 10,000 queued).
|
|
227
268
|
|
|
269
|
+
## Errors and troubleshooting
|
|
270
|
+
|
|
271
|
+
`recommend` never raises for an outage: it returns popular items, or an empty
|
|
272
|
+
list on a 401 or 403, and logs one warning to the `recapi` logger. A bad
|
|
273
|
+
request or a reply that isn't the API's raises `recapi.RecapiError` (`code`,
|
|
274
|
+
`status`, `retryable`); `upsert_items` raises `recapi.RejectedItemsError` for
|
|
275
|
+
the items the API refused.
|
|
276
|
+
|
|
277
|
+
- [Errors](https://recapi.io/docs/errors): each error code, its cause and fix.
|
|
278
|
+
- [Troubleshooting](https://recapi.io/docs/troubleshooting): no lists yet,
|
|
279
|
+
empty lists, only popular items, key errors.
|
|
280
|
+
|
|
281
|
+
## Development
|
|
282
|
+
|
|
228
283
|
The API builds the wheel from `recapi/*.py` and `pyproject.toml`, and pip
|
|
229
284
|
caches its URL for a year: a change there needs a new `version` in
|
|
230
285
|
`pyproject.toml` and `__version__` in `recapi/client.py`, and a new entry in
|
|
@@ -232,7 +287,6 @@ caches its URL for a year: a change there needs a new `version` in
|
|
|
232
287
|
An older version's URL then installs the new one, so the library's public
|
|
233
288
|
methods and their arguments only grow.
|
|
234
289
|
|
|
235
|
-
Tests: `cd sdk/python && python3 -m
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
HTTP server.
|
|
290
|
+
Tests, from a checkout of recapi's repository: `cd sdk/python && python3 -m
|
|
291
|
+
unittest discover -s tests`. They run recapi's shared test vectors (history
|
|
292
|
+
and client behaviour) against a local HTTP server.
|
|
@@ -24,6 +24,17 @@ class AsyncClient(APITest):
|
|
|
24
24
|
self.addCleanup(lambda: asyncio.run(client.close()))
|
|
25
25
|
return client
|
|
26
26
|
|
|
27
|
+
def test_async_recommend_lists(self) -> None:
|
|
28
|
+
case = VECTORS["lists"]["cases"][0]
|
|
29
|
+
self.api.on("/v1/recommendations", Reply(200, case["reply"]))
|
|
30
|
+
client = self.async_client()
|
|
31
|
+
result = asyncio.run(
|
|
32
|
+
client.recommend_lists(case["lists"], anon_id="v", exclude=case["exclude"])
|
|
33
|
+
)
|
|
34
|
+
got = [[r.recommendation_id, [i.item_id for i in r.items]] for r in result]
|
|
35
|
+
self.assertEqual(got, case["expected"])
|
|
36
|
+
self.assertEqual(self.last_body("/v1/recommendations")["exclude"], case["exclude"])
|
|
37
|
+
|
|
27
38
|
def test_async_list_calls_keep_the_page_up(self) -> None:
|
|
28
39
|
client = self.async_client()
|
|
29
40
|
dead = recapi.AsyncClient(KEY, dead_url(), flush_interval=3600)
|
|
@@ -154,7 +165,9 @@ class AsyncClient(APITest):
|
|
|
154
165
|
self.api.on("/v1/recommendations", Reply(200, recs(["r1"]), delay=0.3))
|
|
155
166
|
client = self.async_client()
|
|
156
167
|
worst, results = self.worst_loop_delay(lambda u: client.recommend(user_id=u), 20)
|
|
157
|
-
|
|
168
|
+
# A blocking call stalls the loop for the whole 0.3 s reply; 0.1 s tells the two apart
|
|
169
|
+
# while leaving room for a busy host's scheduler, which measured up to 24 ms (AP-0729).
|
|
170
|
+
self.assertLess(worst, 0.1)
|
|
158
171
|
self.assertEqual([r.recommendation_id for r in results], ["rec_1"] * 20)
|
|
159
172
|
|
|
160
173
|
sync = self.client()
|
|
@@ -406,6 +406,47 @@ class ClientVectors(APITest):
|
|
|
406
406
|
attributed = [[e["item_id"], e.get("recommendation_id")] for e in events]
|
|
407
407
|
self.assertEqual(attributed, case["attributed"])
|
|
408
408
|
|
|
409
|
+
def test_vector_lists(self) -> None:
|
|
410
|
+
for case in VECTORS["lists"]["cases"]:
|
|
411
|
+
with self.subTest(case["name"]):
|
|
412
|
+
self.api.calls.clear()
|
|
413
|
+
reply = (
|
|
414
|
+
error_reply(case["error"]) if "error" in case else Reply(200, case.get("reply"))
|
|
415
|
+
)
|
|
416
|
+
self.api.on("/v1/recommendations", reply)
|
|
417
|
+
if "popular_error" in case:
|
|
418
|
+
self.api.on("/v1/popular", error_reply(case["popular_error"]))
|
|
419
|
+
else:
|
|
420
|
+
self.api.on("/v1/popular", Reply(200, popular(case.get("popular", []))))
|
|
421
|
+
client = self.client(timeout=0.2)
|
|
422
|
+
result = client.recommend_lists(
|
|
423
|
+
case["lists"],
|
|
424
|
+
anon_id="v",
|
|
425
|
+
exclude=case.get("exclude"),
|
|
426
|
+
allow_repeats=case.get("allow_repeats", False),
|
|
427
|
+
)
|
|
428
|
+
posts = [c.body for c in self.api.calls if c.path == "/v1/recommendations"]
|
|
429
|
+
self.assertEqual(len(posts), 1 if "sent" in case or "error" in case else 0)
|
|
430
|
+
if "sent" in case:
|
|
431
|
+
keys = ("placements", "exclude", "allow_repeats")
|
|
432
|
+
self.assertEqual({k: posts[0][k] for k in keys if k in posts[0]}, case["sent"])
|
|
433
|
+
queries = [c.query for c in self.api.calls if c.path == "/v1/popular"]
|
|
434
|
+
self.assertEqual(queries, case.get("popular_queries", []))
|
|
435
|
+
got = [[r.recommendation_id, [i.item_id for i in r.items]] for r in result]
|
|
436
|
+
self.assertEqual(got, case["expected"])
|
|
437
|
+
self.assertEqual([r.fallback for r in result], [i is None for i, _ in got])
|
|
438
|
+
if "reply" not in case or case.get("allow_repeats"):
|
|
439
|
+
continue
|
|
440
|
+
# Each item is credited to its own list.
|
|
441
|
+
for _, items in case["expected"]:
|
|
442
|
+
for item in items:
|
|
443
|
+
client.track(item, "view", anon_id="v")
|
|
444
|
+
client.flush()
|
|
445
|
+
events = [e for batch in self.api.events() for e in batch]
|
|
446
|
+
credited = [[e["item_id"], e.get("recommendation_id")] for e in events]
|
|
447
|
+
want = [[item, rec_id] for rec_id, items in case["expected"] for item in items]
|
|
448
|
+
self.assertEqual(credited, want)
|
|
449
|
+
|
|
409
450
|
def test_vector_upsert_items(self) -> None:
|
|
410
451
|
vectors = VECTORS["upsert_items"]
|
|
411
452
|
for case in vectors["cases"]:
|
|
@@ -413,7 +454,10 @@ class ClientVectors(APITest):
|
|
|
413
454
|
self.api.calls.clear()
|
|
414
455
|
replies = iter(case["replies"])
|
|
415
456
|
self.api.on("/v1/items:batch", lambda call, r=replies: Reply(200, next(r)))
|
|
416
|
-
|
|
457
|
+
template = case.get(
|
|
458
|
+
"item", vectors["item"]
|
|
459
|
+
) # a case's own item replaces the section's
|
|
460
|
+
items = [{"item_id": f"i{k}", **template} for k in range(case["count"])]
|
|
417
461
|
rejected = None
|
|
418
462
|
try:
|
|
419
463
|
got = self.client().upsert_items(items, merge=case["merge"])
|
|
@@ -424,6 +468,7 @@ class ClientVectors(APITest):
|
|
|
424
468
|
self.assertEqual([len(b["items"]) for b in bodies], case["sizes"])
|
|
425
469
|
for body in bodies: # true when asked, else absent
|
|
426
470
|
self.assertEqual(body.get("merge", "absent"), case["merge"] or "absent")
|
|
471
|
+
# Every item as given: a metadata key set to None goes out as null.
|
|
427
472
|
self.assertEqual([it for b in bodies for it in b["items"]], items)
|
|
428
473
|
self.assertEqual(got, case["upserted"])
|
|
429
474
|
self.assertEqual(rejected, case["rejected"] or None)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|