> This is a page from the ElevenLabs documentation. For a complete page index, fetch https://elevenlabs.io/docs/llms.txt. For the full documentation in a single file, fetch https://elevenlabs.io/docs/llms-full.txt.

# 検索拡張生成

## 概要

\*\*検索拡張生成（RAG）\*\*を使用すると、エージェントは会話中に大規模なナレッジベースへアクセスして活用できます。ドキュメント全体をコンテキストウィンドウに読み込む代わりに、RAGはユーザーのクエリごとに最も関連性の高い情報だけを取得するため、次のことが可能になります。

* プロンプトに収まりきらないほど大規模なナレッジベースにアクセス
* ナレッジに基づいた、より正確な応答を提供
* ソース資料を参照してハルシネーションを削減
* 複数の専門エージェントを作成せずにナレッジを拡張

RAGは、大量のドキュメント、技術マニュアル、または従来のプロンプトの
コンテキストウィンドウの制限を超える広範なナレッジベースを参照する必要があるエージェントに最適です。
RAGを使用すると、エージェントの応答時間に約250msのわずかなレイテンシーが追加されます。

> **Note**
>
> この動画は以前のバージョンのダッシュボードで収録されています。RAGの設定手順は
> 変わりませんが、一部のインターフェース要素は異なる場合があります。

## RAGの仕組み

RAGを有効にすると、エージェントは次の手順でユーザーのクエリを処理します。

1. **クエリ処理**：ユーザーの質問を分析し、最適な検索のために再構成します。
2. **埋め込みの生成**：処理済みのクエリを、ユーザーの質問を表すベクトル埋め込みに変換します。
3. **検索**：ナレッジベースから意味的に最も類似したコンテンツを検索します。
4. **応答生成**：会話のコンテキストと取得した情報の両方を使用して、エージェントが応答を生成します。

このプロセスにより、ユーザーのクエリに関連する情報がLLMに渡され、事実に基づいた正確な回答を生成できます。

## ガイド

### 前提条件

* [ElevenLabsアカウント](https://elevenlabs.io)
* 設定済みのElevenLabs[会話型エージェント](/docs/ja/eleven-agents/quickstart)
* エージェントのナレッジベースに追加されたドキュメントが1つ以上あること

### エージェントでRAGを有効にする

#### ダッシュボードで更新

エージェントの設定で**ナレッジベース**セクションに移動し、**RAGを使用**オプションをオンにします。必要に応じて、**詳細設定**タブで埋め込みモデル、ドキュメントチャンクの最大数、ベクトル距離の最大値を設定します。

![埋め込みモデルの選択を含むRAG設定オプション](/docs/_fern-img/6e8a6273d26090d92a2ed237ffbc488f44e5e9a408aca6511afa94461d177c86.webp)

#### CLIで更新

#### エージェント設定を取得

```bash
elevenlabs agents pull --agent "<agent-name>"
```

#### \`agent_configs/\<agent-name>.json\`を編集

`conversation_config.agent.prompt.rag`を設定します。

```json
{
  "conversation_config": {
    "agent": {
      "prompt": {
        "rag": {
          "enabled": true,
          "embedding_model": "e5_mistral_7b_instruct",
          "max_vector_distance": 0.6,
          "max_documents_length": 50000,
          "max_retrieved_rag_chunks_count": 20
        }
      }
    }
  }
}
```

#### 変更をプッシュ

```bash
elevenlabs agents push --agent "<agent-name>"
```

#### APIで更新

ドキュメントのRAGインデックス作成をトリガーし、エージェント設定を更新する完全なコードについては、以下の[API実装](#api-implementation)セクションを参照してください。

### ナレッジベースのインデックス作成

ナレッジベース内の各ドキュメントは、RAGで使用する前にインデックスを作成する必要があります。この
処理は、RAGが有効なエージェントにドキュメントを追加すると自動的に行われます。

> **Info**
>
> 大規模なドキュメントでは、インデックス作成に数分かかる場合があります。インデックスのステータスは
> ナレッジベースのリストで確認できます。

### ドキュメントの使用モードを設定する（任意）

ナレッジベース内のドキュメントごとに、使用方法を選択できます。

* **自動（デフォルト）**：クエリに関連する場合にのみドキュメントを取得します
* **プロンプト**：関連性にかかわらず、ドキュメントを常にシステムプロンプトに含めます

![ナレッジベース内のドキュメント使用モードのオプション](/docs/_fern-img/265aa612b4ad2da915b617552312b47c965892559b2a8615ecb42551763de4a5.webp)

> **Warning**
>
> 多数のドキュメントを「プロンプト」モードに設定すると、コンテキストの上限を超える場合があります。重要な情報にのみ
> このオプションを慎重に使用してください。

### RAG有効化済みエージェントをテストする

設定を保存したら、ナレッジベースに関連する質問をしてエージェントをテストしてください。エージェントはドキュメントから特定の情報を取得して参照できるようになります。

## 使用制限

公平なリソース配分のため、ElevenLabsではサブスクリプションティアに応じて、ワークスペースごとにRAG用にインデックスを作成できるドキュメントの合計サイズを制限しています。

制限は次のとおりです。

| サブスクリプションティア | ドキュメント合計サイズの上限 | 注記                                |
| :----------- | :------------- | :-------------------------------- |
| 無料           | 1MB            | 非アクティブな状態が続くとインデックスが削除される場合があります。 |
| スターター        | 2MB            |                                   |
| クリエイター       | 20MB           |                                   |
| プロ           | 100MB          |                                   |
| スケール         | 500MB          |                                   |
| ビジネス         | 1GB            |                                   |
| エンタープライズ     | 1GB            | ティアおよび契約に応じて、より高い上限を利用できます。       |

**注：**

* これらの制限は、RAGインデックス自体の内部ストレージサイズ（大幅に大きくなる場合があります）ではなく、RAG用にインデックスを作成するドキュメントの合計**元ファイルサイズ**に適用されます。
* 500バイト未満のドキュメントはRAG用にインデックスを作成できず、代わりに自動的にプロンプトで使用されます。

## API実装

[API](/docs/ja/api-reference/knowledge-base/compute-rag-index)を通じてRAGを実装することもできます。

```python
from elevenlabs import ElevenLabs
import time

# Initialize the ElevenLabs client
elevenlabs = ElevenLabs(api_key="your-api-key")

# First, index a document for RAG
document_id = "your-document-id"
embedding_model = "e5_mistral_7b_instruct"

# Trigger RAG indexing
response = elevenlabs.conversational_ai.knowledge_base.document.compute_rag_index(
    documentation_id=document_id,
    model=embedding_model
)

# Check indexing status
while response.status not in ["SUCCEEDED", "FAILED"]:
    time.sleep(5)  # Wait 5 seconds before checking status again
    response = elevenlabs.conversational_ai.knowledge_base.document.compute_rag_index(
        documentation_id=document_id,
        model=embedding_model
    )

# Then update agent configuration to use RAG
agent_id = "agent_7101k5zvyjhmfg983brhmhkd98n6"

# Get the current agent configuration
agent_config = elevenlabs.conversational_ai.agents.get(agent_id=agent_id)

# Enable RAG in the agent configuration
agent_config.agent.prompt.rag = {
    "enabled": True,
    "embedding_model": "e5_mistral_7b_instruct",
    "max_documents_length": 10000
}

# Update document usage mode if needed
for i, doc in enumerate(agent_config.agent.prompt.knowledge_base):
    if doc.id == document_id:
        agent_config.agent.prompt.knowledge_base[i].usage_mode = "auto"

# Update the agent configuration
elevenlabs.conversational_ai.agents.update(
    agent_id=agent_id,
    conversation_config=agent_config.agent
)

```

```javascript
// First, index a document for RAG
async function enableRAG(documentId, agentId, apiKey) {
  try {
    // Initialize the ElevenLabs client
    const { ElevenLabsClient } = require("@elevenlabs/elevenlabs-js");
    const elevenlabs = new ElevenLabsClient({
      apiKey: apiKey,
    });

    // Start document indexing for RAG
    let response = await elevenlabs.conversationalAi.knowledgeBase.document.computeRagIndex(
      documentId,
      {
        model: "e5_mistral_7b_instruct",
      }
    );

    // Check indexing status until completion
    while (response.status !== "SUCCEEDED" && response.status !== "FAILED") {
      await new Promise((resolve) => setTimeout(resolve, 5000)); // Wait 5 seconds
      response = await elevenlabs.conversationalAi.knowledgeBase.document.computeRagIndex(
        documentId,
        {
          model: "e5_mistral_7b_instruct",
        }
      );
    }

    if (response.status === "FAILED") {
      throw new Error("RAG indexing failed");
    }

    // Get current agent configuration
    const agentConfig = await elevenlabs.conversationalAi.agents.get(agentId);

    // Enable RAG in the agent configuration
    const updatedConfig = {
      conversation_config: {
        ...agentConfig.agent,
        prompt: {
          ...agentConfig.agent.prompt,
          rag: {
            enabled: true,
            embedding_model: "e5_mistral_7b_instruct",
            max_documents_length: 10000,
          },
        },
      },
    };

    // Update document usage mode if needed
    if (agentConfig.agent.prompt.knowledge_base) {
      agentConfig.agent.prompt.knowledge_base.forEach((doc, index) => {
        if (doc.id === documentId) {
          updatedConfig.conversation_config.prompt.knowledge_base[index].usage_mode = "auto";
        }
      });
    }

    // Update the agent configuration
    await elevenlabs.conversationalAi.agents.update(agentId, updatedConfig);

    console.log("RAG configuration updated successfully");
    return true;
  } catch (error) {
    console.error("Error configuring RAG:", error);
    throw error;
  }
}

// Example usage
// enableRAG('your-document-id', 'agent_7101k5zvyjhmfg983brhmhkd98n6', 'your-api-key')
//   .then(() => console.log('RAG setup complete'))
//   .catch(err => console.error('Error:', err));
```