@minded-ai/mindedjs 1.0.108 → 1.0.109-beta-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/dist/agent.d.ts +12 -12
  2. package/dist/agent.d.ts.map +1 -1
  3. package/dist/agent.js +37 -13
  4. package/dist/agent.js.map +1 -1
  5. package/dist/browserTask/README.md +419 -0
  6. package/dist/browserTask/browserAgent.py +632 -0
  7. package/dist/browserTask/captcha_isolated.png +0 -0
  8. package/dist/browserTask/executeBrowserTask.d.ts +1 -11
  9. package/dist/browserTask/executeBrowserTask.d.ts.map +1 -1
  10. package/dist/browserTask/executeBrowserTask.js +67 -170
  11. package/dist/browserTask/executeBrowserTask.js.map +1 -1
  12. package/dist/browserTask/executeBrowserTask.ts +79 -0
  13. package/dist/browserTask/requirements.txt +8 -0
  14. package/dist/browserTask/setup.sh +144 -0
  15. package/dist/cli/index.js +103 -1
  16. package/dist/cli/index.js.map +1 -1
  17. package/dist/edges/createLogicalRouter.d.ts +3 -1
  18. package/dist/edges/createLogicalRouter.d.ts.map +1 -1
  19. package/dist/edges/createLogicalRouter.js +41 -2
  20. package/dist/edges/createLogicalRouter.js.map +1 -1
  21. package/dist/edges/edgeFactory.d.ts.map +1 -1
  22. package/dist/edges/edgeFactory.js +7 -7
  23. package/dist/edges/edgeFactory.js.map +1 -1
  24. package/dist/events/AgentEvents.d.ts +19 -1
  25. package/dist/events/AgentEvents.d.ts.map +1 -1
  26. package/dist/events/AgentEvents.js +2 -0
  27. package/dist/events/AgentEvents.js.map +1 -1
  28. package/dist/index.d.ts +2 -0
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +4 -1
  31. package/dist/index.js.map +1 -1
  32. package/dist/internalTools/timer.d.ts +3 -3
  33. package/dist/internalTools/timer.d.ts.map +1 -1
  34. package/dist/internalTools/timer.js +3 -3
  35. package/dist/internalTools/timer.js.map +1 -1
  36. package/dist/nodes/addBrowserTaskNode.d.ts +1 -3
  37. package/dist/nodes/addBrowserTaskNode.d.ts.map +1 -1
  38. package/dist/nodes/addBrowserTaskNode.js +54 -186
  39. package/dist/nodes/addBrowserTaskNode.js.map +1 -1
  40. package/dist/nodes/nodeFactory.js +1 -1
  41. package/dist/nodes/nodeFactory.js.map +1 -1
  42. package/docs/SUMMARY.md +8 -4
  43. package/docs/low-code-editor/edges.md +4 -0
  44. package/docs/sdk/debugging.md +342 -0
  45. package/docs/{platform → sdk}/events.md +168 -1
  46. package/package.json +12 -5
  47. package/dist/nodes/addBrowserTaskRunNode.d.ts +0 -13
  48. package/dist/nodes/addBrowserTaskRunNode.d.ts.map +0 -1
  49. package/dist/nodes/addBrowserTaskRunNode.js +0 -130
  50. package/dist/nodes/addBrowserTaskRunNode.js.map +0 -1
  51. package/src/agent.ts +0 -928
  52. package/src/browserTask/executeBrowserTask.ts +0 -213
  53. package/src/checkpointer/checkpointSaverFactory.ts +0 -18
  54. package/src/cli/index.ts +0 -170
  55. package/src/cli/lambdaHandlerTemplate.ts +0 -45
  56. package/src/edges/createDirectEdge.ts +0 -16
  57. package/src/edges/createLogicalRouter.ts +0 -114
  58. package/src/edges/createPromptRouter.ts +0 -218
  59. package/src/edges/edgeFactory.ts +0 -141
  60. package/src/events/AgentEvents.ts +0 -47
  61. package/src/events/index.ts +0 -3
  62. package/src/index.ts +0 -70
  63. package/src/interfaces/zendesk.ts +0 -157
  64. package/src/internalTools/appActionRunnerTool.ts +0 -68
  65. package/src/internalTools/documentExtraction/documentExtraction.ts +0 -809
  66. package/src/internalTools/documentExtraction/types.ts +0 -59
  67. package/src/internalTools/libraryActionRunnerTool.ts +0 -63
  68. package/src/internalTools/retell.ts +0 -28
  69. package/src/internalTools/sendPlaceholderMessage.ts +0 -27
  70. package/src/internalTools/timer.ts +0 -137
  71. package/src/llm/createLlmInstance.ts +0 -33
  72. package/src/nodes/addAppToolNode.ts +0 -106
  73. package/src/nodes/addBrowserTaskNode.ts +0 -231
  74. package/src/nodes/addBrowserTaskRunNode.ts +0 -144
  75. package/src/nodes/addHumanInTheLoopNode.ts +0 -25
  76. package/src/nodes/addJumpToNode.ts +0 -25
  77. package/src/nodes/addJunctionNode.ts +0 -20
  78. package/src/nodes/addPromptNode.ts +0 -119
  79. package/src/nodes/addToolNode.ts +0 -72
  80. package/src/nodes/addToolRunNode.ts +0 -76
  81. package/src/nodes/addTriggerNode.ts +0 -27
  82. package/src/nodes/nodeFactory.ts +0 -57
  83. package/src/platform/config.ts +0 -77
  84. package/src/platform/mindedCheckpointSaver.ts +0 -146
  85. package/src/platform/mindedConnection.ts +0 -199
  86. package/src/platform/mindedConnectionTypes.ts +0 -220
  87. package/src/platform/models/mindedChatOpenAI.ts +0 -49
  88. package/src/platform/models/parallelWrapper.ts +0 -141
  89. package/src/platform/piiGateway/gateway.ts +0 -103
  90. package/src/platform/piiGateway/index.ts +0 -5
  91. package/src/platform/piiGateway/types.ts +0 -29
  92. package/src/platform/utils/parseAttachments.ts +0 -56
  93. package/src/playbooks/playbooks.ts +0 -209
  94. package/src/toolsLibrary/index.ts +0 -6
  95. package/src/toolsLibrary/parseDocument.ts +0 -136
  96. package/src/triggers/triggerTypeToDefaultMessage.ts +0 -9
  97. package/src/types/Agent.types.ts +0 -67
  98. package/src/types/Flows.types.ts +0 -200
  99. package/src/types/LLM.types.ts +0 -15
  100. package/src/types/LangGraph.types.ts +0 -53
  101. package/src/types/Platform.types.ts +0 -1
  102. package/src/types/Tools.types.ts +0 -31
  103. package/src/types/Voice.types.ts +0 -4
  104. package/src/utils/extractStateMemoryResponse.ts +0 -16
  105. package/src/utils/history.ts +0 -9
  106. package/src/utils/logger.ts +0 -22
  107. package/src/utils/wait.ts +0 -1
  108. package/src/voice/elevenLabsUtils.ts +0 -81
  109. package/src/voice/voiceSession.ts +0 -294
  110. /package/docs/{platform → sdk}/logging.md +0 -0
  111. /package/docs/{platform → sdk}/memory.md +0 -0
  112. /package/docs/{platform → sdk}/parallel-llm.md +0 -0
@@ -1,809 +0,0 @@
1
- import { ZodSchema, ZodTypeAny } from 'zod';
2
- import { BaseLanguageModel } from '@langchain/core/language_models/base';
3
- import * as fs from 'fs';
4
- import * as path from 'path';
5
- import { logger } from '../../utils/logger';
6
- import * as os from 'os';
7
- import { DocumentExtractionOptions, DocumentProcessingResult, DocumentProcessorConfig, SUPPORTED_DOCUMENT_TYPES } from './types';
8
-
9
- /**
10
- * Extract data from documents using AI or return raw text.
11
- *
12
- * This function allows you to process various document types (PDFs, images, Word docs, etc.)
13
- * in multiple ways:
14
- * - With LLM + Schema: Extract structured data according to a Zod schema
15
- * - With LLM + System Prompt: Extract unstructured data based on prompt instructions
16
- * - Without LLM: Extract raw text content using LlamaParse
17
- *
18
- * @param options - Document extraction options
19
- * @param options.llm - Optional language model for AI-powered extraction
20
- * @param options.documentPath - Path to the document file
21
- * @param options.documentContent - Document content as Buffer or string
22
- * @param options.documentUrl - URL to fetch the document from
23
- * @param options.schema - Optional Zod schema for structured data extraction
24
- * @param options.systemPrompt - Optional prompt for guiding extraction
25
- * @param options.config - Optional document processor configuration
26
- *
27
- * @returns Promise resolving to extracted data/text and metadata
28
- *
29
- * @example
30
- * ```typescript
31
- * import { extractFromDocument } from '@minded-ai/mindedjs';
32
- * import { z } from 'zod';
33
- *
34
- * // Extract structured data with schema
35
- * const result1 = await extractFromDocument({
36
- * llm: agent.llm,
37
- * documentPath: './invoice.pdf',
38
- * schema: z.object({
39
- * invoiceNumber: z.string(),
40
- * amount: z.number(),
41
- * })
42
- * });
43
- *
44
- * // Extract unstructured data with prompt
45
- * const result2 = await extractFromDocument({
46
- * llm: agent.llm,
47
- * documentPath: './contract.pdf',
48
- * systemPrompt: 'Extract all payment terms and conditions'
49
- * });
50
- *
51
- * // Extract raw text without LLM
52
- * const result3 = await extractFromDocument({
53
- * documentPath: './document.pdf'
54
- * });
55
- * ```
56
- */
57
- export async function extractFromDocument<T = string>(options: {
58
- llm?: BaseLanguageModel;
59
- documentPath?: string;
60
- documentContent?: Buffer | string;
61
- documentUrl?: string;
62
- schema?: ZodSchema<T>;
63
- systemPrompt?: string;
64
- config?: DocumentProcessorConfig;
65
- }): Promise<{
66
- data: T;
67
- metadata: {
68
- fileSize?: number;
69
- fileType: string;
70
- processingTime: number;
71
- contentLength: number;
72
- };
73
- }> {
74
- // Create a document processor
75
- const processor = new DocumentProcessor(options.config, options.llm);
76
-
77
- // Extract from document using the processor
78
- return processor.extractFromDocument({
79
- documentPath: options.documentPath,
80
- documentContent: options.documentContent,
81
- documentUrl: options.documentUrl,
82
- schema: options.schema,
83
- systemPrompt: options.systemPrompt,
84
- });
85
- }
86
-
87
- /**
88
- * Generic document processor that can extract structured data from various document types
89
- * including images, PDFs, Word documents, spreadsheets, and more.
90
- */
91
- export class DocumentProcessor {
92
- private config: DocumentProcessorConfig;
93
- private llm: BaseLanguageModel | null = null;
94
- private llamaCloudApiKey: string | null = null;
95
- private sharpModule: any = null;
96
- private sharpLoadAttempted = false;
97
-
98
- constructor(config: DocumentProcessorConfig = {}, llm?: BaseLanguageModel) {
99
- this.config = {
100
- maxImageWidth: 1200,
101
- imageQuality: 85,
102
- useBase64: false,
103
- ...config,
104
- };
105
-
106
- this.llm = llm || null;
107
- this.llamaCloudApiKey = this.config.llamaCloudApiKey || process.env.LLAMA_CLOUD_API_KEY || null;
108
- }
109
-
110
- /**
111
- * Parse document using LlamaCloud REST API
112
- */
113
- private async parseWithLlamaCloud(filePath: string): Promise<string | null> {
114
- if (!this.llamaCloudApiKey) {
115
- return null;
116
- }
117
-
118
- try {
119
- // Step 1: Upload file and start parsing
120
- const fileContent = fs.readFileSync(filePath);
121
- const fileName = path.basename(filePath);
122
- const mimeType = this.getMimeType(path.extname(filePath));
123
-
124
- const formData = new FormData();
125
- const blob = new Blob([fileContent], { type: mimeType });
126
- formData.append('file', blob, fileName);
127
-
128
- const uploadResponse = await fetch('https://api.cloud.llamaindex.ai/api/v1/parsing/upload', {
129
- method: 'POST',
130
- headers: {
131
- Accept: 'application/json',
132
- Authorization: `Bearer ${this.llamaCloudApiKey}`,
133
- },
134
- body: formData,
135
- });
136
-
137
- if (!uploadResponse.ok) {
138
- const errorText = await uploadResponse.text();
139
- throw new Error(`Failed to upload file: ${uploadResponse.status} - ${errorText}`);
140
- }
141
-
142
- const uploadResult = await uploadResponse.json();
143
- const jobId = uploadResult.id || uploadResult.job_id;
144
-
145
- if (!jobId) {
146
- throw new Error('No job ID returned from upload');
147
- }
148
-
149
- logger.info({
150
- msg: '[DocumentProcessor] File uploaded to LlamaCloud',
151
- jobId,
152
- fileName,
153
- });
154
-
155
- // Step 2: Poll for job completion
156
- let attempts = 0;
157
- const maxAttempts = 60; // 60 attempts with 2 second delay = 2 minutes max
158
- const pollDelay = 2000; // 2 seconds
159
-
160
- while (attempts < maxAttempts) {
161
- const statusResponse = await fetch(`https://api.cloud.llamaindex.ai/api/v1/parsing/job/${jobId}`, {
162
- method: 'GET',
163
- headers: {
164
- Accept: 'application/json',
165
- Authorization: `Bearer ${this.llamaCloudApiKey}`,
166
- },
167
- });
168
-
169
- if (!statusResponse.ok) {
170
- throw new Error(`Failed to check job status: ${statusResponse.status}`);
171
- }
172
-
173
- const statusResult = await statusResponse.json();
174
- const status = statusResult.status || statusResult.job_status;
175
-
176
- if (status === 'SUCCESS' || status === 'COMPLETED' || status === 'completed') {
177
- // Step 3: Retrieve results in Markdown
178
-
179
- // Create an AbortController for timeout
180
- const controller = new AbortController();
181
- const timeout = setTimeout(() => controller.abort(), 20000); // 20 second timeout
182
-
183
- let resultResponse;
184
- try {
185
- resultResponse = await fetch(`https://api.cloud.llamaindex.ai/api/v1/parsing/job/${jobId}/result/markdown`, {
186
- method: 'GET',
187
- headers: {
188
- Accept: 'application/json',
189
- Authorization: `Bearer ${this.llamaCloudApiKey}`,
190
- },
191
- signal: controller.signal,
192
- });
193
- } catch (fetchError) {
194
- clearTimeout(timeout);
195
- if (fetchError instanceof Error && fetchError.name === 'AbortError') {
196
- throw new Error('Timeout fetching results from LlamaCloud after 20 seconds');
197
- }
198
- throw fetchError;
199
- }
200
-
201
- clearTimeout(timeout);
202
-
203
- if (!resultResponse.ok) {
204
- const errorText = await resultResponse.text();
205
- throw new Error(`Failed to retrieve results: ${resultResponse.status} - ${errorText}`);
206
- }
207
-
208
- let resultData: any;
209
- try {
210
- // Read response using manual stream reading (more reliable than text())
211
- let responseText;
212
- if (resultResponse.body) {
213
- const reader = resultResponse.body.getReader();
214
- const chunks: Uint8Array[] = [];
215
- let totalLength = 0;
216
-
217
- try {
218
- while (true) {
219
- const { done, value } = await reader.read();
220
- if (done) break;
221
- if (value) {
222
- chunks.push(value);
223
- totalLength += value.length;
224
- }
225
- }
226
-
227
- // Combine chunks
228
- const combined = new Uint8Array(totalLength);
229
- let offset = 0;
230
- for (const chunk of chunks) {
231
- combined.set(chunk, offset);
232
- offset += chunk.length;
233
- }
234
-
235
- responseText = new TextDecoder().decode(combined);
236
- } finally {
237
- reader.releaseLock();
238
- }
239
- } else {
240
- responseText = await resultResponse.text();
241
- }
242
-
243
- // Try to parse as JSON, but if it fails, use the text directly
244
- try {
245
- resultData = JSON.parse(responseText);
246
- } catch {
247
- // If it's not JSON, assume it's the markdown content directly
248
- resultData = responseText;
249
- }
250
- } catch (textError) {
251
- logger.error({
252
- msg: '[DocumentProcessor] Failed to read response text',
253
- jobId,
254
- error: textError instanceof Error ? textError.message : String(textError),
255
- stack: textError instanceof Error ? textError.stack : undefined,
256
- });
257
- throw new Error('Failed to read response from LlamaCloud');
258
- }
259
-
260
- logger.debug({
261
- msg: '[DocumentProcessor] Result data structure',
262
- jobId,
263
- dataType: typeof resultData,
264
- keys: typeof resultData === 'object' && resultData !== null ? Object.keys(resultData) : [],
265
- hasMarkdown: typeof resultData === 'object' && 'markdown' in resultData,
266
- hasContent: typeof resultData === 'object' && 'content' in resultData,
267
- hasText: typeof resultData === 'object' && 'text' in resultData,
268
- });
269
-
270
- // The API might return the markdown directly as a string or nested in an object
271
- let markdownContent: string;
272
- if (typeof resultData === 'string') {
273
- markdownContent = resultData;
274
- } else {
275
- markdownContent = resultData.markdown || resultData.content || resultData.text || '';
276
- }
277
-
278
- if (!markdownContent) {
279
- logger.error({
280
- msg: '[DocumentProcessor] No content in result',
281
- jobId,
282
- resultData: JSON.stringify(resultData).substring(0, 500),
283
- });
284
- throw new Error('No content returned from parsing');
285
- }
286
-
287
- logger.info({
288
- msg: '[DocumentProcessor] Successfully parsed document with LlamaCloud',
289
- jobId,
290
- contentLength: markdownContent.length,
291
- preview: markdownContent.substring(0, 100),
292
- });
293
-
294
- logger.debug({
295
- msg: '[DocumentProcessor] About to return markdown content',
296
- jobId,
297
- });
298
-
299
- return markdownContent;
300
- } else if (status === 'FAILED' || status === 'ERROR' || status === 'failed') {
301
- throw new Error(`Parsing job failed: ${statusResult.error || 'Unknown error'}`);
302
- }
303
-
304
- // Wait before next attempt
305
- await new Promise((resolve) => setTimeout(resolve, pollDelay));
306
- attempts++;
307
- }
308
-
309
- throw new Error('Parsing job timed out after 2 minutes');
310
- } catch (error) {
311
- logger.warn({
312
- msg: '[DocumentProcessor] LlamaCloud parsing failed',
313
- error: error instanceof Error ? error.message : String(error),
314
- });
315
- return null;
316
- } finally {
317
- logger.debug({
318
- msg: '[DocumentProcessor] parseWithLlamaCloud finished',
319
- filePath,
320
- });
321
- }
322
- }
323
-
324
- /**
325
- * Get MIME type for file extension
326
- */
327
- private getMimeType(fileExtension: string): string {
328
- const mimeTypes: { [key: string]: string } = {
329
- '.pdf': 'application/pdf',
330
- '.doc': 'application/msword',
331
- '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
332
- '.txt': 'text/plain',
333
- '.rtf': 'application/rtf',
334
- '.jpg': 'image/jpeg',
335
- '.jpeg': 'image/jpeg',
336
- '.png': 'image/png',
337
- '.gif': 'image/gif',
338
- '.bmp': 'image/bmp',
339
- '.webp': 'image/webp',
340
- '.tiff': 'image/tiff',
341
- '.xls': 'application/vnd.ms-excel',
342
- '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
343
- '.csv': 'text/csv',
344
- '.html': 'text/html',
345
- '.htm': 'text/html',
346
- '.xml': 'application/xml',
347
- '.md': 'text/markdown',
348
- };
349
-
350
- return mimeTypes[fileExtension.toLowerCase()] || 'application/octet-stream';
351
- }
352
-
353
- /**
354
- * Extract data from a document - either structured data using AI or raw text
355
- */
356
- async extractFromDocument<T = string>(options: DocumentExtractionOptions): Promise<DocumentProcessingResult<T>> {
357
- logger.debug({
358
- msg: '[DocumentProcessor] extractFromDocument called',
359
- hasDocumentPath: !!options.documentPath,
360
- hasDocumentUrl: !!options.documentUrl,
361
- hasDocumentContent: !!options.documentContent,
362
- hasLLM: !!this.llm,
363
- hasSchema: !!options.schema,
364
- });
365
-
366
- const startTime = Date.now();
367
-
368
- try {
369
- logger.debug({
370
- msg: '[DocumentProcessor] Getting document content',
371
- });
372
-
373
- // Determine document source and content
374
- const { content, fileType, fileSize } = await this.getDocumentContent(options);
375
-
376
- // Process document content based on type
377
- let processedContent: string;
378
-
379
- if (this.isImageFile(fileType)) {
380
- processedContent = await this.processImageDocument(content as Buffer, fileType, options.documentPath);
381
- } else {
382
- processedContent = await this.processTextDocument(content, options.documentPath, fileType);
383
- }
384
-
385
- logger.info({
386
- msg: '[DocumentProcessor] Document content processed',
387
- fileType,
388
- contentLength: processedContent.length,
389
- });
390
-
391
- const processingTime = Date.now() - startTime;
392
-
393
- // If no LLM is provided, return the raw text content
394
- if (!this.llm) {
395
- return {
396
- data: processedContent as T,
397
- metadata: {
398
- fileSize,
399
- fileType,
400
- processingTime,
401
- contentLength: processedContent.length,
402
- },
403
- };
404
- }
405
-
406
- // If LLM is provided, extract data (structured or unstructured)
407
- const extractedData = await this.extractStructuredData<T>(processedContent, options.schema, options.llmConfig, options.systemPrompt);
408
-
409
- return {
410
- data: extractedData,
411
- metadata: {
412
- fileSize,
413
- fileType,
414
- processingTime,
415
- contentLength: processedContent.length,
416
- },
417
- };
418
- } catch (error) {
419
- logger.error({
420
- msg: '[DocumentProcessor] Document processing failed',
421
- error: error instanceof Error ? error.message : String(error),
422
- });
423
- throw new Error(`Document processing failed: ${error instanceof Error ? error.message : String(error)}`);
424
- }
425
- }
426
-
427
- /**
428
- * Get document content from various sources
429
- */
430
- private async getDocumentContent(options: DocumentExtractionOptions): Promise<{
431
- content: Buffer | string;
432
- fileType: string;
433
- fileSize?: number;
434
- }> {
435
- logger.debug({
436
- msg: '[DocumentProcessor] getDocumentContent called',
437
- hasPath: !!options.documentPath,
438
- hasContent: !!options.documentContent,
439
- hasUrl: !!options.documentUrl,
440
- });
441
-
442
- // From file path
443
- if (options.documentPath) {
444
- if (!fs.existsSync(options.documentPath)) {
445
- throw new Error(`Document not found: ${options.documentPath}`);
446
- }
447
-
448
- const content = fs.readFileSync(options.documentPath);
449
- const fileType = path.extname(options.documentPath).toLowerCase();
450
-
451
- return {
452
- content,
453
- fileType,
454
- fileSize: content.length,
455
- };
456
- }
457
-
458
- // From provided content
459
- if (options.documentContent) {
460
- // Try to infer file type from content if it's a buffer
461
- let fileType = '.unknown';
462
- if (Buffer.isBuffer(options.documentContent)) {
463
- fileType = this.inferFileTypeFromBuffer(options.documentContent);
464
- } else if (typeof options.documentContent === 'string') {
465
- fileType = '.txt'; // Assume text content
466
- }
467
-
468
- return {
469
- content: options.documentContent,
470
- fileType,
471
- fileSize: Buffer.isBuffer(options.documentContent) ? options.documentContent.length : Buffer.byteLength(options.documentContent),
472
- };
473
- }
474
-
475
- // From URL
476
- if (options.documentUrl) {
477
- logger.debug({
478
- msg: '[DocumentProcessor] Fetching document from URL',
479
- url: options.documentUrl,
480
- });
481
-
482
- const response = await fetch(options.documentUrl);
483
-
484
- logger.debug({
485
- msg: '[DocumentProcessor] URL fetch response',
486
- status: response.status,
487
- ok: response.ok,
488
- });
489
-
490
- if (!response.ok) {
491
- throw new Error(`Failed to fetch document from URL: ${response.statusText}`);
492
- }
493
-
494
- const arrayBuffer = await response.arrayBuffer();
495
- const content = Buffer.from(arrayBuffer);
496
- const fileType = this.inferFileTypeFromUrl(options.documentUrl) || this.inferFileTypeFromBuffer(content);
497
-
498
- logger.debug({
499
- msg: '[DocumentProcessor] Document fetched from URL',
500
- contentSize: content.length,
501
- fileType,
502
- });
503
-
504
- return {
505
- content,
506
- fileType,
507
- fileSize: content.length,
508
- };
509
- }
510
-
511
- throw new Error('No document source provided. Specify documentPath, documentContent, or documentUrl.');
512
- }
513
-
514
- /**
515
- * Process image documents by converting them to a standardized format
516
- */
517
- private async processImageDocument(content: Buffer, fileType: string, filePath?: string): Promise<string> {
518
- try {
519
- // First, try to use LlamaParser if available for text extraction
520
- if (filePath && this.llamaCloudApiKey) {
521
- logger.debug({
522
- msg: '[DocumentProcessor] Calling parseWithLlamaCloud for image',
523
- filePath,
524
- });
525
- const parsedContent = await this.parseWithLlamaCloud(filePath);
526
- logger.debug({
527
- msg: '[DocumentProcessor] parseWithLlamaCloud returned for image',
528
- hasContent: !!parsedContent,
529
- contentLength: parsedContent?.length,
530
- });
531
- if (parsedContent) {
532
- return parsedContent;
533
- }
534
- }
535
-
536
- // If no file path, create a temporary file for LlamaCloud parsing
537
- if (!filePath && this.llamaCloudApiKey) {
538
- const tempDir = os.tmpdir();
539
- const tempFileName = `temp_${Date.now()}${fileType}`;
540
- const tempFilePath = path.join(tempDir, tempFileName);
541
-
542
- logger.debug({
543
- msg: '[DocumentProcessor] Creating temp file for image',
544
- tempFilePath,
545
- contentSize: content.length,
546
- });
547
-
548
- try {
549
- fs.writeFileSync(tempFilePath, content);
550
- logger.debug({
551
- msg: '[DocumentProcessor] Calling parseWithLlamaCloud for temp image',
552
- tempFilePath,
553
- });
554
- const parsedContent = await this.parseWithLlamaCloud(tempFilePath);
555
- logger.debug({
556
- msg: '[DocumentProcessor] parseWithLlamaCloud returned for temp image',
557
- hasContent: !!parsedContent,
558
- contentLength: parsedContent?.length,
559
- });
560
- fs.unlinkSync(tempFilePath);
561
-
562
- if (parsedContent) {
563
- return parsedContent;
564
- }
565
- } catch (error) {
566
- // Clean up temp file on error
567
- if (fs.existsSync(tempFilePath)) {
568
- fs.unlinkSync(tempFilePath);
569
- }
570
- logger.warn({
571
- msg: '[DocumentProcessor] Failed to parse image with LlamaCloud',
572
- error: error instanceof Error ? error.message : String(error),
573
- });
574
- }
575
- }
576
-
577
- // Fallback: Convert to image format for LLM processing
578
- // For PDFs, convert first page to image
579
- if (fileType === '.pdf') {
580
- throw new Error('Failed to convert PDF to image');
581
- }
582
-
583
- logger.warn({
584
- msg: '[DocumentProcessor] Sharp module not available. Using original image without optimization.',
585
- fileType,
586
- contentSize: content.length,
587
- });
588
-
589
- // If sharp is not available, use the original image
590
- if (this.config.useBase64) {
591
- // Return original image as base64
592
- const base64Image = content.toString('base64');
593
- const mimeType = this.getMimeType(fileType);
594
- return `data:${mimeType};base64,${base64Image}`;
595
- } else {
596
- // Without sharp and without base64, we cannot process the image
597
- return `[IMAGE CONTENT - ${fileType.toUpperCase()} file. Size: ${
598
- content.length
599
- } bytes. Consider using LLAMA_CLOUD_API_KEY for text extraction or set useBase64: true]`;
600
- }
601
- } catch (error) {
602
- throw new Error(`Failed to process image document: ${error instanceof Error ? error.message : String(error)}`);
603
- }
604
- }
605
-
606
- /**
607
- * Process text-based documents using LlamaParser or fallback methods
608
- */
609
- private async processTextDocument(content: Buffer | string, filePath?: string, fileType?: string): Promise<string> {
610
- // Try LlamaCloud parsing if we have a file path
611
- if (filePath && this.llamaCloudApiKey) {
612
- const parsedContent = await this.parseWithLlamaCloud(filePath);
613
- if (parsedContent) {
614
- return parsedContent;
615
- }
616
- }
617
-
618
- // If no file path but we have content and LlamaCloud API key, create a temp file
619
- if (!filePath && this.llamaCloudApiKey && Buffer.isBuffer(content)) {
620
- const tempDir = os.tmpdir();
621
- const tempFileName = `temp_${Date.now()}${fileType || '.txt'}`;
622
- const tempFilePath = path.join(tempDir, tempFileName);
623
-
624
- try {
625
- fs.writeFileSync(tempFilePath, content);
626
- const parsedContent = await this.parseWithLlamaCloud(tempFilePath);
627
- fs.unlinkSync(tempFilePath);
628
-
629
- if (parsedContent) {
630
- return parsedContent;
631
- }
632
- } catch (error) {
633
- // Clean up temp file on error
634
- if (fs.existsSync(tempFilePath)) {
635
- fs.unlinkSync(tempFilePath);
636
- }
637
- logger.warn({
638
- msg: '[DocumentProcessor] Failed to parse text document with LlamaCloud',
639
- error: error instanceof Error ? error.message : String(error),
640
- });
641
- }
642
- }
643
-
644
- // Fallback: handle based on file type
645
- if (typeof content === 'string') {
646
- return content;
647
- }
648
-
649
- // For binary content, convert to text
650
- if (fileType === '.pdf' && !this.llamaCloudApiKey) {
651
- throw new Error('PDF processing requires LLAMA_CLOUD_API_KEY environment variable for LlamaParser');
652
- }
653
-
654
- // Basic text extraction for simple formats
655
- if (['.txt', '.md', '.html', '.htm', '.xml', '.csv'].includes(fileType || '')) {
656
- return content.toString('utf-8');
657
- }
658
-
659
- // For unsupported binary formats without LlamaParser
660
- throw new Error(`Unsupported document type ${fileType}. Please provide LLAMA_CLOUD_API_KEY for advanced document processing.`);
661
- }
662
-
663
- /**
664
- * Extract data using LLM - either structured with schema or unstructured with prompt
665
- */
666
- private async extractStructuredData<T>(
667
- content: string,
668
- schema?: ZodSchema<T> | ZodTypeAny,
669
- llmConfig?: { model?: string; temperature?: number },
670
- systemPrompt?: string,
671
- ): Promise<T> {
672
- if (!this.llm) {
673
- throw new Error('LLM instance is required for data extraction. Please provide an LLM when creating the DocumentProcessor.');
674
- }
675
-
676
- // Note: llmConfig is ignored when using the provided LLM instance
677
- // The LLM should already be configured with the desired model and temperature
678
-
679
- const defaultSystemPrompt =
680
- 'You are an expert data-extraction assistant. ' +
681
- 'Extract the requested information from the provided document content. ' +
682
- 'If you cannot find a value for a required field, use "N/A" or a descriptive placeholder. ' +
683
- 'Be accurate and thorough in your extraction.';
684
-
685
- const finalSystemPrompt = systemPrompt || defaultSystemPrompt;
686
-
687
- try {
688
- // If schema is provided, use structured output
689
- if (schema) {
690
- // Check if the LLM supports withStructuredOutput
691
- if (!('withStructuredOutput' in this.llm)) {
692
- throw new Error('The provided LLM does not support structured output. Please use a compatible LLM instance.');
693
- }
694
-
695
- const structuredLlm = (this.llm as any).withStructuredOutput(schema as any);
696
-
697
- const result = await structuredLlm.invoke([
698
- {
699
- role: 'system',
700
- content: finalSystemPrompt,
701
- },
702
- {
703
- role: 'user',
704
- content: `Please extract the following information from this document:\n\n${content}`,
705
- },
706
- ]);
707
-
708
- logger.debug({
709
- msg: '[DocumentProcessor] Structured data extraction completed',
710
- extractedData: JSON.stringify(result, null, 2),
711
- });
712
-
713
- return result as T;
714
- } else {
715
- // Without schema, return the LLM's text response
716
- const response = await this.llm.invoke([
717
- {
718
- role: 'system',
719
- content: finalSystemPrompt,
720
- },
721
- {
722
- role: 'user',
723
- content: `Please analyze and extract information from this document:\n\n${content}`,
724
- },
725
- ]);
726
-
727
- // Extract the text content from the response
728
- let textContent: string;
729
- if (typeof response.content === 'string') {
730
- textContent = response.content;
731
- } else if (Array.isArray(response.content) && response.content.length > 0) {
732
- // Handle array of content blocks
733
- textContent = response.content.map((block: any) => (typeof block === 'string' ? block : block.text || '')).join('\n');
734
- } else {
735
- textContent = String(response.content);
736
- }
737
-
738
- logger.debug({
739
- msg: '[DocumentProcessor] Unstructured data extraction completed',
740
- contentLength: textContent.length,
741
- });
742
-
743
- return textContent as T;
744
- }
745
- } catch (error) {
746
- throw new Error(`LLM extraction failed: ${error instanceof Error ? error.message : String(error)}`);
747
- }
748
- }
749
-
750
- /**
751
- * Check if file is an image type
752
- */
753
- private isImageFile(fileType: string): boolean {
754
- const imageTypes = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tiff'];
755
- return imageTypes.includes(fileType.toLowerCase());
756
- }
757
-
758
- /**
759
- * Infer file type from buffer content
760
- */
761
- private inferFileTypeFromBuffer(buffer: Buffer): string {
762
- // Check common file signatures
763
- const signatures: { [key: string]: string } = {
764
- '89504E47': '.png',
765
- FFD8FF: '.jpg',
766
- '47494638': '.gif',
767
- '25504446': '.pdf',
768
- '504B0304': '.zip', // Also used by docx, xlsx, pptx
769
- D0CF11E0: '.doc', // Also xls, ppt
770
- };
771
-
772
- const hex = buffer.toString('hex', 0, 4).toUpperCase();
773
-
774
- for (const [signature, type] of Object.entries(signatures)) {
775
- if (hex.startsWith(signature)) {
776
- return type;
777
- }
778
- }
779
-
780
- return '.unknown';
781
- }
782
-
783
- /**
784
- * Infer file type from URL
785
- */
786
- private inferFileTypeFromUrl(url: string): string | null {
787
- try {
788
- const pathname = new URL(url).pathname;
789
- const extension = path.extname(pathname).toLowerCase();
790
- return extension || null;
791
- } catch {
792
- return null;
793
- }
794
- }
795
-
796
- /**
797
- * Get list of supported document types
798
- */
799
- static getSupportedDocumentTypes(): string[] {
800
- return [...SUPPORTED_DOCUMENT_TYPES];
801
- }
802
-
803
- /**
804
- * Check if a file type is supported
805
- */
806
- static isDocumentTypeSupported(fileType: string): boolean {
807
- return SUPPORTED_DOCUMENT_TYPES.includes(fileType.toLowerCase());
808
- }
809
- }