Repository navigation
Expand file tree
/
Copy pathdocument-chunking.tool.ts
More file actions
1744 lines (1624 loc) · 64.7 KB
/
Copy pathdocument-chunking.tool.ts
File metadata and controls
1744 lines (1624 loc) · 64.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { SpanType, getOrCreateSpan } from '@mastra/core/observability'
import type { TracingContext } from '@mastra/core/observability'
import type { InferToolInput, InferUITool, InferToolOutput } from '@mastra/core/tools'
import { createTool } from '@mastra/core/tools'
import { MDocument, rerank } from '@mastra/rag'
import { randomUUID } from 'crypto'
import { fastembed } from '@mastra/fastembed'
import {
ModelRouterEmbeddingModel,
ModelRouterLanguageModel,
} from '@mastra/core/llm'
import { embed, embedMany } from 'ai'
import { z } from 'zod'
import {
log,
logError,
logStepEnd,
logStepStart,
logToolExecution,
} from '../config/logger'
import { libsqlvector } from '../config/libsql'
import type { RequestContext } from '@mastra/core/request-context'
import type { ExtractParams } from '@mastra/rag'
import { resolveAbortSignal } from './abort-signal.utils'
log.info('Initializing Document Chunking Tool...')
type DocumentJsonPrimitive = string | number | boolean | null
type DocumentJsonValue =
| DocumentJsonPrimitive
| DocumentJsonObject
| DocumentJsonValue[]
interface DocumentJsonObject {
[key: string]: DocumentJsonValue
}
const documentJsonValueSchema: z.ZodType<DocumentJsonValue> = z.lazy(() =>
z.union([
z.string(),
z.number(),
z.boolean(),
z.null(),
z.array(documentJsonValueSchema),
z.record(z.string(), documentJsonValueSchema),
])
)
/**
* Remove metadata keys that are not safe for vector stores (leading $ or containing dots)
*/
function sanitizeMetadata(m: DocumentJsonObject): DocumentJsonObject {
const out: DocumentJsonObject = {}
const keys = Object.keys(m)
for (const k of keys) {
if (k.startsWith('$') || k.includes('.')) {
continue
}
out[k] = m[k]
}
return out
}
/**
* Normalize reranking weights so they sum to 1. Returns normalized object.
*/
export function normalizeWeights(
semantic: number,
vector: number,
position: number
) {
const sum = semantic + vector + position
if (sum <= 0) {
return { semantic: 0.5, vector: 0.3, position: 0.2 }
}
return {
semantic: semantic / sum,
vector: vector / sum,
position: position / sum,
}
}
// Define runtime context for this tool
export interface DocumentChunkingContext extends RequestContext {
userId?: string
chunkStrategy?: string
}
/**
* Input schema for custom document chunking tool with embeddings and storage
*/
const CustomDocumentChunkingInputSchema = z.object({
documentContent: z.string().min(1, 'Document content cannot be empty'),
documentMetadata: z.record(z.string(), documentJsonValueSchema).optional().default({}),
chunkingStrategy: z
.enum([
'recursive',
'character',
'token',
'markdown',
'semantic-markdown',
'html',
'json',
'latex',
'sentence',
])
.default('recursive'),
chunkSize: z.number().min(50).max(4000).default(512),
chunkOverlap: z.number().min(0).max(500).default(50),
chunkSeparator: z.string().default('\n'),
indexName: z.string().default('memory_messages_768'),
// Embedding model name for ModelRouterEmbeddingModel (e.g. 'google/gemini-embedding-2-preview')
embeddingModel: z.string().default(fastembed.base),
// Number of texts to embed per batch
embeddingBatchSize: z.number().min(1).max(500).default(50),
generateEmbeddings: z.boolean().default(true),
})
/**
* Output schema for custom document chunking tool
*/
const CustomDocumentChunkingOutputSchema = z.object({
success: z.boolean(),
chunkCount: z.number(),
totalTextLength: z.number(),
chunks: z.array(
z.object({
id: z.string(),
text: z.string(),
metadata: z.record(z.string(), documentJsonValueSchema),
embeddingGenerated: z.boolean(),
})
),
processingTimeMs: z.number(),
})
/**
* Input schema for Mastra chunker tool with metadata extraction
*/
const MastraDocumentChunkingInputSchema = z.object({
documentContent: z.string().min(1, 'Document content cannot be empty'),
documentMetadata: z.record(z.string(), documentJsonValueSchema).optional().default({}),
chunkingStrategy: z
.enum([
'recursive',
'character',
'token',
'markdown',
'semantic-markdown',
'html',
'json',
'latex',
'sentence',
])
.default('recursive'),
chunkSize: z.number().min(50).max(4000).default(512),
chunkOverlap: z.number().min(0).max(500).default(50),
chunkSeparator: z.string().default('\n'),
// ExtractParams for metadata extraction (supports full ExtractParams)
// Keep legacy boolean flags for convenience
extract: z.custom<ExtractParams>().optional(),
extractTitle: z.boolean().default(false),
extractSummary: z.boolean().default(false),
extractKeywords: z.boolean().default(false),
extractQuestions: z.boolean().default(false),
})
/**
* Output schema for Mastra chunker tool
*/
const MastraDocumentChunkingOutputSchema = z.object({
success: z.boolean(),
chunkCount: z.number(),
totalTextLength: z.number(),
chunks: z.array(
z.object({
text: z.string(),
metadata: z.record(z.string(), documentJsonValueSchema),
})
),
processingTimeMs: z.number(),
})
/**
* Mastra Chunker Tool with Metadata Extraction
*
* Uses MDocument.chunk() with ExtractParams for comprehensive document processing
* including title extraction, summarization, keyword extraction, and question generation.
*
* Features:
* - LLM-powered metadata extraction (titles, summaries, keywords, questions)
* - Configurable extraction options
* - Multiple chunking strategies
* - Comprehensive error handling and logging
* - Performance monitoring and metrics
*
* Use this tool when you need advanced document processing with metadata extraction.
*/
export const mastraChunker = createTool({
id: 'mastra:chunker',
description: `
Mastra Document Chunker Tool with Metadata Extraction
This tool processes document content using MDocument.chunk() with advanced metadata extraction:
Features:
- LLM-powered metadata extraction:
* Title extraction with hierarchical document structure
* Summary generation for each chunk
* Keyword extraction for semantic search
* Question generation for conversational retrieval
- Multiple chunking strategies (recursive, character, token, markdown, etc.)
- Configurable extraction options
- Comprehensive error handling and logging
- Performance monitoring and metrics
Use this tool when you need advanced document processing with metadata extraction.
`,
inputSchema: MastraDocumentChunkingInputSchema,
outputSchema: MastraDocumentChunkingOutputSchema,
strict: true,
onInputStart: ({ toolCallId, messages }) => {
log.info('Mastra chunker tool input streaming started', {
toolCallId,
messages,
hook: 'onInputStart',
})
},
onInputDelta: ({ inputTextDelta, toolCallId, messages }) => {
log.info('Mastra chunker tool received input chunk', {
toolCallId,
inputTextDelta,
messages,
chunkingStrategy: 'recursive',
hook: 'onInputDelta',
})
},
onInputAvailable: ({ input, toolCallId, messages }) => {
log.info('Mastra chunker received complete input', {
toolCallId,
documentLength: input.documentContent.length,
chunkingStrategy: input.chunkingStrategy,
messages,
hook: 'onInputAvailable',
})
},
execute: async (inputData, context) => {
const writer = context.writer
const abortSignal = context.abortSignal
const tracingContext: TracingContext | undefined =
context.tracingContext
const chunkingStrategy = inputData.chunkingStrategy ?? 'recursive'
const chunkSize = inputData.chunkSize ?? 512
const chunkOverlap = inputData.chunkOverlap ?? 50
// Check if operation was already cancelled
if (abortSignal?.aborted) {
throw new Error('Mastra chunker cancelled')
}
await writer?.custom({
type: 'data-tool-progress',
data: {
status: 'in-progress',
message: '📄 Starting Mastra chunker',
stage: 'mastra:chunker',
},
id: 'mastra:chunker',
})
const startTime = Date.now()
logToolExecution('mastra:chunker', { input: inputData })
const span = getOrCreateSpan({
type: SpanType.TOOL_CALL,
name: 'mastra:chunker',
input: {
documentLength: inputData.documentContent.length,
chunkingStrategy: inputData.chunkingStrategy,
chunkSize,
extractTitle: inputData.extractTitle,
extractSummary: inputData.extractSummary,
extractKeywords: inputData.extractKeywords,
extractQuestions: inputData.extractQuestions,
},
requestContext: context.requestContext,
tracingContext,
metadata: {
'tool.id': 'mastra:chunker',
operation: 'mastra:chunker',
},
})
try {
// Create MDocument from input
const document = new MDocument({
docs: [
{
text: inputData.documentContent,
metadata: {
...inputData.documentMetadata,
chunkingStrategy: inputData.chunkingStrategy,
chunkSize: inputData.chunkSize,
chunkOverlap: inputData.chunkOverlap,
processedAt: new Date().toISOString(),
source: 'mastra:chunker',
},
},
],
type: 'document',
})
// Build chunking parameters with ExtractParams
const buildChunkParams = (
strategy: string,
maxSize: number,
overlap: number,
extract: ExtractParams
) => {
const baseParams = {
maxSize,
overlap,
extract,
}
switch (strategy) {
case 'recursive':
return {
strategy: 'recursive' as const,
...baseParams,
separators: ['\n\n', '\n', ' '],
}
case 'character':
return {
strategy: 'character' as const,
...baseParams,
separator: '\n',
isSeparatorRegex: false,
}
case 'markdown':
return {
strategy: 'markdown' as const,
...baseParams,
headers: [
['#', 'title'],
['##', 'section'],
] as Array<[string, string]>,
}
case 'latex':
return {
strategy: 'latex' as const,
...baseParams,
}
case 'sentence':
return {
strategy: 'sentence' as const,
...baseParams,
minSize: 50,
sentenceEnders: ['.'],
}
case 'token':
return {
strategy: 'token' as const,
...baseParams,
}
case 'semantic-markdown':
return {
strategy: 'semantic-markdown' as const,
...baseParams,
joinThreshold: 500,
}
default:
// Fallback to recursive
return {
strategy: 'recursive' as const,
...baseParams,
separators: ['\n\n', '\n', ' '],
}
}
}
// Build ExtractParams based on user preferences
const extractParams: ExtractParams = {}
// Accept full ExtractParams via `extract` or fall back to legacy booleans
if (
inputData.extract !== undefined &&
inputData.extract !== null &&
typeof inputData.extract === 'object'
) {
Object.assign(extractParams, inputData.extract as ExtractParams)
}
if (inputData.extractTitle === true) {
extractParams.title = true
}
if (inputData.extractSummary === true) {
extractParams.summary = true
}
if (inputData.extractKeywords === true) {
extractParams.keywords = true
}
if (inputData.extractQuestions === true) {
extractParams.questions = true
}
// Execute chunking with metadata extraction
const chunkingStartTime = Date.now()
const chunkParams = buildChunkParams(
chunkingStrategy,
chunkSize,
chunkOverlap,
extractParams
)
const chunks = await document.chunk(chunkParams)
const chunkingTime = Date.now() - chunkingStartTime
logStepStart('mastra-chunking-completed', {
chunkCount: chunks.length,
chunkingTimeMs: chunkingTime,
strategy: chunkingStrategy,
extractOptions: Object.keys(extractParams),
})
// Prepare output chunks
const outputChunks = chunks.map((chunk, index) => ({
text: chunk.text,
metadata: {
...chunk.metadata,
chunkIndex: index,
totalChunks: chunks.length,
documentId: `doc_${String(Date.now())}_${String(index)}`,
chunkingStrategy,
chunkSize,
chunkOverlap,
},
}))
const totalProcessingTime = Date.now() - startTime
const output = {
success: true,
chunkCount: chunks.length,
totalTextLength: inputData.documentContent.length,
chunks: outputChunks,
processingTimeMs: totalProcessingTime,
}
logStepEnd('mastra:chunker', output, totalProcessingTime)
return output
} catch (error) {
const processingTime = Date.now() - startTime
const safeError =
error instanceof Error
? error
: new Error('Unknown error occurred')
logError('mastra:chunker', safeError, {
inputData,
processingTimeMs: processingTime,
})
// Record error in tracing span
span?.error({
error: safeError,
endSpan: true,
})
throw safeError
} finally {
span?.end()
}
},
onOutput: ({ output, toolCallId, toolName }) => {
log.info('Mastra chunker completed', {
toolCallId,
toolName,
chunkCount: output.chunkCount,
processingTimeMs: output.processingTimeMs,
hook: 'onOutput',
})
},
})
/**
* MDocument Chunker Tool with PgVector Integration
*
* This tool processes document content by:
* 1. Creating chunks using MDocument.chunk() method with configurable strategies
* 2. Generating embeddings for each chunk using Gemini embedding model
* 3. Storing chunks and embeddings in PgVector for efficient similarity search
*
* Features:
* - Multiple chunking strategies with customizable parameters
* - Automatic embedding generation (3072 dimensions for text-embedding-3-large)
* - PgVector storage with metadata support
* - Comprehensive error handling and logging
* - Performance monitoring and metrics
*
* Use this tool when you need to process documents for RAG applications,
* content indexing, or semantic search capabilities.
*/
export const mdocumentChunker = createTool({
id: 'mdocument:chunker',
description: `
Custom Document Chunking Tool with PgVector Integration
This tool processes document content by:
1. Creating chunks using configurable strategies (recursive, character, token, markdown, etc.)
2. Generating embeddings for each chunk using Gemini embedding model
3. Storing chunks and embeddings in PgVector for efficient similarity search
Features:
- Multiple chunking strategies with customizable parameters
- Automatic embedding generation (768 dimensions for fastembed.base)
- PgVector storage with metadata support
- Comprehensive error handling and logging
- Performance monitoring and metrics
Use this tool when you need to process documents for RAG applications,
content indexing, or semantic search capabilities.
`,
inputSchema: CustomDocumentChunkingInputSchema,
outputSchema: CustomDocumentChunkingOutputSchema,
strict: true,
onInputStart: ({ toolCallId, messages }) => {
log.info('MDocument chunker tool input streaming started', {
toolCallId,
messages,
hook: 'onInputStart',
})
},
onInputDelta: ({ inputTextDelta, toolCallId, messages }) => {
log.info('MDocument chunker tool received input chunk', {
toolCallId,
inputTextDelta,
messages,
chunkingStrategy: 'recursive',
hook: 'onInputDelta',
})
},
onInputAvailable: ({ input, toolCallId, messages }) => {
log.info('MDocument chunker received complete input', {
toolCallId,
documentLength: input.documentContent.length,
chunkingStrategy: input.chunkingStrategy,
generateEmbeddings: input.generateEmbeddings,
messages,
hook: 'onInputAvailable',
})
},
execute: async (inputData, context) => {
const writer = context.writer
const abortSignal = context.abortSignal
const tracingContext: TracingContext | undefined =
context.tracingContext
const chunkingStrategy = inputData.chunkingStrategy ?? 'recursive'
const chunkSize = inputData.chunkSize ?? 512
const chunkOverlap = inputData.chunkOverlap ?? 50
const indexName = inputData.indexName ?? 'memory_messages_768'
const embeddingModel =
inputData.embeddingModel ?? fastembed
const embeddingBatchSize = inputData.embeddingBatchSize ?? 50
// Check if operation was already cancelled
if (abortSignal?.aborted ?? false) {
throw new Error('MDocument chunker cancelled')
}
await writer?.custom({
type: 'data-tool-progress',
data: {
status: 'in-progress',
message: '📄 Starting MDocument chunker',
stage: 'mdocument:chunker',
},
id: 'mdocument:chunker',
})
const startTime = Date.now()
logToolExecution('mdocument:chunker', { input: inputData })
const span = getOrCreateSpan({
type: SpanType.MODEL_CHUNK,
name: 'mdocument:chunker',
input: {
documentLength: inputData.documentContent.length,
chunkingStrategy: inputData.chunkingStrategy,
chunkSize,
generateEmbeddings: inputData.generateEmbeddings,
},
requestContext: context.requestContext,
tracingContext,
metadata: {
'tool.id': 'mdocument:chunker',
operation: 'mdocument:chunker',
},
})
try {
// Create MDocument from input
const document = new MDocument({
docs: [
{
text: inputData.documentContent,
metadata: {
...inputData.documentMetadata,
chunkingStrategy: inputData.chunkingStrategy,
chunkSize,
chunkOverlap,
processedAt: new Date().toISOString(),
source: 'mdocument:chunker',
},
},
],
type: 'document',
})
// Build chunking parameters based on strategy
const buildChunkParams = (
strategy: string,
maxSize: number,
overlap: number
) => {
const baseParams = {
maxSize,
overlap,
}
switch (strategy) {
case 'recursive':
return {
strategy: 'recursive' as const,
...baseParams,
separators: ['\n\n', '\n', ' '], // Removed 'as const' to make it mutable string[]
}
case 'character':
return {
strategy: 'character' as const,
...baseParams,
separators: ['\n'],
isSeparatorRegex: false,
}
case 'markdown':
return {
strategy: 'markdown' as const,
...baseParams,
headers: [
['#', 'title'],
['##', 'section'],
] as Array<[string, string]>,
}
case 'html':
return {
strategy: 'html' as const,
...baseParams,
headers: [
['h1', 'title'],
['h2', 'section'],
] as Array<[string, string]>,
}
case 'json':
return {
strategy: 'json' as const,
...baseParams,
}
case 'latex':
return {
strategy: 'latex' as const,
...baseParams,
}
case 'sentence':
return {
strategy: 'sentence' as const,
...baseParams,
minSize: 50,
sentenceEnders: ['.'], // Removed 'as const' to make it mutable string[]
}
case 'token':
return {
strategy: 'token' as const,
...baseParams,
}
case 'semantic-markdown':
return {
strategy: 'semantic-markdown' as const,
...baseParams,
joinThreshold: 500,
}
default:
// Fallback to recursive
return {
strategy: 'recursive' as const,
...baseParams,
separators: ['\n\n', '\n', ' '],
isSeparatorRegex: false,
}
}
}
// Execute chunking using MDocument.chunk() method
const chunkingStartTime = Date.now()
const chunkParams = buildChunkParams(
chunkingStrategy,
chunkSize,
chunkOverlap
)
const chunks = await document.chunk(chunkParams)
const chunkingTime = Date.now() - chunkingStartTime
logStepStart('custom-chunking-completed', {
chunkCount: chunks.length,
chunkingTimeMs: chunkingTime,
strategy: chunkingStrategy,
})
// Prepare chunks for embedding and storage
const chunksForProcessing = chunks.map((chunk, index) => ({
text: chunk.text,
metadata: {
...chunk.metadata,
chunkIndex: index,
totalChunks: chunks.length,
documentId: `doc_${String(Date.now())}_${String(index)}`,
chunkingStrategy,
chunkSize,
chunkOverlap,
},
id:
typeof chunk.metadata.id === 'string'
? chunk.metadata.id
: `chunk_${String(Date.now())}_${randomUUID()}`,
}))
let embeddingGenerated = false
let embeddings: number[][] = []
// Generate embeddings if requested
if (
(inputData.generateEmbeddings ?? false) &&
chunksForProcessing.length > 0
) {
await writer?.custom({
type: 'data-tool-progress',
data: {
status: 'in-progress',
message: '🧠 Generating embeddings',
stage: 'mdocument:chunker',
},
id: 'mdocument:chunker',
})
const embeddingStartTime = Date.now()
// Prepare texts and keep mapping so we can upsert only non-empty embeddings
const texts = chunksForProcessing.map((chunk) =>
typeof chunk.text === 'string' ? chunk.text.trim() : ''
)
const nonEmptyIndexes = texts
.map((t, i) => (t.length > 0 ? i : -1))
.filter((i) => i !== -1)
const nonEmptyValues = nonEmptyIndexes.map((i) => texts[i])
try {
const allEmbeddings: number[][] = []
for (
let i = 0;
i < nonEmptyValues.length;
i += embeddingBatchSize
) {
const batch = nonEmptyValues.slice(
i,
i + embeddingBatchSize
)
const result = await embedMany({
values: batch,
model: new ModelRouterEmbeddingModel(
embeddingModel
),
maxRetries: 3,
abortSignal: new AbortController().signal,
experimental_telemetry: {
isEnabled: true,
recordInputs: true,
recordOutputs: true,
functionId: 'document-chunking-tool-embedMany',
},
})
allEmbeddings.push(...result.embeddings)
}
embeddings = allEmbeddings
embeddingGenerated = embeddings.length > 0
const embeddingTime = Date.now() - embeddingStartTime
logStepStart('embeddings-generated', {
embeddingCount: embeddings.length,
embeddingTimeMs: embeddingTime,
dimension: embeddings[0].length,
})
} catch (embedError) {
const safeError =
embedError instanceof Error
? embedError
: new Error('Unknown error occurred')
logError('mdocument-chunker-embeddings', safeError, {
embeddingBatchSize,
})
// fall back to no embeddings so chunks are still returned
embeddings = []
embeddingGenerated = false
}
}
// Store chunks in libsqlVector if embeddings were generated
if (embeddingGenerated && embeddings.length > 0) {
await writer?.custom({
type: 'data-tool-progress',
data: {
status: 'in-progress',
message: '💾 Storing vectors in database',
stage: 'mdocument:chunker',
},
id: 'mdocument:chunker',
})
const storageStartTime = Date.now()
// Ensure index exists with the same dimension as embeddings
try {
await libsqlvector.createIndex({
indexName,
dimension: embeddings[0].length,
})
} catch (idxErr) {
log.info('createIndex skipped or failed', {
error:
idxErr instanceof Error
? idxErr.message
: String(idxErr),
})
}
// Ensure chunk ids are stable and unique
// Ensure ids are present and sanitize metadata
const allIds = chunksForProcessing.map((chunk) => chunk.id)
const sanitizedMetadata = chunksForProcessing.map((chunk) => ({
...sanitizeMetadata(chunk.metadata),
text: chunk.text,
}))
// Map embeddings back to the full set: only non-empty values produced embeddings
const finalVectors: number[][] = []
const finalMetadata: DocumentJsonObject[] = []
const finalIds: string[] = []
if (embeddings.length > 0) {
// Rebuild arrays using nonEmptyIndexes mapping
const texts = chunksForProcessing.map((c) =>
typeof c.text === 'string' ? c.text.trim() : ''
)
const nonEmptyIndexes = texts
.map((t, i) => (t.length > 0 ? i : -1))
.filter((i) => i !== -1)
for (let i = 0; i < nonEmptyIndexes.length; i++) {
const idx = nonEmptyIndexes[i]
finalVectors.push(embeddings[i])
finalMetadata.push(sanitizedMetadata[idx])
finalIds.push(allIds[idx])
}
}
// Store vectors with metadata
if (finalVectors.length > 0) {
await libsqlvector.upsert({
indexName,
vectors: finalVectors,
metadata: finalMetadata,
ids: finalIds,
})
} else {
log.info(
'No embeddings to upsert after processing (empty or embedding generation failed)'
)
}
const storageTime = Date.now() - storageStartTime
logStepStart('vectors-stored', {
indexName,
vectorCount: embeddings.length,
storageTimeMs: storageTime,
})
}
const totalProcessingTime = Date.now() - startTime
// Prepare output
const output = {
success: true,
chunkCount: chunks.length,
totalTextLength: inputData.documentContent.length,
chunks: chunksForProcessing.map((chunk) => ({
id: chunk.id,
text: chunk.text,
metadata: chunk.metadata,
embeddingGenerated,
})),
processingTimeMs: totalProcessingTime,
}
logStepEnd('mdocument:chunker', output, totalProcessingTime)
await writer?.custom({
type: 'data-tool-progress',
data: {
status: 'done',
message: `✅ Processed ${String(chunks.length)} chunks successfully`,
stage: 'mdocument:chunker',
},
id: 'mdocument:chunker',
})
return output
} catch (error) {
const processingTime = Date.now() - startTime
const safeError =
error instanceof Error
? error
: new Error('Unknown error occurred')
logError('mdocument:chunker', safeError, {
inputData,
processingTimeMs: processingTime,
})
// Record error in tracing span
span?.error({
error: safeError,
endSpan: true,
})
throw safeError
} finally {
span?.end()
}
},
onOutput: ({ output, toolCallId, toolName }) => {
log.info('MDocument chunker completed', {
toolCallId,
toolName,
chunkCount: output.chunkCount,
processingTimeMs: output.processingTimeMs,
hook: 'onOutput',
})
},
})
/**
* LibSQL (Turso) Document Chunking Tool
*
* This tool processes document content by:
* 1. Creating chunks using configurable strategies (recursive, character, token, markdown, etc.)
* 2. Generating embeddings for each chunk using Gemini embedding model
* 3. Storing chunks and embeddings in LibSQL (Turso) for efficient similarity search
*
* Features:
* - Multiple chunking strategies with customizable parameters
* - Automatic embedding generation (768 dimensions for fastembed.base)
* - LibSQL/Turso storage with metadata support
* - Comprehensive error handling and logging
* - Performance monitoring and metrics
*
* Use this tool when you need to process documents for RAG applications,
* content indexing, or semantic search capabilities using LibSQL/Turso.
*/
export const libsqlChunker = createTool({
id: 'libsql:chunker',
description: `
Custom Document Chunking Tool with LibSQL (Turso) Integration
This tool processes document content by:
1. Creating chunks using configurable strategies (recursive, character, token, markdown, etc.)
2. Generating embeddings for each chunk using fastembed.base model
3. Storing chunks and embeddings in LibSQL (Turso) for efficient similarity search
Features:
- Multiple chunking strategies with customizable parameters
- Automatic embedding generation (768 dimensions for fastembed.base)
- LibSQL/Turso storage with metadata support
- Comprehensive error handling and logging
- Performance monitoring and metrics
Use this tool when you need to process documents for RAG applications,
content indexing, or semantic search capabilities using LibSQL/Turso.
`,
inputSchema: CustomDocumentChunkingInputSchema,
outputSchema: CustomDocumentChunkingOutputSchema,
strict: true,
onInputStart: ({ toolCallId, messages }) => {
log.info('LibSQL chunker tool input streaming started', {
toolCallId,
messages,
hook: 'onInputStart',
})
},
onInputDelta: ({ inputTextDelta, toolCallId, messages }) => {