@minded-ai/mindedjs 2.0.5 → 2.0.6-beta-2

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