[docs]classTokenEscaper:""" Escape punctuation within an input string. """# Characters that RediSearch requires us to escape during queries.# Source: https://redis.io/docs/stack/search/reference/escaping/#the-rules-of-text-field-tokenizationDEFAULT_ESCAPED_CHARS:str=r"[,.<>{}\[\]\\\"\':;!@#$%^&*()\-+=~\/ ]"
[docs]defescape(self,value:str)->str:ifnotisinstance(value,str):raiseTypeError("Value must be a string object for token escaping."f"Got type {type(value)}")defescape_symbol(match:re.Match)->str:value=match.group(0)returnf"\\{value}"returnself.escaped_chars_re.sub(escape_symbol,value)
[docs]defcheck_redis_module_exist(client:RedisType,required_modules:List[dict])->None:"""Check if the correct Redis modules are installed."""installed_modules=client.module_list()installed_modules={module[b"name"].decode("utf-8"):moduleformoduleininstalled_modules}formoduleinrequired_modules:ifmodule["name"]ininstalled_modulesandint(installed_modules[module["name"]][b"ver"])>=int(module["ver"]):return# otherwise raise errorerror_message=("Redis cannot be used as a vector database without RediSearch >=2.4""Please head to https://redis.io/docs/stack/search/quick_start/""to know more about installing the RediSearch module within Redis Stack.")logger.error(error_message)raiseValueError(error_message)
[docs]defget_client(redis_url:str,**kwargs:Any)->RedisType:"""Get a redis client from the connection url given. This helper accepts urls for Redis server (TCP with/without TLS or UnixSocket) as well as Redis Sentinel connections. Redis Cluster is not supported. Before creating a connection the existence of the database driver is checked an and ValueError raised otherwise To use, you should have the ``redis`` python package installed. Example: .. code-block:: python from langchain_community.utilities.redis import get_client redis_client = get_client( redis_url="redis://username:password@localhost:6379" index_name="my-index", embedding_function=embeddings.embed_query, ) To use a redis replication setup with multiple redis server and redis sentinels set "redis_url" to "redis+sentinel://" scheme. With this url format a path is needed holding the name of the redis service within the sentinels to get the correct redis server connection. The default service name is "mymaster". The optional second part of the path is the redis db number to connect to. An optional username or password is used for booth connections to the rediserver and the sentinel, different passwords for server and sentinel are not supported. And as another constraint only one sentinel instance can be given: Example: .. code-block:: python from langchain_community.utilities.redis import get_client redis_client = get_client( redis_url="redis+sentinel://username:password@sentinelhost:26379/mymaster/0" index_name="my-index", embedding_function=embeddings.embed_query, ) """# Initialize with necessary components.try:importredisexceptImportError:raiseImportError("Could not import redis python package. ""Please install it with `pip install redis>=4.1.0`.")# check if normal redis:// or redis+sentinel:// urlifredis_url.startswith("redis+sentinel"):redis_client=_redis_sentinel_client(redis_url,**kwargs)elifredis_url.startswith("rediss+sentinel"):# sentinel with TLS support enableskwargs["ssl"]=Trueif"ssl_cert_reqs"notinkwargs:kwargs["ssl_cert_reqs"]="none"redis_client=_redis_sentinel_client(redis_url,**kwargs)else:# connect to redis server from url, reconnect with cluster client if neededredis_client=redis.from_url(redis_url,**kwargs)if_check_for_cluster(redis_client):redis_client.close()redis_client=_redis_cluster_client(redis_url,**kwargs)returnredis_client
def_redis_sentinel_client(redis_url:str,**kwargs:Any)->RedisType:"""helper method to parse an (un-official) redis+sentinel url and create a Sentinel connection to fetch the final redis client connection to a replica-master for read-write operations. If username and/or password for authentication is given the same credentials are used for the Redis Sentinel as well as Redis Server. With this implementation using a redis url only it is not possible to use different data for authentication on booth systems. """importredisparsed_url=urlparse(redis_url)# sentinel needs list with (host, port) tuple, use default port if none availablesentinel_list=[(parsed_url.hostnameor"localhost",parsed_url.portor26379)]ifparsed_url.path:# "/mymaster/0" first part is service name, optional second part is db numberpath_parts=parsed_url.path.split("/")service_name=path_parts[1]or"mymaster"iflen(path_parts)>2:kwargs["db"]=path_parts[2]else:service_name="mymaster"sentinel_args={}ifparsed_url.password:sentinel_args["password"]=parsed_url.passwordkwargs["password"]=parsed_url.passwordifparsed_url.username:sentinel_args["username"]=parsed_url.usernamekwargs["username"]=parsed_url.username# check for all SSL related properties and copy them into sentinel_kwargs too,# add client_name alsoforarginkwargs:ifarg.startswith("ssl")orarg=="client_name":sentinel_args[arg]=kwargs[arg]# sentinel user/pass is part of sentinel_kwargs, user/pass for redis server# connection as direct parameter in kwargssentinel_client=redis.sentinel.Sentinel(sentinel_list,sentinel_kwargs=sentinel_args,**kwargs)# redis server might have password but not sentinel - fetch this error and try# again without pass, everything else cannot be handled here -> user neededtry:sentinel_client.execute_command("ping")exceptredis.exceptions.AuthenticationErrorasae:if"no password is set"inae.args[0]:logger.warning("Redis sentinel connection configured with password but Sentinel \answered NO PASSWORD NEEDED - Please check Sentinel configuration")sentinel_client=redis.sentinel.Sentinel(sentinel_list,**kwargs)else:raiseaereturnsentinel_client.master_for(service_name)def_check_for_cluster(redis_client:RedisType)->bool:importredistry:cluster_info=redis_client.info("cluster")returncluster_info["cluster_enabled"]==1exceptredis.exceptions.RedisError:returnFalsedef_redis_cluster_client(redis_url:str,**kwargs:Any)->RedisType:fromredis.clusterimportRedisClusterreturnRedisCluster.from_url(redis_url,**kwargs)# type: ignore[return-value]