-
-
Notifications
You must be signed in to change notification settings - Fork 24.2k
Expand file tree
/
Copy pathutils.ts
More file actions
2342 lines (2116 loc) · 85.4 KB
/
utils.ts
File metadata and controls
2342 lines (2116 loc) · 85.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import axios from 'axios'
import { load } from 'cheerio'
import * as fs from 'fs'
import * as path from 'path'
import { JSDOM } from 'jsdom'
import { z } from 'zod/v3'
import { cloneDeep, omit, get } from 'lodash'
import TurndownService from 'turndown'
import { DataSource, Equal } from 'typeorm'
import { ICommonObject, IDatabaseEntity, IFileUpload, IMessage, INodeData, IVariable, MessageContentImageUrl } from './Interface'
import { BaseChatModel } from '@langchain/core/language_models/chat_models'
import { AES, enc } from 'crypto-js'
import { AIMessage, AIMessageChunk, HumanMessage, BaseMessage } from '@langchain/core/messages'
import { Runnable, type RunnableConfig } from '@langchain/core/runnables'
import { Document } from '@langchain/core/documents'
import { getFileFromStorage } from './storageUtils'
import { GetSecretValueCommand, SecretsManagerClient, SecretsManagerClientConfig } from '@aws-sdk/client-secrets-manager'
import { customGet } from '../nodes/sequentialagents/commonUtils'
import { TextSplitter } from '@langchain/textsplitters'
import { DocumentLoader } from '@langchain/classic/document_loaders/base'
import { NodeVM } from 'vm2'
import { Sandbox } from '@e2b/code-interpreter'
import { secureFetch, checkDenyList, secureAxiosRequest } from './httpSecurity'
import JSON5 from 'json5'
import zodToJsonSchema, { type JsonSchema7Type } from 'zod-to-json-schema'
export const numberOrExpressionRegex = '^(\\d+\\.?\\d*|{{.*}})$' //return true if string consists only numbers OR expression {{}}
export const notEmptyRegex = '(.|\\s)*\\S(.|\\s)*' //return true if string is not empty or blank
export const FLOWISE_CHATID = 'flowise_chatId'
let secretsManagerClient: SecretsManagerClient | null = null
const USE_AWS_SECRETS_MANAGER = process.env.SECRETKEY_STORAGE_TYPE === 'aws'
if (USE_AWS_SECRETS_MANAGER) {
const region = process.env.SECRETKEY_AWS_REGION || 'us-east-1' // Default region if not provided
const accessKeyId = process.env.SECRETKEY_AWS_ACCESS_KEY
const secretAccessKey = process.env.SECRETKEY_AWS_SECRET_KEY
const secretManagerConfig: SecretsManagerClientConfig = {
region: region
}
if (accessKeyId && secretAccessKey) {
secretManagerConfig.credentials = {
accessKeyId,
secretAccessKey
}
}
secretsManagerClient = new SecretsManagerClient(secretManagerConfig)
}
/*
* List of dependencies allowed to be import in @flowiseai/nodevm
*/
export const availableDependencies = [
'@aws-sdk/client-bedrock-runtime',
'@aws-sdk/client-dynamodb',
'@aws-sdk/client-s3',
'@elastic/elasticsearch',
'@dqbd/tiktoken',
'@getzep/zep-js',
'@gomomento/sdk',
'@gomomento/sdk-core',
'@google-ai/generativelanguage',
'@google/generative-ai',
'@huggingface/inference',
'@langchain/anthropic',
'@langchain/aws',
'@langchain/cohere',
'@langchain/community',
'@langchain/core',
'@langchain/google-genai',
'@langchain/google-vertexai',
'@langchain/groq',
'@langchain/langgraph',
'@langchain/mistralai',
'@langchain/mongodb',
'@langchain/ollama',
'@langchain/openai',
'@langchain/pinecone',
'@langchain/qdrant',
'@langchain/weaviate',
'@notionhq/client',
'@opensearch-project/opensearch',
'@pinecone-database/pinecone',
'@qdrant/js-client-rest',
'@supabase/supabase-js',
'@upstash/redis',
'@zilliz/milvus2-sdk-node',
'apify-client',
'cheerio',
'chromadb',
'cohere-ai',
'd3-dsv',
'faiss-node',
'form-data',
'google-auth-library',
'graphql',
'html-to-text',
'ioredis',
'langchain',
'langfuse',
'langsmith',
'langwatch',
'linkifyjs',
'lunary',
'mammoth',
'mongodb',
'mysql2',
'node-html-markdown',
'notion-to-md',
'openai',
'pdf-parse',
'pdfjs-dist',
'pg',
'playwright',
'puppeteer',
'redis',
'replicate',
'srt-parser-2',
'typeorm',
'weaviate-client'
]
const defaultAllowExternalDependencies = ['axios', 'moment', 'node-fetch']
export const defaultAllowBuiltInDep = ['assert', 'buffer', 'crypto', 'events', 'path', 'querystring', 'timers', 'url', 'zlib']
/**
* Get base classes of components
*
* @export
* @param {any} targetClass
* @returns {string[]}
*/
export const getBaseClasses = (targetClass: any) => {
const baseClasses: string[] = []
const skipClassNames = ['BaseLangChain', 'Serializable']
if (targetClass instanceof Function) {
let baseClass = targetClass
while (baseClass) {
const newBaseClass = Object.getPrototypeOf(baseClass)
if (newBaseClass && newBaseClass !== Object && newBaseClass.name) {
baseClass = newBaseClass
if (!skipClassNames.includes(baseClass.name)) baseClasses.push(baseClass.name)
} else {
break
}
}
}
return baseClasses
}
/**
* Serialize axios query params
*
* @export
* @param {any} params
* @param {boolean} skipIndex // Set to true if you want same params to be: param=1¶m=2 instead of: param[0]=1¶m[1]=2
* @returns {string}
*/
export function serializeQueryParams(params: any, skipIndex?: boolean): string {
const parts: any[] = []
const encode = (val: string) => {
return encodeURIComponent(val)
.replace(/%3A/gi, ':')
.replace(/%24/g, '$')
.replace(/%2C/gi, ',')
.replace(/%20/g, '+')
.replace(/%5B/gi, '[')
.replace(/%5D/gi, ']')
}
const convertPart = (key: string, val: any) => {
if (val instanceof Date) val = val.toISOString()
else if (val instanceof Object) val = JSON.stringify(val)
parts.push(encode(key) + '=' + encode(val))
}
Object.entries(params).forEach(([key, val]) => {
if (val === null || typeof val === 'undefined') return
if (Array.isArray(val)) val.forEach((v, i) => convertPart(`${key}${skipIndex ? '' : `[${i}]`}`, v))
else convertPart(key, val)
})
return parts.join('&')
}
/**
* Handle error from try catch
*
* @export
* @param {any} error
* @returns {string}
*/
export function handleErrorMessage(error: any): string {
let errorMessage = ''
if (error.message) {
errorMessage += error.message + '. '
}
if (error.response && error.response.data) {
if (error.response.data.error) {
if (typeof error.response.data.error === 'object') errorMessage += JSON.stringify(error.response.data.error) + '. '
else if (typeof error.response.data.error === 'string') errorMessage += error.response.data.error + '. '
} else if (error.response.data.msg) errorMessage += error.response.data.msg + '. '
else if (error.response.data.Message) errorMessage += error.response.data.Message + '. '
else if (typeof error.response.data === 'string') errorMessage += error.response.data + '. '
}
if (!errorMessage) errorMessage = 'Unexpected Error.'
return errorMessage
}
/**
* Returns the path of node modules package
* @param {string} packageName
* @returns {string}
*/
export const getNodeModulesPackagePath = (packageName: string): string => {
const checkPaths = [
path.join(__dirname, '..', 'node_modules', packageName),
path.join(__dirname, '..', '..', 'node_modules', packageName),
path.join(__dirname, '..', '..', '..', 'node_modules', packageName),
path.join(__dirname, '..', '..', '..', '..', 'node_modules', packageName),
path.join(__dirname, '..', '..', '..', '..', '..', 'node_modules', packageName)
]
for (const checkPath of checkPaths) {
if (fs.existsSync(checkPath)) {
return checkPath
}
}
return ''
}
/**
* Get input variables
* @param {string} paramValue
* @returns {boolean}
*/
export const getInputVariables = (paramValue: string): string[] => {
if (typeof paramValue !== 'string') return []
const returnVal = paramValue
const variableStack = []
const inputVariables = []
let startIdx = 0
const endIdx = returnVal.length
while (startIdx < endIdx) {
const substr = returnVal.substring(startIdx, startIdx + 1)
// Check for escaped curly brackets
if (substr === '\\' && (returnVal[startIdx + 1] === '{' || returnVal[startIdx + 1] === '}')) {
startIdx += 2 // Skip the escaped bracket
continue
}
// Store the opening double curly bracket
if (substr === '{') {
variableStack.push({ substr, startIdx: startIdx + 1 })
}
// Found the complete variable
if (substr === '}' && variableStack.length > 0 && variableStack[variableStack.length - 1].substr === '{') {
const variableStartIdx = variableStack[variableStack.length - 1].startIdx
const variableEndIdx = startIdx
const variableFullPath = returnVal.substring(variableStartIdx, variableEndIdx)
if (!variableFullPath.includes(':')) inputVariables.push(variableFullPath)
variableStack.pop()
}
startIdx += 1
}
return inputVariables
}
/**
* Transform single curly braces into double curly braces if the content includes a colon.
* @param input - The original string that may contain { ... } segments.
* @returns The transformed string, where { ... } containing a colon has been replaced with {{ ... }}.
*/
export const transformBracesWithColon = (input: string): string => {
// This regex uses negative lookbehind (?<!{) and negative lookahead (?!})
// to ensure we only match single curly braces, not double ones.
// It will match a single { that's not preceded by another {,
// followed by any content without braces, then a single } that's not followed by another }.
const regex = /(?<!\{)\{([^{}]*?)\}(?!\})/g
return input.replace(regex, (match, groupContent) => {
// groupContent is the text inside the braces `{ ... }`.
if (groupContent.includes(':')) {
// If there's a colon in the content, we turn { ... } into {{ ... }}
// The match is the full string like: "{ answer: hello }"
// groupContent is the inner part like: " answer: hello "
return `{{${groupContent}}}`
} else {
// Otherwise, leave it as is
return match
}
})
}
/**
* Extracts text content from an AIMessageChunk, filtering out reasoning/thinking
* content blocks that reasoning models may return.
*/
const extractTextFromChunk = (response: AIMessageChunk): string => {
if (typeof response.content === 'string') {
return response.content
}
if (Array.isArray(response.content)) {
return response.content
.filter((block: any) => block.type === 'text' || block.type === 'text_delta')
.map((block: any) => block.text ?? '')
.join('')
}
return ''
}
/**
* Creates a streaming-compatible output parser that extracts text content from
* chat model responses, filtering out reasoning/thinking content blocks.
* https://github.com/FlowiseAI/Flowise/pull/5893#issuecomment-4045466531
*/
export const createTextOnlyOutputParser = () => {
return new TextOnlyOutputParser()
}
class TextOnlyOutputParser extends Runnable<AIMessageChunk, string> {
static lc_name() {
return 'TextOnlyOutputParser'
}
lc_namespace = ['flowise', 'output_parsers']
async invoke(input: AIMessageChunk, _options?: Partial<RunnableConfig>): Promise<string> {
return extractTextFromChunk(input)
}
async *_transform(generator: AsyncGenerator<AIMessageChunk>): AsyncGenerator<string> {
for await (const chunk of generator) {
const text = extractTextFromChunk(chunk)
if (text) {
yield text
}
}
}
async *transform(generator: AsyncGenerator<AIMessageChunk>, options?: Partial<RunnableConfig>): AsyncGenerator<string> {
yield* this._transformStreamWithConfig(generator, this._transform.bind(this), options)
}
}
/**
* Crawl all available urls given a domain url and limit
* @param {string} url
* @param {number} limit
* @returns {string[]}
*/
export const getAvailableURLs = async (url: string, limit: number) => {
try {
const availableUrls: string[] = []
console.info(`Crawling: ${url}`)
availableUrls.push(url)
const response = await axios.get(url)
const $ = load(response.data)
const relativeLinks = $("a[href^='/']")
console.info(`Available Relative Links: ${relativeLinks.length}`)
if (relativeLinks.length === 0) return availableUrls
limit = Math.min(limit + 1, relativeLinks.length) // limit + 1 is because index start from 0 and index 0 is occupy by url
console.info(`True Limit: ${limit}`)
// availableUrls.length cannot exceed limit
for (let i = 0; availableUrls.length < limit; i++) {
if (i === limit) break // some links are repetitive so it won't added into the array which cause the length to be lesser
console.info(`index: ${i}`)
const element = relativeLinks[i]
const relativeUrl = $(element).attr('href')
if (!relativeUrl) continue
const absoluteUrl = new URL(relativeUrl, url).toString()
if (!availableUrls.includes(absoluteUrl)) {
availableUrls.push(absoluteUrl)
console.info(`Found unique relative link: ${absoluteUrl}`)
}
}
return availableUrls
} catch (err) {
throw new Error(`getAvailableURLs: ${err?.message}`)
}
}
/**
* Search for href through htmlBody string
* @param {string} htmlBody
* @param {string} baseURL
* @returns {string[]}
*/
function getURLsFromHTML(htmlBody: string, baseURL: string): string[] {
const dom = new JSDOM(htmlBody)
const linkElements = dom.window.document.querySelectorAll('a')
const urls: string[] = []
for (const linkElement of linkElements) {
try {
const urlObj = new URL(linkElement.href, baseURL)
urls.push(urlObj.href)
} catch (err) {
if (process.env.DEBUG === 'true') console.error(`error with scraped URL: ${err.message}`)
continue
}
}
return urls
}
/**
* Normalize URL to prevent crawling the same page
* @param {string} urlString
* @returns {string}
*/
function normalizeURL(urlString: string): string {
const urlObj = new URL(urlString)
const port = urlObj.port ? `:${urlObj.port}` : ''
const hostPath = urlObj.hostname + port + urlObj.pathname + urlObj.search
if (hostPath.length > 0 && hostPath.slice(-1) == '/') {
// handling trailing slash
return hostPath.slice(0, -1)
}
return hostPath
}
/**
* Recursive crawl using normalizeURL and getURLsFromHTML
* @param {string} baseURL
* @param {string} currentURL
* @param {string[]} pages
* @param {number} limit
* @returns {Promise<string[]>}
*/
async function crawl(baseURL: string, currentURL: string, pages: string[], limit: number): Promise<string[]> {
const baseURLObj = new URL(baseURL)
const currentURLObj = new URL(currentURL)
if (limit !== 0 && pages.length === limit) return pages
if (baseURLObj.hostname !== currentURLObj.hostname) return pages
const normalizeCurrentURL = baseURLObj.protocol + '//' + normalizeURL(currentURL)
if (pages.includes(normalizeCurrentURL)) {
return pages
}
pages.push(normalizeCurrentURL)
if (process.env.DEBUG === 'true') console.info(`actively crawling ${currentURL}`)
try {
const resp = await secureFetch(currentURL)
if (resp.status > 399) {
if (process.env.DEBUG === 'true') console.error(`error in fetch with status code: ${resp.status}, on page: ${currentURL}`)
return pages
}
const contentType: string | null = resp.headers.get('content-type')
if ((contentType && !contentType.includes('text/html')) || !contentType) {
if (process.env.DEBUG === 'true') console.error(`non html response, content type: ${contentType}, on page: ${currentURL}`)
return pages
}
const htmlBody = await resp.text()
const nextURLs = getURLsFromHTML(htmlBody, currentURL)
for (const nextURL of nextURLs) {
pages = await crawl(baseURL, nextURL, pages, limit)
}
} catch (err) {
if (process.env.DEBUG === 'true') console.error(`error in fetch url: ${err.message}, on page: ${currentURL}`)
}
return pages
}
/**
* Prep URL before passing into recursive crawl function
* @param {string} stringURL
* @param {number} limit
* @returns {Promise<string[]>}
*/
export async function webCrawl(stringURL: string, limit: number): Promise<string[]> {
await checkDenyList(stringURL)
const URLObj = new URL(stringURL)
const modifyURL = stringURL.slice(-1) === '/' ? stringURL.slice(0, -1) : stringURL
return await crawl(URLObj.protocol + '//' + URLObj.hostname, modifyURL, [], limit)
}
export function getURLsFromXML(xmlBody: string, limit: number): string[] {
const dom = new JSDOM(xmlBody, { contentType: 'text/xml' })
const linkElements = dom.window.document.querySelectorAll('url')
const urls: string[] = []
for (const linkElement of linkElements) {
const locElement = linkElement.querySelector('loc')
if (limit !== 0 && urls.length === limit) break
if (locElement?.textContent) {
urls.push(locElement.textContent)
}
}
return urls
}
export async function xmlScrape(currentURL: string, limit: number): Promise<string[]> {
let urls: string[] = []
if (process.env.DEBUG === 'true') console.info(`actively scarping ${currentURL}`)
try {
const resp = await secureFetch(currentURL)
if (resp.status > 399) {
if (process.env.DEBUG === 'true') console.error(`error in fetch with status code: ${resp.status}, on page: ${currentURL}`)
return urls
}
const contentType: string | null = resp.headers.get('content-type')
if ((contentType && !contentType.includes('application/xml') && !contentType.includes('text/xml')) || !contentType) {
if (process.env.DEBUG === 'true') console.error(`non xml response, content type: ${contentType}, on page: ${currentURL}`)
return urls
}
const xmlBody = await resp.text()
urls = getURLsFromXML(xmlBody, limit)
} catch (err) {
if (process.env.DEBUG === 'true') console.error(`error in fetch url: ${err.message}, on page: ${currentURL}`)
}
return urls
}
/**
* Get env variables
* @param {string} name
* @returns {string | undefined}
*/
export const getEnvironmentVariable = (name: string): string | undefined => {
try {
return typeof process !== 'undefined' ? process.env?.[name] : undefined
} catch (e) {
return undefined
}
}
/**
* Returns the path of encryption key
* @returns {string}
*/
const getEncryptionKeyFilePath = (): string => {
const checkPaths = [
path.join(__dirname, '..', '..', 'encryption.key'),
path.join(__dirname, '..', '..', 'server', 'encryption.key'),
path.join(__dirname, '..', '..', '..', 'encryption.key'),
path.join(__dirname, '..', '..', '..', 'server', 'encryption.key'),
path.join(__dirname, '..', '..', '..', '..', 'encryption.key'),
path.join(__dirname, '..', '..', '..', '..', 'server', 'encryption.key'),
path.join(__dirname, '..', '..', '..', '..', '..', 'encryption.key'),
path.join(__dirname, '..', '..', '..', '..', '..', 'server', 'encryption.key'),
path.join(getUserHome(), '.flowise', 'encryption.key')
]
for (const checkPath of checkPaths) {
if (fs.existsSync(checkPath)) {
return checkPath
}
}
return ''
}
export const getEncryptionKeyPath = (): string => {
return process.env.SECRETKEY_PATH ? path.join(process.env.SECRETKEY_PATH, 'encryption.key') : getEncryptionKeyFilePath()
}
/**
* Returns the encryption key
* @returns {Promise<string>}
*/
const getEncryptionKey = async (): Promise<string> => {
if (process.env.FLOWISE_SECRETKEY_OVERWRITE !== undefined && process.env.FLOWISE_SECRETKEY_OVERWRITE !== '') {
return process.env.FLOWISE_SECRETKEY_OVERWRITE
}
try {
if (USE_AWS_SECRETS_MANAGER && secretsManagerClient) {
const secretId = process.env.SECRETKEY_AWS_NAME || 'FlowiseEncryptionKey'
const command = new GetSecretValueCommand({ SecretId: secretId })
const response = await secretsManagerClient.send(command)
if (response.SecretString) {
return response.SecretString
}
}
return await fs.promises.readFile(getEncryptionKeyPath(), 'utf8')
} catch (error) {
throw new Error(error)
}
}
/**
* Decrypt credential data
* @param {string} encryptedData
* @param {string} componentCredentialName
* @param {IComponentCredentials} componentCredentials
* @returns {Promise<ICommonObject>}
*/
const decryptCredentialData = async (encryptedData: string): Promise<ICommonObject> => {
let decryptedDataStr: string
if (USE_AWS_SECRETS_MANAGER && secretsManagerClient) {
try {
if (encryptedData.startsWith('FlowiseCredential_')) {
const command = new GetSecretValueCommand({ SecretId: encryptedData })
const response = await secretsManagerClient.send(command)
if (response.SecretString) {
const secretObj = JSON.parse(response.SecretString)
decryptedDataStr = JSON.stringify(secretObj)
} else {
throw new Error('Failed to retrieve secret value.')
}
} else {
const encryptKey = await getEncryptionKey()
const decryptedData = AES.decrypt(encryptedData, encryptKey)
decryptedDataStr = decryptedData.toString(enc.Utf8)
}
} catch (error) {
console.error(error)
throw new Error('Failed to decrypt credential data.')
}
} else {
// Fallback to existing code
const encryptKey = await getEncryptionKey()
const decryptedData = AES.decrypt(encryptedData, encryptKey)
decryptedDataStr = decryptedData.toString(enc.Utf8)
}
if (!decryptedDataStr) return {}
try {
return JSON.parse(decryptedDataStr)
} catch (e) {
console.error(e)
throw new Error('Credentials could not be decrypted.')
}
}
/**
* Get credential data
* @param {string} selectedCredentialId
* @param {ICommonObject} options
* @returns {Promise<ICommonObject>}
*/
export const getCredentialData = async (selectedCredentialId: string, options: ICommonObject): Promise<ICommonObject> => {
const appDataSource = options.appDataSource as DataSource
const databaseEntities = options.databaseEntities as IDatabaseEntity
try {
if (!selectedCredentialId) {
return {}
}
const credential = await appDataSource.getRepository(databaseEntities['Credential']).findOneBy({
id: selectedCredentialId
})
if (!credential) return {}
// Decrypt credentialData
const decryptedCredentialData = await decryptCredentialData(credential.encryptedData)
return decryptedCredentialData
} catch (e) {
throw new Error(e)
}
}
/**
* Get first non falsy value
*
* @param {...any} values
*
* @returns {any|undefined}
*/
export const defaultChain = (...values: any[]): any | undefined => {
return values.filter(Boolean)[0]
}
export const getCredentialParam = (paramName: string, credentialData: ICommonObject, nodeData: INodeData, defaultValue?: any): any => {
return (nodeData.inputs as ICommonObject)[paramName] ?? credentialData[paramName] ?? defaultValue ?? undefined
}
// reference https://www.freeformatter.com/json-escape.html
const jsonEscapeCharacters = [
{ escape: '"', value: 'FLOWISE_DOUBLE_QUOTE' },
{ escape: '\n', value: 'FLOWISE_NEWLINE' },
{ escape: '\b', value: 'FLOWISE_BACKSPACE' },
{ escape: '\f', value: 'FLOWISE_FORM_FEED' },
{ escape: '\r', value: 'FLOWISE_CARRIAGE_RETURN' },
{ escape: '\t', value: 'FLOWISE_TAB' },
{ escape: '\\', value: 'FLOWISE_BACKSLASH' }
]
function handleEscapesJSONParse(input: string, reverse: Boolean): string {
for (const element of jsonEscapeCharacters) {
input = reverse ? input.replaceAll(element.value, element.escape) : input.replaceAll(element.escape, element.value)
}
return input
}
function iterateEscapesJSONParse(input: any, reverse: Boolean): any {
for (const element in input) {
const type = typeof input[element]
if (type === 'string') input[element] = handleEscapesJSONParse(input[element], reverse)
else if (type === 'object') input[element] = iterateEscapesJSONParse(input[element], reverse)
}
return input
}
export function handleEscapeCharacters(input: any, reverse: Boolean): any {
const type = typeof input
if (type === 'string') return handleEscapesJSONParse(input, reverse)
else if (type === 'object') return iterateEscapesJSONParse(input, reverse)
return input
}
/**
* Get user home dir
* @returns {string}
*/
export const getUserHome = (): string => {
let variableName = 'HOME'
if (process.platform === 'win32') {
variableName = 'USERPROFILE'
}
if (process.env[variableName] === undefined) {
// If for some reason the variable does not exist, fall back to current folder
return process.cwd()
}
return process.env[variableName] as string
}
/**
* Map ChatMessage to BaseMessage
* @param {IChatMessage[]} chatmessages
* @returns {BaseMessage[]}
*/
export const mapChatMessageToBaseMessage = async (chatmessages: any[] = [], orgId: string): Promise<BaseMessage[]> => {
const chatHistory = []
for (const message of chatmessages) {
if (message.role === 'apiMessage' || message.type === 'apiMessage') {
chatHistory.push(new AIMessage(message.content || ''))
} else if (message.role === 'userMessage' || message.type === 'userMessage') {
// check for image/files uploads
if (message.fileUploads) {
// example: [{"type":"stored-file","name":"0_DiXc4ZklSTo3M8J4.jpg","mime":"image/jpeg"}]
try {
let messageWithFileUploads = ''
const uploads: IFileUpload[] = JSON.parse(message.fileUploads)
const imageContents: MessageContentImageUrl[] = []
for (const upload of uploads) {
if (upload.type === 'stored-file' && upload.mime.startsWith('image/')) {
const fileData = await getFileFromStorage(upload.name, orgId, message.chatflowid, message.chatId)
// as the image is stored in the server, read the file and convert it to base64
const bf = 'data:' + upload.mime + ';base64,' + fileData.toString('base64')
imageContents.push({
type: 'image_url',
image_url: {
url: bf
}
})
} else if (upload.type === 'url' && upload.mime.startsWith('image') && upload.data) {
imageContents.push({
type: 'image_url',
image_url: {
url: upload.data
}
})
} else if (upload.type === 'stored-file:full') {
const fileLoaderNodeModule = await import('../nodes/documentloaders/File/File')
// @ts-ignore
const fileLoaderNodeInstance = new fileLoaderNodeModule.nodeClass()
const options = {
retrieveAttachmentChatId: true,
chatflowid: message.chatflowid,
chatId: message.chatId,
orgId
}
let fileInputFieldFromMimeType = 'txtFile'
fileInputFieldFromMimeType = mapMimeTypeToInputField(upload.mime)
const nodeData = {
inputs: {
[fileInputFieldFromMimeType]: `FILE-STORAGE::${JSON.stringify([upload.name])}`
}
}
const documents: string = await fileLoaderNodeInstance.init(nodeData, '', options)
messageWithFileUploads += `<doc name='${upload.name}'>${handleEscapeCharacters(documents, true)}</doc>\n\n`
}
}
const messageContent = messageWithFileUploads ? `${messageWithFileUploads}\n\n${message.content}` : message.content
chatHistory.push(
new HumanMessage({
content: [
{
type: 'text',
text: messageContent
},
...imageContents
]
})
)
} catch (e) {
// failed to parse fileUploads, continue with text only
chatHistory.push(new HumanMessage(message.content || ''))
}
} else {
chatHistory.push(new HumanMessage(message.content || ''))
}
}
}
return chatHistory
}
/**
* Convert incoming chat history to string
* @param {IMessage[]} chatHistory
* @returns {string}
*/
export const convertChatHistoryToText = (chatHistory: IMessage[] | { content: string; role: string }[] = []): string => {
return chatHistory
.map((chatMessage) => {
if (!chatMessage) return ''
const messageContent = 'message' in chatMessage ? chatMessage.message : chatMessage.content
if (!messageContent || messageContent.trim() === '') return ''
const messageType = 'type' in chatMessage ? chatMessage.type : chatMessage.role
if (messageType === 'apiMessage' || messageType === 'assistant') {
return `Assistant: ${messageContent}`
} else if (messageType === 'userMessage' || messageType === 'user') {
return `Human: ${messageContent}`
} else {
return `${messageContent}`
}
})
.filter((message) => message !== '') // Remove empty messages
.join('\n')
}
/**
* Serialize array chat history to string
* @param {string | Array<string>} chatHistory
* @returns {string}
*/
export const serializeChatHistory = (chatHistory: string | Array<string>) => {
if (Array.isArray(chatHistory)) {
return chatHistory.join('\n')
}
return chatHistory
}
/**
* Convert schema to zod schema
* @param {string | object} schema
* @returns {ICommonObject}
*/
export const convertSchemaToZod = (schema: string | object): ICommonObject => {
try {
const parsedSchema = typeof schema === 'string' ? JSON.parse(schema) : schema
const zodObj: ICommonObject = {}
for (const sch of parsedSchema) {
if (sch.type === 'string') {
if (sch.required) {
zodObj[sch.property] = z.string({ required_error: `${sch.property} required` }).describe(sch.description)
} else {
zodObj[sch.property] = z.string().describe(sch.description).optional()
}
} else if (sch.type === 'number') {
if (sch.required) {
zodObj[sch.property] = z.number({ required_error: `${sch.property} required` }).describe(sch.description)
} else {
zodObj[sch.property] = z.number().describe(sch.description).optional()
}
} else if (sch.type === 'boolean') {
if (sch.required) {
zodObj[sch.property] = z.boolean({ required_error: `${sch.property} required` }).describe(sch.description)
} else {
zodObj[sch.property] = z.boolean().describe(sch.description).optional()
}
} else if (sch.type === 'date') {
if (sch.required) {
zodObj[sch.property] = z.date({ required_error: `${sch.property} required` }).describe(sch.description)
} else {
zodObj[sch.property] = z.date().describe(sch.description).optional()
}
}
}
return zodObj
} catch (e) {
throw new Error(e)
}
}
/**
* Flatten nested object
* @param {ICommonObject} obj
* @param {string} parentKey
* @returns {ICommonObject}
*/
export const flattenObject = (obj: ICommonObject, parentKey?: string) => {
let result: any = {}
if (!obj) return result
Object.keys(obj).forEach((key) => {
const value = obj[key]
const _key = parentKey ? parentKey + '.' + key : key
if (typeof value === 'object') {
result = { ...result, ...flattenObject(value, _key) }
} else {
result[_key] = value
}
})
return result
}
/**
* Convert BaseMessage to IMessage
* @param {BaseMessage[]} messages
* @returns {IMessage[]}
*/
export const convertBaseMessagetoIMessage = (messages: BaseMessage[]): IMessage[] => {
const formatmessages: IMessage[] = []
for (const m of messages) {
if (m._getType() === 'human') {
formatmessages.push({
message: m.content as string,
type: 'userMessage'
})
} else if (m._getType() === 'ai') {
formatmessages.push({
message: m.content as string,
type: 'apiMessage'
})
} else if (m._getType() === 'system') {
formatmessages.push({
message: m.content as string,
type: 'apiMessage'
})
}
}
return formatmessages
}
/**
* Convert MultiOptions String to String Array
* @param {string} inputString
* @returns {string[]}
*/
export const convertMultiOptionsToStringArray = (inputString: string): string[] => {
let ArrayString: string[] = []
try {
ArrayString = JSON.parse(inputString)
} catch (e) {
ArrayString = []
}
return ArrayString
}
/**
* Get variables
* @param {DataSource} appDataSource
* @param {IDatabaseEntity} databaseEntities
* @param {INodeData} nodeData
*/
export const getVars = async (
appDataSource: DataSource,
databaseEntities: IDatabaseEntity,
nodeData: INodeData,
options: ICommonObject
) => {
if (!options.workspaceId) {
return []
}
const variables =
((await appDataSource
.getRepository(databaseEntities['Variable'])
.findBy({ workspaceId: Equal(options.workspaceId) })) as IVariable[]) ?? []
// override variables defined in overrideConfig
// nodeData.inputs.vars is an Object, check each property and override the variable