1
1
import { getBaseClasses , getCredentialData , getCredentialParam , ICommonObject , INode , INodeData , INodeParams } from '../../../src'
2
2
import { RedisCache as LangchainRedisCache } from 'langchain/cache/ioredis'
3
- import { Redis } from 'ioredis'
3
+ import { Redis , RedisOptions } from 'ioredis'
4
+ import { isEqual } from 'lodash'
4
5
import { Generation , ChatGeneration , StoredGeneration , mapStoredMessageToChatMessage } from 'langchain/schema'
5
6
import hash from 'object-hash'
6
7
8
+ let redisClientSingleton : Redis
9
+ let redisClientOption : RedisOptions
10
+ let redisClientUrl : string
11
+
12
+ const getRedisClientbyOption = ( option : RedisOptions ) => {
13
+ if ( ! redisClientSingleton ) {
14
+ // if client doesn't exists
15
+ redisClientSingleton = new Redis ( option )
16
+ redisClientOption = option
17
+ return redisClientSingleton
18
+ } else if ( redisClientSingleton && ! isEqual ( option , redisClientOption ) ) {
19
+ // if client exists but option changed
20
+ redisClientSingleton . quit ( )
21
+ redisClientSingleton = new Redis ( option )
22
+ redisClientOption = option
23
+ return redisClientSingleton
24
+ }
25
+ return redisClientSingleton
26
+ }
27
+
28
+ const getRedisClientbyUrl = ( url : string ) => {
29
+ if ( ! redisClientSingleton ) {
30
+ // if client doesn't exists
31
+ redisClientSingleton = new Redis ( url )
32
+ redisClientUrl = url
33
+ return redisClientSingleton
34
+ } else if ( redisClientSingleton && url !== redisClientUrl ) {
35
+ // if client exists but option changed
36
+ redisClientSingleton . quit ( )
37
+ redisClientSingleton = new Redis ( url )
38
+ redisClientUrl = url
39
+ return redisClientSingleton
40
+ }
41
+ return redisClientSingleton
42
+ }
43
+
7
44
class RedisCache implements INode {
8
45
label : string
9
46
name : string
@@ -60,15 +97,15 @@ class RedisCache implements INode {
60
97
61
98
const tlsOptions = sslEnabled === true ? { tls : { rejectUnauthorized : false } } : { }
62
99
63
- client = new Redis ( {
100
+ client = getRedisClientbyOption ( {
64
101
port : portStr ? parseInt ( portStr ) : 6379 ,
65
102
host,
66
103
username,
67
104
password,
68
105
...tlsOptions
69
106
} )
70
107
} else {
71
- client = new Redis ( redisUrl )
108
+ client = getRedisClientbyUrl ( redisUrl )
72
109
}
73
110
74
111
const redisClient = new LangchainRedisCache ( client )
@@ -94,7 +131,7 @@ class RedisCache implements INode {
94
131
for ( let i = 0 ; i < value . length ; i += 1 ) {
95
132
const key = getCacheKey ( prompt , llmKey , String ( i ) )
96
133
if ( ttl ) {
97
- await client . set ( key , JSON . stringify ( serializeGeneration ( value [ i ] ) ) , 'EX ' , parseInt ( ttl , 10 ) )
134
+ await client . set ( key , JSON . stringify ( serializeGeneration ( value [ i ] ) ) , 'PX ' , parseInt ( ttl , 10 ) )
98
135
} else {
99
136
await client . set ( key , JSON . stringify ( serializeGeneration ( value [ i ] ) ) )
100
137
}
0 commit comments