recapi 0.4.9__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: recapi
3
- Version: 0.4.9
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.9-py3-none-any.whl
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,6 +226,7 @@ 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
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 |
@@ -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.9-py3-none-any.whl
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,6 +216,7 @@ 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
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 |
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "recapi"
7
- version = "0.4.9"
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"
@@ -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(client._recommend, deadline, **params)
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(client._recommend, deadline, **params)
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.9"
32
+ __version__ = "0.4.10"
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
- context_item_id: str | None = None,
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._fallback(
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
- "placement": placement,
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
- rec_id, items = _parse_recommendations(response)
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._fallback(
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 item in items:
735
- state.shown.pop(item.item_id, None)
736
- state.shown[item.item_id] = [rec_id, t]
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 Recommendations(rec_id, False, items)
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
- error: RecapiError,
753
- rejected: list[str],
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
- skip = set(_with_rejected(exclude, rejected) or ())
771
- if context_item_id is not None:
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
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: recapi
3
- Version: 0.4.9
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.9-py3-none-any.whl
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,6 +226,7 @@ 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
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 |
@@ -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)
@@ -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"]:
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes