> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kleep.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# AI Recommendations

> Fetch AI Recommendations from the Kleep API, render them in your placements, and track impressions, clicks and conversions with kleep.track.

Your storefront tells Kleep which page the shopper is on and what they are looking at. Kleep returns the products to show in each placement, ranked by the strategy configured in the dashboard, and measures what shoppers do with them.

| | |
| - | - |
| Base URL | `https://reco.kleep.ai/reco/v1` |
| Format | JSON over HTTPS |
| Authentication | None — requests identify the store with the retailer **public id** (a UUID, provided by Kleep) |

```mermaid theme={null}
sequenceDiagram
  participant D as Kleep dashboard
  participant S as Your storefront
  participant K as Kleep engine
  D-->>K: placements you configure (strategy chain, rules, size-aware, fallback)
  S->>K: POST /reco/v1/recommendations (surface, seed, context)
  K-->>S: products per placement + reco_id
  S->>K: kleep.track reco_displayed / reco_clicked (with the reco_id) + commerce events
  K-->>D: served, clicks, CTR, add-to-carts, attributed revenue
```

## Concepts

* **Surface** — the type of page the shopper is on: `pdp` (seed required), `plp`, `cart`, `home`, `search`, `post_purchase`, `not_found`, `other`.
* **Placement** — a slot on a surface, configured in the dashboard (e.g. `pdp-similar`). Each placement sets its strategy chain, product count, rules, size-aware mode and fallback (fill with trending, or hide).
* **Strategy** — how products are chosen: `catalogue`, `similar`, `complementary`, `bought_together`, `recently_viewed`, `personalised`. Best sellers, new arrivals and trending are orderings applied to a strategy's results, not separate strategies.

Placements are created with your Kleep contact in the dashboard. A placement changed in the dashboard applies to the next call, with no storefront release.

## Endpoints

| Endpoint | Purpose |
| - | - |
| `POST /reco/v1/recommendations` | Serve the products for every requested placement, one call per page view. Returns the `reco_id` to echo in analytics events. |
| `POST /reco/v1/recommendations/events` | Feed the **`recently_viewed` strategy**: report `view` events as the shopper browses products. Only needed if one of your placements uses that strategy. Not an attribution channel — attribution goes through `kleep.track` (below). |
| `POST /reco/v1/users` | **API-only integrations**: create a Kleep app user and its first session. Returns `user_id` and `session_id`. With the JS library, users and sessions are managed for you. |
| `POST /reco/v1/sessions` | **API-only integrations**: open a new session for an existing `user_id`. |

## Prerequisites

* Your catalogue is imported into Kleep and at least one **placement** is configured in the dashboard.
* You have your retailer **public id** (a UUID, provided by Kleep).
* The [Kleep JS library](https://docs.kleep.ai/cms/js-library.md) is installed site-wide and gated behind cookie consent.

> [!WARNING]
>
> Loading the Kleep JS library processes personal data. **Legally condition its loading on the visitor's prior consent to cookies** — see [Cookies, CMP & Data Privacy](https://docs.kleep.ai/cookie-consent.md). The recommendations API call itself can be made without the library, but the analytics described in this guide require it.

## 1. Install the JS library

Before `</body>`, on **every page** of your site:

```html theme={null}
<script src="https://module.kleep.ai/api/widget"></script>
```

The library exposes the global `kleep` object, which provides:

* `kleep.getSessionId()` — the visitor's Kleep session id. Pass it to the recommendations API so served recommendations and analytics events join on the same session.
* `kleep.track(event, data)` — the analytics calls described in [step 4](#4-track-analytics-events).

If you also use Kleep AI Sizing, keep calling `kleep.load(...)` on product pages as usual — the same library and session serve both features.

## 2. Fetch recommendations

One `POST /reco/v1/recommendations` per page view returns the products for every placement on the page.

### Request

```javascript theme={null}
const response = await fetch("https://reco.kleep.ai/reco/v1/recommendations", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    retailer: "67522fe2-19e8-4e1a-b19a-1f968d53d4cf", // your retailer public id
    surface: "pdp",                 // pdp | plp | cart | home | search | post_purchase | not_found | other
    placements: ["pdp-similar"],    // omit to get every placement configured for the surface
    seed: { product_id: "SKU123" }, // required on pdp: the product the shopper is viewing
    count: 8,
    context: {
      session_id: window.kleep.getSessionId(),
      market: { country: "FR", locale: "fr-FR", currency: "EUR" }
    }
  }),
  signal: AbortSignal.timeout(1000)
});
const reco = await response.json();
```

Key request fields:

| Field | Type | Description |
| - | - | - |
| `retailer` | UUID, required | Your retailer public id |
| `surface` | string | The type of page the shopper is on |
| `placements` | string\[] | Placement ids to fill. Omit to fill all placements configured for the surface |
| `seed.product_id` | string | The product in view. Required on `pdp`; the basis for similar / complementary / bought-together strategies |
| `count` | int (1–100) | Max products per placement (default 8; the placement config can cap it lower) |
| `context.session_id` | UUID | The value of `kleep.getSessionId()`. **Always send it** — it links the recommendation to the shopper's analytics events |
| `context.market` | object | `country`, `locale`, `currency` — used for pricing, translations and market rules |
| `context.customer` | object | Optional: `ref` (your customer id), `segments`, `gender`, `preferred_brands` — used by personalised strategies |
| `context.cart` | array | Optional on `cart`/checkout surfaces: `[{ product_id, variant_id, quantity, unit_price }]` — cart lines act as seeds |

### Response

```json theme={null}
{
  "request_id": "req_6f2b1c9a",
  "reco_id": "a3f1c2d4-5b6e-4f7a-8c9d-0e1f2a3b4c5d",
  "placements": {
    "pdp-similar": {
      "placement_id": "pdp-similar",
      "result_id": "res_8d4e2f1a",
      "result_type": "primary",
      "strategy_used": "similar",
      "title": { "default": "You may also like", "fr": "Vous aimerez aussi" },
      "hidden": false,
      "products": [
        {
          "product_id": "SKU456",
          "variant_id": "SKU456-M",
          "name": "Linen shirt",
          "url": "https://yourshop.com/products/linen-shirt",
          "image_url": "https://cdn.yourshop.com/linen-shirt.jpg",
          "price": 79.0,
          "list_price": 99.0,
          "currency": "EUR",
          "brand": "Your Brand",
          "availability": "in_stock",
          "size_available": true,
          "badges": []
        }
      ]
    }
  },
  "warnings": []
}
```

Key response fields:

| Field | Description |
| - | - |
| `reco_id` | **The attribution key.** Echo it on `reco_displayed` and `reco_clicked` (step 4) |
| `placements` | One entry per requested placement, keyed by placement id |
| `placements[].result_type` | `primary` (the configured strategy chain) or `fallback` |
| `placements[].title` | The placement title configured in the dashboard, per language |
| `placements[].hidden` | `true` when the placement could not be filled and is configured to hide — render nothing |
| `placements[].products` | The ranked products to display, with name, image, price and URL ready to render |

### Errors and warnings

Errors come back with a non-2xx status and a JSON body `{ "error": { "code", "message", "timestamp", "request_id" } }` — `USER_INPUT_ERROR` (400), `RESOURCE_NOT_FOUND` (404, unknown retailer), `VALIDATION_ERROR` (422, failing fields in `error.details.validation_errors`), `INTERNAL_SERVER_ERROR` (5xx). Non-fatal conditions keep the 200 and are named in `warnings` as plain strings (e.g. `"fallback trending used to fill results"`).

Recommendations are never worth a slow page: set a one-second timeout, render the page without the placement when the call fails, and let the next page view try again.

## 3. Render the placement

Render the products however fits your design — the response carries everything needed for a product card:

```javascript theme={null}
const placement = reco.placements["pdp-similar"];
if (placement && !placement.hidden && placement.products.length) {
  container.innerHTML = placement.products
    .map(
      (p) => `
      <a class="reco-card" href="${p.url}" data-product-id="${p.product_id}">
        <img src="${p.image_url}" alt="${p.name}" />
        <span>${p.name}</span>
        <span>${p.price} ${p.currency}</span>
      </a>`
    )
    .join("");
}
```

> [!NOTE]
>
> Respect `hidden: true`: it means the placement is configured to disappear rather than show weak results. Render nothing in that case.

## 4. Track analytics events

Analytics close the loop: they tell the dashboard which recommendations were seen, clicked and converted. All events go through `kleep.track` — the library stamps them with the session id, user id and page context automatically.

The two recommendation events echo the **`reco_id` from the API response**. That is the join key for attribution.

### `reco_displayed` — the placement was seen

Fire **once per placement** when it becomes visible to the shopper (use an `IntersectionObserver` rather than firing on render, so below-the-fold placements only count when scrolled into view):

```javascript theme={null}
kleep.track("reco_displayed", {
  reco_id: reco.reco_id,                                   // string, required
  placement_id: placement.placement_id,                    // string, required
  product_ids: placement.products.map((p) => p.product_id) // string[], required, non-empty
});
```

### `reco_clicked` — a recommended product was clicked

Fire when the shopper clicks a product card, before navigating:

```javascript theme={null}
kleep.track("reco_clicked", {
  reco_id: reco.reco_id,          // string, required
  placement_id: placement.placement_id, // string, required
  product_id: product.product_id, // string, required
  position: index                 // number, optional: 0-based position in the placement
});
```

### Conversion events — the funnel joins itself

The standard commerce events do **not** take a `reco_id`: send them as usual and Kleep attributes views, add-to-carts and revenue to the placement server-side, by joining `reco_clicked` with the later commerce events of the same session and product:

```javascript theme={null}
// On the product page reached from a recommendation — nothing reco-specific
kleep.track("product_viewed", {
  productId: "SKU456"
});

// When the recommended product is added to cart
kleep.track("product_added_to_cart", {
  productId: "SKU456",
  variantId: "SKU456-M",
  cart: [{ productId: "SKU456", variantId: "SKU456-M", quantity: 1 }]
});

// On the order confirmation page
kleep.track("checkout_completed", {
  orderId: "ORDER-1001",
  cart: [{ productId: "SKU456", variantId: "SKU456-M", quantity: 1 }]
});
```

> [!TIP]
>
> Nothing to carry across pages: as long as `reco_clicked` is sent on the click, the dashboard attributes the rest of the funnel automatically.

### Event reference

| Event | Required fields | Optional fields | When |
| - | - | - | - |
| `reco_displayed` | `reco_id`, `placement_id`, `product_ids` | — | Placement becomes visible |
| `reco_clicked` | `reco_id`, `placement_id`, `product_id` | `position` | Product card clicked |
| `product_viewed` | `productId` | `variantId`, `sku`, `ean` | Product page viewed |
| `product_added_to_cart` | `productId`, `variantId` | `cart`, `size`, `quantity` | Product added to cart |
| `checkout_completed` | `orderId`, `cart` | — | Order confirmation page |

Field names on recommendation events are `snake_case` (`reco_id`, `placement_id`, `product_ids`, `product_id`, `position`); camelCase variants are rejected.

> [!NOTE]
>
> Not running the Kleep JS library (native app, server-side)? Manage users and sessions with `POST /reco/v1/users` and `POST /reco/v1/sessions`, and pass the returned `session_id` as `context.session_id`. Contact Kleep for the analytics integration in that setup — `kleep.track` is the attribution channel for web.

### Feeding the `recently_viewed` strategy

If a placement uses the `recently_viewed` strategy, tell Kleep what the shopper views by posting a `view` event from each product page (the JS library does not send these automatically):

```javascript theme={null}
fetch("https://reco.kleep.ai/reco/v1/recommendations/events", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    type: "view",
    result_id: placement.result_id, // from the last recommendations response
    product_id: currentProductId,
    session_id: window.kleep.getSessionId()
  })
});
```

Viewed products are kept per session (most recent first) and feed the shopper's `recently_viewed` placements on subsequent calls with the same `context.session_id`.

## Complete example

```html theme={null}
<div id="reco-pdp-similar"></div>

<script>
  async function loadRecommendations() {
    const response = await fetch("https://reco.kleep.ai/reco/v1/recommendations", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        retailer: "67522fe2-19e8-4e1a-b19a-1f968d53d4cf",
        surface: "pdp",
        placements: ["pdp-similar"],
        seed: { product_id: currentProductId },
        count: 8,
        context: {
          session_id: window.kleep.getSessionId(),
          market: { country: "FR", locale: "fr-FR", currency: "EUR" }
        }
      }),
      signal: AbortSignal.timeout(1000)
    });
    const reco = await response.json();
    const placement = reco.placements["pdp-similar"];
    if (!placement || placement.hidden || !placement.products.length) return;

    const container = document.getElementById("reco-pdp-similar");
    container.innerHTML = placement.products
      .map(
        (p, i) => `
        <a href="${p.url}" data-product-id="${p.product_id}" data-position="${i}">
          <img src="${p.image_url}" alt="${p.name}" />
          <span>${p.name}</span><span>${p.price} ${p.currency}</span>
        </a>`
      )
      .join("");

    // Impression: once, when the placement is actually seen
    new IntersectionObserver((entries, observer) => {
      if (entries.some((e) => e.isIntersecting)) {
        kleep.track("reco_displayed", {
          reco_id: reco.reco_id,
          placement_id: placement.placement_id,
          product_ids: placement.products.map((p) => p.product_id)
        });
        observer.disconnect();
      }
    }).observe(container);

    // Clicks
    container.addEventListener("click", (event) => {
      const card = event.target.closest("[data-product-id]");
      if (!card) return;
      kleep.track("reco_clicked", {
        reco_id: reco.reco_id,
        placement_id: placement.placement_id,
        product_id: card.dataset.productId,
        position: Number(card.dataset.position)
      });
    });
  }

  loadRecommendations();
</script>
```

On the destination product page, track the view as usual — attribution to the clicked placement is joined server-side:

```javascript theme={null}
kleep.track("product_viewed", {
  productId: currentProductId
});
```

## Troubleshooting

* **Empty `placements` or `hidden: true`** — the placement has no eligible products for this seed/market and is configured to hide. Check the placement configuration in the dashboard.
* **`warnings` in the response** — non-fatal issues (e.g. a strategy fell back). Log them during integration.
* **Events not showing in the dashboard** — verify the library is loaded (the `kleep` object exists), that `context.session_id` was sent on the API call, and that `reco_id` on the events matches the API response. Add `?debug=true` to the library script URL to see `[KLEEP]` logs in the console.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.