# 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 %}


---

# Agent Instructions: 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:

```
GET https://developer.eagle.cool/plugin-api/ja-jp/extra-module/ai-search.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
