跳至主要內容

.chunk()

.chunk() 函式會使用不同策略與選項,將文件分割成較小的區段。

範例
「範例」的直接連結

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
= 4000
每個區塊的最大大小。部分策略設定(含標題的 markdown、含標題的 HTML)會忽略此參數。

overlap?:

number
= 50
區塊之間重疊的字元/token 數量。

lengthFunction?:

(text: string) => number
計算文字長度的函式。預設為字元數。

separatorPosition?:

'start' | 'end'
分隔符在區塊中的位置。'start' 會將分隔符附加至下一個區塊的開頭,'end' 則會附加至目前區塊的結尾。若未指定,會捨棄分隔符。

addStartIndex?:

boolean
= false
是否將起始索引中繼資料加入區塊。

stripWhitespace?:

boolean
= true
是否移除區塊中的空白字元。

extract?:

ExtractParams
中繼資料擷取設定。

如需 extract 參數的詳細資訊,請參閱 ExtractParams 參考

各策略專屬選項
「各策略專屬選項」的直接連結

各策略專屬選項會與 strategy 參數一起作為頂層參數傳入。例如:

// 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
= false
分隔符是否為 regex 模式

遞迴
「遞迴」的直接連結

separators?:

string[]
依優先順序嘗試的分隔符陣列。策略會先嘗試使用第一個分隔符分割,再依序改用後續分隔符。

isSeparatorRegex?:

boolean
= false
分隔符是否為 regex 模式

language?:

Language
用於語言專屬分割行為的程式語言或標記語言。支援的值請參閱 Language enum。

句子
「句子」的直接連結

maxSize:

number
每個區塊的最大大小(sentence 策略的必要參數)

minSize?:

number
= 50
每個區塊的最小大小。若情況允許,小於此值的區塊會與相鄰區塊合併。

targetSize?:

number
偏好的區塊目標大小。預設為 maxSize 的 80%。此策略會嘗試建立接近此大小的區塊。

sentenceEnders?:

string[]
= ['.', '!', '?']
標記句子結尾、作為分割邊界的字元陣列。

fallbackToWords?:

boolean
= true
句子超過 maxSize 時,是否改用單字層級分割。

fallbackToCharacters?:

boolean
= true
單字超過 maxSize 時,是否改用字元層級分割。僅在啟用 fallbackToWords 時適用。

HTML
「HTML」的直接連結

headers:

Array<[string, string]>
用於依標題分割的 [selector, metadata key] 配對陣列

sections:

Array<[string, string]>
用於依區段分割的 [selector, metadata key] 配對陣列

returnEachLine?:

boolean
是否將每一行作為個別區塊傳回

使用 HTML 策略時,會忽略所有一般選項。請使用 headers 依標題分割,或使用 sections 依區段分割。若同時使用,則會忽略 sections

Markdown
「Markdown」的直接連結

headers?:

Array<[string, string]>
[標題層級, 中繼資料鍵] 配對陣列

stripHeaders?:

boolean
是否從輸出中移除標題

returnEachLine?:

boolean
是否將每一行作為個別區塊傳回

使用 headers 選項時,markdown 策略會忽略所有一般選項,並依 markdown 標題結構分割內容。若要依大小分割 markdown,請省略 headers 參數。

語意 Markdown
「語意 Markdown」的直接連結

joinThreshold?:

number
= 500
合併相關區段時的最大 token 數量。單一區段若超過此限制會維持原樣;若合併後的大小仍低於此門檻,較小的區段則會與同層或父層區段合併。

modelName?:

string
用於 tokenization 的模型名稱。若有提供,將使用模型底層的 tokenization encodingName

encodingName?:

string
= cl100k_base
要使用的 token 編碼名稱。若可取得,會從 modelName 衍生。

allowedSpecial?:

Set<string> | 'all'
tokenization 期間允許的特殊 token 集合,或設為 'all' 以允許所有特殊 token

disallowedSpecial?:

Set<string> | 'all'
= all
tokenization 期間禁止的特殊 token 集合,或設為 'all' 以禁止所有特殊 token

Token
「Token」的直接連結

encodingName?:

string
要使用的 token 編碼名稱

modelName?:

string
用於 tokenization 的模型名稱

allowedSpecial?:

Set<string> | 'all'
tokenization 期間允許的特殊 token 集合,或設為 'all' 以允許所有特殊 token

disallowedSpecial?:

Set<string> | 'all'
tokenization 期間禁止的特殊 token 集合,或設為 'all' 以禁止所有特殊 token

JSON
「JSON」的直接連結

maxSize:

number
每個區塊的最大大小

minSize?:

number
每個區塊的最小大小

ensureAscii?:

boolean
是否確保使用 ASCII 編碼

convertLists?:

boolean
是否轉換 JSON 中的清單

Latex
「Latex」的直接連結

Latex 策略只會使用上方列出的一般分塊選項。它提供可辨識 LaTeX 結構的分割方式,並針對數學與學術文件進行最佳化。

傳回值
「傳回值」的直接連結

傳回包含已分塊文件的 MDocument 執行個體。每個區塊包含:

interface DocumentNode {
text: string
metadata: Record<string, any>
embedding?: number[]
}