> For the complete documentation index, see [llms.txt](https://rosetta-ai.gitbook.io/tutorials/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://rosetta-ai.gitbook.io/tutorials/javascript-sdk/quick-start.md).

# Quick Start

The Rosetta SDK for JavaScript provides a rich set of client-side functionality that:

* Makes it easy to embed recommendations from Rosetta on your site.
* Enables you to track user behavior for anonymous and identified users.
* Enables you to track and profile users across multiple devices.

This quick-start will show you how to setup the SDK and get it to make some basic recommendations.

## Step 1-1: Copy the Snippet

Installing Rosetta.ai is easy, just paste the following snippet into the `<head>` tag of your site.

```javascript
<script type="text/javascript">
  (function(i,s,o,g,r,a,m) {i['RosettaCmd']=i['RosettaCmd']||[],
  i[r]=i[r]||function(){i['RosettaCmd'].push(arguments)};a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://cdn.rosetta.ai/rosetta-web.js','rosetta');
</script>
```

## Step 1-2: Upload .html File for Domain Verification

**Please contact Rosetta.ai's staff for your .html file.**

The file name is like `_KVaX5UWPGKpOo.html`. You have to upload it to your website's root folder so that it can be accessed like this: `https://example.com/_KVaX5UWPGKpOo.html`

## Step 2: Configure Rosetta.ai

In order to set up Rosetta.ai, the following three methods - `config`, `event`, `query` - are required and need to be implemented properly.

### Step 2a: `config`

The `config` is required to exist on every page. The `config` method provides:

1. Authentication with Rosetta
2. Definition for which page uses which recommendation engine

The configuration code should be placed into javascript tags in the footer of the page.

#### `config` Definition

`config` method definition:

```javascript
rosetta('config', {
  appID: '{{ APP_ID }}',
  engines: [
    {route: '{{ ROUTE }}', engine: '{{ ENGINE_ID }}', container: '{{ CONTAINER }}'}
  ],
  attribution: {
    enable: true,
    detector: {
      type: 'queryString',  // 'dataAttribute',
      name: 'name',
      value: 'value'
    }
  }
})
```

**config Call**

The `config` call has the following fields:

| Field         | Required | Data Type        | Description                                                                                                                                                                   |
| ------------- | -------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `appID`       | Yes      | String           | <p>Authentication for Rosetta.ai is done via <code>appID</code> and site domain name. <br><br> <strong>Contact Rosetta.ai's staff for your <code>APP\_ID</code>.</strong></p> |
| `engines`     | Yes      | Array of Objects | A dictionary of URL paths - `ROUTE`, recommendation engines - `ENGINE_ID`, and containers - `CONTAINER`.                                                                      |
| `attribution` | No       | Object           | Usually used for testing purposes. Attribution is used to attribute recommendations to the Rosetta.ai engine.                                                                 |

**engines Object**

| Fields      | Required | Data Type | Description                                                                                                                                                                                                                                                                                                                               |
| ----------- | -------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ROUTE`     | Yes      | String    | The path of a URL. This specifics where a specific recommendation engine, defined by `engineId`, should run.   For example, given the URL: `store.foo.bar/products/clothing`, if you wanted to match only clothing products, the route should be `products/clothing`. If you wanted to match all products, the route should be `products` |
| `ENGINE_ID` | Yes      | String    | <p>The engine ID for the recommendation engine. <br><br> <strong>Contact Rosetta.ai's staff for the<code>ENGINE\_ID</code>.</strong></p>                                                                                                                                                                                                  |
| `CONTAINER` | Yes      | String    | The container for the recommendation engine. The Rosetta.ai engine searches for a container specified via the HTML id attribute of an element first, then class name. We highly recommend that you choose a unique value for the container.                                                                                               |

**attribution Object**

| Fields     | Required | Data Type | Description                      |
| ---------- | -------- | --------- | -------------------------------- |
| `enable`   | Yes      | Boolean   | Enables or disables attribution. |
| `detector` | Yes      | Object    | Defines the attribution trigger. |

| Sub-Fields | Required | Data Type | Description                                                                                                                                                                                                                                                                                                                                                                                 |
| ---------- | -------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `type`     | Yes      | String    | Options are `dataAttribute` or `queryString`.    `queryString` would mean that an attribution would trigger by looking at the `name` and `value` defined in the URL parameters. For example, `<a href="http://www.url.com/?name=value>Product A</a>`.   An example of an URL attributed defined by `dataAttribute` would be `<a href="http://www.url.com/" data-name="value">Product A</a>` |
| `name`     | Yes      | String    | The identifier based on the attribution type.                                                                                                                                                                                                                                                                                                                                               |
| `value`    | Yes      | String    | The associated value of the `name`.                                                                                                                                                                                                                                                                                                                                                         |

#### `config` Example

```javascript
rosetta('config', {
  appID: 'a_sampleaXaPUkPGoxGLm3gr',
  engines: [
    {route: 'product',  engine: 'eng_sampleexNjT19LlwwN30vM', container: 'layout-2'},
    {route: 'tools',  engine: 'eng_samplefbwZo03CeqoJ29yZ', container: 'top-insert'},
  ],
  attribution: {
    enable: true,
    detector: { // This means that any link with <a href="[URL]?recom=rosetta"></a> would be attributed to the Rosetta.ai Engine>
      type: 'queryString',
      name: 'recom',
      value: 'rosetta'
    }
  }
})
```

### Step 2b: `event`

The `event` method is how you associate and track your users to their actions. By doing so, you increase the reliability and accuracy of predictions over time.

#### `event` Definition

`event` method definition:

```javascript
rosetta('event', {
  type: 'type',
  target: 'item_id',
  // targets: ['item_id_1', 'item_id_2', ...]
})
```

#### `event` Call

| Fields                | Required | Data Type                  | Description                                                                                                                                                                                                                 |
| --------------------- | -------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `type`                | Yes      | String                     | The event type defines what action your user performs  Possible values: `click`, `select`, `buy`, `search`, `share`, `collect`, `view`.                                                                                     |
| `target` or `targets` | Yes      | String or Array of Strings | Depending on the `type` of action that occurs, you would choose either `target` or `targets` as a way of defining which item IDs are relevant. The `item_id` is defined by the unique identifier for that specific product. |

{% hint style="info" %}
You **must have** the `click`, `select`, `buy` events defined throughout your site. By not doing so, the accuracy of predictions will suffer greatly. This also affects the types of recommendations available.
{% endhint %}

**The type Field**

| Value     | Definition                                                                                  |
| --------- | ------------------------------------------------------------------------------------------- |
| `click`   | User clicks on an item.                                                                     |
| `select`  | User adds an item to a cart.                                                                |
| `buy`     | User has completed the purchase of an item.                                                 |
| `search`  | List of results returned via a query.                                                       |
| `collect` | User adds item(s) to wishlist.                                                              |
| `view`    | User visits a page. (In general, There tends to be more `view` events, than `click` events) |
| `play`    | User plays a product video.                                                                 |
| `pause`   | User pauses aformenetioned video.                                                           |

#### `event` Examples

**Example 1: An event triggered by a button click**

```javascript
document.getElementsByClassName('tryme')[0].onclick = function (type) {
  rosetta('event', {
    type: 'buy',
    target: '136CL317',
  })
}
```

**Example 2: A user clicks on a specific item to get more information on it**

```javascript
rosetta('event', {
  type: 'click',
  target: 'B134',
})
```

**Example 3: A user searches for products matching a keyword**

```javascript
rosetta('event', {
  type: 'search',
  targets: ['B133', 'C024', 'E932'] // These 3 products were the results of the query.
})
```

**Example 4: A user purchases multiple items**

```javascript
rosetta('event', {
  type: 'buy',
  targets: ['A123', 'B456', 'C789']
}
```

### Step 2c: `query`

The `query` method an asynchronous call to get a list of products that Rosetta.ai's recommendation engine provides. You will need to process the response returned from the query.

#### `query` Definition

`query` method definition:

```javascript
rosetta('query', {
  container: 'container',
  item: 'item_id',
  filter: {
    key: 'value'
  }
}, function (response) {
  /**
   * Render here
   */
})
```

#### `query` Call

The `query` call has the following fields:

| Fields      | Required | Data Type | Description                                                                                                                                                                                                                                                        |
| ----------- | -------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `container` | Yes      | String    | The container for the recommendation engine. The Rosetta.ai engine searches for a container specified via the HTML id attribute of an element first, then class name. We highly recommend that you choose a unique value for the container. (Same as the `config`) |
| `item_id`   | No       | String    | The `item_id` is the unique identifier of the product seeded for the query. For pages wherein you don't have or know the `item_id`, this field is not required.                                                                                                    |
| `filter`    | No       | Object    | The recommendation engine may return a possible list of multiple items with attributes (key-values). You can use the filtering option to select items based on a specific key-value attribute.                                                                     |

#### `query` Example

**Example 1: For the container defined by 'layout-1', run a recommendation based on item 'sample123'**

```javascript
rosetta('query', {
  container: 'layout-1',
  item: 'sample123',
}, function (res) {
  console.log(res)
})
```

**Example 2: For the container defined by 'layout-1', run a recommendation based on item 'sample123' wherein the results are of the 'New Arrival' category and of the 'cool', 'hot', and 'warm' tags**

```javascript
rosetta('query', {
  container: 'layout-1',
  item: 'example-item-id-123',
  filter: {
    category: 'New Arrival',
    tags: ['cool', 'hot', 'warm']
  }
}, function (res) {
  console.log(res)
})
```

**Sample response**

```javascript
{
  "id": "q_GdNloj1Ar4OAcLqEZKr5Xjgr",
  "data": [
    {
      "item": "ent_RJQY9yexqWYrTlZVQPNNjOJl",
      "score": 1,
      "property": {
        "availability": "in stock",
        "brand": "Pazzo",
        "color": "杏",
        "condition": "new",
        "currency": "TWD",
        "description": "V領領口修飾脖子線條/透肌感建議著內搭/舒適手感針織材質",
        "google_product_category": "1604",
        "image_link": "https://pic.pzcdn.tw/pazzo/ProductBasic/affe1f23-16a5-4aca-8845-f24b7a289930.jpg",
        "inventory_status": "N",
        "is_hot": "N",
        "link": "https://www.pazzo.com.tw/market/n/16082?c=35889",
        "local_id": "MT1M16082CL35889",
        "name": "慵懶感透肌Ｖ領針織上衣",
        "price": "690.00",
        "sale_price": "690.00",
        "type": "item"
      }
    },
    {
      "item": "ent_nvB6m7ZR6E88hB23Vaa15lvM",
      "score": 0.9422,
      "property": {
        "availability": "in stock",
        "brand": "Pazzo",
        "color": "灰藍",
        "condition": "new",
        "currency": "TWD",
        "description": "V領領口修飾脖子線條/透肌感建議著內搭/舒適手感針織材質",
        "google_product_category": "1604",
        "image_link": "https://pic.pzcdn.tw/pazzo/ProductBasic/99829ed0-dac9-477a-9710-ea9781f59400.jpg",
        "inventory_status": "Y",
        "is_hot": "N",
        "link": "https://www.pazzo.com.tw/market/n/16082?c=35891",
        "local_id": "MT1M16082CL35891",
        "name": "慵懶感透肌Ｖ領針織上衣",
        "price": "690.00",
        "sale_price": "690.00",
        "type": "item"
      }
    },
    {
      "item": "ent_VJ4Mx6qKVaX5UWPGKpOo6Nge",
      "score": 0.9085,
      "property": {
        "availability": "in stock",
        "brand": "Pazzo",
        "color": "橄欖綠",
        "condition": "new",
        "currency": "TWD",
        "description": "V領領口修飾脖子線條/透肌感建議著內搭/舒適手感針織材質",
        "google_product_category": "1604",
        "image_link": "https://pic.pzcdn.tw/pazzo/ProductBasic/b906b9ab-b351-4f74-ae6c-40cf620eedb5.jpg",
        "inventory_status": "N",
        "is_hot": "N",
        "link": "https://www.pazzo.com.tw/market/n/16082?c=35892",
        "local_id": "MT1M16082CL35892",
        "name": "慵懶感透肌Ｖ領針織上衣",
        "price": "690.00",
        "sale_price": "690.00",
        "type": "item"
      }
    }
  ],
  "created_at": 1592976508
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://rosetta-ai.gitbook.io/tutorials/javascript-sdk/quick-start.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
