recapi 0.4.8__tar.gz → 0.4.10__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.8/recapi.egg-info → recapi-0.4.10}/PKG-INFO +21 -3
- {recapi-0.4.8 → recapi-0.4.10}/README.md +20 -2
- {recapi-0.4.8 → recapi-0.4.10}/pyproject.toml +1 -1
- {recapi-0.4.8 → recapi-0.4.10}/recapi/__init__.py +11 -1
- {recapi-0.4.8 → recapi-0.4.10}/recapi/async_client.py +11 -4
- {recapi-0.4.8 → recapi-0.4.10}/recapi/client.py +196 -63
- {recapi-0.4.8 → recapi-0.4.10/recapi.egg-info}/PKG-INFO +21 -3
- {recapi-0.4.8 → recapi-0.4.10}/tests/test_async_client.py +11 -0
- {recapi-0.4.8 → recapi-0.4.10}/tests/test_client_vectors.py +63 -0
- {recapi-0.4.8 → recapi-0.4.10}/LICENSE +0 -0
- {recapi-0.4.8 → recapi-0.4.10}/recapi/history.py +0 -0
- {recapi-0.4.8 → recapi-0.4.10}/recapi.egg-info/SOURCES.txt +0 -0
- {recapi-0.4.8 → recapi-0.4.10}/recapi.egg-info/dependency_links.txt +0 -0
- {recapi-0.4.8 → recapi-0.4.10}/recapi.egg-info/top_level.txt +0 -0
- {recapi-0.4.8 → recapi-0.4.10}/setup.cfg +0 -0
- {recapi-0.4.8 → recapi-0.4.10}/tests/test_client.py +0 -0
- {recapi-0.4.8 → recapi-0.4.10}/tests/test_history.py +0 -0
- {recapi-0.4.8 → recapi-0.4.10}/tests/test_stores.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: recapi
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.10
|
|
4
4
|
Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
|
|
5
5
|
License: MIT
|
|
6
6
|
Requires-Python: >=3.11
|
|
@@ -37,7 +37,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
|
|
|
37
37
|
(the dashboard's quick start shows the line with your API's address):
|
|
38
38
|
|
|
39
39
|
```sh
|
|
40
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
40
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.10-py3-none-any.whl
|
|
41
41
|
```
|
|
42
42
|
|
|
43
43
|
To work on the library itself, install it from a checkout of this repository
|
|
@@ -99,6 +99,23 @@ itself: recapi stores the `anon_id` and the dashboard shows it. Call
|
|
|
99
99
|
items they were shown become the user's, so what they did before logging in
|
|
100
100
|
keeps counting.
|
|
101
101
|
|
|
102
|
+
### Several rows in one call
|
|
103
|
+
|
|
104
|
+
A page with several rows (similar items, then "for you") asks for them in one
|
|
105
|
+
call: the history is sent once and the call is billed as one recommendation.
|
|
106
|
+
You get one `Recommendations` per list, in order; a list holds none of the
|
|
107
|
+
items of the lists before it unless `allow_repeats=True`.
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
similar, for_you = client.recommend_lists(
|
|
111
|
+
[
|
|
112
|
+
{"placement": "product", "count": 4, "context_item_id": "item-42"},
|
|
113
|
+
{"placement": "for_you", "count": 8},
|
|
114
|
+
],
|
|
115
|
+
user_id="user-881",
|
|
116
|
+
)
|
|
117
|
+
```
|
|
118
|
+
|
|
102
119
|
## Where the history lives
|
|
103
120
|
|
|
104
121
|
By default each process keeps its users' state in memory (the 10,000 most
|
|
@@ -209,8 +226,9 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
209
226
|
|---|---|
|
|
210
227
|
| `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
228
|
| `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](../../docs/api.md#item-metadata)), None when it has none; `why` its [reason code](../../docs/api.md#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 |
|
|
229
|
+
| `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
230
|
| `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)` | Creates or replaces items (dicts with the [item fields](../../docs/api.md#put-v1itemsitem_id--secret-key)), 1,000 per request, with retries. Returns how many were stored |
|
|
231
|
+
| `upsert_items(items, *, merge=False)` | Creates or replaces items (dicts with the [item fields](../../docs/api.md#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. 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
232
|
| `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
233
|
| `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
|
|
216
234
|
| `flush()` / `close()` | Send queued events now; `close()` also stops the background sender |
|
|
@@ -27,7 +27,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
|
|
|
27
27
|
(the dashboard's quick start shows the line with your API's address):
|
|
28
28
|
|
|
29
29
|
```sh
|
|
30
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
30
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.10-py3-none-any.whl
|
|
31
31
|
```
|
|
32
32
|
|
|
33
33
|
To work on the library itself, install it from a checkout of this repository
|
|
@@ -89,6 +89,23 @@ itself: recapi stores the `anon_id` and the dashboard shows it. Call
|
|
|
89
89
|
items they were shown become the user's, so what they did before logging in
|
|
90
90
|
keeps counting.
|
|
91
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
|
+
|
|
92
109
|
## Where the history lives
|
|
93
110
|
|
|
94
111
|
By default each process keeps its users' state in memory (the 10,000 most
|
|
@@ -199,8 +216,9 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
199
216
|
|---|---|
|
|
200
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 |
|
|
201
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](../../docs/api.md#item-metadata)), None when it has none; `why` its [reason code](../../docs/api.md#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 |
|
|
202
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` |
|
|
203
|
-
| `upsert_items(items)` | Creates or replaces items (dicts with the [item fields](../../docs/api.md#put-v1itemsitem_id--secret-key)), 1,000 per request, with retries. Returns how many were stored |
|
|
221
|
+
| `upsert_items(items, *, merge=False)` | Creates or replaces items (dicts with the [item fields](../../docs/api.md#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. 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
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 |
|
|
205
223
|
| `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
|
|
206
224
|
| `flush()` / `close()` | Send queued events now; `close()` also stops the background sender |
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "recapi"
|
|
7
|
-
version = "0.4.
|
|
7
|
+
version = "0.4.10"
|
|
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"
|
|
@@ -14,7 +14,16 @@ coroutines. See ``sdk/python/README.md``.
|
|
|
14
14
|
|
|
15
15
|
from typing import Any
|
|
16
16
|
|
|
17
|
-
from .client import
|
|
17
|
+
from .client import (
|
|
18
|
+
Client,
|
|
19
|
+
Item,
|
|
20
|
+
MemoryStore,
|
|
21
|
+
RecapiError,
|
|
22
|
+
Recommendations,
|
|
23
|
+
RejectedItemsError,
|
|
24
|
+
Store,
|
|
25
|
+
__version__,
|
|
26
|
+
)
|
|
18
27
|
|
|
19
28
|
__all__ = [
|
|
20
29
|
"AsyncClient",
|
|
@@ -23,6 +32,7 @@ __all__ = [
|
|
|
23
32
|
"MemoryStore",
|
|
24
33
|
"RecapiError",
|
|
25
34
|
"Recommendations",
|
|
35
|
+
"RejectedItemsError",
|
|
26
36
|
"Store",
|
|
27
37
|
"__version__",
|
|
28
38
|
]
|
|
@@ -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`."""
|
|
@@ -75,9 +82,9 @@ class AsyncClient:
|
|
|
75
82
|
"""Popular items: :meth:`Client.popular`."""
|
|
76
83
|
return await self._run(self._client.popular, **params)
|
|
77
84
|
|
|
78
|
-
async def upsert_items(self, items: Any) -> int:
|
|
85
|
+
async def upsert_items(self, items: Any, *, merge: bool = False) -> int:
|
|
79
86
|
"""Create or replace items: :meth:`Client.upsert_items`."""
|
|
80
|
-
return await self._run(self._client.upsert_items, items)
|
|
87
|
+
return await self._run(self._client.upsert_items, items, merge=merge)
|
|
81
88
|
|
|
82
89
|
async def delete_user(self, user_id: str) -> None:
|
|
83
90
|
"""Erase a user (GDPR): :meth:`Client.delete_user`."""
|
|
@@ -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.10"
|
|
33
33
|
|
|
34
34
|
log = logging.getLogger("recapi")
|
|
35
35
|
Tags = Sequence[str] | None
|
|
@@ -153,6 +153,21 @@ class RecapiError(Exception):
|
|
|
153
153
|
return self.status in (401, 403)
|
|
154
154
|
|
|
155
155
|
|
|
156
|
+
class RejectedItemsError(RecapiError):
|
|
157
|
+
"""upsert_items' error when the API refused some items: the others were stored.
|
|
158
|
+
|
|
159
|
+
``upserted`` is how many were stored, ``rejected`` the refused ones as
|
|
160
|
+
(index in the list given to upsert_items, error) pairs.
|
|
161
|
+
"""
|
|
162
|
+
|
|
163
|
+
def __init__(self, upserted: int, rejected: list[tuple[int, str]]) -> None:
|
|
164
|
+
index, error = rejected[0]
|
|
165
|
+
message = f"{len(rejected)} items refused, the first items[{index}]: {error}"
|
|
166
|
+
super().__init__("invalid_request", message, status=200)
|
|
167
|
+
self.upserted = upserted
|
|
168
|
+
self.rejected = rejected
|
|
169
|
+
|
|
170
|
+
|
|
156
171
|
@dataclass(frozen=True)
|
|
157
172
|
class Item:
|
|
158
173
|
"""One recommended or popular item."""
|
|
@@ -181,6 +196,31 @@ class Recommendations:
|
|
|
181
196
|
items: list[Item]
|
|
182
197
|
|
|
183
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
|
+
|
|
184
224
|
class Store(Protocol):
|
|
185
225
|
"""Where per-user state lives: a Redis client, Django's cache, memcached...
|
|
186
226
|
|
|
@@ -633,6 +673,34 @@ class Client:
|
|
|
633
673
|
discovery=discovery,
|
|
634
674
|
)
|
|
635
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
|
+
|
|
636
704
|
@property
|
|
637
705
|
def _recommend_timeout(self) -> float:
|
|
638
706
|
return min(self._timeout, RECOMMEND_TIMEOUT)
|
|
@@ -643,33 +711,69 @@ class Client:
|
|
|
643
711
|
*,
|
|
644
712
|
user_id: str | None = None,
|
|
645
713
|
anon_id: str | None = None,
|
|
646
|
-
count: int = 0,
|
|
647
|
-
placement: str | None = None,
|
|
648
|
-
tags_any: Tags = None,
|
|
649
|
-
tags_all: Tags = None,
|
|
650
714
|
exclude: Tags = None,
|
|
651
|
-
|
|
652
|
-
discovery: float | None = None,
|
|
715
|
+
**row: Any,
|
|
653
716
|
) -> Recommendations:
|
|
654
717
|
"""recommend() with its deadline as a ``time.monotonic()`` instant.
|
|
655
718
|
|
|
656
719
|
AsyncClient sets it at the ``await``: a call that waited for a thread
|
|
657
720
|
past it goes straight to the fallback.
|
|
658
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."""
|
|
659
763
|
key = self._key(user_id, anon_id)
|
|
660
764
|
t = _now_ms()
|
|
661
765
|
state = self._load(key) if key is not None else _UserState()
|
|
662
|
-
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:
|
|
663
768
|
_, _, rejected = state.history.wire(t)
|
|
664
769
|
# The message never quotes the id: a visitor may have written it.
|
|
665
770
|
# No id goes on to the fallback: no item can have this one.
|
|
771
|
+
unusable.context_item_id = None
|
|
666
772
|
cause = RecapiError(
|
|
667
773
|
"invalid_request",
|
|
668
774
|
"context_item_id must be 1-256 bytes of UTF-8 without control characters",
|
|
669
775
|
)
|
|
670
|
-
return self.
|
|
671
|
-
cause, rejected, count=count, tags_any=tags_any, tags_all=tags_all, exclude=exclude
|
|
672
|
-
)
|
|
776
|
+
return self._fallbacks(cause, rows, _with_rejected(shared, rejected), repeats)
|
|
673
777
|
if (
|
|
674
778
|
user_id
|
|
675
779
|
and not state.restored
|
|
@@ -678,6 +782,15 @@ class Client:
|
|
|
678
782
|
):
|
|
679
783
|
state = self._restore(key, user_id, state, deadline, t)
|
|
680
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)
|
|
681
794
|
try:
|
|
682
795
|
response = self._request(
|
|
683
796
|
"POST",
|
|
@@ -687,38 +800,33 @@ class Client:
|
|
|
687
800
|
{
|
|
688
801
|
"user_id": user_id,
|
|
689
802
|
"anon_id": anon_id,
|
|
690
|
-
|
|
691
|
-
"count": count or None,
|
|
692
|
-
"tags_any": _list(tags_any),
|
|
693
|
-
"tags_all": _list(tags_all),
|
|
694
|
-
"exclude": _with_rejected(exclude, rejected),
|
|
695
|
-
"context_item_id": context_item_id,
|
|
803
|
+
**fields,
|
|
696
804
|
"history": history,
|
|
697
805
|
"recent": recent,
|
|
698
|
-
"discovery": discovery,
|
|
699
806
|
}
|
|
700
807
|
),
|
|
701
808
|
)
|
|
702
|
-
|
|
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
|
+
]
|
|
703
818
|
except RecapiError as error:
|
|
704
819
|
if not error._spare_the_page:
|
|
705
820
|
raise
|
|
706
|
-
return self.
|
|
707
|
-
error,
|
|
708
|
-
rejected,
|
|
709
|
-
count=count,
|
|
710
|
-
tags_any=tags_any,
|
|
711
|
-
tags_all=tags_all,
|
|
712
|
-
exclude=exclude,
|
|
713
|
-
context_item_id=context_item_id,
|
|
714
|
-
)
|
|
821
|
+
return self._fallbacks(error, rows, exclude, repeats)
|
|
715
822
|
|
|
716
823
|
if key is not None:
|
|
717
824
|
with self._lock_for(key):
|
|
718
825
|
state = self._load(key)
|
|
719
|
-
for
|
|
720
|
-
|
|
721
|
-
|
|
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]
|
|
722
830
|
while len(state.shown) > MAX_SHOWN_ITEMS:
|
|
723
831
|
del state.shown[next(iter(state.shown))]
|
|
724
832
|
# Only trusted when we sent nothing; merged, never replacing
|
|
@@ -730,34 +838,48 @@ class Client:
|
|
|
730
838
|
state.history = state.history.merge_snapshot(History.from_snapshot(snapshot), t)
|
|
731
839
|
state.restored = True
|
|
732
840
|
self._save(key, state, t)
|
|
733
|
-
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
|
|
734
865
|
|
|
735
866
|
def _fallback(
|
|
736
|
-
self,
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
*,
|
|
740
|
-
count: int,
|
|
741
|
-
tags_any: Tags,
|
|
742
|
-
tags_all: Tags,
|
|
743
|
-
exclude: Tags,
|
|
744
|
-
context_item_id: str | None = None,
|
|
745
|
-
) -> Recommendations:
|
|
746
|
-
"""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)."""
|
|
747
870
|
if error._key_refused:
|
|
748
871
|
log.warning(
|
|
749
872
|
"recapi: recommendations refused, served no items: %s: %s", error.code, error
|
|
750
873
|
)
|
|
751
|
-
return Recommendations(None, True, [])
|
|
874
|
+
return Recommendations(None, True, []), True
|
|
752
875
|
# The requested length without the excluded items, so a few more
|
|
753
876
|
# are asked for. 0 is the recommendations default; popular refuses it.
|
|
754
|
-
n = count or DEFAULT_COUNT
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
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)
|
|
758
880
|
try:
|
|
759
881
|
popular = self._popular(
|
|
760
|
-
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
|
|
761
883
|
)
|
|
762
884
|
except RecapiError as fallback_error:
|
|
763
885
|
# recapi is down or the limit covers popular too. The README
|
|
@@ -769,12 +891,12 @@ class Client:
|
|
|
769
891
|
error,
|
|
770
892
|
fallback_error,
|
|
771
893
|
)
|
|
772
|
-
return Recommendations(None, True, [])
|
|
894
|
+
return Recommendations(None, True, []), True
|
|
773
895
|
log.warning(
|
|
774
896
|
"recapi: recommendations failed, served popular items: %s: %s", error.code, error
|
|
775
897
|
)
|
|
776
898
|
items = [item for item in popular if item.item_id not in skip][:n]
|
|
777
|
-
return Recommendations(None, True, items)
|
|
899
|
+
return Recommendations(None, True, items), False
|
|
778
900
|
|
|
779
901
|
def _restore(
|
|
780
902
|
self, key: str, user_id: str, state: _UserState, deadline: float, t: int
|
|
@@ -872,28 +994,39 @@ class Client:
|
|
|
872
994
|
|
|
873
995
|
# --- catalog and users --------------------------------------------------
|
|
874
996
|
|
|
875
|
-
def upsert_items(self, items: Iterable[Mapping[str, Any]]) -> int:
|
|
997
|
+
def upsert_items(self, items: Iterable[Mapping[str, Any]], *, merge: bool = False) -> int:
|
|
876
998
|
"""Create or replace items (dicts of the API's item fields), 1,000 per request.
|
|
877
999
|
|
|
878
|
-
|
|
879
|
-
|
|
1000
|
+
With ``merge``, each item changes only the fields it has and keeps the
|
|
1001
|
+
others' stored values (a field set to None goes back to its default).
|
|
1002
|
+
Retried like events. Returns how many were stored. An invalid item
|
|
1003
|
+
doesn't keep the others out: once every request is sent,
|
|
1004
|
+
:class:`RejectedItemsError` lists the refused ones.
|
|
880
1005
|
"""
|
|
881
1006
|
batch: list[dict[str, Any]] = []
|
|
882
|
-
upserted = 0
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
1007
|
+
upserted, sent = 0, 0
|
|
1008
|
+
rejected: list[tuple[int, str]] = []
|
|
1009
|
+
|
|
1010
|
+
def send() -> None:
|
|
1011
|
+
nonlocal upserted, sent
|
|
1012
|
+
# "merge" only when asked: an older API refuses the field.
|
|
1013
|
+
body = {"items": batch, "merge": True} if merge else {"items": batch}
|
|
1014
|
+
response = _with_retry(lambda: self._request("POST", "/v1/items:batch", body=body))
|
|
1015
|
+
if isinstance(response, dict):
|
|
1016
|
+
upserted += int(response.get("upserted", 0))
|
|
1017
|
+
for entry in response.get("rejected") or []:
|
|
1018
|
+
rejected.append((sent + int(entry["index"]), str(entry.get("error", ""))))
|
|
1019
|
+
sent += len(batch)
|
|
889
1020
|
|
|
890
1021
|
for item in items:
|
|
891
1022
|
batch.append(dict(item))
|
|
892
1023
|
if len(batch) == MAX_ITEMS_PER_REQUEST:
|
|
893
|
-
|
|
1024
|
+
send()
|
|
894
1025
|
batch = []
|
|
895
1026
|
if batch:
|
|
896
|
-
|
|
1027
|
+
send()
|
|
1028
|
+
if rejected:
|
|
1029
|
+
raise RejectedItemsError(upserted, rejected)
|
|
897
1030
|
return upserted
|
|
898
1031
|
|
|
899
1032
|
def delete_user(self, user_id: str) -> None:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: recapi
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.10
|
|
4
4
|
Summary: Python client for the recapi recommendation API: per-user history, event batching, retries, popular fallback.
|
|
5
5
|
License: MIT
|
|
6
6
|
Requires-Python: >=3.11
|
|
@@ -37,7 +37,7 @@ Your recapi API serves the same library, for servers that can't reach PyPI
|
|
|
37
37
|
(the dashboard's quick start shows the line with your API's address):
|
|
38
38
|
|
|
39
39
|
```sh
|
|
40
|
-
pip install https://api.<your-domain>/sdk/python/recapi-0.4.
|
|
40
|
+
pip install https://api.<your-domain>/sdk/python/recapi-0.4.10-py3-none-any.whl
|
|
41
41
|
```
|
|
42
42
|
|
|
43
43
|
To work on the library itself, install it from a checkout of this repository
|
|
@@ -99,6 +99,23 @@ itself: recapi stores the `anon_id` and the dashboard shows it. Call
|
|
|
99
99
|
items they were shown become the user's, so what they did before logging in
|
|
100
100
|
keeps counting.
|
|
101
101
|
|
|
102
|
+
### Several rows in one call
|
|
103
|
+
|
|
104
|
+
A page with several rows (similar items, then "for you") asks for them in one
|
|
105
|
+
call: the history is sent once and the call is billed as one recommendation.
|
|
106
|
+
You get one `Recommendations` per list, in order; a list holds none of the
|
|
107
|
+
items of the lists before it unless `allow_repeats=True`.
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
similar, for_you = client.recommend_lists(
|
|
111
|
+
[
|
|
112
|
+
{"placement": "product", "count": 4, "context_item_id": "item-42"},
|
|
113
|
+
{"placement": "for_you", "count": 8},
|
|
114
|
+
],
|
|
115
|
+
user_id="user-881",
|
|
116
|
+
)
|
|
117
|
+
```
|
|
118
|
+
|
|
102
119
|
## Where the history lives
|
|
103
120
|
|
|
104
121
|
By default each process keeps its users' state in memory (the 10,000 most
|
|
@@ -209,8 +226,9 @@ one recommendation id collects the events of many users ("Page caches").
|
|
|
209
226
|
|---|---|
|
|
210
227
|
| `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
228
|
| `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](../../docs/api.md#item-metadata)), None when it has none; `why` its [reason code](../../docs/api.md#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 |
|
|
229
|
+
| `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
230
|
| `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)` | Creates or replaces items (dicts with the [item fields](../../docs/api.md#put-v1itemsitem_id--secret-key)), 1,000 per request, with retries. Returns how many were stored |
|
|
231
|
+
| `upsert_items(items, *, merge=False)` | Creates or replaces items (dicts with the [item fields](../../docs/api.md#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. 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
232
|
| `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
233
|
| `delete_user(user_id)` | Erases the user's events in recapi (GDPR) and their state in the store |
|
|
216
234
|
| `flush()` / `close()` | Send queued events now; `close()` also stops the background sender |
|
|
@@ -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)
|
|
@@ -405,3 +405,66 @@ class ClientVectors(APITest):
|
|
|
405
405
|
]
|
|
406
406
|
attributed = [[e["item_id"], e.get("recommendation_id")] for e in events]
|
|
407
407
|
self.assertEqual(attributed, case["attributed"])
|
|
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
|
+
|
|
450
|
+
def test_vector_upsert_items(self) -> None:
|
|
451
|
+
vectors = VECTORS["upsert_items"]
|
|
452
|
+
for case in vectors["cases"]:
|
|
453
|
+
with self.subTest(case=case["name"]):
|
|
454
|
+
self.api.calls.clear()
|
|
455
|
+
replies = iter(case["replies"])
|
|
456
|
+
self.api.on("/v1/items:batch", lambda call, r=replies: Reply(200, next(r)))
|
|
457
|
+
items = [{"item_id": f"i{k}", **vectors["item"]} for k in range(case["count"])]
|
|
458
|
+
rejected = None
|
|
459
|
+
try:
|
|
460
|
+
got = self.client().upsert_items(items, merge=case["merge"])
|
|
461
|
+
except recapi.RejectedItemsError as error:
|
|
462
|
+
self.assertEqual(error.code, "invalid_request")
|
|
463
|
+
got, rejected = error.upserted, [list(r) for r in error.rejected]
|
|
464
|
+
bodies = [c.body for c in self.api.calls if c.path == "/v1/items:batch"]
|
|
465
|
+
self.assertEqual([len(b["items"]) for b in bodies], case["sizes"])
|
|
466
|
+
for body in bodies: # true when asked, else absent
|
|
467
|
+
self.assertEqual(body.get("merge", "absent"), case["merge"] or "absent")
|
|
468
|
+
self.assertEqual([it for b in bodies for it in b["items"]], items)
|
|
469
|
+
self.assertEqual(got, case["upserted"])
|
|
470
|
+
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
|