behaviorgpt 0.6.2__tar.gz → 0.6.4__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.4
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,23 @@ 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
+ `catalog_ids` also draws several catalogs on one map, one colour each, so you can see where they overlap. The first request takes a few minutes; later ones for the same catalogs return the stored map:
138
+
139
+ ```python
140
+ page = client.umap(catalog_ids=[job.catalog_id, "retail_catalog"], wait=300)
141
+ with open("map.html", "w") as f:
142
+ f.write(page)
143
+ ```
144
+
145
+ [`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
146
 
129
147
  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
148
 
@@ -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,23 @@ 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
+ `catalog_ids` also draws several catalogs on one map, one colour each, so you can see where they overlap. The first request takes a few minutes; later ones for the same catalogs return the stored map:
121
+
122
+ ```python
123
+ page = client.umap(catalog_ids=[job.catalog_id, "retail_catalog"], wait=300)
124
+ with open("map.html", "w") as f:
125
+ f.write(page)
126
+ ```
127
+
128
+ [`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
129
 
112
130
  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
131
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "behaviorgpt"
3
- version = "0.6.2"
3
+ version = "0.6.4"
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.4"
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
@@ -22,6 +23,7 @@ from behaviorgpt.types import (
22
23
  AddKeywordsJobDetails,
23
24
  AddToCart,
24
25
  CartItem,
26
+ CatalogMap,
25
27
  CatalogSummary,
26
28
  Domains,
27
29
  EmbedJobDetails,
@@ -36,7 +38,9 @@ from behaviorgpt.types import (
36
38
  UnboxAIResponse,
37
39
  UserEvent,
38
40
  UserHistoryInput,
41
+ View,
39
42
  )
43
+ from behaviorgpt.types.events import ItemRef
40
44
  from behaviorgpt.types.http import RecommendationType
41
45
 
42
46
  # An embed upload streams the whole parquet, and the API answers only once the
@@ -47,6 +51,45 @@ DEFAULT_TRAILING_SEARCHES = 3
47
51
  UMAP_POLL = 5.0
48
52
 
49
53
  Predict = Literal["view", "purchase"]
54
+ CATALOG_IDS_HEADER = "x-catalog-ids"
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class _Target:
59
+ """The catalogs one request reads. Several (`catalog_ids=`) are ranked
60
+ together, and then every item names the catalog it is in."""
61
+
62
+ catalog_ids: tuple[str, ...]
63
+ multi: bool = False
64
+
65
+ @property
66
+ def primary(self) -> str:
67
+ return self.catalog_ids[0]
68
+
69
+ @property
70
+ def headers(self) -> dict:
71
+ if self.multi:
72
+ return {CATALOG_IDS_HEADER: ",".join(self.catalog_ids)}
73
+ return {"x-catalog-id": self.primary}
74
+
75
+ def of(self, catalog_id: Optional[str]) -> str:
76
+ """The catalog of an item that names `catalog_id`, or none."""
77
+ if catalog_id is None or catalog_id == self.primary:
78
+ return self.primary
79
+ if catalog_id not in self.catalog_ids:
80
+ hint = "" if self.multi else "; pass catalog_ids= to rank several"
81
+ raise ValueError(
82
+ f"an item is in catalog {catalog_id!r}, but this request reads "
83
+ f"{', '.join(map(repr, self.catalog_ids))}{hint}"
84
+ )
85
+ return catalog_id
86
+
87
+ def label(self, items: Iterable[Item]) -> None:
88
+ """Give each item of a response its catalog: the API names it only when
89
+ the request reads several."""
90
+ for item in items:
91
+ if item.catalog_id is None:
92
+ item.catalog_id = self.primary
50
93
 
51
94
 
52
95
  class _BaseClient:
@@ -59,7 +102,7 @@ class _BaseClient:
59
102
  timezone: str = "UTC",
60
103
  api_key: Optional[str] = None,
61
104
  base_url: str = DEFAULT_BASE_URL,
62
- default_catalog_id: str = "retail_catalog",
105
+ default_catalog_id: Optional[str] = None,
63
106
  ):
64
107
  self.api_key = api_key or os.environ.get("UNBOXAI_API_KEY")
65
108
  if not self.api_key:
@@ -67,16 +110,50 @@ class _BaseClient:
67
110
  raise AuthenticationError(msg)
68
111
 
69
112
  self.base_url = base_url
70
- self.default_catalog_id = default_catalog_id
113
+ # the catalog of calls that name none
114
+ self.default_catalog_id = (
115
+ default_catalog_id
116
+ or os.environ.get("UNBOXAI_CATALOG_ID")
117
+ or "retail_catalog"
118
+ )
71
119
 
72
120
  self.domains = Domains(market=market)
73
121
  self.timezone = timezone
74
122
 
75
123
  self.requester = UnboxAIRequester(domains=self.domains, timezone=self.timezone)
76
124
 
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}
125
+ def _target(
126
+ self, catalog_id: Optional[str], catalog_ids: Optional[Sequence[str]]
127
+ ) -> _Target:
128
+ if catalog_ids is None:
129
+ return _Target((catalog_id or self.default_catalog_id,))
130
+ if catalog_id is not None:
131
+ raise ValueError("pass catalog_id or catalog_ids, not both")
132
+ if isinstance(catalog_ids, str):
133
+ raise TypeError("catalog_ids takes a list of catalog ids, not a string")
134
+ ids = tuple(dict.fromkeys(catalog_ids))
135
+ if not ids:
136
+ raise ValueError("catalog_ids names no catalog")
137
+ return _Target(ids, multi=True)
138
+
139
+ def _similar_request(
140
+ self,
141
+ item: ItemRef,
142
+ catalog_id: Optional[str],
143
+ catalog_ids: Optional[Sequence[str]],
144
+ ) -> tuple[_Target, str, str]:
145
+ """The catalogs a similar-items request reads, and the id and catalog
146
+ of its item. The item's catalog is `catalog_id`, else the `Item`'s own;
147
+ over `catalog_ids` it must be one of them, by default the first."""
148
+ item_id = item if isinstance(item, str) else item.id
149
+ item_catalog = catalog_id or (
150
+ None if isinstance(item, str) else item.catalog_id
151
+ )
152
+ if catalog_ids is None:
153
+ target = self._target(item_catalog, None)
154
+ return target, item_id, target.primary
155
+ target = self._target(None, catalog_ids)
156
+ return target, item_id, target.of(item_catalog)
80
157
 
81
158
  def _complete_request(
82
159
  self,
@@ -88,13 +165,15 @@ class _BaseClient:
88
165
  register_event: bool,
89
166
  max_trailing_searches: int = DEFAULT_TRAILING_SEARCHES,
90
167
  predict: Predict = "view",
91
- ) -> tuple[bool, UnboxAIRequest, dict]:
92
- """The request `complete` sends, whether it goes to search, and its headers."""
168
+ catalog_ids: Optional[Sequence[str]] = None,
169
+ ) -> tuple[bool, UnboxAIRequest, _Target]:
170
+ """The request `complete` sends, whether it goes to search, and the
171
+ catalogs it reads."""
93
172
  if predict not in ("view", "purchase"):
94
173
  raise ValueError(f"predict must be 'view' or 'purchase', not {predict!r}")
95
- active_catalog, request_headers = self._catalog_headers(catalog_id)
174
+ target = self._target(catalog_id, catalog_ids)
96
175
 
97
- history_events = self.__from_sequence(active_catalog, history)
176
+ history_events = self.__from_sequence(target, history)
98
177
  last_event = self._get_last_event(history)
99
178
 
100
179
  if isinstance(last_event, Search):
@@ -106,18 +185,18 @@ class _BaseClient:
106
185
  req = self.requester.make(
107
186
  query=last_event.query,
108
187
  history=history_events[:-1],
109
- catalog_id=active_catalog,
188
+ catalog_id=target.primary,
110
189
  limit=limit,
111
190
  offset=offset,
112
191
  filters=filters,
113
192
  register_event=register_event,
114
193
  max_trailing_searches=max_trailing_searches,
115
194
  )
116
- return True, req, request_headers
195
+ return True, req, target
117
196
 
118
197
  req = self.requester.make(
119
198
  history=history_events,
120
- catalog_id=active_catalog,
199
+ catalog_id=target.primary,
121
200
  limit=limit,
122
201
  offset=offset,
123
202
  filters=filters,
@@ -126,7 +205,7 @@ class _BaseClient:
126
205
  RecommendationType(name="buy_next") if predict == "purchase" else None
127
206
  ),
128
207
  )
129
- return False, req, request_headers
208
+ return False, req, target
130
209
 
131
210
  def _sections_request(
132
211
  self,
@@ -137,18 +216,19 @@ class _BaseClient:
137
216
  max_sections: int,
138
217
  max_items_per_section: int,
139
218
  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
219
+ catalog_ids: Optional[Sequence[str]] = None,
220
+ ) -> tuple[dict, _Target]:
221
+ """The body `sections` sends, and the catalogs it reads."""
222
+ _, req, target = self._complete_request(
223
+ history, 10, 0, catalog_id, filters, register_event, catalog_ids=catalog_ids
144
224
  )
145
225
  body = sections_body(
146
226
  req, max_sections, max_items_per_section, min_items_per_section
147
227
  )
148
- return body, headers
228
+ return body, target
149
229
 
150
230
  def __from_sequence(
151
- self, catalog_id: str, context: UserHistoryInput
231
+ self, target: _Target, context: UserHistoryInput
152
232
  ) -> list[SessionEvent]:
153
233
  events: list[SessionEvent] = []
154
234
 
@@ -159,7 +239,7 @@ class _BaseClient:
159
239
  def _process_session_events(
160
240
  session_events: Sequence[UserEvent], session_id: str, session_offset: int
161
241
  ):
162
- cart_state: dict[str, int] = defaultdict(int)
242
+ cart_state: dict[tuple[Optional[str], str], int] = defaultdict(int)
163
243
  current_cart_id = str(uuid4())
164
244
 
165
245
  # Base time for the start of the sequence
@@ -167,17 +247,19 @@ class _BaseClient:
167
247
 
168
248
  for i, ev in enumerate(session_events):
169
249
  if isinstance(ev, AddToCart):
170
- cart_state[ev.item] += 1
250
+ cart_state[(ev.catalog_id, ev.item)] += 1
171
251
  elif isinstance(ev, RemoveFromCart):
172
- if cart_state[ev.item] > 1:
173
- cart_state[ev.item] -= 1
252
+ key = (ev.catalog_id, ev.item)
253
+ if cart_state[key] > 1:
254
+ cart_state[key] -= 1
174
255
  else:
175
- cart_state.pop(ev.item)
256
+ cart_state.pop(key)
176
257
  elif isinstance(ev, Order):
177
258
  if not getattr(ev, "items", None):
178
259
  ev.cart_id = current_cart_id
179
260
  ev.items = [
180
- CartItem(item, qty) for item, qty in cart_state.items()
261
+ CartItem(item, qty, catalog_id=catalog)
262
+ for (catalog, item), qty in cart_state.items()
181
263
  ]
182
264
  cart_state.clear()
183
265
  current_cart_id = str(uuid4())
@@ -189,9 +271,15 @@ class _BaseClient:
189
271
  milliseconds=(session_offset * 1000) + i
190
272
  )
191
273
 
192
- events.append(
193
- self.__to_session_evt(ev, session_id, catalog_id, event_time)
194
- )
274
+ for j, (catalog, event) in enumerate(_by_catalog(ev, target)):
275
+ events.append(
276
+ self.__to_session_evt(
277
+ event,
278
+ session_id,
279
+ catalog,
280
+ event_time + timedelta(microseconds=j),
281
+ )
282
+ )
195
283
 
196
284
  if isinstance(context[0], (list, tuple)):
197
285
  context_2d = cast(Sequence[Sequence[UserEvent]], context)
@@ -236,7 +324,7 @@ class UnboxAIClient(_BaseClient):
236
324
  timezone: str = "UTC",
237
325
  api_key: Optional[str] = None,
238
326
  base_url: str = DEFAULT_BASE_URL,
239
- default_catalog_id: str = "retail_catalog",
327
+ default_catalog_id: Optional[str] = None,
240
328
  http_timeout: float | httpx.Timeout = DEFAULT_HTTP_TIMEOUT,
241
329
  ):
242
330
  super().__init__(
@@ -264,6 +352,7 @@ class UnboxAIClient(_BaseClient):
264
352
  offset: int = 0,
265
353
  *,
266
354
  catalog_id: Optional[str] = None,
355
+ catalog_ids: Optional[Sequence[str]] = None,
267
356
  filters: Optional[dict[str, Any]] = None,
268
357
  register_event: bool = False,
269
358
  max_trailing_searches: int = DEFAULT_TRAILING_SEARCHES,
@@ -280,8 +369,16 @@ class UnboxAIClient(_BaseClient):
280
369
  When the history ends in searches, up to `max_trailing_searches` of
281
370
  them in a row, the query included, reach the model, so `nike` then
282
371
  `shoes` reads as one intent.
372
+
373
+ `catalog_ids` ranks several catalogs together instead of one, for
374
+ instance your own and `retail_catalog`: each item of the result says
375
+ which it is in (`item.catalog_id`). Items in the history are in the
376
+ first catalog unless they name another, `View(item_id,
377
+ catalog_id=...)`, or are `Item`s of an earlier response, which know
378
+ theirs. In `filters`, `catalog_id` is the item's catalog, e.g.
379
+ `{"catalog_id": "retail_catalog"}`.
283
380
  """
284
- is_search, req, headers = self._complete_request(
381
+ is_search, req, target = self._complete_request(
285
382
  history,
286
383
  limit,
287
384
  offset,
@@ -290,15 +387,19 @@ class UnboxAIClient(_BaseClient):
290
387
  register_event,
291
388
  max_trailing_searches,
292
389
  predict,
390
+ catalog_ids,
293
391
  )
294
392
  endpoint = self.search if is_search else self.recommendations
295
- return endpoint.create(payload=req, headers=headers)
393
+ response = endpoint.create(payload=req, headers=target.headers)
394
+ target.label(response.items)
395
+ return response
296
396
 
297
397
  def sections(
298
398
  self,
299
399
  history: UserHistoryInput,
300
400
  *,
301
401
  catalog_id: Optional[str] = None,
402
+ catalog_ids: Optional[Sequence[str]] = None,
302
403
  max_sections: int = 10,
303
404
  max_items_per_section: int = 25,
304
405
  min_items_per_section: int = 5,
@@ -317,8 +418,12 @@ class UnboxAIClient(_BaseClient):
317
418
  `max_sections` can be at most 15 and `max_items_per_section` at most
318
419
  100. Each item's `data` holds its generated search terms in
319
420
  `top_terms`, best first.
421
+
422
+ `catalog_ids` groups several catalogs together, as for `complete`: a
423
+ section can hold items of any of them, each weighed by its catalog's
424
+ size, so a small catalog does not crowd out a large one.
320
425
  """
321
- body, headers = self._sections_request(
426
+ body, target = self._sections_request(
322
427
  history,
323
428
  catalog_id,
324
429
  filters,
@@ -326,8 +431,11 @@ class UnboxAIClient(_BaseClient):
326
431
  max_sections,
327
432
  max_items_per_section,
328
433
  min_items_per_section,
434
+ catalog_ids,
329
435
  )
330
- return self._sections.create(body, headers=headers)
436
+ response = self._sections.create(body, headers=target.headers)
437
+ target.label(item for section in response.sections for item in section.items)
438
+ return response
331
439
 
332
440
  def embed(
333
441
  self,
@@ -462,20 +570,34 @@ class UnboxAIClient(_BaseClient):
462
570
 
463
571
  def similar_items(
464
572
  self,
465
- item_id: str,
573
+ item_id: ItemRef,
466
574
  limit: int = 10,
467
575
  offset: int = 0,
468
576
  *,
469
577
  catalog_id: Optional[str] = None,
578
+ catalog_ids: Optional[Sequence[str]] = None,
579
+ filters: Optional[dict[str, Any]] = None,
470
580
  ) -> 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,
581
+ """The items most like `item_id`, an item id or an `Item` of a
582
+ response, most similar first.
583
+
584
+ `catalog_id` is the catalog the item is in; for an `Item`, its own.
585
+ `catalog_ids` looks for similar items in several catalogs, the item's
586
+ among them (by default the first): each result says which it is in.
587
+ """
588
+ target, item, item_catalog = self._similar_request(
589
+ item_id, catalog_id, catalog_ids
590
+ )
591
+ response = self.catalogs.get_similar_items(
592
+ item,
593
+ catalog_id=item_catalog,
475
594
  limit=limit,
476
595
  offset=offset,
477
- headers=request_headers,
596
+ filters=filters,
597
+ headers=target.headers,
478
598
  )
599
+ target.label(response.items)
600
+ return response
479
601
 
480
602
  def similar_products(
481
603
  self, product_id: str, *args: Any, **kwargs: Any
@@ -502,7 +624,13 @@ class UnboxAIClient(_BaseClient):
502
624
  )
503
625
  return self.random_item(*args, **kwargs)
504
626
 
505
- def umap(self, *, catalog_id: Optional[str] = None, wait: float = 0.0) -> str:
627
+ def umap(
628
+ self,
629
+ *,
630
+ catalog_id: Optional[str] = None,
631
+ catalog_ids: Optional[Sequence[str]] = None,
632
+ wait: float = 0.0,
633
+ ) -> str:
506
634
  """The catalog's UMAP, a 2D map of its items, as an HTML page.
507
635
 
508
636
  Maps exist only for catalogs of up to 100,000 items, and appear within
@@ -511,12 +639,27 @@ class UnboxAIClient(_BaseClient):
511
639
  (such as the shared `retail_catalog`) never get one. A missing map
512
640
  raises `UnboxAIError` with status 404 and says which case applies.
513
641
 
642
+ `catalog_ids` lays several catalogs out on one map instead, one colour
643
+ each, so items of different catalogs that sit close together are
644
+ alike. It is drawn on request, within a few minutes, and kept until one
645
+ of the catalogs is uploaded again. Above 100,000 items every catalog is
646
+ sampled evenly, so any catalog can be mapped this way, `retail_catalog`
647
+ too, alone or with others. A map still being drawn when `wait` is up
648
+ raises `UnboxAIError` with status 202; asking again later finds it.
649
+
514
650
  `wait` is how many seconds to keep asking while the map is missing,
515
651
  for a catalog that just became ready. A catalog that never gets a map
516
652
  raises only once that time is up.
517
653
  """
518
- active_catalog: str = catalog_id or self.default_catalog_id
519
654
  deadline = time.monotonic() + wait
655
+ if catalog_ids is not None:
656
+ ids = self._target(catalog_id, catalog_ids).catalog_ids
657
+ joint = self.catalogs.create_map(catalog_ids=ids)
658
+ while not _map_ready(joint, deadline):
659
+ time.sleep(UMAP_POLL)
660
+ joint = self.catalogs.get_map(joint.map_id)
661
+ return self.catalogs.get_map_page(joint.map_id)
662
+ active_catalog: str = catalog_id or self.default_catalog_id
520
663
  while True:
521
664
  try:
522
665
  return self.catalogs.get_umap(catalog_id=active_catalog)
@@ -540,7 +683,7 @@ class AsyncUnboxAIClient(_BaseClient):
540
683
  timezone: str = "UTC",
541
684
  api_key: Optional[str] = None,
542
685
  base_url: str = DEFAULT_BASE_URL,
543
- default_catalog_id: str = "retail_catalog",
686
+ default_catalog_id: Optional[str] = None,
544
687
  http_timeout: float | httpx.Timeout = DEFAULT_HTTP_TIMEOUT,
545
688
  ):
546
689
  super().__init__(
@@ -577,6 +720,7 @@ class AsyncUnboxAIClient(_BaseClient):
577
720
  offset: int = 0,
578
721
  *,
579
722
  catalog_id: Optional[str] = None,
723
+ catalog_ids: Optional[Sequence[str]] = None,
580
724
  filters: Optional[dict[str, Any]] = None,
581
725
  register_event: bool = False,
582
726
  max_trailing_searches: int = DEFAULT_TRAILING_SEARCHES,
@@ -584,7 +728,7 @@ class AsyncUnboxAIClient(_BaseClient):
584
728
  ) -> UnboxAIResponse:
585
729
  """Rank the items most likely to come after `history`; see
586
730
  `UnboxAIClient.complete`."""
587
- is_search, req, headers = self._complete_request(
731
+ is_search, req, target = self._complete_request(
588
732
  history,
589
733
  limit,
590
734
  offset,
@@ -593,15 +737,19 @@ class AsyncUnboxAIClient(_BaseClient):
593
737
  register_event,
594
738
  max_trailing_searches,
595
739
  predict,
740
+ catalog_ids,
596
741
  )
597
742
  endpoint = self.search if is_search else self.recommendations
598
- return await endpoint.create(payload=req, headers=headers)
743
+ response = await endpoint.create(payload=req, headers=target.headers)
744
+ target.label(response.items)
745
+ return response
599
746
 
600
747
  async def sections(
601
748
  self,
602
749
  history: UserHistoryInput,
603
750
  *,
604
751
  catalog_id: Optional[str] = None,
752
+ catalog_ids: Optional[Sequence[str]] = None,
605
753
  max_sections: int = 10,
606
754
  max_items_per_section: int = 25,
607
755
  min_items_per_section: int = 5,
@@ -609,7 +757,7 @@ class AsyncUnboxAIClient(_BaseClient):
609
757
  register_event: bool = False,
610
758
  ) -> SectionsResponse:
611
759
  """Items grouped into titled sections; see `UnboxAIClient.sections`."""
612
- body, headers = self._sections_request(
760
+ body, target = self._sections_request(
613
761
  history,
614
762
  catalog_id,
615
763
  filters,
@@ -617,8 +765,11 @@ class AsyncUnboxAIClient(_BaseClient):
617
765
  max_sections,
618
766
  max_items_per_section,
619
767
  min_items_per_section,
768
+ catalog_ids,
620
769
  )
621
- return await self._sections.create(body, headers=headers)
770
+ response = await self._sections.create(body, headers=target.headers)
771
+ target.label(item for section in response.sections for item in section.items)
772
+ return response
622
773
 
623
774
  async def embed(
624
775
  self,
@@ -705,20 +856,28 @@ class AsyncUnboxAIClient(_BaseClient):
705
856
 
706
857
  async def similar_items(
707
858
  self,
708
- item_id: str,
859
+ item_id: ItemRef,
709
860
  limit: int = 10,
710
861
  offset: int = 0,
711
862
  *,
712
863
  catalog_id: Optional[str] = None,
864
+ catalog_ids: Optional[Sequence[str]] = None,
865
+ filters: Optional[dict[str, Any]] = None,
713
866
  ) -> 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,
867
+ """The items most like `item_id`; see `UnboxAIClient.similar_items`."""
868
+ target, item, item_catalog = self._similar_request(
869
+ item_id, catalog_id, catalog_ids
870
+ )
871
+ response = await self.catalogs.get_similar_items(
872
+ item,
873
+ catalog_id=item_catalog,
718
874
  limit=limit,
719
875
  offset=offset,
720
- headers=request_headers,
876
+ filters=filters,
877
+ headers=target.headers,
721
878
  )
879
+ target.label(response.items)
880
+ return response
722
881
 
723
882
  async def random_item(
724
883
  self, catalog_id: Optional[str] = None, window: int = 100
@@ -727,10 +886,23 @@ class AsyncUnboxAIClient(_BaseClient):
727
886
  top = await self.complete(history=[], catalog_id=catalog_id, limit=window)
728
887
  return _pick_random(top, catalog_id or self.default_catalog_id)
729
888
 
730
- async def umap(self, *, catalog_id: Optional[str] = None, wait: float = 0.0) -> str:
889
+ async def umap(
890
+ self,
891
+ *,
892
+ catalog_id: Optional[str] = None,
893
+ catalog_ids: Optional[Sequence[str]] = None,
894
+ wait: float = 0.0,
895
+ ) -> str:
731
896
  """The catalog's UMAP as an HTML page; see `UnboxAIClient.umap`."""
732
- active_catalog: str = catalog_id or self.default_catalog_id
733
897
  deadline = time.monotonic() + wait
898
+ if catalog_ids is not None:
899
+ ids = self._target(catalog_id, catalog_ids).catalog_ids
900
+ joint = await self.catalogs.create_map(catalog_ids=ids)
901
+ while not _map_ready(joint, deadline):
902
+ await asyncio.sleep(UMAP_POLL)
903
+ joint = await self.catalogs.get_map(joint.map_id)
904
+ return await self.catalogs.get_map_page(joint.map_id)
905
+ active_catalog: str = catalog_id or self.default_catalog_id
734
906
  while True:
735
907
  try:
736
908
  return await self.catalogs.get_umap(catalog_id=active_catalog)
@@ -740,6 +912,46 @@ class AsyncUnboxAIClient(_BaseClient):
740
912
  await asyncio.sleep(UMAP_POLL)
741
913
 
742
914
 
915
+ def _map_ready(joint: CatalogMap, deadline: float) -> bool:
916
+ """Whether the map can be read; raises when it failed, or when it is still
917
+ being drawn and polling once more would pass `deadline`."""
918
+ if joint.status == "ready":
919
+ return True
920
+ catalogs = ", ".join(joint.catalog_ids)
921
+ if joint.status == "failed":
922
+ raise UnboxAIError(
923
+ f"the map of {catalogs} failed: {joint.error}",
924
+ response=joint.model_dump(mode="json"),
925
+ )
926
+ if time.monotonic() + UMAP_POLL > deadline:
927
+ raise UnboxAIError(
928
+ f"the map of {catalogs} is still being drawn ({joint.map_id}); pass "
929
+ "wait= (seconds) to wait for it, e.g. wait=300, or ask again later",
930
+ status_code=202,
931
+ response=joint.model_dump(mode="json"),
932
+ )
933
+ return False
934
+
935
+
936
+ def _by_catalog(event: UserEvent, target: _Target) -> list[tuple[str, UserEvent]]:
937
+ """An event as the API reads it, each with the catalog its items are in.
938
+ An event names one catalog, so an order of items from several becomes one
939
+ order per catalog."""
940
+ if isinstance(event, Order) and event.items:
941
+ groups: dict[str, list[CartItem]] = {}
942
+ for item in event.items:
943
+ groups.setdefault(target.of(item.catalog_id), []).append(item)
944
+ if len(groups) == 1:
945
+ return [(next(iter(groups)), event)]
946
+ return [
947
+ (catalog, event.model_copy(update={"items": items}))
948
+ for catalog, items in groups.items()
949
+ ]
950
+ if isinstance(event, (View, AddToCart, RemoveFromCart)):
951
+ return [(target.of(event.catalog_id), event)]
952
+ return [(target.primary, event)]
953
+
954
+
743
955
  def _pick_random(top: UnboxAIResponse, catalog_id: str) -> Item:
744
956
  if not top.items:
745
957
  raise ValueError(f"catalog {catalog_id!r} returned no items")
@@ -5,7 +5,7 @@ import time
5
5
  import warnings
6
6
  from datetime import UTC, datetime
7
7
  from pathlib import Path
8
- from typing import Any, Callable, Optional, TextIO
8
+ from typing import Any, Callable, Optional, Sequence, TextIO
9
9
  from urllib.parse import quote
10
10
 
11
11
  import httpx
@@ -19,6 +19,7 @@ from behaviorgpt.resources._shared import handle_response
19
19
  from behaviorgpt.types import (
20
20
  AddItemsJobDetails,
21
21
  AddKeywordsJobDetails,
22
+ CatalogMap,
22
23
  CatalogSummary,
23
24
  EmbedJobDetails,
24
25
  JobStatus,
@@ -355,6 +356,16 @@ def umap_page(response: httpx.Response) -> str:
355
356
  return response.text
356
357
 
357
358
 
359
+ def map_body(catalog_ids: Sequence[str]) -> dict:
360
+ if isinstance(catalog_ids, str):
361
+ raise TypeError("catalog_ids takes a list of catalog ids, not a string")
362
+ return {"catalog_ids": list(dict.fromkeys(catalog_ids))}
363
+
364
+
365
+ def map_path(map_id: str, part: str = "") -> str:
366
+ return f"/maps/{quote(map_id, safe='')}" + (f"/{part}" if part else "")
367
+
368
+
358
369
  class JobWatcher:
359
370
  """The rules `wait_for_job` polls by, for the sync and the async client alike.
360
371
 
@@ -650,6 +661,24 @@ class Catalogs:
650
661
  def get_umap(self, *, catalog_id: str):
651
662
  return umap_page(self._client.get(f"/{catalog_id}/umap"))
652
663
 
664
+ def create_map(self, *, catalog_ids: Sequence[str]) -> CatalogMap:
665
+ """Ask for one map of these catalogs; it is drawn in the background
666
+ unless it already exists. `UnboxAIClient.umap(catalog_ids=...)` waits
667
+ for it and returns its page."""
668
+ response = self._client.post("/maps", json=map_body(catalog_ids))
669
+ return CatalogMap(**handle_response(response))
670
+
671
+ def get_map(self, map_id: str) -> CatalogMap:
672
+ return CatalogMap(**handle_response(self._client.get(map_path(map_id))))
673
+
674
+ def get_map_page(self, map_id: str) -> str:
675
+ return umap_page(self._client.get(map_path(map_id, "page")))
676
+
677
+ def get_map_points(self, map_id: str) -> dict:
678
+ """The map as data, to draw it yourself: one list per field and one
679
+ entry per item, `catalog` indexing `catalogs`."""
680
+ return handle_response(self._client.get(map_path(map_id, "points")))
681
+
653
682
  def list_catalogs(self) -> list[CatalogSummary]:
654
683
  return catalog_summaries(self._client.get("/catalogs"))
655
684
 
@@ -800,6 +829,19 @@ class AsyncCatalogs:
800
829
  async def get_umap(self, *, catalog_id: str) -> str:
801
830
  return umap_page(await self._client.get(f"/{catalog_id}/umap"))
802
831
 
832
+ async def create_map(self, *, catalog_ids: Sequence[str]) -> CatalogMap:
833
+ response = await self._client.post("/maps", json=map_body(catalog_ids))
834
+ return CatalogMap(**handle_response(response))
835
+
836
+ async def get_map(self, map_id: str) -> CatalogMap:
837
+ return CatalogMap(**handle_response(await self._client.get(map_path(map_id))))
838
+
839
+ async def get_map_page(self, map_id: str) -> str:
840
+ return umap_page(await self._client.get(map_path(map_id, "page")))
841
+
842
+ async def get_map_points(self, map_id: str) -> dict:
843
+ return handle_response(await self._client.get(map_path(map_id, "points")))
844
+
803
845
  async def list_catalogs(self) -> list[CatalogSummary]:
804
846
  return catalog_summaries(await self._client.get("/catalogs"))
805
847
 
@@ -17,6 +17,7 @@ from behaviorgpt.types.events import (
17
17
  from behaviorgpt.types.http import (
18
18
  AddItemsJobDetails,
19
19
  AddKeywordsJobDetails,
20
+ CatalogMap,
20
21
  CatalogSummary,
21
22
  EmbedJobDetails,
22
23
  Item,
@@ -47,6 +48,7 @@ __all__ = [
47
48
  "EmbedJobDetails",
48
49
  "AddItemsJobDetails",
49
50
  "AddKeywordsJobDetails",
51
+ "CatalogMap",
50
52
  "CatalogSummary",
51
53
  "JobStatus",
52
54
  "ItemsRejected",
@@ -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
 
@@ -176,6 +186,19 @@ class CatalogSummary(BaseModel):
176
186
  owned: bool
177
187
 
178
188
 
189
+ class CatalogMap(BaseModel):
190
+ """A map of several catalogs laid out together (`POST /maps`)."""
191
+
192
+ # the same for the same catalogs until one of them is uploaded again
193
+ map_id: str
194
+ # "building", "ready" or "failed"
195
+ status: str
196
+ catalog_ids: list[str]
197
+ requested_at: Optional[datetime] = None
198
+ # why the map failed; asking for it again retries it
199
+ error: Optional[str] = None
200
+
201
+
179
202
  class SimilarItemsRequest(BaseModel):
180
203
  model_config = ConfigDict(serialize_by_alias=True)
181
204
 
@@ -183,6 +206,7 @@ class SimilarItemsRequest(BaseModel):
183
206
  validation_alias=AliasChoices("item_id", "product_id"),
184
207
  serialization_alias="product_id",
185
208
  )
209
+ # the catalog of the item; the results can come from several
186
210
  store_id: str
187
211
  limit: int = Field(default=10, ge=1, le=100)
188
212
  offset: int = Field(default=0, ge=0)
File without changes