> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # .chunk() `.chunk()` 函數會按指定的策略和選項,將文件分割成較小的片段。 ## 範例 ```typescript import { MDocument } from '@mastra/rag' const doc = MDocument.fromMarkdown(` # Introduction This is a sample document that we want to split into chunks. ## Section 1 Here is the first section with some content. ## Section 2 Here is another section with different content. `) // Basic chunking with defaults const chunks = await doc.chunk() // Markdown-specific chunking with header extraction const chunksWithMetadata = await doc.chunk({ strategy: 'markdown', headers: [ ['#', 'title'], ['##', 'section'], ], extract: { summary: true, // Extract summaries with default settings keywords: true, // Extract keywords with default settings }, }) ``` ## 參數 以下參數適用於所有分塊策略。 每項策略只會使用與其特定用途相關的部分參數。 **strategy** (`'recursive' | 'character' | 'token' | 'markdown' | 'semantic-markdown' | 'html' | 'json' | 'latex' | 'sentence'`): 要使用的分塊策略。如未指定,系統會按文件類型採用預設值。視乎分塊策略,亦會有額外的選用設定。預設值:.md 檔案 → 'markdown'、.html/.htm → 'html'、.json → 'json'、.tex → 'latex',其他類型 → 'recursive' **maxSize** (`number`): 每個片段的大小上限。部分策略設定(帶有標題的 markdown、帶有標題的 HTML)會忽略此參數。 (Default: `4000`) **overlap** (`number`): 片段之間重疊的字元/token 數目。 (Default: `50`) **lengthFunction** (`(text: string) => number`): 計算文字長度的函數。預設按字元數目計算。 **separatorPosition** (`'start' | 'end'`): 分隔符在片段中的位置。'start' 會將分隔符附加至下一個片段的開首,'end' 則附加至目前片段的結尾。如未指定,分隔符會被捨棄。 **addStartIndex** (`boolean`): 是否在片段中加入起始索引 metadata。 (Default: `false`) **stripWhitespace** (`boolean`): 是否移除片段中的空白字元。 (Default: `true`) **extract** (`ExtractParams`): Metadata 擷取設定。 有關 `extract` 參數的詳情,請參閱 [ExtractParams 參考](https://mastra.zisheng.pro/zh-HK/reference/rag/extract-params)。 ## 各策略專用選項 各策略專用選項會與 strategy 參數一併作為頂層參數傳入。例如: ```typescript // Character strategy example const chunks = await doc.chunk({ strategy: 'character', separator: '.', // Character-specific option isSeparatorRegex: false, // Character-specific option maxSize: 300, // general option }) // Recursive strategy example const chunks = await doc.chunk({ strategy: 'recursive', separators: ['\n\n', '\n', ' '], // Recursive-specific option language: 'markdown', // Recursive-specific option maxSize: 500, // general option }) // Sentence strategy example const chunks = await doc.chunk({ strategy: 'sentence', maxSize: 450, // Required for sentence strategy minSize: 50, // Sentence-specific option sentenceEnders: ['.'], // Sentence-specific option fallbackToCharacters: false, // Sentence-specific option }) // HTML strategy example const chunks = await doc.chunk({ strategy: 'html', headers: [ ['h1', 'title'], ['h2', 'subtitle'], ], // HTML-specific option }) // Markdown strategy example const chunks = await doc.chunk({ strategy: 'markdown', headers: [ ['#', 'title'], ['##', 'section'], ], // Markdown-specific option stripHeaders: true, // Markdown-specific option }) // Semantic Markdown strategy example const chunks = await doc.chunk({ strategy: 'semantic-markdown', joinThreshold: 500, // Semantic Markdown-specific option modelName: 'gpt-3.5-turbo', // Semantic Markdown-specific option }) // Token strategy example const chunks = await doc.chunk({ strategy: 'token', encodingName: 'gpt2', // Token-specific option modelName: 'gpt-3.5-turbo', // Token-specific option maxSize: 1000, // general option }) ``` 以下選項會直接在設定物件的頂層傳入,而不是巢狀置於另一個 options 物件內。 ### 字元 **separators** (`string[]`): 按優先次序排列並依次嘗試的分隔符陣列。策略會先嘗試使用第一個分隔符進行分割,然後再依次改用其後的分隔符。 **isSeparatorRegex** (`boolean`): 分隔符是否為 regex 模式 (Default: `false`) ### 遞迴 **separators** (`string[]`): 按優先次序排列並依次嘗試的分隔符陣列。策略會先嘗試使用第一個分隔符進行分割,然後再依次改用其後的分隔符。 **isSeparatorRegex** (`boolean`): 分隔符是否為 regex 模式 (Default: `false`) **language** (`Language`): 用於按特定語言執行分割的程式語言或標記語言。支援的值請參閱 Language enum。 ### 句子 **maxSize** (`number`): 每個片段的大小上限(sentence 策略的必填設定) **minSize** (`number`): 每個片段的大小下限。情況許可時,小於此大小的片段會與相鄰片段合併。 (Default: `50`) **targetSize** (`number`): 片段的理想目標大小。預設為 maxSize 的 80%。策略會嘗試建立接近此大小的片段。 **sentenceEnders** (`string[]`): 標示句子結尾並用作分割界線的字元陣列。 (Default: `['.', '!', '?']`) **fallbackToWords** (`boolean`): 當句子超過 maxSize 時,是否改用單詞層級分割。 (Default: `true`) **fallbackToCharacters** (`boolean`): 當單詞超過 maxSize 時,是否改用字元層級分割。只有啟用 fallbackToWords 時才適用。 (Default: `true`) ### HTML **headers** (`Array<[string, string]>`): 用於按標題分割的 \[selector, metadata key] 配對陣列 **sections** (`Array<[string, string]>`): 用於按章節分割的 \[selector, metadata key] 配對陣列 **returnEachLine** (`boolean`): 是否將每一行作為獨立片段傳回 使用 HTML 策略時,所有一般選項都會被忽略。使用 `headers` 按標題分割,或使用 `sections` 按章節分割。如果兩者同時使用,`sections` 會被忽略。 ### Markdown **headers** (`Array<[string, string]>`): \[header level, metadata key] 配對陣列 **stripHeaders** (`boolean`): 是否從輸出中移除標題 **returnEachLine** (`boolean`): 是否將每一行作為獨立片段傳回 使用 `headers` 選項時,markdown 策略會忽略所有一般選項,並按 markdown 標題結構分割內容。如要按大小分割 markdown,請省略 `headers` 參數。 ### 語義 Markdown **joinThreshold** (`number`): 合併相關章節時的 token 數目上限。個別超出此上限的章節會保持不變;如果合併後的大小仍低於此門檻,較小的章節則會與同層或上層章節合併。 (Default: `500`) **modelName** (`string`): 用於 tokenization 的模型名稱。如有提供,便會使用模型底層 tokenization 的 encodingName。 **encodingName** (`string`): 要使用的 token encoding 名稱。如有 modelName,便會從中取得。 (Default: `cl100k_base`) **allowedSpecial** (`Set | 'all'`): tokenization 期間允許的特殊 token 集合,或設為 'all' 以允許所有特殊 token **disallowedSpecial** (`Set | 'all'`): tokenization 期間不允許的特殊 token 集合,或設為 'all' 以禁止所有特殊 token (Default: `all`) ### Token **encodingName** (`string`): 要使用的 token encoding 名稱 **modelName** (`string`): 用於 tokenization 的模型名稱 **allowedSpecial** (`Set | 'all'`): tokenization 期間允許的特殊 token 集合,或設為 'all' 以允許所有特殊 token **disallowedSpecial** (`Set | 'all'`): tokenization 期間不允許的特殊 token 集合,或設為 'all' 以禁止所有特殊 token ### JSON **maxSize** (`number`): 每個片段的大小上限 **minSize** (`number`): 每個片段的大小下限 **ensureAscii** (`boolean`): 是否確保使用 ASCII encoding **convertLists** (`boolean`): 是否轉換 JSON 中的清單 ### Latex Latex 策略只使用上列的一般分塊選項。它提供能識別 LaTeX 的分割方式,並針對數學及學術文件作出最佳化。 ## 傳回值 傳回包含已分塊文件的 `MDocument` 實例。每個片段包括: ```typescript interface DocumentNode { text: string metadata: Record embedding?: number[] } ```