> For the complete documentation index, see [llms.txt](https://docs.maiagent.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.maiagent.ai/tech/quickstart/rag.md).

# RAG 知識庫檢索系統

RAG（Retrieval-Augmented Generation，檢索增強生成）先從知識庫找出相關段落，再交給大型語言模型作答。本頁說明 MaiAgent 的資料處理與檢索流程：解析、向量化、混合檢索、Reranker、相似度門檻與標籤過濾。

RAG（Retrieval-Augmented Generation，檢索增強生成）讓大型語言模型在回答前，先從知識庫找出與問題相關的段落，再依這些段落作答。模型因此能引用組織自己的文件，而不只依賴訓練資料。

<figure><img src="https://527168072-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F38pkhhqHl1oA6yyE9R2n%2Fuploads%2Fgit-blob-0ce05108866ecded0daa5a9fb3cd8b9137ffef26%2F2%20(1).png?alt=media" alt=""><figcaption><p>RAG 流程</p></figcaption></figure>

可以把 RAG 想成開書考試：模型不必背下所有資料，而是每次作答前先翻知識庫，找出和題目最相關的段落當作依據。也因為如此，知識庫只放與 Agent 任務相關的資料比較好；不相關的內容仍可能被檢索出來當成上下文，反而讓回答失準。

本頁說明 MaiAgent 實際的處理流程與可調整的參數。後台操作步驟見使用者手冊的 [知識庫總覽](https://docs.maiagent.ai/build/knowledge-base/km)。

## 資料如何進入知識庫 <a href="#ingestion" id="ingestion"></a>

上傳到知識庫的檔案會依序經過：

1. **解析**：解析器把檔案轉成文字（必要時含表格與圖片），見 [Parser 解析工具](/tech/quickstart/parser.md)。
2. **切塊**：文字切成段落（chunk），之後檢索與引用都以段落為單位。
3. **向量化**：以知識庫選定的 Embedding 模型把每個段落轉成向量，見 [Embedding 模型](/tech/quickstart/embedding.md)。
4. **寫入向量資料庫**：段落文字與向量一起寫入向量資料庫，預設使用平台內建的資料庫；也可以改接自己的資料庫，見 [自帶向量資料庫](/tech/platform-development/bring-your-own-vector-db.md)。

檔案狀態變成 `done` 後，內容才會被檢索到。

## 一次檢索的流程 <a href="#retrieval-flow" id="retrieval-flow"></a>

### 1. 決定檢索範圍 <a href="#scope" id="scope"></a>

檢索前，平台先決定這次可以查哪些知識庫、檔案與標籤，並把條件直接加在向量資料庫的查詢上。不在範圍內的段落根本不會被查出來，也就不會進入模型。

範圍依序取自：訊息 → 對話 → 聯絡人的查詢元資料（Query Metadata）；三者都沒有設定時，套用 Agent 的預設標籤過濾；都沒有時查詢整個知識庫。設定方式見 [Query Metadata 總覽](/tech/identity-and-access/zhi-shi-guan-li-quan-xian-query-metadata-cha-xun-yuan-zi-liao-zong-lan.md) 與使用者手冊的 [知識庫標籤過濾](https://docs.maiagent.ai/build/agent/label-filter)。

{% hint style="warning" %}
要限制「誰能看到哪些文件」，請用查詢元資料或標籤過濾，不要只靠角色指令。角色指令是在檢索之後才給模型的文字，擋不住已經被檢索出來的段落。
{% endhint %}

### 2. 混合檢索 <a href="#hybrid-search" id="hybrid-search"></a>

預設以**混合檢索**同時進行兩種查詢：

* **向量檢索**：用問題的向量找語意相近的段落，措辭不同也找得到。
* **關鍵字檢索（BM25）**：比對字詞，適合產品型號、專有名詞、代碼。

知識庫開啟 <mark style="color:blue;">啟用 Reciprocal Rank Fusion</mark>（RRF）時，兩種結果以 RRF 依排名合併。在 Elasticsearch 上使用 RRF 需要 Enterprise、Platinum 或 Trial 授權；自帶的 Elasticsearch 沒有這類授權時，後台會自動關閉這個選項。平台關閉混合檢索時，改為只用向量檢索。

Agent 對話時一律依平台設定檢索，不能另選模式。後台的 [搜尋測試](https://docs.maiagent.ai/build/knowledge-base/test-search-result#search-modes) 與 [知識庫檢索 API](/tech/api-integration/knowledge-base-api.md#search-knowledge-base) 則可以另外指定只用向量（<mark style="color:blue;">語意搜尋</mark>，`semantic`）或只用關鍵字（<mark style="color:blue;">關鍵字搜尋</mark>，`keyword`，僅 Elasticsearch），方便比對兩種檢索各自找到什麼。

### 3. Reranker 重新排序 <a href="#rerank" id="rerank"></a>

知識庫開啟 <mark style="color:blue;">啟用搜尋結果重排序 (Reranking)</mark> 時，第一階段會先多取一些候選段落（<mark style="color:blue;">檢索片段數量</mark> × 平台設定的放大係數，預設 7 倍），再由 Reranker 模型逐一比對問題與段落、重新評分，只保留分數最高的 <mark style="color:blue;">檢索片段數量</mark> 筆。說明見 [Reranker 模型](/tech/quickstart/reranker.md)。

組織 Credits 低於平台門檻時，該次對話會略過 Reranker，直接使用第一階段的結果。

### 4. 相似度門檻 <a href="#similarity-cutoff" id="similarity-cutoff"></a>

<mark style="color:blue;">相似度門檻值（0-1）</mark> 會濾掉 Reranker 評分低於門檻的段落。預設為 0，代表不過濾。門檻作用在 Reranker 的分數上，所以**只有開啟 Reranker 時才有效**。設得太高時，可能一筆段落都不剩，模型就沒有參考資料可用。

### 5. 多個知識庫的合併 <a href="#multiple-knowledge-bases" id="multiple-knowledge-bases"></a>

Agent 掛了多個知識庫時，各知識庫的結果會合併，再依 Agent 的 <mark style="color:blue;">檢索區塊最大數量</mark> 決定最後送進模型的段落數。只要這次查到的知識庫中有一個開啟 Reranker，合併後的結果就會再經過一次重新排序。

### 6. 送進模型並標示引用 <a href="#generation" id="generation"></a>

選出的段落連同 Agent 的角色指令一起送進大型語言模型。檔案的中繼資料欄位勾選 <mark style="color:blue;">檢索時使用</mark> 時，該欄位的值也會一併送進模型，作為回答判斷的參考。回覆中的引用會連回來源段落與檔案。

## Agentic RAG：Agent 模式下的檢索 <a href="#agentic-rag" id="agentic-rag"></a>

上面的流程是「一次檢索、一次生成」：每則訊息固定先檢索再回答，模型不決定要不要查、查什麼。Agentic RAG 則把檢索交給模型決定：模型在回答過程中可以多次呼叫檢索，依前一次結果調整查詢、換關鍵字或改讀另一份檔案，再整理成回答。

在 MaiAgent，兩者對應 Agent 的回答模式：

| 回答模式                              | 檢索方式                                                                                                            |
| --------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| RAG 問答（API 的 `replyMode: normal`） | 一次檢索：每則訊息依本頁流程檢索一次，段落直接送進模型                                                                                     |
| Agent 模式（`replyMode: agent`）      | Agentic RAG：知識庫以工具的形式交給模型，模型可在同一回合內多次檢索段落、依檔名或中繼資料篩選檔案、以關鍵字搜尋檔案內容、讀取整份檔案，每次呼叫都走本頁的檢索流程（包含 Query Metadata 的範圍限制） |

Agent 模式的檢索輪數受 Agent 的執行上限約束（見 [Function Calling：執行上限](/tech/advanced-genai-tech/function-calling.md#limits)），延遲與用量也比一次檢索高。問答型、答案在單一段落的場景用 RAG 問答即可；需要比對多份文件、先找檔再細讀的場景再用 Agent 模式。

## 對話模式與 Agent 模式怎麼查知識庫 <a href="#chat-vs-agent-retrieval" id="chat-vs-agent-retrieval"></a>

承上節，兩種模式的差異逐項對照如下：

|                           | RAG 問答（對話模式，`replyMode: normal`）                                                                             | Agent 模式（`replyMode: agent`）                                                                                                                                                        |
| ------------------------- | ------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 何時檢索                      | 每一則訊息回答前**固定**先檢索一次，不經模型判斷                                                                                   | 檢索是**工具**，模型依問題決定要不要呼叫、呼叫幾次、用什麼查詢字串                                                                                                                                                 |
| 取幾筆                       | 每個知識庫各取自己的 <mark style="color:blue;">檢索片段數量</mark>，合併後依 Agent 的 <mark style="color:blue;">檢索區塊最大數量</mark> 截斷 | `retrieve_text_nodes` 工具由模型自填 `top_k`（預設 3），所以通常少於檢索片段數量；Agent 勾選 <mark style="color:blue;">強制使用完整檢索範圍</mark> 時，一律改用 <mark style="color:blue;">檢索區塊最大數量</mark>                      |
| 可用的工具                     | 無，只有這次檢索到的段落                                                                                                 | `retrieve_text_nodes`（語意／混合檢索）、`query_files`（列出檔案與中繼資料）、`grep_files`（在檔案內容比對字串）、`read_file`（整份讀取）、`get_surrounding_context`（取段落前後文）、`image_search`（多模態知識庫找圖，可在工具設定關閉）               |
| 查詢元資料、標籤過濾、Reranker、相似度門檻 | 兩種模式都套用，規則相同                                                                                                 |                                                                                                                                                                                     |
| 對話中上傳的附件                  | 上傳時立即解析、建索引，回答時與知識庫一起檢索，取 Agent 的檢索區塊最大數量                                                                    | 上傳時不解析；Agent 依問題用附件工具（`parse_attachment_content`、`read_attachment_full_text`、`ingest_attachment`）讀取或建索引，見 [訊息附件怎麼被處理](/tech/api-integration/api_knowledge.md#attachment-processing) |
| 搜尋結果不理想時                  | 調整知識庫參數與 Agent 的檢索區塊最大數量                                                                                     | 先確認模型有沒有呼叫檢索工具（在[對話詳情與執行時間軸](https://docs.maiagent.ai/build/agent-ops/evaluations/trace-timeline)看工具呼叫），再調參數或在角色指令要求先查知識庫                                                           |

{% hint style="warning" %}
Agent 開啟 <mark style="color:blue;">啟用工具搜尋功能</mark>（動態工具搜尋）時，知識庫工具也在「要先搜尋才載入」的池子裡，和 Text to SQL、API 工具一樣要先呼叫 `tool_searching_tool`。模型偶爾會跳過搜尋、回答「沒有知識庫檢索工具」而只用其他工具；遇到時在角色指令寫明「回答前先用 `retrieve_text_nodes` 查詢知識庫」，或關閉工具搜尋讓所有工具直接可用。掛載知識庫本身不會自動檢索，也不需要另外建立檢索工具。
{% endhint %}

## 可調整的參數 <a href="#parameters" id="parameters"></a>

| 參數                                                         | 設定位置  | 預設值   | 說明                                    |
| ---------------------------------------------------------- | ----- | ----- | ------------------------------------- |
| <mark style="color:blue;">Embedding 模型</mark>              | 知識庫   | 依平台設定 | 建立後無法在後台更改；需要更換時請另建知識庫，或洽 MaiAgent 窗口 |
| <mark style="color:blue;">檢索片段數量</mark>                    | 知識庫   | 12    | 每個知識庫最多取回的段落數，最小值 1                   |
| <mark style="color:blue;">啟用搜尋結果重排序 (Reranking)</mark>     | 知識庫   | 開啟    | 開啟後使用知識庫選定的 Reranker 模型               |
| <mark style="color:blue;">相似度門檻值（0-1）</mark>               | 知識庫   | 0     | 只在開啟 Reranker 時生效                     |
| <mark style="color:blue;">啟用 Reciprocal Rank Fusion</mark> | 知識庫   | 依平台設定 | 混合檢索的合併方式；OpenSearch 的混合檢索必須開啟        |
| <mark style="color:blue;">檢索區塊最大數量</mark>                  | Agent | 12    | 對話時最後送進模型的段落數；介面建議 5～15，數值越高延遲越高      |

想確認某個問題會檢索到哪些段落，可以使用後台的 [搜尋測試](https://docs.maiagent.ai/build/knowledge-base/test-search-result)，或呼叫 [知識庫檢索 API](/tech/api-integration/knowledge-base-api.md#search-knowledge-base)。

### 怎麼調 <a href="#tuning-guide" id="tuning-guide"></a>

片段大小與重疊由解析器決定，後台沒有欄位可調；能調的是下列參數。每次只改一項，用同一組問題在搜尋測試比較。

| 症狀                 | 先檢查                                 | 再調整                                                |
| ------------------ | ----------------------------------- | -------------------------------------------------- |
| 正確段落找得到，但排在很後面或被截掉 | 搜尋測試中它排第幾                           | 開啟 Reranker；仍不夠時提高檢索片段數量與檢索區塊最大數量（延遲與 token 會增加）   |
| 常帶進不相關的段落          | 開啟 Reranker 後各段落的順序                 | 調高相似度門檻值（每次加 0.05～0.1，太高會一筆都不剩）；或用標籤過濾縮小範圍         |
| 型號、代碼、專有名詞找不到      | 用關鍵字搜尋能不能找到                         | 確認文件中的寫法和使用者一致；混合檢索關閉時改回開啟（Elasticsearch 需 RRF 授權） |
| 表格或長文件只答到一半        | 片段是否把表格切開                           | 換解析器重新解析、在片段內補上表頭或章節名稱，或在 Agent 勾選強制使用完整檢索範圍       |
| 回答只用到附件、沒用知識庫（或相反） | Agent 模式下工具呼叫記錄                     | 在角色指令寫明先查知識庫；對話模式下兩者會一起檢索，提高檢索區塊最大數量               |
| Reranker 開了但沒效果    | 組織 Credits 是否低於平台門檻（會自動略過 Reranker） | 先儲值，再比較                                            |

Embedding 模型建立後不能換，換模型等於重建知識庫；請在上線前用搜尋測試比較不同模型的結果再定案。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.maiagent.ai/tech/quickstart/rag.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
