# AI Search

{% hint style="info" %}
**需要 AI Search 插件。** 此功能需要安装并启用 [AI Search](https://eagle.cool/support/article/ai-search) 插件。
{% endhint %}

***

## AI Search 插件简介

「AI Search」是一款提供 AI 语意搜索功能的插件，支持文字语意搜索、以图搜图等智能搜索能力。通过整合此插件，开发者可以在自己的插件中轻松实现强大的 AI 搜索功能。

### 主要功能

* **文字语意搜索** - 使用自然语言描述，搜索相关图片
* **以图搜图** - 使用图片搜索相似的图片
* **Item ID 搜索** - 根据已有项目搜索相似图片

***

## 如何使用 AI Search

使用 `eagle.extraModule.aiSearch` 来调用 AI Search 插件提供的功能。

### 状态查询

在调用搜索方法前，建议先检查服务状态：

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

    // 检查插件是否已安装
    const isInstalled = await aiSearch.isInstalled();
    console.log('已安装:', isInstalled);

    // 检查服务是否就绪
    const isReady = await aiSearch.isReady();
    console.log('服务就绪:', isReady);

    // 检查是否正在启动中
    const isStarting = await aiSearch.isStarting();
    console.log('启动中:', isStarting);

    // 检查是否正在同步数据
    const isSyncing = await aiSearch.isSyncing();
    console.log('同步中:', isSyncing);
});
```

### 服务控制

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

    // 打开 AI Search 插件（若未安装会提示安装）
    await aiSearch.open();

    // 检查服务健康状态
    const isHealthy = await aiSearch.checkServiceHealth();
    console.log('服务健康:', isHealthy);

    // 获取同步状态详情
    const syncStatus = await aiSearch.getSyncStatus();
    console.log('同步状态:', syncStatus);
});
```

***

## 搜索方法

### searchByText(query, options) - 文字语意搜索

使用自然语言描述搜索相关图片。

* `query` string - 搜索关键字或描述
* `options` Object (可选) - 搜索选项
  * `limit` number - 结果数量限制，默认 20
* 返回 `Promise<Object>` - 搜索结果
  * `results` Array - 搜索结果数组
    * `item` Item - 完整的 Item 对象
    * `score` number - 相似度分数

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

    // 检查服务是否就绪
    if (!await aiSearch.isReady()) {
        console.log('AI Search 服务尚未就绪');
        return;
    }

    // 文字语意搜索
    const result = await aiSearch.searchByText('一只橘色的猫咪', {
        limit: 10
    });

    // 遍历搜索结果
    result.results.forEach(r => {
        console.log('相似度:', r.score);
        console.log('文件名称:', r.item.name);
        console.log('标签:', r.item.tags);
    });
});
```

### searchByBase64(base64, options) - Base64 图片搜索

使用 Base64 编码的图片搜索相似图片。

* `base64` string - Base64 编码的图片字符串
* `options` Object (可选) - 搜索选项
  * `limit` number - 结果数量限制，默认 20
* 返回 `Promise<Object>` - 搜索结果

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

    // 使用 Base64 图片搜索
    const base64Image = 'data:image/jpeg;base64,/9j/4AAQSkZJRg...';
    const result = await aiSearch.searchByBase64(base64Image, {
        limit: 20
    });

    console.log('找到', result.results.length, '个相似图片');

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

### searchByItemId(itemId, options) - 以现有项目搜索

使用已存在的 Eagle 项目 ID 搜索相似图片。

* `itemId` string - Eagle 项目 ID
* `options` Object (可选) - 搜索选项
  * `limit` number - 结果数量限制，默认 20
* 返回 `Promise<Object>` - 搜索结果

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

    // 获取当前选中的项目
    const selectedItems = await eagle.item.get({ isSelected: true });

    if (selectedItems.length === 0) {
        console.log('请先选择一个项目');
        return;
    }

    // 使用选中项目的 ID 搜索相似图片
    const result = await aiSearch.searchByItemId(selectedItems[0].id, {
        limit: 30
    });

    console.log('找到', result.results.length, '个相似图片');

    // 结果中的 item 是完整的 Item 对象，可以直接使用其方法
    for (const r of result.results) {
        console.log(`${r.item.name} (${r.item.ext}) - 相似度: ${r.score}`);

        // 可以直接使用 Item 的方法
        // await r.item.save();
    }
});
```

***

## 完整示例

### 创建相似图片搜索功能

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

    // 1. 检查服务状态
    if (!await aiSearch.isInstalled()) {
        // 打开安装提示
        await aiSearch.open();
        return;
    }

    if (!await aiSearch.isReady()) {
        console.log('请等待 AI Search 服务启动完成');
        return;
    }

    // 2. 执行搜索
    try {
        const result = await aiSearch.searchByText('日落时的海滩风景');

        if (result.results.length === 0) {
            console.log('没有找到相关图片');
            return;
        }

        // 3. 处理搜索结果
        const topResults = result.results
            .filter(r => r.score > 0.5)  // 只保留相似度 > 50% 的结果
            .slice(0, 10);               // 取前 10 个

        console.log(`找到 ${topResults.length} 个高相关度图片：`);

        topResults.forEach((r, index) => {
            console.log(`${index + 1}. ${r.item.name}`);
            console.log(`   相似度: ${(r.score * 100).toFixed(1)}%`);
            console.log(`   尺寸: ${r.item.width} x ${r.item.height}`);
            console.log(`   标签: ${r.item.tags.join(', ') || '无'}`);
        });

        // 4. 可以进一步操作这些项目
        // 例如：选中这些项目
        const itemIds = topResults.map(r => r.item.id);
        await eagle.item.select(itemIds);

    } catch (error) {
        console.error('搜索失败:', error.message);
    }
});
```

***

## API 参考

### 状态查询方法

| 方法              | 返回类型               | 说明                   |
| --------------- | ------------------ | -------------------- |
| `isInstalled()` | `Promise<boolean>` | 检查 AI Search 插件是否已安装 |
| `isReady()`     | `Promise<boolean>` | 检查服务是否就绪可用           |
| `isStarting()`  | `Promise<boolean>` | 检查服务是否正在启动中          |
| `isSyncing()`   | `Promise<boolean>` | 检查是否正在同步数据           |

### 服务控制方法

| 方法                     | 返回类型               | 说明              |
| ---------------------- | ------------------ | --------------- |
| `open()`               | `Promise<void>`    | 打开 AI Search 插件 |
| `checkServiceHealth()` | `Promise<boolean>` | 检查服务健康状态        |
| `getSyncStatus()`      | `Promise<Object>`  | 获取详细的同步状态       |

### 搜索方法

| 方法                                 | 返回类型              | 说明            |
| ---------------------------------- | ----------------- | ------------- |
| `searchByText(query, options?)`    | `Promise<Object>` | 文字语意搜索        |
| `searchByBase64(base64, options?)` | `Promise<Object>` | Base64 图片搜索   |
| `searchByItemId(itemId, options?)` | `Promise<Object>` | 以项目 ID 搜索相似图片 |

### 搜索结果格式

```javascript
{
    // ... 其他字段
    results: [
        {
            item: Item,    // 完整的 Item 对象，包含所有属性和方法
            score: number  // 相似度分数 (0-1)
        },
        // ...
    ]
}
```

{% hint style="info" %}
**提示**：搜索结果中的 `item` 是完整的 Item 对象实例，可以直接使用 `save()`、`refreshThumbnail()` 等所有 Item 方法。
{% endhint %}
