# AI Search

{% hint style="info" %}
**Requires AI Search Plugin.** This feature requires the [AI Search](https://eagle.cool/support/article/ai-search) plugin to be installed and running.
{% endhint %}

***

## Introduction to AI Search Plugin

"AI Search" is a plugin that provides AI semantic search capabilities, supporting text-based semantic search and image-based similarity search. By integrating this plugin, developers can easily implement powerful AI search functionality in their own plugins.

### Key Features

* **Text Semantic Search** - Search for related images using natural language descriptions
* **Image-based Search** - Find similar images using an image
* **Item ID Search** - Find similar images based on existing items

***

## How to Use AI Search

Use `eagle.extraModule.aiSearch` to access the AI Search plugin functionality.

### Status Queries

Before calling search methods, it's recommended to check the service status:

```javascript
eagle.onPluginCreate(async (plugin) => {
    const aiSearch = eagle.extraModule.aiSearch;

    // Check if the plugin is installed
    const isInstalled = await aiSearch.isInstalled();
    console.log('Installed:', isInstalled);

    // Check if the service is ready
    const isReady = await aiSearch.isReady();
    console.log('Service Ready:', isReady);

    // Check if the service is starting
    const isStarting = await aiSearch.isStarting();
    console.log('Starting:', isStarting);

    // Check if data is syncing
    const isSyncing = await aiSearch.isSyncing();
    console.log('Syncing:', isSyncing);
});
```

### Service Control

```javascript
eagle.onPluginCreate(async (plugin) => {
    const aiSearch = eagle.extraModule.aiSearch;

    // Open AI Search plugin (will prompt installation if not installed)
    await aiSearch.open();

    // Check service health
    const isHealthy = await aiSearch.checkServiceHealth();
    console.log('Service Healthy:', isHealthy);

    // Get sync status details
    const syncStatus = await aiSearch.getSyncStatus();
    console.log('Sync Status:', syncStatus);
});
```

***

## Search Methods

### searchByText(query, options) - Text Semantic Search

Search for related images using natural language descriptions.

* `query` string - Search keywords or description
* `options` Object (optional) - Search options
  * `limit` number - Result count limit, default 20
* Returns `Promise<Object>` - Search results
  * `results` Array - Array of search results
    * `item` Item - Complete Item object
    * `score` number - Similarity score

```javascript
eagle.onPluginCreate(async (plugin) => {
    const aiSearch = eagle.extraModule.aiSearch;

    // Check if service is ready
    if (!await aiSearch.isReady()) {
        console.log('AI Search service is not ready');
        return;
    }

    // Text semantic search
    const result = await aiSearch.searchByText('an orange cat', {
        limit: 10
    });

    // Iterate through search results
    result.results.forEach(r => {
        console.log('Similarity:', r.score);
        console.log('File Name:', r.item.name);
        console.log('Tags:', r.item.tags);
    });
});
```

### searchByBase64(base64, options) - Base64 Image Search

Search for similar images using a Base64 encoded image.

* `base64` string - Base64 encoded image string
* `options` Object (optional) - Search options
  * `limit` number - Result count limit, default 20
* Returns `Promise<Object>` - Search results

```javascript
eagle.onPluginCreate(async (plugin) => {
    const aiSearch = eagle.extraModule.aiSearch;

    // Search using Base64 image
    const base64Image = 'data:image/jpeg;base64,/9j/4AAQSkZJRg...';
    const result = await aiSearch.searchByBase64(base64Image, {
        limit: 20
    });

    console.log('Found', result.results.length, 'similar images');

    result.results.forEach(r => {
        console.log(`${r.item.name} - Similarity: ${(r.score * 100).toFixed(1)}%`);
    });
});
```

### searchByItemId(itemId, options) - Search by Existing Item

Search for similar images using an existing Eagle item ID.

* `itemId` string - Eagle item ID
* `options` Object (optional) - Search options
  * `limit` number - Result count limit, default 20
* Returns `Promise<Object>` - Search results

```javascript
eagle.onPluginCreate(async (plugin) => {
    const aiSearch = eagle.extraModule.aiSearch;

    // Get currently selected items
    const selectedItems = await eagle.item.get({ isSelected: true });

    if (selectedItems.length === 0) {
        console.log('Please select an item first');
        return;
    }

    // Search for similar images using the selected item's ID
    const result = await aiSearch.searchByItemId(selectedItems[0].id, {
        limit: 30
    });

    console.log('Found', result.results.length, 'similar images');

    // The item in results is a complete Item object with all methods available
    for (const r of result.results) {
        console.log(`${r.item.name} (${r.item.ext}) - Similarity: ${r.score}`);

        // You can directly use Item methods
        // await r.item.save();
    }
});
```

***

## Complete Example

### Building a Similar Image Search Feature

```javascript
eagle.onPluginCreate(async (plugin) => {
    const aiSearch = eagle.extraModule.aiSearch;

    // 1. Check service status
    if (!await aiSearch.isInstalled()) {
        // Open installation prompt
        await aiSearch.open();
        return;
    }

    if (!await aiSearch.isReady()) {
        console.log('Please wait for AI Search service to start');
        return;
    }

    // 2. Execute search
    try {
        const result = await aiSearch.searchByText('sunset beach scenery');

        if (result.results.length === 0) {
            console.log('No related images found');
            return;
        }

        // 3. Process search results
        const topResults = result.results
            .filter(r => r.score > 0.5)  // Keep only results with similarity > 50%
            .slice(0, 10);               // Take top 10

        console.log(`Found ${topResults.length} highly relevant images:`);

        topResults.forEach((r, index) => {
            console.log(`${index + 1}. ${r.item.name}`);
            console.log(`   Similarity: ${(r.score * 100).toFixed(1)}%`);
            console.log(`   Size: ${r.item.width} x ${r.item.height}`);
            console.log(`   Tags: ${r.item.tags.join(', ') || 'None'}`);
        });

        // 4. Further operations on these items
        // For example: select these items
        const itemIds = topResults.map(r => r.item.id);
        await eagle.item.select(itemIds);

    } catch (error) {
        console.error('Search failed:', error.message);
    }
});
```

***

## API Reference

### Status Query Methods

| Method          | Return Type        | Description                            |
| --------------- | ------------------ | -------------------------------------- |
| `isInstalled()` | `Promise<boolean>` | Check if AI Search plugin is installed |
| `isReady()`     | `Promise<boolean>` | Check if service is ready              |
| `isStarting()`  | `Promise<boolean>` | Check if service is starting           |
| `isSyncing()`   | `Promise<boolean>` | Check if data is syncing               |

### Service Control Methods

| Method                 | Return Type        | Description                 |
| ---------------------- | ------------------ | --------------------------- |
| `open()`               | `Promise<void>`    | Open AI Search plugin       |
| `checkServiceHealth()` | `Promise<boolean>` | Check service health status |
| `getSyncStatus()`      | `Promise<Object>`  | Get detailed sync status    |

### Search Methods

| Method                             | Return Type       | Description                      |
| ---------------------------------- | ----------------- | -------------------------------- |
| `searchByText(query, options?)`    | `Promise<Object>` | Text semantic search             |
| `searchByBase64(base64, options?)` | `Promise<Object>` | Base64 image search              |
| `searchByItemId(itemId, options?)` | `Promise<Object>` | Search similar images by item ID |

### Search Result Format

```javascript
{
    // ... other fields
    results: [
        {
            item: Item,    // Complete Item object with all properties and methods
            score: number  // Similarity score (0-1)
        },
        // ...
    ]
}
```

{% hint style="info" %}
**Tip**: The `item` in search results is a complete Item object instance. You can directly use methods like `save()`, `refreshThumbnail()`, and all other Item methods.
{% endhint %}
