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

# E-commerce Integration Guide

> Learn how to integrate your product catalog with Vambe AI assistants. Manage products, sync inventory, and enable AI-powered product recommendations.

## Overview

Vambe's e-commerce integration allows your AI assistants to recommend and discuss products with customers. Products are organized in **Product Blocks** (also called Prompt Blocks), which are containers that hold related products.

## Key Concepts

### Product Blocks

* **Container**: A product block is a container that holds related products
* **AI Context**: AI assistants use product blocks to understand available products
* **Organization**: Organize products by category, brand, or use case
* **Multiple Blocks**: You can have multiple product blocks for different purposes

### Product Structure

Each product has:

* **Basic Info**: Name, description, price, currency
* **Type**: PRODUCT (physical/digital) or SERVICE
* **External ID**: Your unique identifier for tracking
* **Metadata**: Custom key-value pairs for additional data
* **AI Description**: Natural language description for AI understanding

## Getting Started

### Step 1: Get Your Product Block IDs

Before managing products, you need to know which product blocks are available:

```bash theme={null}
curl --request GET \
  'https://api.vambe.me/api/public/product/product-blocks' \
  --header 'x-api-key: your_api_key_here'
```

**Response**:

```json theme={null}
[
  {
    "id": "block-abc123",
    "name": "Main Product Catalog",
    "count": 150
  },
  {
    "id": "block-def456",
    "name": "Seasonal Products",
    "count": 25
  }
]
```

Save these IDs - you'll need them for all product operations!

### Step 2: Choose Your Product Management Strategy

Depending on your needs, choose the right endpoint:

| Endpoint   | Use When                                      | Behavior                        |
| ---------- | --------------------------------------------- | ------------------------------- |
| **Create** | Adding new products or updating specific ones | Keeps existing products         |
| **Upsert** | Full catalog synchronization                  | Deletes products not in request |
| **Delete** | Removing specific products                    | Deletes only specified products |

## Complete Workflows

### Workflow 1: Initial Product Catalog Setup

```javascript theme={null}
// 1. Get product block ID
const blocksResponse = await fetch(
  'https://api.vambe.me/api/public/product/product-blocks',
  {
    headers: { 'x-api-key': 'your_api_key_here' },
  },
);

const blocks = await blocksResponse.json();
const mainBlockId = blocks.find((b) => b.name === 'Main Product Catalog')?.id;

// 2. Create initial products
const createResponse = await fetch(
  `https://api.vambe.me/api/public/product/create/${mainBlockId}`,
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-api-key': 'your_api_key_here',
    },
    body: JSON.stringify([
      {
        name: 'Premium Coffee Beans',
        description:
          'High-quality arabica coffee from Colombia. Rich flavor with chocolate notes. Perfect for espresso.',
        price: 24.99,
        currency: 'USD',
        type: 'PRODUCT',
        external_id: 'coffee-001',
        file_url: 'https://shop.com/coffee.jpg',
        metadata: [
          { key: 'origin', value: 'Colombia' },
          { key: 'roast', value: 'Medium' },
          { key: 'weight', value: '500g' },
        ],
      },
      {
        name: 'Express Delivery',
        description:
          'Fast delivery service. Next-day delivery for orders placed before 2 PM. Available nationwide.',
        price: 5.0,
        currency: 'USD',
        type: 'SERVICE',
        external_id: 'delivery-express',
        metadata: [
          { key: 'delivery_time', value: '1 day' },
          { key: 'coverage', value: 'Nationwide' },
        ],
      },
    ]),
  },
);

console.log('Products created successfully!');
```

### Workflow 2: Nightly Catalog Sync

```javascript theme={null}
// Complete catalog sync from your e-commerce platform
const syncCatalog = async (productBlockId) => {
  // 1. Get products from your e-commerce platform
  const shopProducts = await yourEcommercePlatform.getAllProducts();

  // 2. Transform to Vambe format
  const vambeProducts = shopProducts.map((product) => ({
    name: product.title,
    description: `${product.description}. ${product.features.join('. ')}`,
    price: parseFloat(product.price),
    currency: 'USD',
    type: 'PRODUCT',
    external_id: `shop-${product.id}`,
    file_url: product.image_url,
    metadata: [
      { key: 'sku', value: product.sku },
      { key: 'category', value: product.category },
      { key: 'brand', value: product.brand },
      { key: 'in_stock', value: product.in_stock.toString() },
    ],
  }));

  // 3. Upsert to Vambe (full sync - removes discontinued products)
  const response = await fetch(
    `https://api.vambe.me/api/public/product/upsert/${productBlockId}`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': 'your_api_key_here',
      },
      body: JSON.stringify(vambeProducts),
    },
  );

  const result = await response.json();
  console.log(`Synced ${vambeProducts.length} products`);
  console.log(`Created: ${result.created}, Updated: ${result.updated}`);

  return result;
};

// Run nightly
// cron.schedule('0 2 * * *', () => syncCatalog('block-abc123'));
```

### Workflow 3: Add New Product

```javascript theme={null}
// Add a single new product without affecting others
const addNewProduct = async (productBlockId, newProduct) => {
  const response = await fetch(
    `https://api.vambe.me/api/public/product/create/${productBlockId}`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': 'your_api_key_here',
      },
      body: JSON.stringify([
        {
          name: newProduct.name,
          description: newProduct.description,
          price: newProduct.price,
          currency: 'USD',
          type: 'PRODUCT',
          external_id: `new-${Date.now()}`,
          file_url: newProduct.imageUrl,
          metadata: [
            { key: 'category', value: newProduct.category },
            { key: 'new_arrival', value: 'true' },
          ],
        },
      ]),
    },
  );

  console.log('New product added!');
  return await response.json();
};
```

### Workflow 4: Remove Discontinued Products

```javascript theme={null}
// Remove products that are no longer available
const removeDiscontinued = async (productBlockId, externalIds) => {
  const response = await fetch(
    `https://api.vambe.me/api/public/product/delete/${productBlockId}`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': 'your_api_key_here',
      },
      body: JSON.stringify(externalIds.map((id) => ({ external_id: id }))),
    },
  );

  const result = await response.json();
  console.log(`Deleted ${result.deleted} products`);

  return result;
};

// Usage
removeDiscontinued('block-abc123', ['old-product-001', 'discontinued-002']);
```

## Best Practices

### 1. Writing Good Product Descriptions

The description field is crucial for AI understanding. Follow these guidelines:

**✅ Good Description**:

```
"Premium wireless headphones with active noise cancellation. Over-ear design provides comfort for long listening sessions. 30-hour battery life. Perfect for travel, work, and music lovers who demand high-quality audio."
```

**❌ Poor Description**:

```
"Model: WH-1000XM4. Price: $349.99. Buy now at https://shop.com. SKU: WH1000XM4."
```

**Tips**:

* Use natural language that describes features and benefits
* Avoid URLs, prices (already in price field), or SKU codes
* Focus on what makes the product unique
* Include use cases and who it's for
* Mention key features in conversational language

### 2. Use Meaningful External IDs

```javascript theme={null}
// Good: Trackable, meaningful IDs
external_id: 'sku-WH1000XM4';
external_id: 'shopify-6789012345';
external_id: 'coffee-premium-colombia-500g';

// Avoid: Hard to track
external_id: '1';
external_id: 'product';
```

### 3. Organize with Metadata

```javascript theme={null}
metadata: [
  { key: 'category', value: 'Electronics' },
  { key: 'subcategory', value: 'Audio' },
  { key: 'brand', value: 'Sony' },
  { key: 'in_stock', value: 'true' },
  { key: 'warehouse_location', value: 'A-12' },
  { key: 'seasonal', value: 'false' },
];
```

### 4. Handle Large Catalogs

For catalogs with 1000+ products:

```javascript theme={null}
// Batch products into chunks for reliability
const BATCH_SIZE = 500;

const uploadInBatches = async (products, blockId) => {
  for (let i = 0; i < products.length; i += BATCH_SIZE) {
    const batch = products.slice(i, i + BATCH_SIZE);

    await fetch(`https://api.vambe.me/api/public/product/create/${blockId}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': 'your_api_key_here',
      },
      body: JSON.stringify(batch),
    });

    console.log(`Uploaded batch ${Math.floor(i / BATCH_SIZE) + 1}`);

    // Small delay between batches
    await new Promise((resolve) => setTimeout(resolve, 1000));
  }
};
```

## Product Types

### PRODUCT

Physical or digital items that customers purchase:

* Physical products (clothes, electronics, etc.)
* Digital products (ebooks, software, etc.)
* Consumables (food, drinks, etc.)

### SERVICE

Services or subscriptions:

* Delivery services
* Consulting services
* Subscriptions
* Warranties
* Installation services

## Currency Codes

Supported currencies include:

* **USD**: US Dollar
* **EUR**: Euro
* **GBP**: British Pound
* **CLP**: Chilean Peso
* **MXN**: Mexican Peso
* **COP**: Colombian Peso
* **ARS**: Argentine Peso
* **PEN**: Peruvian Sol
* **BRL**: Brazilian Real

And many more!

## API Endpoints Reference

### Product Management

1. **[GET /api/public/product/product-blocks](/reference/product/get-product-blocks)** - List available product blocks
2. **[POST /api/public/product/create/{promptBlockId}](/reference/product/create-products)** - Add/update products (keeps others)
3. **[POST /api/public/product/upsert/{promptBlockId}](/reference/product/upsert-products)** - Full sync (deletes unlisted)
4. **[POST /api/public/product/delete/{promptBlockId}](/reference/product/delete-products)** - Delete specific products

### Order Information

5. **[GET /api/public/order/{id}/product](/reference/product/get-order-products)** - Get products in an order

## Common Scenarios

### Scenario 1: E-commerce Platform Integration

```javascript theme={null}
// Daily sync from Shopify/WooCommerce/etc
const dailySync = async () => {
  // 1. Get block ID
  const blocks = await getProductBlocks();
  const blockId = blocks[0].id;

  // 2. Get products from your platform
  const products = await shopifyAPI.getProducts();

  // 3. Transform and sync
  const vambeProducts = products.map(transformToVambeFormat);

  // 4. Upsert (removes products no longer in your catalog)
  await upsertProducts(blockId, vambeProducts);

  console.log('Daily sync complete!');
};
```

### Scenario 2: Real-time Updates

```javascript theme={null}
// When a product is added/updated in your system
const onProductChange = async (product) => {
  const blockId = 'block-abc123';

  // Use create (doesn't affect other products)
  await createProducts(blockId, [transformProduct(product)]);

  console.log('Product updated in AI knowledge');
};

// When a product is discontinued
const onProductDiscontinued = async (productId) => {
  const blockId = 'block-abc123';

  await deleteProducts(blockId, [{ external_id: productId }]);

  console.log('Product removed from AI knowledge');
};
```

### Scenario 3: Multi-category Management

```javascript theme={null}
// Different product blocks for different categories
const setupCategories = async () => {
  const blocks = await getProductBlocks();

  const electronicsBlock = blocks.find((b) => b.name === 'Electronics');
  const clothingBlock = blocks.find((b) => b.name === 'Clothing');

  // Sync electronics
  await upsertProducts(electronicsBlock.id, electronicsProducts);

  // Sync clothing
  await upsertProducts(clothingBlock.id, clothingProducts);

  console.log('All categories synced!');
};
```

## Troubleshooting

### Product Not Showing in AI Responses

1. **Check Description**: Ensure description uses natural language
2. **Verify Block**: Confirm product is in the correct block
3. **Check AI Configuration**: Ensure assistant has access to product block
4. **Wait for Processing**: Allow a few minutes for AI indexing

### Products Being Deleted Unexpectedly

* **Using Upsert?**: Remember upsert deletes products not in request
* **Solution**: Use `create` endpoint for partial updates
* **Or**: Include all products in upsert request

### Metadata Not Appearing

* **Check Format**: Metadata must be array of `{key, value}` objects
* **Verify Keys**: Keys should be simple strings
* **Check Response**: Verify metadata was saved

## Related Resources

* [Product Endpoints](/reference/product/get-product-blocks) - Full API reference
* [Create Pipeline](/docs/create-pipeline) - Set up AI assistant to use products
* [Analytics](/docs/analytics) - Track product recommendation performance

## Next Steps

1. **Get Your Block IDs**: Call GET /product-blocks
2. **Upload Products**: Use create or upsert endpoint
3. **Configure AI Assistant**: Link product block to your assistant
4. **Test**: Chat with your AI and ask about products
5. **Monitor**: Track which products are being recommended
