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

# AI Recommendations

> Reference for the RecommendationsService class in the Tybrite SDK.

The `RecommendationsService` class (accessed via `client.recommendations`) allows you to integrate AI-driven product suggestions into your storefront to increase discovery and conversion.

<Warning>
  **Secret Key Required.** This service requires a **Secret Key** (`tybrite_sk_live_*` / `tybrite_sk_test_*`). AI inference is computationally expensive and consumes AI recommendation quota — gating to `sk` prevents abuse from scraped publishable keys. Requests authenticated with a publishable key receive `403 Forbidden`.
</Warning>

## Methods

### `getRecommendations`

Retrieve curated product suggestions based on various AI models. Use the examples below to see how to implement different recommendation strategies.

<CodeGroup>
  ```typescript Similar Products theme={null}
  // Get products similar in meaning or features to a specific item
  const { recommendations } = await client.recommendations.getRecommendations({
    requestBody: {
      type: 'similar',
      productId: '0186665f-f0a1-4c79-976a-919b5b1c2daa',
      limit: 5
    }
  });
  // recommendations[0] => { productId: '3422935b-88ee-43ad-a7df-c03161a35cb4',
  //                         score: 0.87, reason: 'Similar product based on description and attributes' }
  ```

  ```typescript Also Bought theme={null}
  // Frequently purchased together (co-purchase matrix)
  const { recommendations } = await client.recommendations.getRecommendations({
    requestBody: {
      type: 'also-bought',
      productId: '0186665f-f0a1-4c79-976a-919b5b1c2daa',
      limit: 5
    }
  });
  // recommendations[0] => { productId: '3422935b-88ee-43ad-a7df-c03161a35cb4',
  //                         score: 0.87, reason: 'Similar product based on description and attributes' }
  ```

  ```typescript Next-Likely Item theme={null}
  // What this shopper is most likely to view or add next, given their current session.
  // Anchor on the session (the most recent product they touched) and/or an explicit productId.
  const { recommendations } = await client.recommendations.getRecommendations({
    requestBody: {
      type: 'next',
      sessionId: 'browser-session-id',
      limit: 5
    }
  });
  // recommendations[0] => { productId: '068aa59d-1adf-4685-adf5-9793b1ffb9c9',
  //                         score: 0.6, reason: 'Customers viewed this next' }
  ```

  ```typescript Trending theme={null}
  // Currently popular products based on sales velocity
  const { recommendations } = await client.recommendations.getRecommendations({
    requestBody: {
      type: 'trending',
      limit: 10
    }
  });
  // recommendations[0] => { productId: '0186665f-f0a1-4c79-976a-919b5b1c2daa',
  //                         score: 1, reason: 'Trending #1 - 2.1 units/day' }
  ```

  ```typescript Personalized theme={null}
  // Suggestions tailored to a specific customer's preferences and history
  const { recommendations } = await client.recommendations.getRecommendations({
    requestBody: {
      type: 'personalized',
      customerId: 'customer-uuid-here',
      limit: 6
    }
  });
  // recommendations[0] => { productId: '0186665f-f0a1-4c79-976a-919b5b1c2daa',
  //                         score: 1, reason: 'Trending #1 - 2.1 units/day' }
  // (when a shopper has little history, personalized falls back to trending — see fallbackUsed)
  ```

  ```typescript Smart Bundles theme={null}
  // AI embeddings + co-purchase analysis for bundle suggestions
  const { recommendations } = await client.recommendations.getRecommendations({
    requestBody: {
      type: 'bundle',
      productId: '0186665f-f0a1-4c79-976a-919b5b1c2daa',
      limit: 5
    }
  });
  // recommendations[0] => { productId: '068aa59d-1adf-4685-adf5-9793b1ffb9c9',
  //                         score: 0.33, reason: 'Pairs well together (0% co-purchased)' }
  ```
</CodeGroup>

**Recommendation Types Details:**

| Type           | Description                                                                                                                   | Required Parameters            |
| :------------- | :---------------------------------------------------------------------------------------------------------------------------- | :----------------------------- |
| `similar`      | Products with similar features/meaning (Embedding-based).                                                                     | `productId`                    |
| `also-bought`  | Products frequently purchased together. Each item indicates whether it complements the product or is an alternative to it.    | `productId`                    |
| `next`         | The products a shopper is most likely to view or add next, based on the path of products they have viewed/added this session. | `sessionId` and/or `productId` |
| `trending`     | Global trending products (Velocity-based).                                                                                    | -                              |
| `new`          | Recently added products.                                                                                                      | -                              |
| `personalized` | Suggestions tailored to a specific user history.                                                                              | `customerId`                   |
| `bundle`       | Smart bundle suggestions (Semantic + Co-purchase). Items that complement the product are surfaced ahead of alternatives.      | `productId`                    |

**Parameters:**

| Parameter                | Type     | Description                                                                                                                                                                  |
| :----------------------- | :------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `requestBody`            | `object` | Required. The configuration for the recommendation request.                                                                                                                  |
| `requestBody.type`       | `string` | The recommendation algorithm to use.                                                                                                                                         |
| `requestBody.productId`  | `string` | Required for `similar`, `also-bought`, and `bundle`. An optional explicit anchor for `next`.                                                                                 |
| `requestBody.sessionId`  | `string` | Used with `next`. The shopper's current browsing-session identifier; the most recent product viewed/added in that session is used as the anchor when `productId` is omitted. |
| `requestBody.customerId` | `string` | Required for `personalized`.                                                                                                                                                 |
| `requestBody.limit`      | `number` | Optional. Maximum number of suggestions to return.                                                                                                                           |

***

<Note>
  Recommendation results are often cached for high performance. The response includes a `fromCache` boolean, a `computedAt` ISO timestamp, and an optional `fallbackUsed` string indicating if the system had to use a simpler algorithm due to data scarcity.
</Note>

***

## Marketplace recommendations

When you call this method with a **marketplace operator key**, recommendations are computed **across all merchants in the marketplace** rather than a single store. The supported types are the same: `trending`, `new`, `also-bought`, `similar`, `personalized`, `bundle`, and `next` — `next` returns the products shoppers most often go on to view next, aggregated across merchants, and `also-bought` carries the same complement/alternative distinction.

Each returned item is stamped with the merchant it came from via `merchant_store_id`, so you can link straight to that merchant's shop page or product:

```typescript theme={null}
const market = new Tybrite({ apiKey: 'tybrite_pk_live_operator_...' });

const { recommendations } = await market.recommendations.getRecommendations({
  requestBody: { type: 'trending', limit: 12 },
});

for (const r of recommendations) {
  // r.productId, r.score, r.reason
  // r.merchant_store_id — the merchant this product belongs to (marketplace responses only)
}
```

***

## Cascading Fallback Chain

When a recommendation type cannot produce results (insufficient data, missing embeddings, cold-start product, etc.), Tybrite degrades gracefully to a simpler algorithm rather than returning an empty array:

| Requested Type | Fallback Order                              |
| :------------- | :------------------------------------------ |
| `next`         | `next → also-bought → similar → trending`   |
| `bundle`       | `bundle → also-bought → similar → trending` |
| `also-bought`  | `also-bought → similar → trending`          |
| `similar`      | `similar → trending`                        |
| `personalized` | `personalized → trending`                   |
| `trending`     | `trending → most popular products`          |

When a fallback is used, the response's `fallbackUsed` field contains the name of the algorithm that ultimately produced the results.

### Minimum results guarantee

Every recommendation response is topped up to **at least 8 products** (capped at the `limit` you request, and at the number of active products the store has), so a storefront never renders a multi-slot shelf with only one or two items. If the requested algorithm returns fewer than eight, the response is backfilled — in order — from what's trending, what shoppers are viewing and adding to cart, the store's featured products, and its newest arrivals. Backfilled items are de-duplicated and never include the product you anchored on. When a response has been topped up this way, `fallbackUsed` includes `backfill`.

***

## Response Codes

This endpoint is `POST` and **requires a Secret Key**.

| Code  | Meaning                                                                                                                            |
| :---- | :--------------------------------------------------------------------------------------------------------------------------------- |
| `200` | Recommendations returned (possibly via fallback — check `fallbackUsed`).                                                           |
| `400` | Invalid `type` enum or missing required field (`productId` for `similar`/`also-bought`/`bundle`; `customerId` for `personalized`). |
| `401` | Invalid or missing API key.                                                                                                        |
| `403` | Publishable key supplied — recommendations require a Secret Key.                                                                   |
| `404` | `productId` was provided but the product was not found (applies to `similar`, `bundle`, and `also-bought`).                        |
| `429` | Rate limit exceeded.                                                                                                               |
| `500` | Internal server error or upstream AI service failure.                                                                              |
