behaviorgpt 0.6.2__tar.gz → 0.6.3__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: behaviorgpt
3
- Version: 0.6.2
3
+ Version: 0.6.3
4
4
  Summary: Python client for BehaviorGPT, UnboxAI's Large Behavioral Model for search, recommendations and personalization
5
5
  Keywords: recommendations,personalization,search,behavioral model,unboxai
6
6
  Author: Unbox AI
@@ -110,6 +110,8 @@ job = client.embed(path, wait=True, timeout=1800.0)
110
110
  client.complete([Search("...")], catalog_id=job.catalog_id)
111
111
  ```
112
112
 
113
+ To make your catalog the default, so calls need no `catalog_id`, set `UNBOXAI_CATALOG_ID=cat_...` or pass `default_catalog_id=` to the client.
114
+
113
115
  A catalog holds up to 100,000 items, and each API key holds 2 catalogs. The file name is the catalog's name, so uploading the same name again refreshes that catalog.
114
116
 
115
117
  Once it is embedded, you can add or replace items, list and delete catalogs, and generate the keywords that `sections` uses to group results under titles such as "black coats":
@@ -124,7 +126,15 @@ for section in client.sections([Search("coat")], catalog_id=job.catalog_id).sect
124
126
  print(section.title, [item.data["name"] for item in section.items])
125
127
  ```
126
128
 
127
- [`docs/catalogs.md`](https://github.com/Unbox-AI/behaviorgpt/blob/main/docs/catalogs.md) has the details: catalog slots, what replacing an item keeps, how long keywords take and what happens when a job fails.
129
+ To rank several catalogs together, say your own next to `retail_catalog`, pass `catalog_ids` instead of `catalog_id`. One ranking comes back, and each item says which catalog it is in:
130
+
131
+ ```python
132
+ res = client.complete([View(shoe)], catalog_ids=[job.catalog_id, "retail_catalog"])
133
+ for item in res.items:
134
+ print(item.catalog_id, item.data["name"])
135
+ ```
136
+
137
+ [`docs/catalogs.md`](https://github.com/Unbox-AI/behaviorgpt/blob/main/docs/catalogs.md) has the details: catalog slots, what replacing an item keeps, how long keywords take, what happens when a job fails, and how a history names items of several catalogs.
128
138
 
129
139
  If mapping your data to the format is hard, open a coding agent in this directory and ask it to embed your catalog. The repo ships a skill at [`.claude/skills/embed-catalog/SKILL.md`](https://github.com/Unbox-AI/behaviorgpt/blob/main/.claude/skills/embed-catalog/SKILL.md) that walks the agent through mapping your columns, building and validating the parquet, checking image URLs, and uploading. Claude Code picks it up automatically; for other agents, point them at that file.
130
140
 
@@ -93,6 +93,8 @@ job = client.embed(path, wait=True, timeout=1800.0)
93
93
  client.complete([Search("...")], catalog_id=job.catalog_id)
94
94
  ```
95
95
 
96
+ To make your catalog the default, so calls need no `catalog_id`, set `UNBOXAI_CATALOG_ID=cat_...` or pass `default_catalog_id=` to the client.
97
+
96
98
  A catalog holds up to 100,000 items, and each API key holds 2 catalogs. The file name is the catalog's name, so uploading the same name again refreshes that catalog.
97
99
 
98
100
  Once it is embedded, you can add or replace items, list and delete catalogs, and generate the keywords that `sections` uses to group results under titles such as "black coats":
@@ -107,7 +109,15 @@ for section in client.sections([Search("coat")], catalog_id=job.catalog_id).sect
107
109
  print(section.title, [item.data["name"] for item in section.items])
108
110
  ```
109
111
 
110
- [`docs/catalogs.md`](https://github.com/Unbox-AI/behaviorgpt/blob/main/docs/catalogs.md) has the details: catalog slots, what replacing an item keeps, how long keywords take and what happens when a job fails.
112
+ To rank several catalogs together, say your own next to `retail_catalog`, pass `catalog_ids` instead of `catalog_id`. One ranking comes back, and each item says which catalog it is in:
113
+
114
+ ```python
115
+ res = client.complete([View(shoe)], catalog_ids=[job.catalog_id, "retail_catalog"])
116
+ for item in res.items:
117
+ print(item.catalog_id, item.data["name"])
118
+ ```
119
+
120
+ [`docs/catalogs.md`](https://github.com/Unbox-AI/behaviorgpt/blob/main/docs/catalogs.md) has the details: catalog slots, what replacing an item keeps, how long keywords take, what happens when a job fails, and how a history names items of several catalogs.
111
121
 
112
122
  If mapping your data to the format is hard, open a coding agent in this directory and ask it to embed your catalog. The repo ships a skill at [`.claude/skills/embed-catalog/SKILL.md`](https://github.com/Unbox-AI/behaviorgpt/blob/main/.claude/skills/embed-catalog/SKILL.md) that walks the agent through mapping your columns, building and validating the parquet, checking image URLs, and uploading. Claude Code picks it up automatically; for other agents, point them at that file.
113
123
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "behaviorgpt"
3
- version = "0.6.2"
3
+ version = "0.6.3"
4
4
  description = "Python client for BehaviorGPT, UnboxAI's Large Behavioral Model for search, recommendations and personalization"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "behaviorgpt"
3
- version = "0.6.2"
3
+ version = "0.6.3"
4
4
  description = "Python client for BehaviorGPT, UnboxAI's Large Behavioral Model for search, recommendations and personalization"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -12,6 +12,7 @@ from behaviorgpt.resources.catalogs import (
12
12
  )
13
13
  from behaviorgpt.types.events import (
14
14
  AddToCart,
15
+ CartItem,
15
16
  Order,
16
17
  RemoveFromCart,
17
18
  Search,
@@ -24,6 +25,7 @@ __all__ = [
24
25
  "View",
25
26
  "RemoveFromCart",
26
27
  "Order",
28
+ "CartItem",
27
29
  "UnboxAIClient",
28
30
  "AsyncUnboxAIClient",
29
31
  "ProgressBar",
@@ -4,9 +4,10 @@ import random
4
4
  import time
5
5
  import warnings
6
6
  from collections import defaultdict
7
+ from dataclasses import dataclass
7
8
  from datetime import UTC, datetime, timedelta
8
9
  from pathlib import Path
9
- from typing import Any, Callable, Literal, Optional, Sequence, cast
10
+ from typing import Any, Callable, Iterable, Literal, Optional, Sequence, cast
10
11
  from uuid import uuid4
11
12
 
12
13
  import httpx
@@ -36,7 +37,9 @@ from behaviorgpt.types import (
36
37
  UnboxAIResponse,
37
38
  UserEvent,
38
39
  UserHistoryInput,
40
+ View,
39
41
  )
42
+ from behaviorgpt.types.events import ItemRef
40
43
  from behaviorgpt.types.http import RecommendationType
41
44
 
42
45
  # An embed upload streams the whole parquet, and the API answers only once the
@@ -47,6 +50,45 @@ DEFAULT_TRAILING_SEARCHES = 3
47
50
  UMAP_POLL = 5.0
48
51
 
49
52
  Predict = Literal["view", "purchase"]
53
+ CATALOG_IDS_HEADER = "x-catalog-ids"
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class _Target:
58
+ """The catalogs one request reads. Several (`catalog_ids=`) are ranked
59
+ together, and then every item names the catalog it is in."""
60
+
61
+ catalog_ids: tuple[str, ...]
62
+ multi: bool = False
63
+
64
+ @property
65
+ def primary(self) -> str:
66
+ return self.catalog_ids[0]
67
+
68
+ @property
69
+ def headers(self) -> dict:
70
+ if self.multi:
71
+ return {CATALOG_IDS_HEADER: ",".join(self.catalog_ids)}
72
+ return {"x-catalog-id": self.primary}
73
+
74
+ def of(self, catalog_id: Optional[str]) -> str:
75
+ """The catalog of an item that names `catalog_id`, or none."""
76
+ if catalog_id is None or catalog_id == self.primary:
77
+ return self.primary
78
+ if catalog_id not in self.catalog_ids:
79
+ hint = "" if self.multi else "; pass catalog_ids= to rank several"
80
+ raise ValueError(
81
+ f"an item is in catalog {catalog_id!r}, but this request reads "
82
+ f"{', '.join(map(repr, self.catalog_ids))}{hint}"
83
+ )
84
+ return catalog_id
85
+
86
+ def label(self, items: Iterable[Item]) -> None:
87
+ """Give each item of a response its catalog: the API names it only when
88
+ the request reads several."""
89
+ for item in items:
90
+ if item.catalog_id is None:
91
+ item.catalog_id = self.primary
50
92
 
51
93
 
52
94
  class _BaseClient:
@@ -59,7 +101,7 @@ class _BaseClient:
59
101
  timezone: str = "UTC",
60
102
  api_key: Optional[str] = None,
61
103
  base_url: str = DEFAULT_BASE_URL,
62
- default_catalog_id: str = "retail_catalog",
104
+ default_catalog_id: Optional[str] = None,
63
105
  ):
64
106
  self.api_key = api_key or os.environ.get("UNBOXAI_API_KEY")
65
107
  if not self.api_key:
@@ -67,16 +109,50 @@ class _BaseClient:
67
109
  raise AuthenticationError(msg)
68
110
 
69
111
  self.base_url = base_url
70
- self.default_catalog_id = default_catalog_id
112
+ # the catalog of calls that name none
113
+ self.default_catalog_id = (
114
+ default_catalog_id
115
+ or os.environ.get("UNBOXAI_CATALOG_ID")
116
+ or "retail_catalog"
117
+ )
71
118
 
72
119
  self.domains = Domains(market=market)
73
120
  self.timezone = timezone
74
121
 
75
122
  self.requester = UnboxAIRequester(domains=self.domains, timezone=self.timezone)
76
123
 
77
- def _catalog_headers(self, catalog_id: Optional[str]) -> tuple[str, dict]:
78
- active_catalog: str = catalog_id or self.default_catalog_id
79
- return active_catalog, {"x-catalog-id": active_catalog}
124
+ def _target(
125
+ self, catalog_id: Optional[str], catalog_ids: Optional[Sequence[str]]
126
+ ) -> _Target:
127
+ if catalog_ids is None:
128
+ return _Target((catalog_id or self.default_catalog_id,))
129
+ if catalog_id is not None:
130
+ raise ValueError("pass catalog_id or catalog_ids, not both")
131
+ if isinstance(catalog_ids, str):
132
+ raise TypeError("catalog_ids takes a list of catalog ids, not a string")
133
+ ids = tuple(dict.fromkeys(catalog_ids))
134
+ if not ids:
135
+ raise ValueError("catalog_ids names no catalog")
136
+ return _Target(ids, multi=True)
137
+
138
+ def _similar_request(
139
+ self,
140
+ item: ItemRef,
141
+ catalog_id: Optional[str],
142
+ catalog_ids: Optional[Sequence[str]],
143
+ ) -> tuple[_Target, str, str]:
144
+ """The catalogs a similar-items request reads, and the id and catalog
145
+ of its item. The item's catalog is `catalog_id`, else the `Item`'s own;
146
+ over `catalog_ids` it must be one of them, by default the first."""
147
+ item_id = item if isinstance(item, str) else item.id
148
+ item_catalog = catalog_id or (
149
+ None if isinstance(item, str) else item.catalog_id
150
+ )
151
+ if catalog_ids is None:
152
+ target = self._target(item_catalog, None)
153
+ return target, item_id, target.primary
154
+ target = self._target(None, catalog_ids)
155
+ return target, item_id, target.of(item_catalog)
80
156
 
81
157
  def _complete_request(
82
158
  self,
@@ -88,13 +164,15 @@ class _BaseClient:
88
164
  register_event: bool,
89
165
  max_trailing_searches: int = DEFAULT_TRAILING_SEARCHES,
90
166
  predict: Predict = "view",
91
- ) -> tuple[bool, UnboxAIRequest, dict]:
92
- """The request `complete` sends, whether it goes to search, and its headers."""
167
+ catalog_ids: Optional[Sequence[str]] = None,
168
+ ) -> tuple[bool, UnboxAIRequest, _Target]:
169
+ """The request `complete` sends, whether it goes to search, and the
170
+ catalogs it reads."""
93
171
  if predict not in ("view", "purchase"):
94
172
  raise ValueError(f"predict must be 'view' or 'purchase', not {predict!r}")
95
- active_catalog, request_headers = self._catalog_headers(catalog_id)
173
+ target = self._target(catalog_id, catalog_ids)
96
174
 
97
- history_events = self.__from_sequence(active_catalog, history)
175
+ history_events = self.__from_sequence(target, history)
98
176
  last_event = self._get_last_event(history)
99
177
 
100
178
  if isinstance(last_event, Search):
@@ -106,18 +184,18 @@ class _BaseClient:
106
184
  req = self.requester.make(
107
185
  query=last_event.query,
108
186
  history=history_events[:-1],
109
- catalog_id=active_catalog,
187
+ catalog_id=target.primary,
110
188
  limit=limit,
111
189
  offset=offset,
112
190
  filters=filters,
113
191
  register_event=register_event,
114
192
  max_trailing_searches=max_trailing_searches,
115
193
  )
116
- return True, req, request_headers
194
+ return True, req, target
117
195
 
118
196
  req = self.requester.make(
119
197
  history=history_events,
120
- catalog_id=active_catalog,
198
+ catalog_id=target.primary,
121
199
  limit=limit,
122
200
  offset=offset,
123
201
  filters=filters,
@@ -126,7 +204,7 @@ class _BaseClient:
126
204
  RecommendationType(name="buy_next") if predict == "purchase" else None
127
205
  ),
128
206
  )
129
- return False, req, request_headers
207
+ return False, req, target
130
208
 
131
209
  def _sections_request(
132
210
  self,
@@ -137,18 +215,19 @@ class _BaseClient:
137
215
  max_sections: int,
138
216
  max_items_per_section: int,
139
217
  min_items_per_section: int,
140
- ) -> tuple[dict, dict]:
141
- """The body `sections` sends, and its headers."""
142
- _, req, headers = self._complete_request(
143
- history, 10, 0, catalog_id, filters, register_event
218
+ catalog_ids: Optional[Sequence[str]] = None,
219
+ ) -> tuple[dict, _Target]:
220
+ """The body `sections` sends, and the catalogs it reads."""
221
+ _, req, target = self._complete_request(
222
+ history, 10, 0, catalog_id, filters, register_event, catalog_ids=catalog_ids
144
223
  )
145
224
  body = sections_body(
146
225
  req, max_sections, max_items_per_section, min_items_per_section
147
226
  )
148
- return body, headers
227
+ return body, target
149
228
 
150
229
  def __from_sequence(
151
- self, catalog_id: str, context: UserHistoryInput
230
+ self, target: _Target, context: UserHistoryInput
152
231
  ) -> list[SessionEvent]:
153
232
  events: list[SessionEvent] = []
154
233
 
@@ -159,7 +238,7 @@ class _BaseClient:
159
238
  def _process_session_events(
160
239
  session_events: Sequence[UserEvent], session_id: str, session_offset: int
161
240
  ):
162
- cart_state: dict[str, int] = defaultdict(int)
241
+ cart_state: dict[tuple[Optional[str], str], int] = defaultdict(int)
163
242
  current_cart_id = str(uuid4())
164
243
 
165
244
  # Base time for the start of the sequence
@@ -167,17 +246,19 @@ class _BaseClient:
167
246
 
168
247
  for i, ev in enumerate(session_events):
169
248
  if isinstance(ev, AddToCart):
170
- cart_state[ev.item] += 1
249
+ cart_state[(ev.catalog_id, ev.item)] += 1
171
250
  elif isinstance(ev, RemoveFromCart):
172
- if cart_state[ev.item] > 1:
173
- cart_state[ev.item] -= 1
251
+ key = (ev.catalog_id, ev.item)
252
+ if cart_state[key] > 1:
253
+ cart_state[key] -= 1
174
254
  else:
175
- cart_state.pop(ev.item)
255
+ cart_state.pop(key)
176
256
  elif isinstance(ev, Order):
177
257
  if not getattr(ev, "items", None):
178
258
  ev.cart_id = current_cart_id
179
259
  ev.items = [
180
- CartItem(item, qty) for item, qty in cart_state.items()
260
+ CartItem(item, qty, catalog_id=catalog)
261
+ for (catalog, item), qty in cart_state.items()
181
262
  ]
182
263
  cart_state.clear()
183
264
  current_cart_id = str(uuid4())
@@ -189,9 +270,15 @@ class _BaseClient:
189
270
  milliseconds=(session_offset * 1000) + i
190
271
  )
191
272
 
192
- events.append(
193
- self.__to_session_evt(ev, session_id, catalog_id, event_time)
194
- )
273
+ for j, (catalog, event) in enumerate(_by_catalog(ev, target)):
274
+ events.append(
275
+ self.__to_session_evt(
276
+ event,
277
+ session_id,
278
+ catalog,
279
+ event_time + timedelta(microseconds=j),
280
+ )
281
+ )
195
282
 
196
283
  if isinstance(context[0], (list, tuple)):
197
284
  context_2d = cast(Sequence[Sequence[UserEvent]], context)
@@ -236,7 +323,7 @@ class UnboxAIClient(_BaseClient):
236
323
  timezone: str = "UTC",
237
324
  api_key: Optional[str] = None,
238
325
  base_url: str = DEFAULT_BASE_URL,
239
- default_catalog_id: str = "retail_catalog",
326
+ default_catalog_id: Optional[str] = None,
240
327
  http_timeout: float | httpx.Timeout = DEFAULT_HTTP_TIMEOUT,
241
328
  ):
242
329
  super().__init__(
@@ -264,6 +351,7 @@ class UnboxAIClient(_BaseClient):
264
351
  offset: int = 0,
265
352
  *,
266
353
  catalog_id: Optional[str] = None,
354
+ catalog_ids: Optional[Sequence[str]] = None,
267
355
  filters: Optional[dict[str, Any]] = None,
268
356
  register_event: bool = False,
269
357
  max_trailing_searches: int = DEFAULT_TRAILING_SEARCHES,
@@ -280,8 +368,16 @@ class UnboxAIClient(_BaseClient):
280
368
  When the history ends in searches, up to `max_trailing_searches` of
281
369
  them in a row, the query included, reach the model, so `nike` then
282
370
  `shoes` reads as one intent.
371
+
372
+ `catalog_ids` ranks several catalogs together instead of one, for
373
+ instance your own and `retail_catalog`: each item of the result says
374
+ which it is in (`item.catalog_id`). Items in the history are in the
375
+ first catalog unless they name another, `View(item_id,
376
+ catalog_id=...)`, or are `Item`s of an earlier response, which know
377
+ theirs. In `filters`, `catalog_id` is the item's catalog, e.g.
378
+ `{"catalog_id": "retail_catalog"}`.
283
379
  """
284
- is_search, req, headers = self._complete_request(
380
+ is_search, req, target = self._complete_request(
285
381
  history,
286
382
  limit,
287
383
  offset,
@@ -290,15 +386,19 @@ class UnboxAIClient(_BaseClient):
290
386
  register_event,
291
387
  max_trailing_searches,
292
388
  predict,
389
+ catalog_ids,
293
390
  )
294
391
  endpoint = self.search if is_search else self.recommendations
295
- return endpoint.create(payload=req, headers=headers)
392
+ response = endpoint.create(payload=req, headers=target.headers)
393
+ target.label(response.items)
394
+ return response
296
395
 
297
396
  def sections(
298
397
  self,
299
398
  history: UserHistoryInput,
300
399
  *,
301
400
  catalog_id: Optional[str] = None,
401
+ catalog_ids: Optional[Sequence[str]] = None,
302
402
  max_sections: int = 10,
303
403
  max_items_per_section: int = 25,
304
404
  min_items_per_section: int = 5,
@@ -317,8 +417,12 @@ class UnboxAIClient(_BaseClient):
317
417
  `max_sections` can be at most 15 and `max_items_per_section` at most
318
418
  100. Each item's `data` holds its generated search terms in
319
419
  `top_terms`, best first.
420
+
421
+ `catalog_ids` groups several catalogs together, as for `complete`: a
422
+ section can hold items of any of them, each weighed by its catalog's
423
+ size, so a small catalog does not crowd out a large one.
320
424
  """
321
- body, headers = self._sections_request(
425
+ body, target = self._sections_request(
322
426
  history,
323
427
  catalog_id,
324
428
  filters,
@@ -326,8 +430,11 @@ class UnboxAIClient(_BaseClient):
326
430
  max_sections,
327
431
  max_items_per_section,
328
432
  min_items_per_section,
433
+ catalog_ids,
329
434
  )
330
- return self._sections.create(body, headers=headers)
435
+ response = self._sections.create(body, headers=target.headers)
436
+ target.label(item for section in response.sections for item in section.items)
437
+ return response
331
438
 
332
439
  def embed(
333
440
  self,
@@ -462,20 +569,34 @@ class UnboxAIClient(_BaseClient):
462
569
 
463
570
  def similar_items(
464
571
  self,
465
- item_id: str,
572
+ item_id: ItemRef,
466
573
  limit: int = 10,
467
574
  offset: int = 0,
468
575
  *,
469
576
  catalog_id: Optional[str] = None,
577
+ catalog_ids: Optional[Sequence[str]] = None,
578
+ filters: Optional[dict[str, Any]] = None,
470
579
  ) -> UnboxAIResponse:
471
- active_catalog, request_headers = self._catalog_headers(catalog_id)
472
- return self.catalogs.get_similar_items(
473
- item_id,
474
- catalog_id=active_catalog,
580
+ """The items most like `item_id`, an item id or an `Item` of a
581
+ response, most similar first.
582
+
583
+ `catalog_id` is the catalog the item is in; for an `Item`, its own.
584
+ `catalog_ids` looks for similar items in several catalogs, the item's
585
+ among them (by default the first): each result says which it is in.
586
+ """
587
+ target, item, item_catalog = self._similar_request(
588
+ item_id, catalog_id, catalog_ids
589
+ )
590
+ response = self.catalogs.get_similar_items(
591
+ item,
592
+ catalog_id=item_catalog,
475
593
  limit=limit,
476
594
  offset=offset,
477
- headers=request_headers,
595
+ filters=filters,
596
+ headers=target.headers,
478
597
  )
598
+ target.label(response.items)
599
+ return response
479
600
 
480
601
  def similar_products(
481
602
  self, product_id: str, *args: Any, **kwargs: Any
@@ -540,7 +661,7 @@ class AsyncUnboxAIClient(_BaseClient):
540
661
  timezone: str = "UTC",
541
662
  api_key: Optional[str] = None,
542
663
  base_url: str = DEFAULT_BASE_URL,
543
- default_catalog_id: str = "retail_catalog",
664
+ default_catalog_id: Optional[str] = None,
544
665
  http_timeout: float | httpx.Timeout = DEFAULT_HTTP_TIMEOUT,
545
666
  ):
546
667
  super().__init__(
@@ -577,6 +698,7 @@ class AsyncUnboxAIClient(_BaseClient):
577
698
  offset: int = 0,
578
699
  *,
579
700
  catalog_id: Optional[str] = None,
701
+ catalog_ids: Optional[Sequence[str]] = None,
580
702
  filters: Optional[dict[str, Any]] = None,
581
703
  register_event: bool = False,
582
704
  max_trailing_searches: int = DEFAULT_TRAILING_SEARCHES,
@@ -584,7 +706,7 @@ class AsyncUnboxAIClient(_BaseClient):
584
706
  ) -> UnboxAIResponse:
585
707
  """Rank the items most likely to come after `history`; see
586
708
  `UnboxAIClient.complete`."""
587
- is_search, req, headers = self._complete_request(
709
+ is_search, req, target = self._complete_request(
588
710
  history,
589
711
  limit,
590
712
  offset,
@@ -593,15 +715,19 @@ class AsyncUnboxAIClient(_BaseClient):
593
715
  register_event,
594
716
  max_trailing_searches,
595
717
  predict,
718
+ catalog_ids,
596
719
  )
597
720
  endpoint = self.search if is_search else self.recommendations
598
- return await endpoint.create(payload=req, headers=headers)
721
+ response = await endpoint.create(payload=req, headers=target.headers)
722
+ target.label(response.items)
723
+ return response
599
724
 
600
725
  async def sections(
601
726
  self,
602
727
  history: UserHistoryInput,
603
728
  *,
604
729
  catalog_id: Optional[str] = None,
730
+ catalog_ids: Optional[Sequence[str]] = None,
605
731
  max_sections: int = 10,
606
732
  max_items_per_section: int = 25,
607
733
  min_items_per_section: int = 5,
@@ -609,7 +735,7 @@ class AsyncUnboxAIClient(_BaseClient):
609
735
  register_event: bool = False,
610
736
  ) -> SectionsResponse:
611
737
  """Items grouped into titled sections; see `UnboxAIClient.sections`."""
612
- body, headers = self._sections_request(
738
+ body, target = self._sections_request(
613
739
  history,
614
740
  catalog_id,
615
741
  filters,
@@ -617,8 +743,11 @@ class AsyncUnboxAIClient(_BaseClient):
617
743
  max_sections,
618
744
  max_items_per_section,
619
745
  min_items_per_section,
746
+ catalog_ids,
620
747
  )
621
- return await self._sections.create(body, headers=headers)
748
+ response = await self._sections.create(body, headers=target.headers)
749
+ target.label(item for section in response.sections for item in section.items)
750
+ return response
622
751
 
623
752
  async def embed(
624
753
  self,
@@ -705,20 +834,28 @@ class AsyncUnboxAIClient(_BaseClient):
705
834
 
706
835
  async def similar_items(
707
836
  self,
708
- item_id: str,
837
+ item_id: ItemRef,
709
838
  limit: int = 10,
710
839
  offset: int = 0,
711
840
  *,
712
841
  catalog_id: Optional[str] = None,
842
+ catalog_ids: Optional[Sequence[str]] = None,
843
+ filters: Optional[dict[str, Any]] = None,
713
844
  ) -> UnboxAIResponse:
714
- active_catalog, request_headers = self._catalog_headers(catalog_id)
715
- return await self.catalogs.get_similar_items(
716
- item_id,
717
- catalog_id=active_catalog,
845
+ """The items most like `item_id`; see `UnboxAIClient.similar_items`."""
846
+ target, item, item_catalog = self._similar_request(
847
+ item_id, catalog_id, catalog_ids
848
+ )
849
+ response = await self.catalogs.get_similar_items(
850
+ item,
851
+ catalog_id=item_catalog,
718
852
  limit=limit,
719
853
  offset=offset,
720
- headers=request_headers,
854
+ filters=filters,
855
+ headers=target.headers,
721
856
  )
857
+ target.label(response.items)
858
+ return response
722
859
 
723
860
  async def random_item(
724
861
  self, catalog_id: Optional[str] = None, window: int = 100
@@ -740,6 +877,25 @@ class AsyncUnboxAIClient(_BaseClient):
740
877
  await asyncio.sleep(UMAP_POLL)
741
878
 
742
879
 
880
+ def _by_catalog(event: UserEvent, target: _Target) -> list[tuple[str, UserEvent]]:
881
+ """An event as the API reads it, each with the catalog its items are in.
882
+ An event names one catalog, so an order of items from several becomes one
883
+ order per catalog."""
884
+ if isinstance(event, Order) and event.items:
885
+ groups: dict[str, list[CartItem]] = {}
886
+ for item in event.items:
887
+ groups.setdefault(target.of(item.catalog_id), []).append(item)
888
+ if len(groups) == 1:
889
+ return [(next(iter(groups)), event)]
890
+ return [
891
+ (catalog, event.model_copy(update={"items": items}))
892
+ for catalog, items in groups.items()
893
+ ]
894
+ if isinstance(event, (View, AddToCart, RemoveFromCart)):
895
+ return [(target.of(event.catalog_id), event)]
896
+ return [(target.primary, event)]
897
+
898
+
743
899
  def _pick_random(top: UnboxAIResponse, catalog_id: str) -> Item:
744
900
  if not top.items:
745
901
  raise ValueError(f"catalog {catalog_id!r} returned no items")
@@ -1,11 +1,17 @@
1
1
  import warnings
2
2
  from datetime import UTC, datetime
3
- from typing import List, Literal, Optional, Sequence, Tuple, Union
3
+ from typing import TYPE_CHECKING, List, Literal, Optional, Sequence, Tuple, Union
4
4
 
5
5
  from pydantic import AliasChoices, BaseModel, ConfigDict, Field
6
6
 
7
7
  from behaviorgpt.types.domains import Domains
8
8
 
9
+ if TYPE_CHECKING:
10
+ from behaviorgpt.types.http import Item
11
+
12
+ # an item id, or an `Item` of a response, which knows its catalog
13
+ ItemRef = Union[str, "Item"]
14
+
9
15
 
10
16
  class _ItemEvent(BaseModel):
11
17
  # the API calls the item "product"
@@ -15,8 +21,12 @@ class _ItemEvent(BaseModel):
15
21
  validation_alias=AliasChoices("item", "product"),
16
22
  serialization_alias="product",
17
23
  )
24
+ # the catalog the item is in, for a request over several catalogs
25
+ # (`catalog_ids=`); unset, the request's first catalog. Not sent as part of
26
+ # the event: it becomes the event's store_id.
27
+ catalog_id: Optional[str] = Field(default=None, exclude=True)
18
28
 
19
- def __init__(self, item: Optional[str] = None, **data):
29
+ def __init__(self, item: Optional[ItemRef] = None, **data):
20
30
  if "product" in data:
21
31
  warnings.warn(
22
32
  "`product=` is deprecated, use `item=`",
@@ -25,6 +35,10 @@ class _ItemEvent(BaseModel):
25
35
  )
26
36
  product = data.pop("product")
27
37
  item = product if item is None else item
38
+ if item is not None and not isinstance(item, str):
39
+ if data.get("catalog_id") is None:
40
+ data["catalog_id"] = item.catalog_id
41
+ item = item.id
28
42
  if item is not None:
29
43
  data["item"] = item
30
44
  super().__init__(**data)
@@ -41,7 +55,7 @@ class CartItem(_ItemEvent):
41
55
  quantity: int
42
56
 
43
57
  def __init__(
44
- self, item: Optional[str] = None, quantity: Optional[int] = None, **data
58
+ self, item: Optional[ItemRef] = None, quantity: Optional[int] = None, **data
45
59
  ):
46
60
  if quantity is not None:
47
61
  data["quantity"] = quantity
@@ -65,7 +79,7 @@ class View(_ItemEvent):
65
79
  class AddToCart(_ItemEvent):
66
80
  type: Literal["addToCart"] = "addToCart"
67
81
 
68
- def __init__(self, item: Optional[str] = None, **data):
82
+ def __init__(self, item: Optional[ItemRef] = None, **data):
69
83
  warnings.warn(
70
84
  "`AddToCart` is deprecated and will be removed in 0.7: the model reads "
71
85
  "it the same as `View`. Send a `View`, and list what was bought in "
@@ -79,7 +93,7 @@ class AddToCart(_ItemEvent):
79
93
  class RemoveFromCart(_ItemEvent):
80
94
  type: Literal["removeFromCart"] = "removeFromCart"
81
95
 
82
- def __init__(self, item: Optional[str] = None, **data):
96
+ def __init__(self, item: Optional[ItemRef] = None, **data):
83
97
  warnings.warn(
84
98
  "`RemoveFromCart` is deprecated and will be removed in 0.7: it does not "
85
99
  "change results. Leave the item out of `Order([...])` instead",
@@ -89,13 +103,16 @@ class RemoveFromCart(_ItemEvent):
89
103
  super().__init__(item, **data)
90
104
 
91
105
 
92
- OrderItem = Union[str, CartItem, Tuple[str, int]]
106
+ OrderItem = Union[ItemRef, CartItem, Tuple[ItemRef, int]]
93
107
 
94
108
 
95
109
  class Order(BaseModel):
96
- """A finished purchase of `items`: item ids, `(id, quantity)` pairs or
97
- `CartItem`s. The model reads only which items were bought; quantities and
98
- `cart_id` do not change results."""
110
+ """A finished purchase of `items`: item ids, `Item`s, `(item, quantity)`
111
+ pairs or `CartItem`s. The model reads only which items were bought;
112
+ quantities and `cart_id` do not change results.
113
+
114
+ In a request over several catalogs the items can come from any of them:
115
+ each is in the catalog its `Item` or `CartItem(catalog_id=)` names."""
99
116
 
100
117
  type: Literal["order"] = "order"
101
118
 
@@ -135,12 +152,12 @@ class Order(BaseModel):
135
152
 
136
153
 
137
154
  def _order_item(entry: OrderItem) -> CartItem:
138
- if isinstance(entry, str):
139
- return CartItem(entry, 1)
155
+ if isinstance(entry, CartItem):
156
+ return entry
140
157
  if isinstance(entry, tuple):
141
- item_id, quantity = entry
142
- return CartItem(item_id, quantity)
143
- return entry
158
+ item, quantity = entry
159
+ return CartItem(item, quantity)
160
+ return CartItem(entry, 1)
144
161
 
145
162
 
146
163
  UserEvent = Union[Search, AddToCart, View, RemoveFromCart, Order]
@@ -22,6 +22,11 @@ class Item(BaseModel):
22
22
  id: str
23
23
  data: dict
24
24
  score: float
25
+ # the catalog the item is in: an id is unique only within its catalog.
26
+ # "store_id" on the wire.
27
+ catalog_id: Optional[str] = Field(
28
+ default=None, validation_alias=AliasChoices("catalog_id", "store_id")
29
+ )
25
30
 
26
31
  def extract_price(self, market: str | None = None) -> Optional[float]:
27
32
  if "price" in self.data:
@@ -139,7 +144,12 @@ class UnboxAIResponse(BaseModel):
139
144
 
140
145
  items_data = []
141
146
  for item in self.items:
142
- flat_item = {"id": item.id, "score": item.score, **item.data}
147
+ flat_item = {
148
+ "id": item.id,
149
+ "catalog_id": item.catalog_id,
150
+ "score": item.score,
151
+ **item.data,
152
+ }
143
153
  flat_item["price"] = item.extract_price(self.market)
144
154
  items_data.append(flat_item)
145
155
 
@@ -183,6 +193,7 @@ class SimilarItemsRequest(BaseModel):
183
193
  validation_alias=AliasChoices("item_id", "product_id"),
184
194
  serialization_alias="product_id",
185
195
  )
196
+ # the catalog of the item; the results can come from several
186
197
  store_id: str
187
198
  limit: int = Field(default=10, ge=1, le=100)
188
199
  offset: int = Field(default=0, ge=0)
File without changes