Repository navigation
Expand file tree
/
Copy pathdocument-processor.ts
More file actions
1203 lines (1073 loc) · 36.1 KB
/
Copy pathdocument-processor.ts
File metadata and controls
1203 lines (1073 loc) · 36.1 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 {
IAgentRuntime,
Memory,
MemoryType,
ModelType,
UUID,
logger,
splitChunks,
} from '@elizaos/core';
import { Buffer } from 'node:buffer';
import { v4 as uuidv4 } from 'uuid';
import { getProviderRateLimits, validateModelConfig } from './config.ts';
import {
DEFAULT_CHARS_PER_TOKEN,
DEFAULT_CHUNK_OVERLAP_TOKENS,
DEFAULT_CHUNK_TOKEN_SIZE,
getCachingContextualizationPrompt,
getCachingPromptForMimeType,
getChunkWithContext,
getContextualizationPrompt,
getPromptForMimeType,
} from './ctx-embeddings.ts';
import { generateText } from './llm.ts';
import { convertPdfToTextFromBuffer, extractTextFromFileBuffer } from './utils.ts';
/**
* Parse CSV content and convert to readable text format
* @param csvContent Raw CSV content as string
* @param originalFilename Original filename for context
* @returns Formatted text representation of CSV data
*
* Note: Processes up to 10,000 rows for performance optimization.
* Large CSV files will be truncated with a summary note.
*
* @example
* Input CSV:
* ```
* Name,Age,City,Salary
* John,30,"New York",75000
* Alice,25,Boston,65000
* ```
*
* Output Text:
* ```
* Document: data.csv
* CSV Data with 2 rows and 4 columns
*
* Column Headers: Name, Age, City, Salary
*
* Row 1:
* Name: John
* Age: 30
* City: New York
* Salary: 75000
*
* Row 2:
* Name: Alice
* Age: 25
* City: Boston
* Salary: 65000
*
* Numeric Column Statistics:
* Age: avg: 27.50, min: 25, max: 30, count: 2
* Salary: avg: 70000.00, min: 65000, max: 75000, count: 2
* ```
*/
function parseCSVToText(csvContent: string, originalFilename: string): string {
try {
// Split into lines and handle different line endings
const lines = csvContent.split(/\r\n|\r|\n/).filter(line => line.trim() !== '');
if (lines.length === 0) {
throw new Error('Empty CSV file');
}
// Parse CSV manually to handle quoted fields and commas within quotes
const parseCSVLine = (line: string): string[] => {
const result: string[] = [];
let current = '';
let inQuotes = false;
for (let i = 0; i < line.length; i++) {
const char = line[i];
if (char === '"') {
if (inQuotes && line[i + 1] === '"') {
// Handle escaped quotes
current += '"';
i++; // Skip next quote
} else {
// Toggle quote state
inQuotes = !inQuotes;
}
} else if (char === ',' && !inQuotes) {
// End of field
result.push(current.trim());
current = '';
} else {
current += char;
}
}
// Add the last field
result.push(current.trim());
return result;
};
// Parse header row
const headers = parseCSVLine(lines[0]);
const numColumns = headers.length;
// Build formatted text output
let textOutput = `Document: ${originalFilename}\n`;
textOutput += `CSV Data with ${lines.length - 1} rows and ${numColumns} columns\n\n`;
// Add header information
textOutput += `Column Headers: ${headers.join(', ')}\n\n`;
// Process data rows
const dataRows = lines.slice(1);
let processedRows = 0;
const parsedDataRows: string[][] = []; // Store parsed rows for statistics
for (let i = 0; i < dataRows.length && processedRows < 10000; i++) {
const row = parseCSVLine(dataRows[i]);
// Skip empty rows
if (row.every(cell => cell === '')) {
continue;
}
// Store parsed row for statistics
parsedDataRows.push(row);
textOutput += `Row ${processedRows + 1}:\n`;
// Create structured row data
for (let j = 0; j < Math.min(row.length, numColumns); j++) {
const header = headers[j] || `Column_${j + 1}`;
const value = row[j] || '';
if (value.trim() !== '') {
textOutput += ` ${header}: ${value}\n`;
}
}
textOutput += '\n';
processedRows++;
}
// Add summary if we truncated data
if (dataRows.length > 10000) {
textOutput += `\n[Note: CSV contains ${dataRows.length} total rows. Only first 10,000 rows processed for embedding.]\n`;
}
// Add statistical summary for numeric columns
const numericStats = calculateCSVStatistics(parsedDataRows, headers);
if (numericStats.length > 0) {
textOutput += '\nNumeric Column Statistics:\n';
numericStats.forEach(stat => {
textOutput += ` ${stat.column}: ${stat.summary}\n`;
});
}
return textOutput;
} catch (error: any) {
logger.error(`Error parsing CSV file ${originalFilename}: ${error.message}`);
throw new Error(`Failed to parse CSV: ${error.message}`);
}
}
/**
* Calculate basic statistics for numeric columns in CSV
* @param dataRows Array of parsed CSV rows
* @param headers Column headers
* @returns Array of column statistics
*/
function calculateCSVStatistics(dataRows: string[][], headers: string[]): Array<{ column: string, summary: string }> {
const stats: Array<{ column: string, summary: string }> = [];
for (let colIndex = 0; colIndex < headers.length; colIndex++) {
const columnName = headers[colIndex];
const columnValues = dataRows
.map(row => row[colIndex]?.trim())
.filter(val => val && val !== '');
if (columnValues.length === 0) continue;
// Check if column contains numeric data
const numericValues = columnValues
.map(val => parseFloat(val.replace(/[,$%]/g, '')))
.filter(val => !isNaN(val));
if (numericValues.length > columnValues.length * 0.5) {
// Column is mostly numeric
const sum = numericValues.reduce((a, b) => a + b, 0);
const avg = sum / numericValues.length;
const min = Math.min(...numericValues);
const max = Math.max(...numericValues);
stats.push({
column: columnName,
summary: `avg: ${avg.toFixed(2)}, min: ${min}, max: ${max}, count: ${numericValues.length}`
});
} else {
// Column is text-based, provide basic info
const uniqueValues = [...new Set(columnValues)].length;
stats.push({
column: columnName,
summary: `${columnValues.length} values, ${uniqueValues} unique`
});
}
}
return stats;
}
/**
* Estimates token count for a text string (rough approximation)
* Uses the common 4 characters per token rule
*/
function estimateTokens(text: string): number {
return Math.ceil(text.length / 4);
}
/**
* Gets CTX_KNOWLEDGE_ENABLED setting from runtime or environment
* Ensures consistency with config.ts validation
*/
function getCtxKnowledgeEnabled(runtime?: IAgentRuntime): boolean {
let result: boolean;
let source: string;
let rawValue: string | undefined;
if (runtime) {
rawValue = runtime.getSetting('CTX_KNOWLEDGE_ENABLED');
// CRITICAL FIX: Use trim() and case-insensitive comparison
const cleanValue = rawValue?.toString().trim().toLowerCase();
result = cleanValue === 'true';
source = 'runtime.getSetting()';
} else {
rawValue = process.env.CTX_KNOWLEDGE_ENABLED;
const cleanValue = rawValue?.toString().trim().toLowerCase();
result = cleanValue === 'true';
source = 'process.env';
}
// Only log when there's a mismatch or for initial debugging
if (process.env.NODE_ENV === 'development' && rawValue && !result) {
logger.debug(
`[Document Processor] 🔍 CTX config mismatch - ${source}: '${rawValue}' → ${result}`
);
}
return result;
}
/**
* Check if custom LLM should be used based on environment variables
* Custom LLM is enabled when all three key variables are set:
* - TEXT_PROVIDER
* - TEXT_MODEL
* - OPENROUTER_API_KEY (or provider-specific API key)
*/
function shouldUseCustomLLM(): boolean {
const textProvider = process.env.TEXT_PROVIDER;
const textModel = process.env.TEXT_MODEL;
if (!textProvider || !textModel) {
return false;
}
// Check for provider-specific API keys
switch (textProvider.toLowerCase()) {
case 'openrouter':
return !!process.env.OPENROUTER_API_KEY;
case 'openai':
return !!process.env.OPENAI_API_KEY;
case 'anthropic':
return !!process.env.ANTHROPIC_API_KEY;
case 'google':
return !!process.env.GOOGLE_API_KEY;
default:
return false;
}
}
const useCustomLLM = shouldUseCustomLLM();
// =============================================================================
// MAIN DOCUMENT PROCESSING FUNCTIONS
// =============================================================================
/**
* Process document fragments synchronously
* This function:
* 1. Splits the document text into chunks
* 2. Enriches chunks with context if contextual Knowledge is enabled
* 3. Generates embeddings for each chunk
* 4. Stores fragments with embeddings in the database
*
* @param params Fragment parameters
* @returns Number of fragments processed
*/
export async function processFragmentsSynchronously({
runtime,
documentId,
fullDocumentText,
agentId,
contentType,
roomId,
entityId,
worldId,
documentTitle,
chunksDbName = 'knowledge',
}: {
runtime: IAgentRuntime;
documentId: UUID;
fullDocumentText: string;
agentId: UUID;
contentType?: string;
roomId?: UUID;
entityId?: UUID;
worldId?: UUID;
documentTitle?: string;
chunksDbName?: string;
}): Promise<number> {
if (!fullDocumentText || fullDocumentText.trim() === '') {
logger.warn(`No text content available to chunk for document ${documentId}.`);
return 0;
}
// Split the text into chunks using standard parameters
const chunks = await splitDocumentIntoChunks(fullDocumentText);
if (chunks.length === 0) {
logger.warn(`No chunks generated from text for ${documentId}. No fragments to save.`);
return 0;
}
const docName = documentTitle || documentId.substring(0, 8);
logger.info(`[Document Processor] 📄 "${docName}": Split into ${chunks.length} chunks`);
// Get provider limits for rate limiting
const providerLimits = await getProviderRateLimits();
const CONCURRENCY_LIMIT = Math.min(30, providerLimits.maxConcurrentRequests || 30);
const rateLimiter = createRateLimiter(
providerLimits.requestsPerMinute || 60,
providerLimits.tokensPerMinute
);
logger.debug(
`[Document Processor] 🛡️ Rate limits: ${providerLimits.requestsPerMinute} RPM, ${providerLimits.tokensPerMinute} TPM (${providerLimits.provider}, concurrency: ${CONCURRENCY_LIMIT})`
);
// Process and save fragments
const { savedCount, failedCount } = await processAndSaveFragments({
runtime,
documentId,
chunks,
fullDocumentText,
contentType,
agentId,
roomId: roomId || agentId,
entityId: entityId || agentId,
worldId: worldId || agentId,
concurrencyLimit: CONCURRENCY_LIMIT,
rateLimiter,
documentTitle,
chunksDbName,
});
// Report results with summary
const successRate = ((savedCount / chunks.length) * 100).toFixed(1);
if (failedCount > 0) {
logger.warn(
`[Document Processor] ⚠️ "${docName}": ${failedCount}/${chunks.length} chunks failed processing`
);
}
logger.info(
`[Document Processor] ✅ "${docName}" complete: ${savedCount}/${chunks.length} fragments saved (${successRate}% success)`
);
// Provide comprehensive end summary
logKnowledgeGenerationSummary({
documentId,
totalChunks: chunks.length,
savedCount,
failedCount,
successRate: parseFloat(successRate),
ctxEnabled: getCtxKnowledgeEnabled(runtime),
providerLimits,
});
return savedCount;
}
// =============================================================================
// DOCUMENT EXTRACTION & MEMORY FUNCTIONS
// =============================================================================
/**
* Extract text from document buffer based on content type
* @param fileBuffer Document buffer
* @param contentType MIME type of the document
* @param originalFilename Original filename
* @returns Extracted text
*/
export async function extractTextFromDocument(
fileBuffer: Buffer,
contentType: string,
originalFilename: string
): Promise<string> {
// Validate buffer
if (!fileBuffer || fileBuffer.length === 0) {
throw new Error(`Empty file buffer provided for ${originalFilename}. Cannot extract text.`);
}
try {
if (contentType === 'application/pdf') {
logger.debug(`Extracting text from PDF: ${originalFilename}`);
return await convertPdfToTextFromBuffer(fileBuffer, originalFilename);
} else if (contentType === 'text/csv') {
logger.debug(`Extracting text from CSV: ${originalFilename}`);
return parseCSVToText(fileBuffer.toString('utf8'), originalFilename);
} else {
logger.debug(`Extracting text from non-PDF/CSV: ${originalFilename} (Type: ${contentType})`);
// For plain text files, try UTF-8 decoding first
if (
contentType.includes('text/') ||
contentType.includes('application/json') ||
contentType.includes('application/xml')
) {
try {
return fileBuffer.toString('utf8');
} catch (textError) {
logger.warn(
`Failed to decode ${originalFilename} as UTF-8, falling back to binary extraction`
);
}
}
// For other files, use general extraction
return await extractTextFromFileBuffer(fileBuffer, contentType, originalFilename);
}
} catch (error: any) {
logger.error(`Error extracting text from ${originalFilename}: ${error.message}`);
throw new Error(`Failed to extract text from ${originalFilename}: ${error.message}`);
}
}
/**
* Create a memory object for the main document
* @param params Document parameters
* @returns Memory object for the main document
*/
export function createDocumentMemory({
text,
agentId,
clientDocumentId,
originalFilename,
contentType,
worldId,
fileSize,
documentId,
customMetadata,
}: {
text: string;
agentId: UUID;
clientDocumentId: UUID;
originalFilename: string;
contentType: string;
worldId: UUID;
fileSize: number;
documentId?: UUID;
customMetadata?: Record<string, unknown>;
}): Memory {
const fileExt = originalFilename.split('.').pop()?.toLowerCase() || '';
const title = originalFilename.replace(`.${fileExt}`, '');
// Use the provided documentId or generate a new one
const docId = documentId || (uuidv4() as UUID);
return {
id: docId,
agentId,
roomId: agentId,
worldId,
entityId: agentId,
content: { text },
metadata: {
type: MemoryType.DOCUMENT,
documentId: clientDocumentId,
originalFilename,
contentType,
title,
fileExt,
fileSize,
source: 'rag-service-main-upload',
timestamp: Date.now(),
// Merge custom metadata if provided
...(customMetadata || {}),
},
};
}
// =============================================================================
// CHUNKING AND FRAGMENT PROCESSING
// =============================================================================
/**
* Split document text into chunks using standard parameters
* @param documentText The full document text to split
* @returns Array of text chunks
*/
async function splitDocumentIntoChunks(documentText: string): Promise<string[]> {
// Use the standardized constants
const tokenChunkSize = DEFAULT_CHUNK_TOKEN_SIZE;
const tokenChunkOverlap = DEFAULT_CHUNK_OVERLAP_TOKENS;
// Calculate character-based chunking sizes from token sizes for compatibility with splitChunks
const targetCharChunkSize = Math.round(tokenChunkSize * DEFAULT_CHARS_PER_TOKEN);
const targetCharChunkOverlap = Math.round(tokenChunkOverlap * DEFAULT_CHARS_PER_TOKEN);
logger.debug(
`Using core splitChunks with settings: tokenChunkSize=${tokenChunkSize}, tokenChunkOverlap=${tokenChunkOverlap}, ` +
`charChunkSize=${targetCharChunkSize}, charChunkOverlap=${targetCharChunkOverlap}`
);
// Split the text into chunks
return await splitChunks(documentText, tokenChunkSize, tokenChunkOverlap);
}
/**
* Process and save document fragments
* @param params Processing parameters
* @returns Object with counts of saved and failed fragments
*/
async function processAndSaveFragments({
runtime,
documentId,
chunks,
fullDocumentText,
contentType,
agentId,
roomId,
entityId,
worldId,
concurrencyLimit,
rateLimiter,
documentTitle,
chunksDbName = 'knowledge',
}: {
runtime: IAgentRuntime;
documentId: UUID;
chunks: string[];
fullDocumentText: string;
contentType?: string;
agentId: UUID;
roomId?: UUID;
entityId?: UUID;
worldId?: UUID;
concurrencyLimit: number;
rateLimiter: (estimatedTokens?: number) => Promise<void>;
documentTitle?: string;
chunksDbName?: string;
}): Promise<{
savedCount: number;
failedCount: number;
failedChunks: number[];
}> {
let savedCount = 0;
let failedCount = 0;
const failedChunks: number[] = [];
// Process chunks in batches to respect concurrency limits
for (let i = 0; i < chunks.length; i += concurrencyLimit) {
const batchChunks = chunks.slice(i, i + concurrencyLimit);
const batchOriginalIndices = Array.from({ length: batchChunks.length }, (_, k) => i + k);
logger.debug(
`[Document Processor] 📦 Batch ${Math.floor(i / concurrencyLimit) + 1}/${Math.ceil(chunks.length / concurrencyLimit)}: processing ${batchChunks.length} chunks (${batchOriginalIndices[0]}-${batchOriginalIndices[batchOriginalIndices.length - 1]})`
);
// Process context generation in an optimized batch
const contextualizedChunks = await getContextualizedChunks(
runtime,
fullDocumentText,
batchChunks,
contentType,
batchOriginalIndices,
documentTitle
);
// Generate embeddings with rate limiting
const embeddingResults = await generateEmbeddingsForChunks(
runtime,
contextualizedChunks,
rateLimiter
);
// Save fragments with embeddings
for (const result of embeddingResults) {
const originalChunkIndex = result.index;
if (!result.success) {
failedCount++;
failedChunks.push(originalChunkIndex);
logger.warn(`Failed to process chunk ${originalChunkIndex} for document ${documentId}`);
continue;
}
const contextualizedChunkText = result.text;
const embedding = result.embedding;
if (!embedding || embedding.length === 0) {
logger.warn(
`Zero vector detected for chunk ${originalChunkIndex} (document ${documentId}). Embedding: ${JSON.stringify(result.embedding)}`
);
failedCount++;
failedChunks.push(originalChunkIndex);
continue;
}
try {
const fragmentMemory: Memory = {
id: uuidv4() as UUID,
agentId,
roomId: roomId || agentId,
worldId: worldId || agentId,
entityId: entityId || agentId,
embedding,
content: { text: contextualizedChunkText },
metadata: {
type: MemoryType.FRAGMENT,
documentId,
position: originalChunkIndex,
timestamp: Date.now(),
source: 'rag-service-fragment-sync',
},
};
await runtime.createMemory(fragmentMemory, chunksDbName);
// Log when all chunks for this document are processed
if (originalChunkIndex === chunks.length - 1) {
const docName = documentTitle || documentId.substring(0, 8);
logger.info(
`[Document Processor] ✓ "${docName}": All ${chunks.length} chunks processed successfully`
);
}
savedCount++;
} catch (saveError: any) {
logger.error(
`Error saving chunk ${originalChunkIndex} to database: ${saveError.message}`,
saveError.stack
);
failedCount++;
failedChunks.push(originalChunkIndex);
}
}
// Add a small delay between batches to prevent overwhelming the API
if (i + concurrencyLimit < chunks.length) {
await new Promise((resolve) => setTimeout(resolve, 500));
}
}
return { savedCount, failedCount, failedChunks };
}
/**
* Generate embeddings for contextualized chunks
* @param runtime IAgentRuntime
* @param contextualizedChunks Array of contextualized chunks
* @param rateLimiter Rate limiter function
* @returns Array of embedding results
*/
async function generateEmbeddingsForChunks(
runtime: IAgentRuntime,
contextualizedChunks: Array<{
contextualizedText: string;
index: number;
success: boolean;
}>,
rateLimiter: (estimatedTokens?: number) => Promise<void>
): Promise<Array<any>> {
// Filter out failed chunks
const validChunks = contextualizedChunks.filter((chunk) => chunk.success);
const failedChunks = contextualizedChunks.filter((chunk) => !chunk.success);
if (validChunks.length === 0) {
return failedChunks.map((chunk) => ({
success: false,
index: chunk.index,
error: new Error('Chunk processing failed'),
text: chunk.contextualizedText,
}));
}
// Always use individual processing with ElizaOS runtime (keeping embeddings simple)
return await Promise.all(
contextualizedChunks.map(async (contextualizedChunk) => {
if (!contextualizedChunk.success) {
return {
success: false,
index: contextualizedChunk.index,
error: new Error('Chunk processing failed'),
text: contextualizedChunk.contextualizedText,
};
}
// Apply rate limiting before embedding generation
const embeddingTokens = estimateTokens(contextualizedChunk.contextualizedText);
await rateLimiter(embeddingTokens);
try {
const generateEmbeddingOperation = async () => {
return await generateEmbeddingWithValidation(
runtime,
contextualizedChunk.contextualizedText
);
};
const { embedding, success, error } = await withRateLimitRetry(
generateEmbeddingOperation,
`embedding generation for chunk ${contextualizedChunk.index}`
);
if (!success) {
return {
success: false,
index: contextualizedChunk.index,
error,
text: contextualizedChunk.contextualizedText,
};
}
return {
embedding,
success: true,
index: contextualizedChunk.index,
text: contextualizedChunk.contextualizedText,
};
} catch (error: any) {
logger.error(
`Error generating embedding for chunk ${contextualizedChunk.index}: ${error.message}`
);
return {
success: false,
index: contextualizedChunk.index,
error,
text: contextualizedChunk.contextualizedText,
};
}
})
);
}
// =============================================================================
// CONTEXTUAL ENRICHMENT FUNCTIONS
// =============================================================================
/**
* Generate contextual chunks if contextual Knowledge is enabled
*/
async function getContextualizedChunks(
runtime: IAgentRuntime,
fullDocumentText: string | undefined,
chunks: string[],
contentType: string | undefined,
batchOriginalIndices: number[],
documentTitle?: string
): Promise<Array<{ contextualizedText: string; index: number; success: boolean }>> {
const ctxEnabled = getCtxKnowledgeEnabled(runtime);
const isPdf = contentType === 'application/pdf';
// Log configuration state once per document (not per batch)
if (batchOriginalIndices[0] === 0) {
const docName = documentTitle || 'Document';
const provider = runtime?.getSetting('TEXT_PROVIDER') || process.env.TEXT_PROVIDER;
const model = runtime?.getSetting('TEXT_MODEL') || process.env.TEXT_MODEL;
if (isPdf) {
logger.info(`[Document Processor] 📋 "${docName}": PDF detected - skipping CTX enrichment`);
} else {
logger.info(
`[Document Processor] 📋 "${docName}": CTX enrichment ${ctxEnabled ? 'ENABLED' : 'DISABLED'}${ctxEnabled ? ` (${provider}/${model})` : ''}`
);
}
}
// For PDFs or when CTX is disabled, return chunks without modification
if (isPdf || !ctxEnabled || !fullDocumentText) {
if (!isPdf && !ctxEnabled && batchOriginalIndices[0] === 0) {
logger.debug(
`[Document Processor] ℹ️ To enable CTX: Set CTX_KNOWLEDGE_ENABLED=true and configure TEXT_PROVIDER/TEXT_MODEL`
);
}
return chunks.map((chunkText, idx) => ({
contextualizedText: chunkText,
index: batchOriginalIndices[idx],
success: true,
}));
}
// Enhanced logging for contextual processing
return await generateContextsInBatch(
runtime,
fullDocumentText,
chunks,
contentType,
batchOriginalIndices,
documentTitle
);
}
/**
* Generate contexts for multiple chunks in a single batch
*/
async function generateContextsInBatch(
runtime: IAgentRuntime,
fullDocumentText: string,
chunks: string[],
contentType?: string,
batchIndices?: number[],
documentTitle?: string
): Promise<Array<{ contextualizedText: string; success: boolean; index: number }>> {
if (!chunks || chunks.length === 0) {
return [];
}
const providerLimits = await getProviderRateLimits();
const rateLimiter = createRateLimiter(
providerLimits.requestsPerMinute || 60,
providerLimits.tokensPerMinute
);
// Get active provider from validateModelConfig
const config = validateModelConfig();
const isUsingOpenRouter = config.TEXT_PROVIDER === 'openrouter';
const isUsingCacheCapableModel =
isUsingOpenRouter &&
(config.TEXT_MODEL?.toLowerCase().includes('claude') ||
config.TEXT_MODEL?.toLowerCase().includes('gemini'));
logger.debug(
`[Document Processor] 🎯 Contextualizing ${chunks.length} chunks with ${config.TEXT_PROVIDER}/${config.TEXT_MODEL} (cache: ${isUsingCacheCapableModel})`
);
// Prepare prompts or system messages in parallel
const promptConfigs = prepareContextPrompts(
chunks,
fullDocumentText,
contentType,
batchIndices,
isUsingCacheCapableModel
);
// Process valid prompts with rate limiting
const contextualizedChunks = await Promise.all(
promptConfigs.map(async (item) => {
if (!item.valid) {
return {
contextualizedText: item.chunkText,
success: false,
index: item.originalIndex,
};
}
// Apply rate limiting before making API call
const llmTokens = estimateTokens(item.chunkText + (item.prompt || ''));
await rateLimiter(llmTokens);
try {
let llmResponse;
const generateTextOperation = async () => {
if (useCustomLLM) {
// Use custom LLM with caching support
if (item.usesCaching) {
// Use the newer caching approach with separate document
return await generateText(item.promptText!, item.systemPrompt, {
cacheDocument: item.fullDocumentTextForContext,
cacheOptions: { type: 'ephemeral' },
autoCacheContextualRetrieval: true,
});
} else {
// Original approach - document embedded in prompt
return await generateText(item.prompt!);
}
} else {
// Fall back to runtime.useModel (original behavior)
if (item.usesCaching) {
// Use the newer caching approach with separate document
// Note: runtime.useModel doesn't support cacheDocument/cacheOptions
return await runtime.useModel(ModelType.TEXT_LARGE, {
prompt: item.promptText!,
system: item.systemPrompt,
});
} else {
// Original approach - document embedded in prompt
return await runtime.useModel(ModelType.TEXT_LARGE, {
prompt: item.prompt!,
});
}
}
};
llmResponse = await withRateLimitRetry(
generateTextOperation,
`context generation for chunk ${item.originalIndex}`
);
const generatedContext = typeof llmResponse === 'string' ? llmResponse : llmResponse.text;
const contextualizedText = getChunkWithContext(item.chunkText, generatedContext);
// Track context generation progress without spam
if (
(item.originalIndex + 1) % Math.max(1, Math.floor(chunks.length / 3)) === 0 ||
item.originalIndex === chunks.length - 1
) {
const docName = documentTitle || 'Document';
logger.debug(
`[Document Processor] 🧠 "${docName}": Context added for ${item.originalIndex + 1}/${chunks.length} chunks`
);
}
return {
contextualizedText,
success: true,
index: item.originalIndex,
};
} catch (error: any) {
logger.error(
`Error generating context for chunk ${item.originalIndex}: ${error.message}`,
error.stack
);
return {
contextualizedText: item.chunkText,
success: false,
index: item.originalIndex,
};
}
})
);
return contextualizedChunks;
}
/**
* Prepare prompts for contextualization
*/
function prepareContextPrompts(
chunks: string[],
fullDocumentText: string,
contentType?: string,
batchIndices?: number[],
isUsingCacheCapableModel = false
): Array<any> {
return chunks.map((chunkText, idx) => {
const originalIndex = batchIndices ? batchIndices[idx] : idx;
try {
// If we're using OpenRouter with Claude/Gemini, use the newer caching approach
if (isUsingCacheCapableModel) {
// Get optimized caching prompt from ctx-embeddings.ts
const cachingPromptInfo = contentType
? getCachingPromptForMimeType(contentType, chunkText)
: getCachingContextualizationPrompt(chunkText);
// If there was an error in prompt generation
if (cachingPromptInfo.prompt.startsWith('Error:')) {
logger.warn(
`Skipping contextualization for chunk ${originalIndex} due to: ${cachingPromptInfo.prompt}`
);
return {
originalIndex,
chunkText,
valid: false,
usesCaching: false,
};
}
return {
valid: true,
originalIndex,
chunkText,
usesCaching: true,
systemPrompt: cachingPromptInfo.systemPrompt,
promptText: cachingPromptInfo.prompt,
fullDocumentTextForContext: fullDocumentText,
};
} else {
// Original approach - embed document in the prompt
const prompt = contentType
? getPromptForMimeType(contentType, fullDocumentText, chunkText)