跳至主要内容

文件管理

Documents API 讓你透過 API 上傳、管理知識庫文件,控制文件的向量化狀態,以及查看切分結果。

支援的文件格式

格式MIME 類型說明
PDFapplication/pdf.pdf 格式
Markdowntext/markdown程式碼、技術文件首選
Wordapplication/vnd.openxmlformats....docx 格式
純文字text/plain.txt 格式
HTMLtext/html網頁內容

上傳文件

import { readFile } from 'node:fs/promises';

const buffer = await readFile('./faq.pdf');

const doc = await client.documents.upload({
file: buffer,
filename: 'faq.pdf',
contentType: 'application/pdf',
// 切分設定(可選,不設定使用專案預設值)
chunk_strategy: 'recursive', // 切分策略
chunk_size: 800, // 每個段落最大字元數
chunk_overlap: 80, // 相鄰段落重疊的字元數
metadata: { category: 'support', version: '2026-01' },
});

console.log('文件 ID:', doc.id);
console.log('狀態:', doc.status); // processing | ready | failed

上傳後,系統會非同步處理文件。處理完成(狀態 ready)後才能被 RAG 查詢到。

文件狀態

狀態說明
processing正在解析和向量化,尚未可用
ready處理完成,可被 RAG 查詢
failed處理失敗(格式不支援、文件損壞等)
inactive已停用,不會出現在 RAG 結果中

查詢文件清單

const list = await client.documents.list({
search: 'faq', // 按文件名稱搜尋(可選)
page: 1,
page_size: 20,
});

console.log(`${list.total} 份文件`);
for (const doc of list.documents) {
console.log(`${doc.filename}${doc.status}${doc.chunk_count} 個段落`);
}

取得文件詳情

const doc = await client.documents.retrieve('doc-uuid');
console.log('文件名稱:', doc.filename);
console.log('段落數:', doc.chunk_count);
console.log('切分策略:', doc.chunk_strategy);

停用與啟用文件

停用後的文件不會出現在 RAG 查詢結果中,但檔案還在,可以重新啟用。

// 停用:從 RAG 中移除,但保留檔案
await client.documents.deactivate('doc-uuid');

// 啟用:重新加入 RAG,會重新排隊向量化
await client.documents.activate('doc-uuid');

重新索引

當你修改了切分設定,或文件向量化出現問題時,可以觸發重新索引:

// 先更新切分設定
await client.documents.updateChunking('doc-uuid', {
chunk_strategy: 'semantic',
chunk_semantic_threshold: 0.75,
});

// 再觸發重新索引
await client.documents.reindex('doc-uuid');

查看切分結果

可以查看文件被切成了哪些段落,確認切分品質:

const { chunks, total } = await client.documents.chunks('doc-uuid');
console.log(`${total} 個段落`);
for (const chunk of chunks.slice(0, 5)) {
console.log(`段落 ${chunk.index}: ${chunk.content.slice(0, 100)}...`);
}

刪除文件

await client.documents.delete('doc-uuid');
// 刪除後無法復原,向量資料和原始檔案都會一起刪除

切分策略說明

切分(Chunking) 是指把長文件分割成較小的段落,以便向量化和語義搜尋。

切分方式會直接影響搜尋品質。以下是各策略的適用情境:

策略說明適合的文件類型
recursive按文件結構遞迴切分(預設)一般文件、Markdown
fixed按固定字元數切分格式簡單的文件
semantic按語義完整性切分長篇文章、報告
sentence以句子為最小單位FAQ、對話記錄
parent_child雙層索引,保留上下文需要理解前後文的文件
llm用 AI 判斷切分位置需要高精度的重要文件

推薦配置

文件類型建議策略chunk_sizechunk_overlap
PDF 手冊recursive1000200
Markdown 文件recursive1000100
FAQsentence5000
長篇報告parent_child2000200

注意事項

  • 文件大小上限依方案而定
  • PDF 中的圖片文字會透過 AI 視覺辨識,可能較耗時
  • 重新索引會消耗 Embedding Credits
  • 需要 source.write 權限才能上傳和管理文件