# AI Assistant

**Category:** Integrations/AI Assistant

## Design

### Description

Wix Patterns allows you to integrate your AI Assistant with a [collection](./?path=%2Fstory%2Fbase-components-collections--overview) and use it to add items to that collection. Items are added smoothly with a dedicated animation. 

> **Note:** Currently only tables are supported.

### How it works

Once you integrate the AI Assistant, your collection will automatically listen to the appropriate events emitted from your AI Assistant. When such an event is emitted, your collection will automatically play an animation indicating that an item is being added, and then the item will be added to the collection.



### Integrate an AI Assistant with your patterns component

To integrate your AI Assistant:
1. Configure your collection to listen to events from your AI Assistant.
1. Configure your AI Assistant to emit events in a specific format.

#### Before you begin

You must have a [collection with an `fqdn` property](figure out how to link), and an AI Assistant. 

#### Step 1 | Configure your collection

Configure your collection as follows:

1. Add the following import statement: 

    ```js
    import { createAiAssistant } from '@wix/patterns';
    ```
   
2. Add the following property to your collection in your call to `useTableCollection()`:

    ```js
    aiAssistant: createAiAssistant({ appDefId: {{aiAssistantAppDefId}} })
    ```

    Replace `{{aiAssistantAppDefId}}` with the `appDefId` of your AI Assistant app.

#### Step 2 | Configure your AI Assistant

Follow the instructions for [sending events](https://github.com/wix-private/genie/blob/9a4923156f68f7763da4908df9a6a2242410581f/packages/agent-platform-bm-sdk/README.md?plain=1#L22).

Your AI Assistant must emit events with the name:
```js
    "ITEM_CREATED_{{collectionFqdn}}"
```

 and the structure:
```js
{
    item: {{newItemToAdd}}
}
```


- Replace `{{collectionFqdn}}` with the `fqdn` property of your collection. For example, the full value could be `"ITEM_CREATED_wix.contacts.v4.contact"`.
- Replace `{{aiAssistantAppDefId}}` with the `appDefId` of your AI Assistant app. 
- Replace `{{newItemToAdd}}` with the object generated by your AI Assistant. This object must match the structure of the entity with the given `fqdn`.


### Basic

Use createAiAssistant with your appDefId to start integrate with your AI assistant

```tsx
import { Avatar } from '@wix/design-system';
import React from 'react';
import {
  Table,
  useTableCollection,
  PrimaryActions,
  createAiAssistant,
} from '@wix/patterns';
import { CollectionPage } from '@wix/patterns/page';
import { contacts } from '@wix/crm';

function AiAssistant() {
  const aiAssistantAppDefId = 'your-app-def-id';

  const state = useTableCollection<contacts.Contact>({
    aiAssistant: createAiAssistant({ appDefId: aiAssistantAppDefId }),
    fqdn: 'wix.cairo.contactsService.v1.contact',
    queryName: 'contacts-AiAssistant',
    itemName: (contact) =>
      `${contact.info?.name?.first} ${contact.info?.name?.last}`,
    fetchData: (query) => {
      const { limit, offset, search, filters } = query;

      let queryBuilder = contacts.queryContacts().limit(limit).skip(offset);

      if (search) {
        queryBuilder = queryBuilder.startsWith('info.name.first', search);
      }

      return queryBuilder.find().then(({ items = [], totalCount: total }) => ({
        items,
        total,
      }));
    },
    fetchErrorMessage: () => 'Error fetching contacts',
    filters: {},
  });

  return (
    <CollectionPage height="400px">
      <CollectionPage.Header
        title={{ text: 'Contacts' }}
        primaryAction={
          <PrimaryActions
            label="Add new item via AI assistant"
            onClick={() => {
              const newItem: contacts.Contact = {
                _id: 'new-item' + Math.random(),
                info: { name: { first: 'New', last: 'Contact' } },
              };
              // This simulates what is happened behind the scenes when the user adds a new item via ai assitant
              // The ai assistant should emit an event on the required structure
              state.loadingRowState.addLoadingItem(newItem._id || '');
              state.collection.addItem(newItem);
            }}
          />
        }
      />
      <CollectionPage.Content>
        <Table
          state={state}
          columns={[
            {
              id: 'avatar',
              name: 'Avatar',
              title: '',
              width: '50px',
              hideable: false,
              render: (contact) => (
                <Avatar
                  name={`${contact.info?.name?.first} ${contact.info?.name?.last}`}
                  imgProps={{ src: contact.info?.picture?.image }}
                />
              ),
            },
            {
              id: 'name',
              title: 'Name',
              width: '250px',
              render: (contact) =>
                `${contact.info?.name?.first} ${contact.info?.name?.last}`,
            },
          ]}
        />
      </CollectionPage.Content>
    </CollectionPage>
  );
}
```

## API

### Props

| Prop | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `appDefId` | `string` | Yes | - | App def id of your ai-assistant |

