# 資料參考搜尋

此 API 用於在指定的知識版本（Fileset）中，搜尋與查詢內容相關的參考段落（chunk）。檢索流程與 Chat Completions 的 RAG 相同：先以向量檢索與全文檢索取回候選段落，再由 reranker 排序，回傳最相關的段落。適合在不呼叫 LLM 的情況下，單獨驗證知識版本的檢索結果，或自行組裝 RAG 流程。  
要搜尋的知識版本與查詢內容以 **Query String** 傳入，每次請求只能指定**一個**知識版本；Request Body 用來設定相鄰段落擴充與進階檢索參數。

```bash
curl -X 'POST' \
  'http://127.0.0.1:8000/v1/chat/references?fileset_id={fileset_id}&query={query}' \
  -H 'accept: application/json' \
  -H "Authorization: Bearer $PRIVAI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "include_previous": 0,
    "include_after": 0,
    "search_kwargs": {}
  }'
```

`query` 含中文、空白或 `&` 等特殊字元時，請先做 URL encode 再放入網址。

#### Request Headers

| **Key** | **Value** |
| --- | --- |
| Request Method | POST |
| accept | application/json |
| Authorization | Bearer &lt;your-api-key> |
| Content-Type | application/json |

#### Query Parameters

| **Field** | **Type** | **Detail** | **Required** |
| --- | --- | --- | --- |
| fileset_id | string (uuid) | 知識版本的唯一鍵。該知識版本必須為 `completed` 或 `partial_failed` 狀態，否則回傳 409（`FILESET_006`）。 | true |
| query | string | 搜尋的內容 | true |

#### Request Body

Request Body 為必填，但所有欄位皆為選填，因此送出空物件 `{}` 即可。

```json
{
  "include_previous": 0,
  "include_after": 0,
  "search_kwargs": {}
}
```

| **Field** | **Type** | **Detail** |
| --- | --- | --- |
| include_previous | integer (≥ 0) \| null | 對每個命中段落，額外帶回「同一份檔案中、序號在其之前」的 N 個相鄰段落。未提供時不擴充。 |
| include_after | integer (≥ 0) \| null | 對每個命中段落，額外帶回「同一份檔案中、序號在其之後」的 N 個相鄰段落。未提供時不擴充。 |
| search_kwargs | object | 進階檢索調校參數，一般情境不需要調整；可用的鍵見下表。 |

**search_kwargs 可用的鍵**

| **Key** | **Type** | **Detail** |
| --- | --- | --- |
| k | integer | 檢索階段取回的候選段落數（向量檢索與全文檢索各自取 `k` 筆） |
| n | integer | rerank 後保留的段落數（不含 `include_previous` / `include_after` 帶入的相鄰段落） |
| distance_score_threshold | number (0–1) | 向量檢索的相似度門檻（相似度 = 1 − 餘弦距離），低於門檻的候選段落不會被取回。僅作用於向量檢索；全文檢索的結果不受此門檻影響，交由 reranker 判斷。 |
| rerank_score_threshold | number (0–1) | rerank 後的相關性門檻，`relevance_score` 低於門檻的段落會被捨棄。 |

- 未提供的鍵會使用系統預設值。

#### 關於 `include_previous` / `include_after`

- 這兩個參數用來把命中的段落「往前 / 往後」擴充上下文。相鄰段落以檔案內的 `file_chunk_index` 為序，且僅限**同一份檔案**。

- 回應中每個段落的 `metadata.chunk_role` 標示其角色：命中段落為 `match`，被帶入的相鄰段落為 `before` / `after`。

- 被帶入的相鄰段落**不帶**檢索與 rerank 分數（沒有 `_distance`、`score`、`relevance_score`、`rerank_logit`），請以 `chunk_role` 區分命中段落與補充上下文。

- 重疊或相鄰的擴充範圍會自動合併去重；若重疊的段落本身也是命中段落，以 `match` 為準。

- 有擴充時，結果會以檔案為單位分組：依各檔案在 rerank 結果中首次出現的順序排列，同一範圍內的段落依 `file_chunk_index` 由小到大排列。

#### Response Body

回傳段落列表；沒有任何段落符合條件時回傳空陣列 `[]`。

```json
[
  {
    "id": "c7ea032b-eb16-4ccb-94a6-88af66db5d22",
    "metadata": {
      "file_id": "e2a26cf8-6618-4738-98b0-80520fa19b2c",
      "filename": "The Pragmatic Programmer.pdf",
      "filetype": "application/pdf",
      "file_chunk_index": 12,
      "fileset_id": "a1b2c3d4-1111-2222-3333-444455556666",
      "chunk_role": "match",
      "start_index": 0,
      "end_index": 512,
      "_distance": 0.7463585138320923,
      "score": 0.2536414861679077,
      "relevance_score": 0.40771484375,
      "rerank_logit": -3.736328125
    },
    "page_content": "Filename: The Pragmatic Programmer.pdf\n\n\n...",
    "type": "Document"
  }
]
```

**Field Explanation**

| **Field** | **Detail** |
| --- | --- |
| [] | 搜尋到的參考段落列表；無結果時為空陣列 `[]` |
| `[].id` | 段落（chunk）的唯一鍵，uuid |
| `[].page_content` | 段落的實際內容文字 |
| `[].type` | 固定為 `"Document"` |
| `[].metadata` | 段落的描述性資料（見下列欄位）。實際欄位依檔案格式而異，除下列欄位外，也可能包含切分器附加的章節資訊（例如 `__APMICTextSplitter__h1` ~ `__APMICTextSplitter__h3`）或頁碼位置等欄位 |
| `[].metadata.file_id` | 段落所屬檔案的唯一鍵，uuid |
| `[].metadata.filename` | 檔案名稱 |
| `[].metadata.filetype` | 檔案的 MIME type，例如 `application/pdf`、`text/plain` |
| `[].metadata.file_chunk_index` | 段落在該檔案內的序號（從 0 起算），供 `include_previous` / `include_after` 擴充使用 |
| `[].metadata.fileset_id` | 段落所屬的知識版本 ID |
| `[].metadata.chunk_role` | `match`：命中段落；`before` / `after`：由 `include_previous` / `include_after` 帶入的相鄰段落 |
| `[].metadata.start_index` | 段落在原始文件字元流中的起始位置 |
| `[].metadata.end_index` | 段落在原始文件字元流中的結束位置 |
| `[].metadata._distance` | 向量檢索的餘弦距離（cosine distance），數值越小代表越接近。僅由全文檢索命中的段落不會有此欄位 |
| `[].metadata.score` | 由向量距離換算的相似度分數（1 − `_distance`）。僅由全文檢索命中的段落不會有此欄位 |
| `[].metadata.relevance_score` | reranker 分數經正規化後的相關性分數（0～1），為最終排序與 `rerank_score_threshold` 過濾的依據 |
| `[].metadata.rerank_logit` | reranker 正規化前的原始 logit 分數 |

#### 錯誤處理

| **Error Code** | **HTTP Status** | **Scenario** |
| --- | --- | --- |
| `FILESET_001` | 404 | 指定的知識版本不存在 |
| `FILESET_006` | 409 | 指定的知識版本不是 `completed` 或 `partial_failed` 狀態；回應會附帶 `fileset_id` 與 `state` |
| `CHAT_001` | 413 | 查詢內容過長，embedding / rerank 服務無法處理 |
| `CHAT_002` | 502 | Reranker 服務失敗 |
| `CHAT_003` | 502 | Embedding 服務失敗 |

缺少 `fileset_id` 或 `query`、`fileset_id` 不是合法的 UUID、未送出 Request Body，或 `include_previous` / `include_after` 小於 0 時，回傳 422 Validation Error。各錯誤代碼的完整說明請參考 [錯誤代碼說明-知識版本管理類](https://privstation-docs.apmic.ai/latest/privai-400/錯誤代碼說明-知識版本管理類.md) 與 [錯誤代碼說明-Chat](https://privstation-docs.apmic.ai/latest/privai-400/錯誤代碼說明-chat.md)。
