behaviorgpt 0.1.0__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Unbox AI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,120 @@
1
+ Metadata-Version: 2.4
2
+ Name: behaviorgpt
3
+ Version: 0.1.0
4
+ Summary: Python client for BehaviorGPT, UnboxAI's Large Behavioral Model for search, recommendations and personalization
5
+ Keywords: recommendations,personalization,search,behavioral model,unboxai
6
+ Author: Unbox AI
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Requires-Dist: httpx>=0.28.1
10
+ Requires-Dist: pyarrow>=25.0.1
11
+ Requires-Dist: pydantic>=2.13.4
12
+ Requires-Python: >=3.11
13
+ Project-URL: Homepage, https://unboxai.com/behaviorgpt
14
+ Project-URL: Repository, https://github.com/Unbox-AI/behaviorgpt
15
+ Project-URL: Demo, https://behaviorgpt.unboxai.com/
16
+ Description-Content-Type: text/markdown
17
+
18
+ # BehaviorGPT
19
+
20
+ **The foundation model for behavior.**
21
+
22
+ **BehaviorGPT** is UnboxAI's Large Behavioral Model. It is trained on long sequences of things people actually did (viewed this, added that, bought the other) and predicts what comes next, so search, recommendations and personalization are the same call with different histories. BehaviorGPT-v4 is a single 12.5B-parameter model pretrained on 150 billion user actions across retail, engagement and payments, and it ranks catalogs it has never seen with no training.
23
+
24
+ [Website](https://unboxai.com/behaviorgpt) · [Live demo](https://behaviorgpt.unboxai.com/) · [Research](https://research.unboxai.com) · [Notebook](https://github.com/Unbox-AI/behaviorgpt/blob/main/notebooks/showcase.ipynb)
25
+
26
+ This repository holds the Python client for the UnboxAI API and a notebook that walks through the model step by step.
27
+
28
+ ## Requirements
29
+
30
+ - An UnboxAI API key. Create & copy the key at [unboxai.com/behaviorgpt](https://unboxai.com/behaviorgpt); the key also arrives by email.
31
+ - Python 3.11 or newer.
32
+
33
+ ## Quick start
34
+
35
+ ```sh
36
+ pip install behaviorgpt
37
+ export UNBOXAI_API_KEY=... # or pass api_key= to UnboxAIClient
38
+ ```
39
+
40
+ ```python
41
+ from behaviorgpt import Search, UnboxAIClient, View
42
+
43
+ client = UnboxAIClient(market="us")
44
+
45
+ # a history of one search
46
+ res = client.complete([Search("running shoes")], limit=5)
47
+ print(res.names)
48
+
49
+ # the same call, personalized: a viewed item (Nike pants), then a query
50
+ res = client.complete([View("paB08NYK61PJ"), Search("shoes")], limit=5)
51
+ print(res.names)
52
+
53
+ # items close to one another in the model's space
54
+ print(client.similar_items(res.items[0].id).names)
55
+ ```
56
+
57
+ `complete` takes the history and returns the items most likely to come next. Each result in `res.items` has an `id`, a `score` and the catalog row in `data`; `res.to_pandas()` gives a DataFrame if pandas is installed.
58
+
59
+ ## How it works
60
+
61
+ - **One call, many features.** Every request asks the same question: given what this person did, which items are they most likely to act on next? The history picks the feature. End it with a `Search` for search results, with a `View` for "more like this", with an `Order` for what is bought next; leave it empty for a cold start.
62
+ - **The whole sequence counts.** The model reads the history in order, so the same query means different things after different actions: "gloves" after "golf clubs" returns golf gloves. `market` on the client says where the user is, which helps most when the history is short.
63
+ - **Items are read from their content, not their ids.** Each item is embedded from its name, brand, categories, image and price. That is why the model can rank a catalog it has never seen as soon as it is uploaded, with no interaction data and no training, and why those columns decide how well it does ([catalog format](https://github.com/Unbox-AI/behaviorgpt/blob/main/docs/catalog-format.md)).
64
+ - **One pass per request.** Item vectors are computed once when the catalog is embedded, so ranking the whole catalog costs one forward pass over the history rather than one per item: the model itself takes under a millisecond per query, and most of an API call's time is the network.
65
+
66
+ ## The notebook
67
+
68
+ [`notebooks/showcase.ipynb`](https://github.com/Unbox-AI/behaviorgpt/blob/main/notebooks/showcase.ipynb) covers the model in eight steps: setup, a first query, one call for many features, how context changes the answer, then embedding your own catalog, inspecting the embedding space, querying it, and trying it in the demo.
69
+
70
+ Needs [uv](https://github.com/astral-sh/uv). Clone, install, add your key, register the kernel, start JupyterLab:
71
+
72
+ ```sh
73
+ git clone https://github.com/Unbox-AI/behaviorgpt.git
74
+ cd behaviorgpt
75
+ uv sync
76
+ cp .env.example .env # paste your key as UNBOXAI_API_KEY
77
+ uv run ipython kernel install --user --env VIRTUAL_ENV $(pwd)/.venv --name=behaviorgpt-env
78
+ uv run jupyter lab
79
+ ```
80
+
81
+ JupyterLab opens in your browser. Open the notebook and pick the `behaviorgpt-env` kernel.
82
+
83
+ ## Your own catalog
84
+
85
+ The model can only return items it knows about. Out of the box the client uses `retail_catalog`, a sample retail catalog. To use the model on your own data, upload your catalog as a parquet file. A catalog doesn't have to be products for sale: artworks, articles, listings or anything else people browse and pick from work the same way.
86
+
87
+ - The required columns and types are described in [`docs/catalog-format.md`](https://github.com/Unbox-AI/behaviorgpt/blob/main/docs/catalog-format.md).
88
+ - A catalog can hold at most 20 000 items.
89
+ - Each API key can hold 2 catalogs. The file name is the catalog's name: uploading a file with the same name again refreshes that catalog and keeps its `catalog_id`, and a new name takes one of the 2 slots. A failed upload does not use up a slot. Once both slots are in use, an upload under a new name is refused; to remove a catalog or raise the limit, contact alexander@unboxai.com.
90
+ - [`examples/sample_catalog.csv`](https://github.com/Unbox-AI/behaviorgpt/blob/main/examples/sample_catalog.csv) is an example only, showing what each column should contain. Your own file will look different depending on your catalog, and it has to be converted to the parquet structure described in the format doc before upload.
91
+
92
+ ```python
93
+ job = client.embed("my_catalog.parquet", wait=True, timeout=1800.0)
94
+ client.complete([Search("...")], catalog_id=job.catalog_id)
95
+ ```
96
+
97
+ 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.
98
+
99
+ ### Events
100
+
101
+ A history is a list of `Search`, `View`, `AddToCart`, `RemoveFromCart` and `Order` events. The names come from a store because that is what the API accepts, but they work for any catalog: map your users' actions by meaning. Curate my wall, below, sends "look closer" as `View`, "hang it on the wall" as `AddToCart` and "take it down" as `RemoveFromCart`.
102
+
103
+ ## Demo and examples
104
+
105
+ Two apps built on this SDK, one on a store's catalog and one on a museum's:
106
+
107
+ <table>
108
+ <tr>
109
+ <td width="50%"><a href="https://behaviorgpt.unboxai.com/"><img src="https://raw.githubusercontent.com/Unbox-AI/behaviorgpt/main/docs/images/storefront.png" alt="The storefront demo: after a search for golf clubs, a search for gloves returns golf gloves"></a></td>
110
+ <td width="50%"><a href="https://github.com/Unbox-AI/aic-artworks"><img src="https://raw.githubusercontent.com/Unbox-AI/behaviorgpt/main/docs/images/curate-my-wall.png" alt="Curate my wall: three Hokusai prints hung on the wall, and the fashion they lead to: printed scarves, a tiger-print tee and a kimono"></a></td>
111
+ </tr>
112
+ <tr>
113
+ <td><b>Storefront</b> (<a href="https://behaviorgpt.unboxai.com/">live demo</a>). "gloves" after "golf clubs" returns golf gloves; the panel shows the history the model read.</td>
114
+ <td><b>Curate my wall</b> (<a href="https://aic-artworks.streamlit.app/">live app</a>, <a href="https://github.com/Unbox-AI/aic-artworks">source</a>). Hang three Hokusai prints and the same clicks pick your clothes: scarves and kimonos from an art history alone.</td>
115
+ </tr>
116
+ </table>
117
+
118
+ - [behaviorgpt.unboxai.com](https://behaviorgpt.unboxai.com/): a storefront, with recommendations, personalized search and a cart driven by the shopper's clicks. To try it on your catalog once it is embedded, select the **BehaviorGPT V4.0-12.5B** model, choose **Bring your own catalog** and enter your API key. Images must be publicly reachable for the demo to display them.
119
+ - [Curate my wall](https://github.com/Unbox-AI/aic-artworks) ([live app](https://aic-artworks.streamlit.app/)): an art recommender over 19 000 public-domain artworks from the Art Institute of Chicago. It shows the whole path for a catalog that isn't products: turning an open dataset into a catalog, embedding it, and driving recommendations, search, similar items and the embedding map from a visitor's clicks.
120
+ - **Art to fashion.** Its fashion pilot puts H&M clothing in the same catalog as the art, and the "Fashion for you" tab ranks it from the visitor's art clicks alone: kimonos for Japanese prints, beaded bracelets for ancient Egypt, statement earrings for portraits. No event in the history involves clothing. It works because both are in one catalog, so a history of art clicks ranks the clothing too; a `filters` query keeps the art grids art-only.
@@ -0,0 +1,103 @@
1
+ # BehaviorGPT
2
+
3
+ **The foundation model for behavior.**
4
+
5
+ **BehaviorGPT** is UnboxAI's Large Behavioral Model. It is trained on long sequences of things people actually did (viewed this, added that, bought the other) and predicts what comes next, so search, recommendations and personalization are the same call with different histories. BehaviorGPT-v4 is a single 12.5B-parameter model pretrained on 150 billion user actions across retail, engagement and payments, and it ranks catalogs it has never seen with no training.
6
+
7
+ [Website](https://unboxai.com/behaviorgpt) · [Live demo](https://behaviorgpt.unboxai.com/) · [Research](https://research.unboxai.com) · [Notebook](https://github.com/Unbox-AI/behaviorgpt/blob/main/notebooks/showcase.ipynb)
8
+
9
+ This repository holds the Python client for the UnboxAI API and a notebook that walks through the model step by step.
10
+
11
+ ## Requirements
12
+
13
+ - An UnboxAI API key. Create & copy the key at [unboxai.com/behaviorgpt](https://unboxai.com/behaviorgpt); the key also arrives by email.
14
+ - Python 3.11 or newer.
15
+
16
+ ## Quick start
17
+
18
+ ```sh
19
+ pip install behaviorgpt
20
+ export UNBOXAI_API_KEY=... # or pass api_key= to UnboxAIClient
21
+ ```
22
+
23
+ ```python
24
+ from behaviorgpt import Search, UnboxAIClient, View
25
+
26
+ client = UnboxAIClient(market="us")
27
+
28
+ # a history of one search
29
+ res = client.complete([Search("running shoes")], limit=5)
30
+ print(res.names)
31
+
32
+ # the same call, personalized: a viewed item (Nike pants), then a query
33
+ res = client.complete([View("paB08NYK61PJ"), Search("shoes")], limit=5)
34
+ print(res.names)
35
+
36
+ # items close to one another in the model's space
37
+ print(client.similar_items(res.items[0].id).names)
38
+ ```
39
+
40
+ `complete` takes the history and returns the items most likely to come next. Each result in `res.items` has an `id`, a `score` and the catalog row in `data`; `res.to_pandas()` gives a DataFrame if pandas is installed.
41
+
42
+ ## How it works
43
+
44
+ - **One call, many features.** Every request asks the same question: given what this person did, which items are they most likely to act on next? The history picks the feature. End it with a `Search` for search results, with a `View` for "more like this", with an `Order` for what is bought next; leave it empty for a cold start.
45
+ - **The whole sequence counts.** The model reads the history in order, so the same query means different things after different actions: "gloves" after "golf clubs" returns golf gloves. `market` on the client says where the user is, which helps most when the history is short.
46
+ - **Items are read from their content, not their ids.** Each item is embedded from its name, brand, categories, image and price. That is why the model can rank a catalog it has never seen as soon as it is uploaded, with no interaction data and no training, and why those columns decide how well it does ([catalog format](https://github.com/Unbox-AI/behaviorgpt/blob/main/docs/catalog-format.md)).
47
+ - **One pass per request.** Item vectors are computed once when the catalog is embedded, so ranking the whole catalog costs one forward pass over the history rather than one per item: the model itself takes under a millisecond per query, and most of an API call's time is the network.
48
+
49
+ ## The notebook
50
+
51
+ [`notebooks/showcase.ipynb`](https://github.com/Unbox-AI/behaviorgpt/blob/main/notebooks/showcase.ipynb) covers the model in eight steps: setup, a first query, one call for many features, how context changes the answer, then embedding your own catalog, inspecting the embedding space, querying it, and trying it in the demo.
52
+
53
+ Needs [uv](https://github.com/astral-sh/uv). Clone, install, add your key, register the kernel, start JupyterLab:
54
+
55
+ ```sh
56
+ git clone https://github.com/Unbox-AI/behaviorgpt.git
57
+ cd behaviorgpt
58
+ uv sync
59
+ cp .env.example .env # paste your key as UNBOXAI_API_KEY
60
+ uv run ipython kernel install --user --env VIRTUAL_ENV $(pwd)/.venv --name=behaviorgpt-env
61
+ uv run jupyter lab
62
+ ```
63
+
64
+ JupyterLab opens in your browser. Open the notebook and pick the `behaviorgpt-env` kernel.
65
+
66
+ ## Your own catalog
67
+
68
+ The model can only return items it knows about. Out of the box the client uses `retail_catalog`, a sample retail catalog. To use the model on your own data, upload your catalog as a parquet file. A catalog doesn't have to be products for sale: artworks, articles, listings or anything else people browse and pick from work the same way.
69
+
70
+ - The required columns and types are described in [`docs/catalog-format.md`](https://github.com/Unbox-AI/behaviorgpt/blob/main/docs/catalog-format.md).
71
+ - A catalog can hold at most 20 000 items.
72
+ - Each API key can hold 2 catalogs. The file name is the catalog's name: uploading a file with the same name again refreshes that catalog and keeps its `catalog_id`, and a new name takes one of the 2 slots. A failed upload does not use up a slot. Once both slots are in use, an upload under a new name is refused; to remove a catalog or raise the limit, contact alexander@unboxai.com.
73
+ - [`examples/sample_catalog.csv`](https://github.com/Unbox-AI/behaviorgpt/blob/main/examples/sample_catalog.csv) is an example only, showing what each column should contain. Your own file will look different depending on your catalog, and it has to be converted to the parquet structure described in the format doc before upload.
74
+
75
+ ```python
76
+ job = client.embed("my_catalog.parquet", wait=True, timeout=1800.0)
77
+ client.complete([Search("...")], catalog_id=job.catalog_id)
78
+ ```
79
+
80
+ 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.
81
+
82
+ ### Events
83
+
84
+ A history is a list of `Search`, `View`, `AddToCart`, `RemoveFromCart` and `Order` events. The names come from a store because that is what the API accepts, but they work for any catalog: map your users' actions by meaning. Curate my wall, below, sends "look closer" as `View`, "hang it on the wall" as `AddToCart` and "take it down" as `RemoveFromCart`.
85
+
86
+ ## Demo and examples
87
+
88
+ Two apps built on this SDK, one on a store's catalog and one on a museum's:
89
+
90
+ <table>
91
+ <tr>
92
+ <td width="50%"><a href="https://behaviorgpt.unboxai.com/"><img src="https://raw.githubusercontent.com/Unbox-AI/behaviorgpt/main/docs/images/storefront.png" alt="The storefront demo: after a search for golf clubs, a search for gloves returns golf gloves"></a></td>
93
+ <td width="50%"><a href="https://github.com/Unbox-AI/aic-artworks"><img src="https://raw.githubusercontent.com/Unbox-AI/behaviorgpt/main/docs/images/curate-my-wall.png" alt="Curate my wall: three Hokusai prints hung on the wall, and the fashion they lead to: printed scarves, a tiger-print tee and a kimono"></a></td>
94
+ </tr>
95
+ <tr>
96
+ <td><b>Storefront</b> (<a href="https://behaviorgpt.unboxai.com/">live demo</a>). "gloves" after "golf clubs" returns golf gloves; the panel shows the history the model read.</td>
97
+ <td><b>Curate my wall</b> (<a href="https://aic-artworks.streamlit.app/">live app</a>, <a href="https://github.com/Unbox-AI/aic-artworks">source</a>). Hang three Hokusai prints and the same clicks pick your clothes: scarves and kimonos from an art history alone.</td>
98
+ </tr>
99
+ </table>
100
+
101
+ - [behaviorgpt.unboxai.com](https://behaviorgpt.unboxai.com/): a storefront, with recommendations, personalized search and a cart driven by the shopper's clicks. To try it on your catalog once it is embedded, select the **BehaviorGPT V4.0-12.5B** model, choose **Bring your own catalog** and enter your API key. Images must be publicly reachable for the demo to display them.
102
+ - [Curate my wall](https://github.com/Unbox-AI/aic-artworks) ([live app](https://aic-artworks.streamlit.app/)): an art recommender over 19 000 public-domain artworks from the Art Institute of Chicago. It shows the whole path for a catalog that isn't products: turning an open dataset into a catalog, embedding it, and driving recommendations, search, similar items and the embedding map from a visitor's clicks.
103
+ - **Art to fashion.** Its fashion pilot puts H&M clothing in the same catalog as the art, and the "Fashion for you" tab ranks it from the visitor's art clicks alone: kimonos for Japanese prints, beaded bracelets for ancient Egypt, statement earrings for portraits. No event in the history involves clothing. It works because both are in one catalog, so a history of art clicks ranks the clothing too; a `filters` query keeps the art grids art-only.
@@ -0,0 +1,64 @@
1
+ [project]
2
+ name = "behaviorgpt"
3
+ version = "0.1.0"
4
+ description = "Python client for BehaviorGPT, UnboxAI's Large Behavioral Model for search, recommendations and personalization"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ keywords = [
9
+ "recommendations",
10
+ "personalization",
11
+ "search",
12
+ "behavioral model",
13
+ "unboxai",
14
+ ]
15
+ requires-python = ">=3.11"
16
+ dependencies = [
17
+ "httpx>=0.28.1",
18
+ "pyarrow>=25.0.1",
19
+ "pydantic>=2.13.4",
20
+ ]
21
+
22
+ [[project.authors]]
23
+ name = "Unbox AI"
24
+
25
+ [project.urls]
26
+ Homepage = "https://unboxai.com/behaviorgpt"
27
+ Repository = "https://github.com/Unbox-AI/behaviorgpt"
28
+ Demo = "https://behaviorgpt.unboxai.com/"
29
+
30
+ [build-system]
31
+ requires = ["uv_build>=0.12.3,<0.13.0"]
32
+ build-backend = "uv_build"
33
+
34
+ [dependency-groups]
35
+ dev = [
36
+ "ipykernel>=7.3.0",
37
+ "jupyterlab>=4.6.3",
38
+ "matplotlib>=3.11.1",
39
+ "pandas>=3.0.5",
40
+ "pillow>=12.3.0",
41
+ "pytest>=9.1.1",
42
+ "python-dotenv>=1.2.3",
43
+ "requests>=2.34.2",
44
+ "ruff>=0.16.2",
45
+ ]
46
+
47
+ [tool.ruff]
48
+ target-version = "py311"
49
+ line-length = 88
50
+ exclude = ["notebooks/*"]
51
+
52
+ [tool.ruff.lint]
53
+ select = [
54
+ "E",
55
+ "F",
56
+ "I",
57
+ ]
58
+
59
+ [tool.ruff.lint.isort]
60
+ known-first-party = ["behaviorgpt"]
61
+
62
+ [tool.pytest.ini_options]
63
+ testpaths = ["tests"]
64
+ addopts = "-ra --strict-markers"
@@ -0,0 +1,54 @@
1
+ [project]
2
+ name = "behaviorgpt"
3
+ version = "0.1.0"
4
+ description = "Python client for BehaviorGPT, UnboxAI's Large Behavioral Model for search, recommendations and personalization"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "Unbox AI" }]
9
+ keywords = ["recommendations", "personalization", "search", "behavioral model", "unboxai"]
10
+ requires-python = ">=3.11"
11
+ dependencies = [
12
+ "httpx>=0.28.1",
13
+ "pyarrow>=25.0.1",
14
+ "pydantic>=2.13.4",
15
+ ]
16
+
17
+ [project.urls]
18
+ Homepage = "https://unboxai.com/behaviorgpt"
19
+ Repository = "https://github.com/Unbox-AI/behaviorgpt"
20
+ Demo = "https://behaviorgpt.unboxai.com/"
21
+
22
+ [build-system]
23
+ requires = ["uv_build>=0.12.3,<0.13.0"]
24
+ build-backend = "uv_build"
25
+
26
+ [dependency-groups]
27
+ dev = [
28
+ "ipykernel>=7.3.0",
29
+ "jupyterlab>=4.6.3",
30
+ "matplotlib>=3.11.1",
31
+ "pandas>=3.0.5",
32
+ "pillow>=12.3.0",
33
+ "pytest>=9.1.1",
34
+ "python-dotenv>=1.2.3",
35
+ "requests>=2.34.2",
36
+ "ruff>=0.16.2",
37
+ ]
38
+
39
+ [tool.ruff.lint]
40
+ select = ["E", "F", "I"]
41
+
42
+ [tool.ruff]
43
+ target-version = "py311"
44
+ line-length = 88
45
+ exclude = [
46
+ "notebooks/*"
47
+ ]
48
+
49
+ [tool.ruff.lint.isort]
50
+ known-first-party = ["behaviorgpt"]
51
+
52
+ [tool.pytest.ini_options]
53
+ testpaths = ["tests"]
54
+ addopts = "-ra --strict-markers"
@@ -0,0 +1,29 @@
1
+ from behaviorgpt._client import UnboxAIClient
2
+ from behaviorgpt._exceptions import (
3
+ AuthenticationError,
4
+ BadRequestError,
5
+ RateLimitError,
6
+ UnboxAIError,
7
+ )
8
+ from behaviorgpt.resources.catalogs import ProgressPrinter
9
+ from behaviorgpt.types.events import (
10
+ AddToCart,
11
+ Order,
12
+ RemoveFromCart,
13
+ Search,
14
+ View,
15
+ )
16
+
17
+ __all__ = [
18
+ "Search",
19
+ "AddToCart",
20
+ "View",
21
+ "RemoveFromCart",
22
+ "Order",
23
+ "UnboxAIClient",
24
+ "ProgressPrinter",
25
+ "UnboxAIError",
26
+ "AuthenticationError",
27
+ "BadRequestError",
28
+ "RateLimitError",
29
+ ]
@@ -0,0 +1,275 @@
1
+ import os
2
+ import random
3
+ import warnings
4
+ from collections import defaultdict
5
+ from datetime import UTC, datetime, timedelta
6
+ from pathlib import Path
7
+ from typing import Any, Callable, Optional, Sequence, cast
8
+ from uuid import uuid4
9
+
10
+ import httpx
11
+
12
+ from behaviorgpt._exceptions import AuthenticationError
13
+ from behaviorgpt.resources.catalogs import Catalogs
14
+ from behaviorgpt.resources.recommendations import Recommender
15
+ from behaviorgpt.resources.requests import UnboxAIRequester
16
+ from behaviorgpt.resources.search import Searcher
17
+ from behaviorgpt.types import (
18
+ AddToCart,
19
+ CartItem,
20
+ Domains,
21
+ EmbedJobDetails,
22
+ Item,
23
+ JobStatus,
24
+ Order,
25
+ Search,
26
+ SessionEvent,
27
+ UnboxAIResponse,
28
+ UserEvent,
29
+ UserHistoryInput,
30
+ )
31
+
32
+ # An embed upload streams the whole parquet, and the API answers only once the
33
+ # file is stored and queued: httpx's 5 s default is too short for both.
34
+ DEFAULT_HTTP_TIMEOUT = httpx.Timeout(120.0, connect=10.0, write=300.0)
35
+
36
+
37
+ class UnboxAIClient:
38
+ def __init__(
39
+ self,
40
+ market: str,
41
+ *,
42
+ timezone: str = "UTC",
43
+ api_key: Optional[str] = None,
44
+ base_url: str = "https://behaviorgpt-northeurope.api.unboxai.com/v1",
45
+ default_catalog_id: str = "retail_catalog",
46
+ http_timeout: float | httpx.Timeout = DEFAULT_HTTP_TIMEOUT,
47
+ ):
48
+ self.api_key = api_key or os.environ.get("UNBOXAI_API_KEY")
49
+ if not self.api_key:
50
+ msg = "API key is missing. Pass it or set UNBOXAI_API_KEY."
51
+ raise AuthenticationError(msg)
52
+
53
+ self.base_url = base_url
54
+ self.default_catalog_id = default_catalog_id
55
+
56
+ headers = {"x-api-key": self.api_key}
57
+ self._http_client = httpx.Client(
58
+ base_url=self.base_url, headers=headers, timeout=http_timeout
59
+ )
60
+
61
+ self.domains = Domains(market=market)
62
+ self.timezone = timezone
63
+
64
+ self.requester = UnboxAIRequester(domains=self.domains, timezone=self.timezone)
65
+
66
+ self.recommendations = Recommender(self._http_client)
67
+ self.search = Searcher(self._http_client)
68
+ self.catalogs = Catalogs(self._http_client)
69
+
70
+ def complete(
71
+ self,
72
+ history: UserHistoryInput,
73
+ limit: int = 10,
74
+ offset: int = 0,
75
+ *,
76
+ catalog_id: Optional[str] = None,
77
+ filters: Optional[dict[str, Any]] = None,
78
+ register_event: bool = False,
79
+ ) -> UnboxAIResponse:
80
+ active_catalog: str = catalog_id or self.default_catalog_id
81
+ request_headers = {"x-catalog-id": active_catalog}
82
+
83
+ history_events = self.__from_sequence(active_catalog, history)
84
+ last_event = self._get_last_event(history)
85
+
86
+ if isinstance(last_event, Search):
87
+ req = self.requester.make(
88
+ query=last_event.query,
89
+ history=history_events[:-1],
90
+ catalog_id=active_catalog,
91
+ limit=limit,
92
+ offset=offset,
93
+ filters=filters,
94
+ register_event=register_event,
95
+ )
96
+ return self.search.create(payload=req, headers=request_headers)
97
+
98
+ req = self.requester.make(
99
+ history=history_events,
100
+ catalog_id=active_catalog,
101
+ limit=limit,
102
+ offset=offset,
103
+ filters=filters,
104
+ register_event=register_event,
105
+ )
106
+ return self.recommendations.create(payload=req, headers=request_headers)
107
+
108
+ def embed(
109
+ self,
110
+ path: Path | str,
111
+ wait: bool = False,
112
+ interval: float = 5.0,
113
+ timeout: float = 600.0,
114
+ on_progress: Optional[Callable[[JobStatus], None]] = None,
115
+ startup_grace: float = 120.0,
116
+ reference_time: Optional[datetime | str] = None,
117
+ ) -> EmbedJobDetails:
118
+ """Upload and embed a catalog parquet.
119
+
120
+ Pass `wait=True` to block until the embed job finishes. While waiting,
121
+ each new job state is printed once; pass `on_progress` to render
122
+ progress yourself, or `on_progress=lambda _: None` for silence.
123
+
124
+ `reference_time` is when item ages and sales are measured; the upload
125
+ time by default.
126
+ """
127
+ if isinstance(path, str):
128
+ path = Path(path)
129
+
130
+ return self.catalogs.embed(
131
+ path,
132
+ wait=wait,
133
+ interval=interval,
134
+ timeout=timeout,
135
+ on_progress=on_progress,
136
+ startup_grace=startup_grace,
137
+ reference_time=reference_time,
138
+ )
139
+
140
+ def job_status(self, job_id: str) -> JobStatus:
141
+ return self.catalogs.get_job_status(job_id)
142
+
143
+ def similar_items(
144
+ self,
145
+ item_id: str,
146
+ limit: int = 10,
147
+ offset: int = 0,
148
+ *,
149
+ catalog_id: Optional[str] = None,
150
+ ) -> UnboxAIResponse:
151
+ active_catalog: str = catalog_id or self.default_catalog_id
152
+ request_headers = {"x-catalog-id": active_catalog}
153
+
154
+ return self.catalogs.get_similar_items(
155
+ item_id,
156
+ catalog_id=active_catalog,
157
+ limit=limit,
158
+ offset=offset,
159
+ headers=request_headers,
160
+ )
161
+
162
+ def similar_products(
163
+ self, product_id: str, *args: Any, **kwargs: Any
164
+ ) -> UnboxAIResponse:
165
+ warnings.warn(
166
+ "`similar_products` is deprecated, use `similar_items`",
167
+ DeprecationWarning,
168
+ stacklevel=2,
169
+ )
170
+ return self.similar_items(product_id, *args, **kwargs)
171
+
172
+ def random_item(self, catalog_id: Optional[str] = None, window: int = 100) -> Item:
173
+ """One item from the embedded catalog, handy when
174
+ you have no item id at hand.
175
+ """
176
+ top = self.complete(history=[], catalog_id=catalog_id, limit=window)
177
+ if not top.items:
178
+ active = catalog_id or self.default_catalog_id
179
+ raise ValueError(f"catalog {active!r} returned no items")
180
+ return random.choice(top.items)
181
+
182
+ def random_product(self, *args: Any, **kwargs: Any) -> Item:
183
+ warnings.warn(
184
+ "`random_product` is deprecated, use `random_item`",
185
+ DeprecationWarning,
186
+ stacklevel=2,
187
+ )
188
+ return self.random_item(*args, **kwargs)
189
+
190
+ def __from_sequence(
191
+ self, catalog_id: str, context: UserHistoryInput
192
+ ) -> list[SessionEvent]:
193
+ events: list[SessionEvent] = []
194
+
195
+ if not context:
196
+ return events
197
+
198
+ # Track cart state within a single session
199
+ def _process_session_events(
200
+ session_events: Sequence[UserEvent], session_id: str, session_offset: int
201
+ ):
202
+ cart_state: dict[str, int] = defaultdict(int)
203
+ current_cart_id = str(uuid4())
204
+
205
+ # Base time for the start of the sequence
206
+ base_time = datetime.now(tz=UTC)
207
+
208
+ for i, ev in enumerate(session_events):
209
+ if isinstance(ev, AddToCart):
210
+ cart_state[ev.item] += 1
211
+ elif isinstance(ev, Order):
212
+ if not getattr(ev, "items", None):
213
+ ev.cart_id = current_cart_id
214
+ ev.items = [
215
+ CartItem(item, qty) for item, qty in cart_state.items()
216
+ ]
217
+ cart_state.clear()
218
+ current_cart_id = str(uuid4())
219
+
220
+ # Add 1 millisecond for each event to guarantee network-safe distinct
221
+ # ordering. Factors in a session offset just in case 2D arrays
222
+ # were passed
223
+ event_time = base_time + timedelta(
224
+ milliseconds=(session_offset * 1000) + i
225
+ )
226
+
227
+ events.append(
228
+ self.__to_session_evt(ev, session_id, catalog_id, event_time)
229
+ )
230
+
231
+ if isinstance(context[0], (list, tuple)):
232
+ context_2d = cast(Sequence[Sequence[UserEvent]], context)
233
+ for session_index, session_sequence in enumerate(context_2d):
234
+ _process_session_events(session_sequence, str(uuid4()), session_index)
235
+ else:
236
+ context_1d = cast(Sequence[UserEvent], context)
237
+ _process_session_events(context_1d, str(uuid4()), 0)
238
+
239
+ return events
240
+
241
+ def umap(self, *, catalog_id: Optional[str] = None):
242
+ """The catalog's UMAP, a 2D map of its items, as an HTML page.
243
+
244
+ Maps exist only for catalogs of up to 100,000 items, and appear within
245
+ about a minute after the catalog is ready: laying out more items than
246
+ that does not fit in the embedding worker's memory, so larger catalogs
247
+ (such as the shared `retail_catalog`) never get one. A missing map
248
+ raises `UnboxAIError` with status 404 and says which case applies.
249
+ """
250
+ active_catalog: str = catalog_id or self.default_catalog_id
251
+ return self.catalogs.get_umap(catalog_id=active_catalog)
252
+
253
+ def __to_session_evt(
254
+ self, event: UserEvent, session_id: str, catalog_id: str, timestamp: datetime
255
+ ) -> SessionEvent:
256
+ return SessionEvent(
257
+ store_id=catalog_id,
258
+ domains=self.domains,
259
+ timezone=self.timezone,
260
+ event=event,
261
+ session_id=session_id,
262
+ timestamp=timestamp,
263
+ )
264
+
265
+ def _get_last_event(self, history: UserHistoryInput) -> UserEvent | None:
266
+ if not history:
267
+ return None
268
+
269
+ if isinstance(history[0], (list, tuple)):
270
+ history_2d = cast(Sequence[Sequence[UserEvent]], history)
271
+ inner_seq = history_2d[-1]
272
+ return inner_seq[-1] if inner_seq else None
273
+ else:
274
+ history_1d = cast(Sequence[UserEvent], history)
275
+ return history_1d[-1]