a
    bgR                     @  s   d dl mZ d dlZd dlZd dlZd dlmZmZmZm	Z	m
Z
mZmZmZmZ d dlZd dlmZ d dlmZ d dlmZ d dlmZmZ erd dlmZ d d	lmZmZ ee Z!d
dddZ"edddZ#G dd deZ$dS )    )annotationsN)	TYPE_CHECKINGAnyCallableIterableListOptionalTupleTypeVarUnion)Document)
Embeddings)VectorStore)DistanceStrategymaximal_marginal_relevanceClient)NeighborVectorDistanceMetricr   returnc               
   C  sD   zddl m}  W n. ty> } ztd|W Y d }~n
d }~0 0 | S )Nr   r   zoCould not import aerospike_vector_search python package. Please install it with `pip install aerospike_vector`.)aerospike_vector_searchr   ImportError)r   e r   x/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain_community/vectorstores/aerospike.py_import_aerospike#   s    r   AVST	Aerospike)boundc                   @  s  e Zd ZdZdddddejfdddd	dddd	d
d	ddZeddddZdddddZ	dddddZ
edddddZdQdd"d#d	d$d	d%d&d'd(	d)d*ZdRd#d	d&d+d,d-d.ZdSdd$d#d	d&d0d1d2d3ZdTdd$d#d	d&d0d4d5d6ZdUdd$d#d	d&d7d4d8d9ZdVdd$d#d	d&d7d1d:d;Zd<dd=d>Zed?d?d@dAdBZdWdd$d$d?d#d	d&d7dEdFdGZdXdd$d$d?d#d	d&d7dHdIdJZedYd'dLd"ddd	d#d$dMd&d dNdOdPZdS )Zr   zu`Aerospike` vector store.

    To use, you should have the ``aerospike_vector_search`` python package installed.
    NZ_vector_textZ_idr   zUnion[Embeddings, Callable]strzOptional[str]z7Optional[Union[DistanceStrategy, VectorDistanceMetric]])	client	embedding	namespace
index_name
vector_keytext_keyid_keyset_namedistance_strategyc
                 C  sv   t  }
t|tstd t||
s6tdt| || _|| _|| _	|| _
|| _|| _|| _|| _| |	| _dS )a  Initialize with Aerospike client.

        Args:
            client: Aerospike client.
            embedding: Embeddings object or Callable (deprecated) to embed text.
            namespace: Namespace to use for storing vectors. This should match
            index_name: Name of the index previously created in Aerospike. This
            vector_key: Key to use for vector in metadata. This should match the
                key used during index creation.
            text_key: Key to use for text in metadata.
            id_key: Key to use for id in metadata.
            set_name: Default set name to use for storing vectors.
            distance_strategy: Distance strategy to use for similarity search
                This should match the distance strategy used during index creation.
        z`Passing in `embedding` as a Callable is deprecated. Please pass in an Embeddings object instead.zDclient should be an instance of aerospike_vector_search.Client, got N)r   
isinstancer   warningswarn
ValueErrortype_client
_embedding	_text_key_vector_key_id_key_index_name
_namespace	_set_nameconvert_distance_strategy_distance_strategy)selfr"   r#   r$   r%   r&   r'   r(   r)   r*   	aerospiker   r   r   __init__7   s(    

zAerospike.__init__zOptional[Embeddings]r   c                 C  s   t | jtr| jS dS )z/Access the query embedding object if available.N)r+   r1   r   r:   r   r   r   
embeddingsm   s    zAerospike.embeddingszIterable[str]zList[List[float]])textsr   c                   s.   t  jtr jt|S  fdd|D S )zEmbed search docs.c                   s   g | ]}  |qS r   )r1   ).0tr=   r   r   
<listcomp>x       z.Aerospike._embed_documents.<locals>.<listcomp>)r+   r1   r   Zembed_documentslist)r:   r?   r   r=   r   _embed_documentst   s    zAerospike._embed_documentszList[float])textr   c                 C  s"   t | jtr| j|S | |S )zEmbed query text.)r+   r1   r   Zembed_query)r:   rF   r   r   r   _embed_queryz   s    zAerospike._embed_queryz-Union[VectorDistanceMetric, DistanceStrategy]r   )r*   r   c                 C  sV   ddl m} t| tr| S | |jkr*tjS | |jkr:tjS | |jkrJtjS tddS )z
        Convert Aerospikes distance strategy to langchains DistanceStrategy
        enum. This is a convenience method to allow users to pass in the same
        distance metric used to create the index.
        r   )r   DUnknown distance strategy, must be cosine, dot_product, or euclideanN)	aerospike_vector_search.typesr   r+   r   COSINEDOT_PRODUCTZSQUARED_EUCLIDEANEUCLIDEAN_DISTANCEr.   )r*   r   r   r   r   r8      s    	



z#Aerospike.convert_distance_strategy  TzOptional[List[dict]]zOptional[List[str]]intboolr   z	List[str])	r?   	metadatasidsr)   embedding_chunk_sizer%   wait_for_indexkwargsr   c              	   K  sD  |du r| j }|du r| j}|r0|du r0tdt|}|pHdd |D }|r^dd |D }n|pndd |D }tdt||D ]}	||	|	|  }
||	|	|  }||	|	|  }| |
}t|||
D ]\}}}||| j< ||| j	< qt||D ]0\}}||| j
< | jjf | j|||d| qq|r@| jj| j|d	 |S )
a  Run more texts through the embeddings and add to the vectorstore.


        Args:
            texts: Iterable of strings to add to the vectorstore.
            metadatas: Optional list of metadata associated with the texts.
            ids: Optional list of ids to associate with the texts.
            set_name: Optional aerospike set name to add the texts to.
            batch_size: Batch size to use when adding the texts to the vectorstore.
            embedding_chunk_size: Chunk size to use when embedding the texts.
            index_name: Optional aerospike index name used for waiting for index
                completion. If not provided, the default index_name will be used.
            wait_for_index: If True, wait for the all the texts to be indexed
                before returning. Requires index_name to be provided. Defaults
                to True.
            kwargs: Additional keyword arguments to pass to the client upsert call.

        Returns:
            List of ids from adding the texts into the vectorstore.

        Nz6if wait_for_index is True, index_name must be providedc                 S  s   g | ]}t t qS r   )r!   uuiduuid4r@   _r   r   r   rB      rC   z'Aerospike.add_texts.<locals>.<listcomp>c                 S  s   g | ]}|  qS r   )copy)r@   mr   r   r   rB      rC   c                 S  s   g | ]}i qS r   r   rW   r   r   r   rB      rC   r   )r$   keyr)   Zrecord_data)r$   name)r7   r5   r.   rD   rangelenrE   zipr3   r2   r4   r0   Zupsertr6   Zwait_for_index_completion)r:   r?   rP   rQ   r)   rR   r%   rS   rT   iZchunk_textsZ	chunk_idsZchunk_metadatasr>   metadatar#   rF   idr   r   r   	add_texts   sJ     



zAerospike.add_textszOptional[bool])rQ   r)   rT   r   c              	   K  sV   ddl m} |rR|D ]<}z | jjf | j||d| W q |yN   Y  dS 0 qdS )a7  Delete by vector ID or other criteria.

        Args:
            ids: List of ids to delete.
            **kwargs: Other keyword arguments to pass to client delete call.

        Returns:
            Optional[bool]: True if deletion is successful,
            False otherwise, None if not implemented.
        r   )AVSServerError)r$   r[   r)   FT)r   rd   r0   deleter6   )r:   rQ   r)   rT   rd   rb   r   r   r   re      s    
zAerospike.delete   zList[Tuple[Document, float]])querykmetadata_keysr%   rT   r   c                 K  s    | j | |f|||d|S )a  Return aerospike documents most similar to query, along with scores.

        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            metadata_keys: List of metadata keys to return with the documents.
                If None, all metadata keys will be returned. Defaults to None.
            index_name: Name of the index to search. Overrides the default
                index_name.
            kwargs: Additional keyword arguments to pass to the search method.

        Returns:
            List of Documents most similar to the query and associated scores.
        rh   ri   r%   )&similarity_search_by_vector_with_scorerG   )r:   rg   rh   ri   r%   rT   r   r   r   similarity_search_with_score  s    z&Aerospike.similarity_search_with_score)r#   rh   ri   r%   rT   r   c                 K  s   g }|r| j |vr| j g| }|du r,| j}|du r<td| jjf || j|||d|}|D ]T}|j}	| j |	v r|	| j }
|j}|	t
|
|	d|f q`td| j  d q`q`|S )a  Return aerospike documents most similar to embedding, along with scores.

        Args:
            embedding: Embedding to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            metadata_keys: List of metadata keys to return with the documents.
                If None, all metadata keys will be returned. Defaults to None.
            index_name: Name of the index to search. Overrides the default
                index_name.
            kwargs: Additional keyword arguments to pass to the client
                vector_search method.

        Returns:
            List of Documents most similar to the query and associated scores.

        Nzindex_name must be provided)r%   r$   rg   limitfield_names)Zpage_contentra   zFound document with no `z` key. Skipping.)r2   r5   r.   r0   Zvector_searchr6   fieldspopZdistanceappendr   loggerwarning)r:   r#   rh   ri   r%   rT   docsresultsresultra   rF   scorer   r   r   rk   *  s6    	
z0Aerospike.similarity_search_by_vector_with_scorezList[Document]c                 K  s$   dd | j |f|||d|D S )ak  Return docs most similar to embedding vector.

        Args:
            embedding: Embedding to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            metadata_keys: List of metadata keys to return with the documents.
                If None, all metadata keys will be returned. Defaults to None.
            index_name: Name of the index to search. Overrides the default
                index_name.
            kwargs: Additional keyword arguments to pass to the search method.


        Returns:
            List of Documents most similar to the query vector.
        c                 S  s   g | ]\}}|qS r   r   r@   docrX   r   r   r   rB   }  s   z9Aerospike.similarity_search_by_vector.<locals>.<listcomp>rj   )rk   )r:   r#   rh   ri   r%   rT   r   r   r   similarity_search_by_vectorf  s    z%Aerospike.similarity_search_by_vectorc                 K  s(   | j |f|||d|}dd |D S )a*  Return aerospike documents most similar to query.

        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            metadata_keys: List of metadata keys to return with the documents.
                If None, all metadata keys will be returned. Defaults to None.
            index_name: Optional name of the index to search. Overrides the
                default index_name.

        Returns:
            List of Documents most similar to the query and score for each
        rj   c                 S  s   g | ]\}}|qS r   r   rx   r   r   r   rB     rC   z/Aerospike.similarity_search.<locals>.<listcomp>)rl   )r:   rg   rh   ri   r%   rT   Zdocs_and_scoresr   r   r   similarity_search  s    zAerospike.similarity_searchzCallable[[float], float]c                 C  sB   | j tjkr| jS | j tjkr$| jS | j tjkr6| jS tddS )a  
        The 'correct' relevance function
        may differ depending on a few things, including:
        - the distance / similarity metric used by the VectorStore
        - the scale of your embeddings (OpenAI's are unit normed. Many others are not!)
        - embedding dimensionality
        - etc.

        0 is dissimilar, 1 is similar.

        Aerospike's relevance_fn assume euclidean and dot product embeddings are
        normalized to unit norm.
        rH   N)	r9   r   rJ   _cosine_relevance_score_fnrK   Z%_max_inner_product_relevance_score_fnrL   Z_euclidean_relevance_score_fnr.   r=   r   r   r   _select_relevance_score_fn  s    z$Aerospike._select_relevance_score_fnfloat)rw   r   c                 C  s   d| d  S )zgAerospike returns cosine distance scores between [0,2]

        0 is dissimilar, 1 is similar.
              r   )rw   r   r   r   r|     s    z$Aerospike._cosine_relevance_score_fn         ?)r#   rh   fetch_klambda_multri   r%   rT   r   c           
        s   |rj |vrj g| }j|f|||d| ttj|gtjdfdd D ||d}|rj |v r|D ]}	 |	 jj  qr fdd|D S )a  Return docs selected using the maximal marginal relevance.

        Maximal marginal relevance optimizes for similarity to query AND diversity
        among selected documents.

        Args:
            embedding: Embedding to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            fetch_k: Number of Documents to fetch to pass to MMR algorithm.
            lambda_mult: Number between 0 and 1 that determines the degree of
                diversity among the results with 0 corresponding to maximum
                diversity and 1 to minimum diversity. Defaults to 0.5.
            metadata_keys: List of metadata keys to return with the documents.
                If None, all metadata keys will be returned. Defaults to None.
            index_name: Optional name of the index to search. Overrides the
                default index_name.
        Returns:
            List of Documents selected by maximal marginal relevance.
        rj   )Zdtypec                   s   g | ]}|j  j qS r   )ra   r3   )r@   ry   r=   r   r   rB     rC   zEAerospike.max_marginal_relevance_search_by_vector.<locals>.<listcomp>)rh   r   c                   s   g | ]} | qS r   r   )r@   r`   )rt   r   r   rB     rC   )r3   rz   r   nparrayZfloat32ra   rp   )
r:   r#   rh   r   r   ri   r%   rT   Zmmr_selectedr`   r   )rt   r:   r   'max_marginal_relevance_search_by_vector  s*    z1Aerospike.max_marginal_relevance_search_by_vector)rg   rh   r   r   ri   r%   rT   r   c           	      K  s(   |  |}| j||||f||d|S )a  Return docs selected using the maximal marginal relevance.

        Maximal marginal relevance optimizes for similarity to query AND diversity
        among selected documents.

        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            fetch_k: Number of Documents to fetch to pass to MMR algorithm.
            lambda_mult: Number between 0 and 1 that determines the degree
                        of diversity among the results with 0 corresponding
                        to maximum diversity and 1 to minimum diversity.
                        Defaults to 0.5.
            index_name: Name of the index to search.
        Returns:
            List of Documents selected by maximal marginal relevance.
        )ri   r%   )rG   r   )	r:   rg   rh   r   r   ri   r%   rT   r#   r   r   r   max_marginal_relevance_search  s    
z'Aerospike.max_marginal_relevance_searchtestr   zOptional[dict])r?   r#   rP   r"   r$   r%   rQ   embeddings_chunk_sizeclient_kwargsrT   r   c
                 K  s8   | |||fi |
}|j |f||||d|	p.i  |S )a  
        This is a user friendly interface that:
            1. Embeds text.
            2. Converts the texts into documents.
            3. Adds the documents to a provided Aerospike index

        This is intended to be a quick way to get started.

        Example:
            .. code-block:: python

                from langchain_community.vectorstores import Aerospike
                from langchain_openai import OpenAIEmbeddings
                from aerospike_vector_search import Client, HostPort

                client = Client(seeds=HostPort(host="localhost", port=5000))
                aerospike = Aerospike.from_texts(
                    ["foo", "bar", "baz"],
                    embedder,
                    client,
                    "namespace",
                    index_name="index",
                    vector_key="vector",
                    distance_strategy=MODEL_DISTANCE_CALC,
                )
        )rP   rQ   r%   rR   )rc   )clsr?   r#   rP   r"   r$   r%   rQ   r   r   rT   r;   r   r   r   
from_texts  s$    (zAerospike.from_texts)NNNrM   NT)NN)rf   NN)rf   NN)rf   NN)rf   NN)rf   r   r   NN)rf   r   r   NN)NNr   NNrM   N)__name__
__module____qualname____doc__r   rL   r<   propertyr>   rE   rG   staticmethodr8   rc   re   rl   rk   rz   r{   r}   r|   r   r   classmethodr   r   r   r   r   r   1   s   
 6       R  #   "   ?   %   
     8     &       )%
__future__r   loggingrU   r,   typingr   r   r   r   r   r   r	   r
   r   numpyr   Zlangchain_core.documentsr   Zlangchain_core.embeddingsr   Zlangchain_core.vectorstoresr   Z&langchain_community.vectorstores.utilsr   r   r   r   rI   r   r   	getLoggerr   rr   r   r   r   r   r   r   r   <module>   s    ,
