-
-
Notifications
You must be signed in to change notification settings - Fork 18.9k
/
Copy pathindex.ts
1819 lines (1655 loc) · 71.2 KB
/
index.ts
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 { getRunningExpressApp } from '../../utils/getRunningExpressApp'
import { DocumentStore } from '../../database/entities/DocumentStore'
import * as fs from 'fs'
import * as path from 'path'
import {
addArrayFilesToStorage,
addSingleFileToStorage,
getFileFromStorage,
ICommonObject,
IDocument,
mapExtToInputField,
mapMimeTypeToInputField,
removeFilesFromStorage,
removeSpecificFileFromStorage
} from 'flowise-components'
import {
addLoaderSource,
ChatType,
DocumentStoreStatus,
IDocumentStoreFileChunkPagedResponse,
IDocumentStoreLoader,
IDocumentStoreLoaderFile,
IDocumentStoreLoaderForPreview,
IDocumentStoreRefreshData,
IDocumentStoreUpsertData,
IDocumentStoreWhereUsed,
INodeData,
IOverrideConfig
} from '../../Interface'
import { DocumentStoreFileChunk } from '../../database/entities/DocumentStoreFileChunk'
import { v4 as uuidv4 } from 'uuid'
import { databaseEntities, getAppVersion, saveUpsertFlowData } from '../../utils'
import logger from '../../utils/logger'
import nodesService from '../nodes'
import { InternalFlowiseError } from '../../errors/internalFlowiseError'
import { StatusCodes } from 'http-status-codes'
import { getErrorMessage } from '../../errors/utils'
import { ChatFlow } from '../../database/entities/ChatFlow'
import { Document } from '@langchain/core/documents'
import { App } from '../../index'
import { UpsertHistory } from '../../database/entities/UpsertHistory'
import { cloneDeep, omit } from 'lodash'
import { FLOWISE_COUNTER_STATUS, FLOWISE_METRIC_COUNTERS } from '../../Interface.Metrics'
import { DOCUMENTSTORE_TOOL_DESCRIPTION_PROMPT_GENERATOR } from '../../utils/prompt'
import { INPUT_PARAMS_TYPE } from '../../utils/constants'
const DOCUMENT_STORE_BASE_FOLDER = 'docustore'
const createDocumentStore = async (newDocumentStore: DocumentStore) => {
try {
const appServer = getRunningExpressApp()
const documentStore = appServer.AppDataSource.getRepository(DocumentStore).create(newDocumentStore)
const dbResponse = await appServer.AppDataSource.getRepository(DocumentStore).save(documentStore)
return dbResponse
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices.createDocumentStore - ${getErrorMessage(error)}`
)
}
}
const getAllDocumentStores = async () => {
try {
const appServer = getRunningExpressApp()
const entities = await appServer.AppDataSource.getRepository(DocumentStore).find()
return entities
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices.getAllDocumentStores - ${getErrorMessage(error)}`
)
}
}
const getAllDocumentFileChunks = async () => {
try {
const appServer = getRunningExpressApp()
const entities = await appServer.AppDataSource.getRepository(DocumentStoreFileChunk).find()
return entities
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices.getAllDocumentFileChunks - ${getErrorMessage(error)}`
)
}
}
const deleteLoaderFromDocumentStore = async (storeId: string, docId: string) => {
try {
const appServer = getRunningExpressApp()
const entity = await appServer.AppDataSource.getRepository(DocumentStore).findOneBy({
id: storeId
})
if (!entity) {
throw new InternalFlowiseError(
StatusCodes.NOT_FOUND,
`Error: documentStoreServices.deleteLoaderFromDocumentStore - Document store ${storeId} not found`
)
}
const existingLoaders = JSON.parse(entity.loaders)
const found = existingLoaders.find((loader: IDocumentStoreLoader) => loader.id === docId)
if (found) {
if (found.files?.length) {
for (const file of found.files) {
if (file.name) {
try {
await removeSpecificFileFromStorage(DOCUMENT_STORE_BASE_FOLDER, storeId, file.name)
} catch (error) {
console.error(error)
}
}
}
}
const index = existingLoaders.indexOf(found)
if (index > -1) {
existingLoaders.splice(index, 1)
}
// remove the chunks
await appServer.AppDataSource.getRepository(DocumentStoreFileChunk).delete({ docId: found.id })
entity.loaders = JSON.stringify(existingLoaders)
const results = await appServer.AppDataSource.getRepository(DocumentStore).save(entity)
return results
} else {
throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Unable to locate loader in Document Store ${entity.name}`)
}
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices.deleteLoaderFromDocumentStore - ${getErrorMessage(error)}`
)
}
}
const getDocumentStoreById = async (storeId: string) => {
try {
const appServer = getRunningExpressApp()
const entity = await appServer.AppDataSource.getRepository(DocumentStore).findOneBy({
id: storeId
})
if (!entity) {
throw new InternalFlowiseError(
StatusCodes.NOT_FOUND,
`Error: documentStoreServices.getDocumentStoreById - Document store ${storeId} not found`
)
}
return entity
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices.getDocumentStoreById - ${getErrorMessage(error)}`
)
}
}
const getUsedChatflowNames = async (entity: DocumentStore) => {
try {
const appServer = getRunningExpressApp()
if (entity.whereUsed) {
const whereUsed = JSON.parse(entity.whereUsed)
const updatedWhereUsed: IDocumentStoreWhereUsed[] = []
for (let i = 0; i < whereUsed.length; i++) {
const associatedChatflow = await appServer.AppDataSource.getRepository(ChatFlow).findOne({
where: { id: whereUsed[i] },
select: ['id', 'name']
})
if (associatedChatflow) {
updatedWhereUsed.push({
id: whereUsed[i],
name: associatedChatflow.name
})
}
}
return updatedWhereUsed
}
return []
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices.getUsedChatflowNames - ${getErrorMessage(error)}`
)
}
}
// Get chunks for a specific loader or store
const getDocumentStoreFileChunks = async (storeId: string, docId: string, pageNo: number = 1) => {
try {
const appServer = getRunningExpressApp()
const entity = await appServer.AppDataSource.getRepository(DocumentStore).findOneBy({
id: storeId
})
if (!entity) {
throw new InternalFlowiseError(
StatusCodes.NOT_FOUND,
`Error: documentStoreServices.getDocumentStoreById - Document store ${storeId} not found`
)
}
const loaders = JSON.parse(entity.loaders)
let found: IDocumentStoreLoader | undefined
if (docId !== 'all') {
found = loaders.find((loader: IDocumentStoreLoader) => loader.id === docId)
if (!found) {
throw new InternalFlowiseError(
StatusCodes.NOT_FOUND,
`Error: documentStoreServices.getDocumentStoreById - Document loader ${docId} not found`
)
}
}
if (found) {
found.id = docId
found.status = entity.status
}
let characters = 0
if (docId === 'all') {
loaders.forEach((loader: IDocumentStoreLoader) => {
characters += loader.totalChars || 0
})
} else {
characters = found?.totalChars || 0
}
const PAGE_SIZE = 50
const skip = (pageNo - 1) * PAGE_SIZE
const take = PAGE_SIZE
let whereCondition: any = { docId: docId }
if (docId === 'all') {
whereCondition = { storeId: storeId }
}
const count = await appServer.AppDataSource.getRepository(DocumentStoreFileChunk).count({
where: whereCondition
})
const chunksWithCount = await appServer.AppDataSource.getRepository(DocumentStoreFileChunk).find({
skip,
take,
where: whereCondition,
order: {
chunkNo: 'ASC'
}
})
if (!chunksWithCount) {
throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Chunks with docId: ${docId} not found`)
}
const response: IDocumentStoreFileChunkPagedResponse = {
chunks: chunksWithCount,
count: count,
file: found,
currentPage: pageNo,
storeName: entity.name,
description: entity.description,
docId: docId,
characters
}
return response
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices.getDocumentStoreFileChunks - ${getErrorMessage(error)}`
)
}
}
const deleteDocumentStore = async (storeId: string) => {
try {
const appServer = getRunningExpressApp()
// delete all the chunks associated with the store
await appServer.AppDataSource.getRepository(DocumentStoreFileChunk).delete({
storeId: storeId
})
// now delete the files associated with the store
const entity = await appServer.AppDataSource.getRepository(DocumentStore).findOneBy({
id: storeId
})
if (!entity) {
throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Document store ${storeId} not found`)
}
await removeFilesFromStorage(DOCUMENT_STORE_BASE_FOLDER, entity.id)
// delete upsert history
await appServer.AppDataSource.getRepository(UpsertHistory).delete({
chatflowid: storeId
})
// now delete the store
const tbd = await appServer.AppDataSource.getRepository(DocumentStore).delete({
id: storeId
})
return { deleted: tbd.affected }
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices.deleteDocumentStore - ${getErrorMessage(error)}`
)
}
}
const deleteDocumentStoreFileChunk = async (storeId: string, docId: string, chunkId: string) => {
try {
const appServer = getRunningExpressApp()
const entity = await appServer.AppDataSource.getRepository(DocumentStore).findOneBy({
id: storeId
})
if (!entity) {
throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Document store ${storeId} not found`)
}
const loaders = JSON.parse(entity.loaders)
const found = loaders.find((ldr: IDocumentStoreLoader) => ldr.id === docId)
if (!found) {
throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Document store loader ${docId} not found`)
}
const tbdChunk = await appServer.AppDataSource.getRepository(DocumentStoreFileChunk).findOneBy({
id: chunkId
})
if (!tbdChunk) {
throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Document Chunk ${chunkId} not found`)
}
await appServer.AppDataSource.getRepository(DocumentStoreFileChunk).delete(chunkId)
found.totalChunks--
found.totalChars -= tbdChunk.pageContent.length
entity.loaders = JSON.stringify(loaders)
await appServer.AppDataSource.getRepository(DocumentStore).save(entity)
return getDocumentStoreFileChunks(storeId, docId)
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices.deleteDocumentStoreFileChunk - ${getErrorMessage(error)}`
)
}
}
const deleteVectorStoreFromStore = async (storeId: string) => {
try {
const appServer = getRunningExpressApp()
const entity = await appServer.AppDataSource.getRepository(DocumentStore).findOneBy({
id: storeId
})
if (!entity) {
throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Document store ${storeId} not found`)
}
if (!entity.embeddingConfig) {
throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Embedding for Document store ${storeId} not found`)
}
if (!entity.vectorStoreConfig) {
throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Vector Store for Document store ${storeId} not found`)
}
if (!entity.recordManagerConfig) {
throw new InternalFlowiseError(
StatusCodes.NOT_FOUND,
`Record Manager for Document Store ${storeId} is needed to delete data from Vector Store`
)
}
const options: ICommonObject = {
chatflowid: storeId,
appDataSource: appServer.AppDataSource,
databaseEntities,
logger
}
// Get Record Manager Instance
const recordManagerConfig = JSON.parse(entity.recordManagerConfig)
const recordManagerObj = await _createRecordManagerObject(
appServer,
{ recordManagerName: recordManagerConfig.name, recordManagerConfig: recordManagerConfig.config },
options
)
// Get Embeddings Instance
const embeddingConfig = JSON.parse(entity.embeddingConfig)
const embeddingObj = await _createEmbeddingsObject(
appServer,
{ embeddingName: embeddingConfig.name, embeddingConfig: embeddingConfig.config },
options
)
// Get Vector Store Node Data
const vectorStoreConfig = JSON.parse(entity.vectorStoreConfig)
const vStoreNodeData = _createVectorStoreNodeData(
appServer,
{ vectorStoreName: vectorStoreConfig.name, vectorStoreConfig: vectorStoreConfig.config },
embeddingObj,
recordManagerObj
)
// Get Vector Store Instance
const vectorStoreObj = await _createVectorStoreObject(
appServer,
{ vectorStoreName: vectorStoreConfig.name, vectorStoreConfig: vectorStoreConfig.config },
vStoreNodeData
)
const idsToDelete: string[] = [] // empty ids because we get it dynamically from the record manager
// Call the delete method of the vector store
if (vectorStoreObj.vectorStoreMethods.delete) {
await vectorStoreObj.vectorStoreMethods.delete(vStoreNodeData, idsToDelete, options)
}
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices.deleteVectorStoreFromStore - ${getErrorMessage(error)}`
)
}
}
const editDocumentStoreFileChunk = async (storeId: string, docId: string, chunkId: string, content: string, metadata: ICommonObject) => {
try {
const appServer = getRunningExpressApp()
const entity = await appServer.AppDataSource.getRepository(DocumentStore).findOneBy({
id: storeId
})
if (!entity) {
throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Document store ${storeId} not found`)
}
const loaders = JSON.parse(entity.loaders)
const found = loaders.find((ldr: IDocumentStoreLoader) => ldr.id === docId)
if (!found) {
throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Document store loader ${docId} not found`)
}
const editChunk = await appServer.AppDataSource.getRepository(DocumentStoreFileChunk).findOneBy({
id: chunkId
})
if (!editChunk) {
throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Document Chunk ${chunkId} not found`)
}
found.totalChars -= editChunk.pageContent.length
editChunk.pageContent = content
editChunk.metadata = JSON.stringify(metadata)
found.totalChars += content.length
await appServer.AppDataSource.getRepository(DocumentStoreFileChunk).save(editChunk)
entity.loaders = JSON.stringify(loaders)
await appServer.AppDataSource.getRepository(DocumentStore).save(entity)
return getDocumentStoreFileChunks(storeId, docId)
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices.editDocumentStoreFileChunk - ${getErrorMessage(error)}`
)
}
}
// Update documentStore
const updateDocumentStore = async (documentStore: DocumentStore, updatedDocumentStore: DocumentStore) => {
try {
const appServer = getRunningExpressApp()
const tmpUpdatedDocumentStore = appServer.AppDataSource.getRepository(DocumentStore).merge(documentStore, updatedDocumentStore)
const dbResponse = await appServer.AppDataSource.getRepository(DocumentStore).save(tmpUpdatedDocumentStore)
return dbResponse
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices.updateDocumentStore - ${getErrorMessage(error)}`
)
}
}
const _saveFileToStorage = async (fileBase64: string, entity: DocumentStore) => {
const splitDataURI = fileBase64.split(',')
const filename = splitDataURI.pop()?.split(':')[1] ?? ''
const bf = Buffer.from(splitDataURI.pop() || '', 'base64')
const mimePrefix = splitDataURI.pop()
let mime = ''
if (mimePrefix) {
mime = mimePrefix.split(';')[0].split(':')[1]
}
await addSingleFileToStorage(mime, bf, filename, DOCUMENT_STORE_BASE_FOLDER, entity.id)
return {
id: uuidv4(),
name: filename,
mimePrefix: mime,
size: bf.length,
status: DocumentStoreStatus.NEW,
uploaded: new Date()
}
}
const _splitIntoChunks = async (data: IDocumentStoreLoaderForPreview) => {
try {
const appServer = getRunningExpressApp()
let splitterInstance = null
if (data.splitterId && data.splitterConfig && Object.keys(data.splitterConfig).length > 0) {
const nodeInstanceFilePath = appServer.nodesPool.componentNodes[data.splitterId].filePath as string
const nodeModule = await import(nodeInstanceFilePath)
const newNodeInstance = new nodeModule.nodeClass()
let nodeData = {
inputs: { ...data.splitterConfig },
id: 'splitter_0'
}
splitterInstance = await newNodeInstance.init(nodeData)
}
if (!data.loaderId) return []
const nodeInstanceFilePath = appServer.nodesPool.componentNodes[data.loaderId].filePath as string
const nodeModule = await import(nodeInstanceFilePath)
// doc loader configs
const nodeData = {
credential: data.credential || data.loaderConfig['FLOWISE_CREDENTIAL_ID'] || undefined,
inputs: { ...data.loaderConfig, textSplitter: splitterInstance },
outputs: { output: 'document' }
}
const options: ICommonObject = {
chatflowid: uuidv4(),
appDataSource: appServer.AppDataSource,
databaseEntities,
logger
}
const docNodeInstance = new nodeModule.nodeClass()
let docs: IDocument[] = await docNodeInstance.init(nodeData, '', options)
return docs
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices.splitIntoChunks - ${getErrorMessage(error)}`
)
}
}
const _normalizeFilePaths = async (data: IDocumentStoreLoaderForPreview, entity: DocumentStore | null) => {
const keys = Object.getOwnPropertyNames(data.loaderConfig)
let rehydrated = false
for (let i = 0; i < keys.length; i++) {
const input = data.loaderConfig[keys[i]]
if (!input) {
continue
}
if (typeof input !== 'string') {
continue
}
let documentStoreEntity: DocumentStore | null = entity
if (input.startsWith('FILE-STORAGE::')) {
if (!documentStoreEntity) {
const appServer = getRunningExpressApp()
documentStoreEntity = await appServer.AppDataSource.getRepository(DocumentStore).findOneBy({
id: data.storeId
})
if (!documentStoreEntity) {
throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Document store ${data.storeId} not found`)
}
}
const fileName = input.replace('FILE-STORAGE::', '')
let files: string[] = []
if (fileName.startsWith('[') && fileName.endsWith(']')) {
files = JSON.parse(fileName)
} else {
files = [fileName]
}
const loaders = JSON.parse(documentStoreEntity.loaders)
const currentLoader = loaders.find((ldr: IDocumentStoreLoader) => ldr.id === data.id)
if (currentLoader) {
const base64Files: string[] = []
for (const file of files) {
const bf = await getFileFromStorage(file, DOCUMENT_STORE_BASE_FOLDER, documentStoreEntity.id)
// find the file entry that has the same name as the file
const uploadedFile = currentLoader.files.find((uFile: IDocumentStoreLoaderFile) => uFile.name === file)
const mimePrefix = 'data:' + uploadedFile.mimePrefix + ';base64'
const base64String = mimePrefix + ',' + bf.toString('base64') + `,filename:${file}`
base64Files.push(base64String)
}
data.loaderConfig[keys[i]] = JSON.stringify(base64Files)
rehydrated = true
}
}
}
data.rehydrated = rehydrated
}
const previewChunks = async (data: IDocumentStoreLoaderForPreview) => {
try {
if (data.preview) {
if (
data.loaderId === 'cheerioWebScraper' ||
data.loaderId === 'puppeteerWebScraper' ||
data.loaderId === 'playwrightWebScraper'
) {
data.loaderConfig['limit'] = 3
}
}
if (!data.rehydrated) {
await _normalizeFilePaths(data, null)
}
let docs = await _splitIntoChunks(data)
const totalChunks = docs.length
// if -1, return all chunks
if (data.previewChunkCount === -1) data.previewChunkCount = totalChunks
// return all docs if the user ask for more than we have
if (totalChunks <= (data.previewChunkCount || 0)) data.previewChunkCount = totalChunks
// return only the first n chunks
if (totalChunks > (data.previewChunkCount || 0)) docs = docs.slice(0, data.previewChunkCount)
return { chunks: docs, totalChunks: totalChunks, previewChunkCount: data.previewChunkCount }
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices.previewChunks - ${getErrorMessage(error)}`
)
}
}
const saveProcessingLoader = async (data: IDocumentStoreLoaderForPreview): Promise<IDocumentStoreLoader> => {
try {
const appServer = getRunningExpressApp()
const entity = await appServer.AppDataSource.getRepository(DocumentStore).findOneBy({
id: data.storeId
})
if (!entity) {
throw new InternalFlowiseError(
StatusCodes.NOT_FOUND,
`Error: documentStoreServices.saveProcessingLoader - Document store ${data.storeId} not found`
)
}
const existingLoaders = JSON.parse(entity.loaders)
const newDocLoaderId = data.id ?? uuidv4()
const found = existingLoaders.find((ldr: IDocumentStoreLoader) => ldr.id === newDocLoaderId)
if (found) {
const foundIndex = existingLoaders.findIndex((ldr: IDocumentStoreLoader) => ldr.id === newDocLoaderId)
if (!data.loaderId) data.loaderId = found.loaderId
if (!data.loaderName) data.loaderName = found.loaderName
if (!data.loaderConfig) data.loaderConfig = found.loaderConfig
if (!data.splitterId) data.splitterId = found.splitterId
if (!data.splitterName) data.splitterName = found.splitterName
if (!data.splitterConfig) data.splitterConfig = found.splitterConfig
if (found.credential) {
data.credential = found.credential
}
let loader: IDocumentStoreLoader = {
...found,
loaderId: data.loaderId,
loaderName: data.loaderName,
loaderConfig: data.loaderConfig,
splitterId: data.splitterId,
splitterName: data.splitterName,
splitterConfig: data.splitterConfig,
totalChunks: 0,
totalChars: 0,
status: DocumentStoreStatus.SYNCING
}
if (data.credential) {
loader.credential = data.credential
}
existingLoaders[foundIndex] = loader
entity.loaders = JSON.stringify(existingLoaders)
} else {
let loader: IDocumentStoreLoader = {
id: newDocLoaderId,
loaderId: data.loaderId,
loaderName: data.loaderName,
loaderConfig: data.loaderConfig,
splitterId: data.splitterId,
splitterName: data.splitterName,
splitterConfig: data.splitterConfig,
totalChunks: 0,
totalChars: 0,
status: DocumentStoreStatus.SYNCING
}
if (data.credential) {
loader.credential = data.credential
}
existingLoaders.push(loader)
entity.loaders = JSON.stringify(existingLoaders)
}
await appServer.AppDataSource.getRepository(DocumentStore).save(entity)
const newLoaders = JSON.parse(entity.loaders)
const newLoader = newLoaders.find((ldr: IDocumentStoreLoader) => ldr.id === newDocLoaderId)
if (!newLoader) {
throw new Error(`Loader ${newDocLoaderId} not found`)
}
newLoader.source = addLoaderSource(newLoader, true)
return newLoader
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices.saveProcessingLoader - ${getErrorMessage(error)}`
)
}
}
const processLoader = async (data: IDocumentStoreLoaderForPreview, docLoaderId: string) => {
try {
const appServer = getRunningExpressApp()
const entity = await appServer.AppDataSource.getRepository(DocumentStore).findOneBy({
id: data.storeId
})
if (!entity) {
throw new InternalFlowiseError(
StatusCodes.NOT_FOUND,
`Error: documentStoreServices.processLoader - Document store ${data.storeId} not found`
)
}
// this method will run async, will have to be moved to a worker thread
await _saveChunksToStorage(data, entity, docLoaderId)
return getDocumentStoreFileChunks(data.storeId as string, docLoaderId)
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices.processLoader - ${getErrorMessage(error)}`
)
}
}
const _saveChunksToStorage = async (data: IDocumentStoreLoaderForPreview, entity: DocumentStore, newLoaderId: string) => {
const re = new RegExp('^data.*;base64', 'i')
try {
const appServer = getRunningExpressApp()
//step 1: restore the full paths, if any
await _normalizeFilePaths(data, entity)
//step 2: split the file into chunks
const response = await previewChunks(data)
//step 3: remove all files associated with the loader
const existingLoaders = JSON.parse(entity.loaders)
const loader = existingLoaders.find((ldr: IDocumentStoreLoader) => ldr.id === newLoaderId)
if (data.id) {
const index = existingLoaders.indexOf(loader)
if (index > -1) {
existingLoaders.splice(index, 1)
if (!data.rehydrated) {
if (loader.files) {
loader.files.map(async (file: IDocumentStoreLoaderFile) => {
try {
await removeSpecificFileFromStorage(DOCUMENT_STORE_BASE_FOLDER, entity.id, file.name)
} catch (error) {
console.error(error)
}
})
}
}
}
}
//step 4: save new file to storage
let filesWithMetadata = []
const keys = Object.getOwnPropertyNames(data.loaderConfig)
for (let i = 0; i < keys.length; i++) {
const input = data.loaderConfig[keys[i]]
if (!input) {
continue
}
if (typeof input !== 'string') {
continue
}
if (input.startsWith('[') && input.endsWith(']')) {
const files = JSON.parse(input)
const fileNames: string[] = []
for (let j = 0; j < files.length; j++) {
const file = files[j]
if (re.test(file)) {
const fileMetadata = await _saveFileToStorage(file, entity)
fileNames.push(fileMetadata.name)
filesWithMetadata.push(fileMetadata)
}
}
data.loaderConfig[keys[i]] = 'FILE-STORAGE::' + JSON.stringify(fileNames)
} else if (re.test(input)) {
const fileNames: string[] = []
const fileMetadata = await _saveFileToStorage(input, entity)
fileNames.push(fileMetadata.name)
filesWithMetadata.push(fileMetadata)
data.loaderConfig[keys[i]] = 'FILE-STORAGE::' + JSON.stringify(fileNames)
break
}
}
//step 5: update with the new files and loaderConfig
if (filesWithMetadata.length > 0) {
loader.loaderConfig = data.loaderConfig
loader.files = filesWithMetadata
}
//step 6: update the loaders with the new loaderConfig
if (data.id) {
existingLoaders.push(loader)
}
//step 7: remove all previous chunks
await appServer.AppDataSource.getRepository(DocumentStoreFileChunk).delete({ docId: newLoaderId })
if (response.chunks) {
//step 8: now save the new chunks
const totalChars = response.chunks.reduce((acc, chunk) => {
if (chunk.pageContent) {
return acc + chunk.pageContent.length
}
return acc
}, 0)
response.chunks.map(async (chunk: IDocument, index: number) => {
const docChunk: DocumentStoreFileChunk = {
docId: newLoaderId,
storeId: data.storeId || '',
id: uuidv4(),
chunkNo: index + 1,
pageContent: chunk.pageContent,
metadata: JSON.stringify(chunk.metadata)
}
const dChunk = appServer.AppDataSource.getRepository(DocumentStoreFileChunk).create(docChunk)
await appServer.AppDataSource.getRepository(DocumentStoreFileChunk).save(dChunk)
})
// update the loader with the new metrics
loader.totalChunks = response.totalChunks
loader.totalChars = totalChars
}
loader.status = 'SYNC'
// have a flag and iterate over the loaders and update the entity status to SYNC
const allSynced = existingLoaders.every((ldr: IDocumentStoreLoader) => ldr.status === 'SYNC')
entity.status = allSynced ? DocumentStoreStatus.SYNC : DocumentStoreStatus.STALE
entity.loaders = JSON.stringify(existingLoaders)
//step 9: update the entity in the database
await appServer.AppDataSource.getRepository(DocumentStore).save(entity)
return
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices._saveChunksToStorage - ${getErrorMessage(error)}`
)
}
}
// Get all component nodes
const getDocumentLoaders = async () => {
const removeDocumentLoadersWithName = ['documentStore', 'vectorStoreToDocument', 'unstructuredFolderLoader', 'folderFiles']
try {
const dbResponse = await nodesService.getAllNodesForCategory('Document Loaders')
return dbResponse.filter((node) => !removeDocumentLoadersWithName.includes(node.name))
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices.getDocumentLoaders - ${getErrorMessage(error)}`
)
}
}
const updateDocumentStoreUsage = async (chatId: string, storeId: string | undefined) => {
try {
// find the document store
const appServer = getRunningExpressApp()
// find all entities that have the chatId in their whereUsed
const entities = await appServer.AppDataSource.getRepository(DocumentStore).find()
entities.map(async (entity: DocumentStore) => {
const whereUsed = JSON.parse(entity.whereUsed)
const found = whereUsed.find((w: string) => w === chatId)
if (found) {
if (!storeId) {
// remove the chatId from the whereUsed, as the store is being deleted
const index = whereUsed.indexOf(chatId)
if (index > -1) {
whereUsed.splice(index, 1)
entity.whereUsed = JSON.stringify(whereUsed)
await appServer.AppDataSource.getRepository(DocumentStore).save(entity)
}
} else if (entity.id === storeId) {
// do nothing, already found and updated
} else if (entity.id !== storeId) {
// remove the chatId from the whereUsed, as a new store is being used
const index = whereUsed.indexOf(chatId)
if (index > -1) {
whereUsed.splice(index, 1)
entity.whereUsed = JSON.stringify(whereUsed)
await appServer.AppDataSource.getRepository(DocumentStore).save(entity)
}
}
} else {
if (entity.id === storeId) {
// add the chatId to the whereUsed
whereUsed.push(chatId)
entity.whereUsed = JSON.stringify(whereUsed)
await appServer.AppDataSource.getRepository(DocumentStore).save(entity)
}
}
})
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices.updateDocumentStoreUsage - ${getErrorMessage(error)}`
)
}
}
const updateVectorStoreConfigOnly = async (data: ICommonObject) => {
try {
const appServer = getRunningExpressApp()
const entity = await appServer.AppDataSource.getRepository(DocumentStore).findOneBy({
id: data.storeId
})
if (!entity) {
throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Document store ${data.storeId} not found`)
}
if (data.vectorStoreName) {
entity.vectorStoreConfig = JSON.stringify({
config: data.vectorStoreConfig,
name: data.vectorStoreName
})
const updatedEntity = await appServer.AppDataSource.getRepository(DocumentStore).save(entity)
return updatedEntity
}
return {}
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices.updateVectorStoreConfig - ${getErrorMessage(error)}`
)
}
}
const saveVectorStoreConfig = async (data: ICommonObject, isStrictSave = true) => {
try {
const appServer = getRunningExpressApp()
const entity = await appServer.AppDataSource.getRepository(DocumentStore).findOneBy({
id: data.storeId
})
if (!entity) {
throw new InternalFlowiseError(StatusCodes.NOT_FOUND, `Document store ${data.storeId} not found`)
}
if (data.embeddingName) {
entity.embeddingConfig = JSON.stringify({
config: data.embeddingConfig,
name: data.embeddingName
})
} else if (entity.embeddingConfig && !data.embeddingName && !data.embeddingConfig) {
data.embeddingConfig = JSON.parse(entity.embeddingConfig)?.config
data.embeddingName = JSON.parse(entity.embeddingConfig)?.name
if (isStrictSave) entity.embeddingConfig = null
} else if (!data.embeddingName && !data.embeddingConfig) {
entity.embeddingConfig = null
}
if (data.vectorStoreName) {
entity.vectorStoreConfig = JSON.stringify({
config: data.vectorStoreConfig,
name: data.vectorStoreName
})
} else if (entity.vectorStoreConfig && !data.vectorStoreName && !data.vectorStoreConfig) {
data.vectorStoreConfig = JSON.parse(entity.vectorStoreConfig)?.config
data.vectorStoreName = JSON.parse(entity.vectorStoreConfig)?.name
if (isStrictSave) entity.vectorStoreConfig = null
} else if (!data.vectorStoreName && !data.vectorStoreConfig) {
entity.vectorStoreConfig = null
}
if (data.recordManagerName) {
entity.recordManagerConfig = JSON.stringify({
config: data.recordManagerConfig,
name: data.recordManagerName
})
} else if (entity.recordManagerConfig && !data.recordManagerName && !data.recordManagerConfig) {
data.recordManagerConfig = JSON.parse(entity.recordManagerConfig)?.config
data.recordManagerName = JSON.parse(entity.recordManagerConfig)?.name
if (isStrictSave) entity.recordManagerConfig = null
} else if (!data.recordManagerName && !data.recordManagerConfig) {
entity.recordManagerConfig = null
}
if (entity.status !== DocumentStoreStatus.UPSERTED && (data.vectorStoreName || data.recordManagerName || data.embeddingName)) {
// if the store is not already in sync, mark it as sync
// this also means that the store is not yet sync'ed to vector store
entity.status = DocumentStoreStatus.SYNC
}
await appServer.AppDataSource.getRepository(DocumentStore).save(entity)
return entity
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices.saveVectorStoreConfig - ${getErrorMessage(error)}`
)
}
}
const insertIntoVectorStore = async (data: ICommonObject, isStrictSave = true) => {
try {
const appServer = getRunningExpressApp()
const entity = await saveVectorStoreConfig(data, isStrictSave)
entity.status = DocumentStoreStatus.UPSERTING
await appServer.AppDataSource.getRepository(DocumentStore).save(entity)
// TODO: to be moved into a worker thread...
const indexResult = await _insertIntoVectorStoreWorkerThread(data, isStrictSave)
return indexResult
} catch (error) {
throw new InternalFlowiseError(
StatusCodes.INTERNAL_SERVER_ERROR,
`Error: documentStoreServices.insertIntoVectorStore - ${getErrorMessage(error)}`
)
}
}