リファレンス: .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' | 'html' | 'json' | 'latex'
使用するチャンク戦略。指定されていない場合、ドキュメントタイプに基づいてデフォルトが設定されます。チャンク戦略に応じて、追加のオプションがあります。デフォルト: .md ファイル → 'markdown', .html/.htm → 'html', .json → 'json', .tex → 'latex', その他 → 'recursive'
size?:
number
= 512
各チャンクの最大サイズ
overlap?:
number
= 50
チャンク間で重複する文字/トークンの数。
separator?:
string
= \n\n
分割する文字。テキストコンテンツの場合、デフォルトは二重改行です。
isSeparatorRegex?:
boolean
= false
セパレータが正規表現パターンかどうか
keepSeparator?:
'start' | 'end'
チャンクの開始または終了にセパレータを保持するかどうか
extract?:
ExtractParams
メタデータ抽出の設定。詳細は[ExtractParams リファレンス](./extract-params)を参照してください。
戦略固有のオプション
戦略固有のオプションは、戦略パラメータと共にトップレベルのパラメータとして渡されます。例えば:
// HTML戦略の例
const chunks = await doc.chunk({
strategy: 'html',
headers: [['h1', 'title'], ['h2', 'subtitle']], // HTML固有のオプション
sections: [['div.content', 'main']], // HTML固有のオプション
size: 500 // 一般的なオプション
});
// Markdown戦略の例
const chunks = await doc.chunk({
strategy: 'markdown',
headers: [['#', 'title'], ['##', 'section']], // Markdown固有のオプション
stripHeaders: true, // Markdown固有のオプション
overlap: 50 // 一般的なオプション
});
// Token戦略の例
const chunks = await doc.chunk({
strategy: 'token',
encodingName: 'gpt2', // Token固有のオプション
modelName: 'gpt-3.5-turbo', // Token固有のオプション
size: 1000 // 一般的なオプション
});
以下に記載されているオプションは、別のオプションオブジェクト内にネストされるのではなく、設定オブジェクトのトップレベルで直接渡されます。
HTML
headers:
Array<[string, string]>
ヘッダーに基づく分割のための[セレクタ, メタデータキー]ペアの配列
sections:
Array<[string, string]>
セクションに基づく分割のための[セレクタ, メタデータキー]ペアの配列
returnEachLine?:
boolean
各行を個別のチャンクとして返すかどうか
Markdown
headers:
Array<[string, string]>
[ヘッダーレベル, メタデータキー]ペアの配列
stripHeaders?:
boolean
出力からヘッダーを削除するかどうか
returnEachLine?:
boolean
各行を個別のチャンクとして返すかどうか
Token
encodingName?:
string
使用するトークンエンコーディングの名前
modelName?:
string
トークン化のためのモデルの名前
JSON
maxSize:
number
各チャンクの最大サイズ
minSize?:
number
各チャンクの最小サイズ
ensureAscii?:
boolean
ASCIIエンコーディングを保証するかどうか
convertLists?:
boolean
JSON内のリストを変換するかどうか
戻り値
チャンクされたドキュメントを含むMDocument
インスタンスを返します。各チャンクには以下が含まれます:
interface DocumentNode {
text: string;
metadata: Record<string, any>;
embedding?: number[];
}