
    Ngf                    (   d dl mZ d dlZd dl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mZmZ d dlZd dlmZ ej        rd dlmZ d dlmZ d dlmZ d dlmZm Z  d d	l!m"Z" d d
l#m$Z$  edd          Z% ed          Z& G d de          Z'dS )    )annotationsN)Any	AwaitableCallableDictIterableListOptionalTupleTypeTypeVarUnion)Version)SessionDocument)
Embeddings)VectorStoreVectorStoreRetriever)	SetupMode)maximal_marginal_relevanceCVST	Cassandra)boundz0.1.10c            
         e Zd ZU ded<   ddZddZ	 	 	 	 ddej        d	d
ddZe	dd            Z
ddZdd Zdd!Zdd"Zdd#Zdd%Zdd&Zddd,Z	 ddd-Zd.d/dd3Zd.d/dd4Z	 	 	 	 ddd;Z	 	 	 	 ddd=Zd.d/dd@Zd.dAddBZeddF            ZddHZddIZi dJfddMZi dJfddNZ	 	 	 dddVZ eddZ            Z!	 	 	 ddd[Z"	 	 	 ddd\Z#	 	 	 ddd^Z$	 	 	 ddd_Z%	 	 	 dddaZ&	 	 	 dddbZ'	 	 	 ddddZ(	 	 	 dddeZ)	 	 	 dddfZ*	 	 	 dddgZ+	 	 	 dddhZ,	 	 	 dddiZ-eddn            Z.	 	 	 	 	 dddrZ/	 	 	 	 	 dddsZ0	 	 	 	 	 dddtZ1	 	 	 	 	 ddduZ2e	 	 dddv            Z3e4	 dddddddd	dwdd{            Z5e4	 dddddddd	dwdd|            Z6e	 ddd~            Z7e4ddddddd	dwdd            Z8e4ddddddd	dwdd            Z9	 	 	 	 dddZ:dS )r   zUnion[int, None]_embedding_dimensionreturnintc                v    | j         ,t          | j                            d                    | _         | j         S NzThis is a sample sentence.)r   len	embeddingembed_queryselfs    f/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/vectorstores/cassandra.py_get_embedding_dimensionz"Cassandra._get_embedding_dimension*   s<    $,(+**+GHH) )D% ((    c                   K   | j         2t          | j                            d           d {V           | _         | j         S r    )r   r!   r"   aembed_queryr$   s    r&   _aget_embedding_dimensionz#Cassandra._aget_embedding_dimension1   sR      $,(+n112NOOOOOOOO) )D% ((r(   N all)body_index_options
setup_modemetadata_indexingr"   r   sessionOptional[Session]keyspaceOptional[str]
table_namestrttl_secondsOptional[int]r.   Optional[List[Tuple[str, Any]]]r/   r   r0   %Union[Tuple[str, Iterable[str]], str]Nonec                  	 ddl m}	 n$# t          t          f$ r t          d          w xY wt	          t
          j                            d                    }
|
%|
t          k     rdt           d}t          |          |st          d          || _
        || _        || _        || _        || _        d| _        i }|||d	<   |t           j        k    rd
|d<   d}|t           j        k    r|                                 }n$|t           j        k    r|                                 } |	d|||||d|t           j        k    d|| _        | j        | j        j        | _        dS dS )a  Apache Cassandra(R) for vector-store workloads.

        To use it, you need a recent installation of the `cassio` library
        and a Cassandra cluster / Astra DB instance supporting vector capabilities.

        Visit the cassio.org website for extensive quickstarts and code examples.

        Example:
            .. code-block:: python

                    from langchain_community.vectorstores import Cassandra
                    from langchain_openai import OpenAIEmbeddings

                    embeddings = OpenAIEmbeddings()
                    session = ...             # create your Cassandra session object
                    keyspace = 'my_keyspace'  # the keyspace should exist already
                    table_name = 'my_vector_store'
                    vectorstore = Cassandra(embeddings, session, keyspace, table_name)

        Args:
            embedding: Embedding function to use.
            session: Cassandra driver session. If not provided, it is resolved from
                cassio.
            keyspace: Cassandra keyspace. If not provided, it is resolved from cassio.
            table_name: Cassandra table (required).
            ttl_seconds: Optional time-to-live for the added texts.
            body_index_options: Optional options used to create the body index.
                Eg. body_index_options = [cassio.table.cql.STANDARD_ANALYZER]
            setup_mode: mode used to create the Cassandra table (SYNC,
                ASYNC or OFF).
            metadata_indexing: Optional specification of a metadata indexing policy,
                i.e. to fine-tune which of the metadata fields are indexed.
                It can be a string ("all" or "none"), or a 2-tuple. The following
                means that all fields except 'f1', 'f2' ... are NOT indexed:
                    metadata_indexing=("allowlist", ["f1", "f2", ...])
                The following means all fields EXCEPT 'g1', 'g2', ... are indexed:
                    metadata_indexing("denylist", ["g1", "g2", ...])
                The default is to index every metadata field.
                Note: if you plan to have massive unique text metadata entries,
                consider not indexing them for performance
                (and to overcome max-length limitations).
        r   )MetadataVectorCassandraTablezTCould not import cassio python package. Please install it with `pip install cassio`.cassioNz?Cassio version not supported. Please upgrade cassio to version z or higher.z(Missing required parameter 'table_name'.r.   Tasync_setupTEXT)r1   r3   tablevector_dimensionr0   primary_key_typeskip_provisioning )cassio.tabler=   ImportErrorModuleNotFoundErrorr   	importlibmetadataversionMIN_CASSIO_VERSION
ValueErrorr"   r1   r3   r5   r7   r   r   ASYNCr+   SYNCr'   OFFrA   )r%   r"   r1   r3   r5   r7   r.   r/   r0   r=   cassio_versionmsgkwargsembedding_dimensions                 r&   __init__zCassandra.__init__8   s   l	AAAAAAA01 	 	 	?  	
 !!3!;!;H!E!EFF%.;M*M*M>0> > >  c""" 	IGHHH" $&$(!!#)+=F'((($(F=!@D(("&"@"@"B"B9>))"&"?"?"A"A11 	
0/#(IM9	
 	
 	
 	

 <:-DLLL  s   	 !*c                    | j         S N)r"   r$   s    r&   
embeddingszCassandra.embeddings   s
    ~r(   Callable[[float], float]c                    d S )z
        The underlying VectorTable already returns a "score proper",
        i.e. one in [0, 1] where higher means more *similar*,
        so here the final score transformation is not reversing the interval:
        c                    | S rW   rE   )scores    r&   <lambda>z6Cassandra._select_relevance_score_fn.<locals>.<lambda>   s    U r(   rE   r$   s    r&   _select_relevance_score_fnz$Cassandra._select_relevance_score_fn   s     #""r(   c                .    |                                   dS )zm
        Just an alias for `clear`
        (to better align with other VectorStore implementations).
        N)clearr$   s    r&   delete_collectionzCassandra.delete_collection   s    
 	

r(   c                >   K   |                                   d{V  dS )zn
        Just an alias for `aclear`
        (to better align with other VectorStore implementations).
        N)aclearr$   s    r&   adelete_collectionzCassandra.adelete_collection   s.      
 kkmmr(   c                8    | j                                          dS zEmpty the table.N)rA   r`   r$   s    r&   r`   zCassandra.clear   s    
r(   c                H   K   | j                                          d{V  dS rf   )rA   rc   r$   s    r&   rc   zCassandra.aclear   s2      j!!!!!!!!!!!r(   document_idc                8    | j                             |          S )bDelete by document ID.

        Args:
            document_id: the document ID to delete.
        row_id)rA   deleter%   rh   s     r&   delete_by_document_idzCassandra.delete_by_document_id   s     z   444r(   c                H   K   | j                             |           d{V S )rj   rk   N)rA   adeletern   s     r&   adelete_by_document_idz Cassandra.adelete_by_document_id   s3       Z''{';;;;;;;;;r(   idsOptional[List[str]]rS   r   Optional[bool]c                \    |t          d          |D ]}|                     |           dS zDelete by vector IDs.

        Args:
            ids: List of ids to delete.

        Returns:
            Optional[bool]: True if deletion is successful,
            False otherwise, None if not implemented.
        NzNo ids provided to delete.T)rM   ro   r%   rs   rS   rh   s       r&   rm   zCassandra.delete   sC     ;9::: 	4 	4K&&{3333tr(   c                l   K   |t          d          |D ]}|                     |           d{V  dS rw   )rM   rr   rx   s       r&   rq   zCassandra.adelete   sY       ;9::: 	; 	;K--k::::::::::tr(   2   )
batch_sizefilterdict[str, Any]r{   c               `    |sd}t          |          | j                            ||          S )  Delete all documents matching a certain metadata filtering condition.

        This operation does not use the vector embeddings in any way, it simply
        removes all documents whose metadata match the provided condition.

        Args:
            filter: Filter on the metadata to apply. The filter cannot be empty.
            batch_size: amount of deletions per each batch (until exhaustion of
                the matching documents).

        Returns:
            A number expressing the amount of deleted documents.
        Method `delete_by_metadata_filter` does not accept an empty filter. Use the `clear()` method if you really want to empty the vector store.rJ   r{   )rM   rA   find_and_delete_entriesr%   r|   r{   rR   s       r&   delete_by_metadata_filterz#Cassandra.delete_by_metadata_filter   sI    &  	"$ 
 S//!z11! 2 
 
 	
r(   c               p   K   |sd}t          |          | j                            ||           d{V S )r   r   r   N)rM   rA   afind_and_delete_entriesr   s       r&   adelete_by_metadata_filterz$Cassandra.adelete_by_metadata_filter  sk      &  	"$ 
 S//!Z88! 9 
 
 
 
 
 
 
 
 	
r(      textsIterable[str]	metadatasOptional[List[dict]]	List[str]c                    t          |          }|pd |D             }|pi gt          |          z  }p j         j                            |          }t          dt          |          |          D ]n}	||	|	|z            }
||	|	|z            }||	|	|z            }||	|	|z            } fdt          |
|||          D             }|D ]}|                                 o|S )a  Run more texts through the embeddings and add to the vectorstore.

        Args:
            texts: Texts to add to the vectorstore.
            metadatas: Optional list of metadatas.
            ids: Optional list of IDs.
            batch_size: Number of concurrent requests to send to the server.
            ttl_seconds: Optional time-to-live for the added texts.

        Returns:
            List[str]: List of IDs of the added texts.
        c                >    g | ]}t          j                    j        S rE   uuiduuid4hex.0_s     r&   
<listcomp>z'Cassandra.add_texts.<locals>.<listcomp>P  !    7771djll&777r(   r   c           	     \    g | ](\  }}}}j                             ||||pi            )S )rl   	body_blobvectorrJ   r7   rA   	put_async)r   textembedding_vectortext_idrJ   r%   r7   s        r&   r   z'Cassandra.add_texts.<locals>.<listcomp>[  s^        >D*GX 
$$""+%^ + %    r(   )listr!   r7   r"   embed_documentsrangezipresult)r%   r   r   rs   r{   r7   rS   _textsembedding_vectorsibatch_textsbatch_embedding_vectors	batch_idsbatch_metadatasfuturesfutures   `    `          r&   	add_textszCassandra.add_texts:  sC   * e7777773"F!3	!5T%5 N::6BBq#f++z22 	  	 A Q^!34K&7A
N8J&K#AJ./I'A
N(:;O     BE!8)_B B  G "     
r(   concurrencyc           
        K   t          |          }|pd |D             }|pi gt          |          z  }p j         j                            |           d{V }	t          j        |          d fd}
t          dt          |                    D ]O}t          j         |
||         ||         |	|         ||                             g}t          j	        |  d{V  P|S )a  Run more texts through the embeddings and add to the vectorstore.

        Args:
            texts: Texts to add to the vectorstore.
            metadatas: Optional list of metadatas.
            ids: Optional list of IDs.
            concurrency: Number of concurrent queries to the database.
                Defaults to 16.
            ttl_seconds: Optional time-to-live for the added texts.

        Returns:
            List[str]: List of IDs of the added texts.
        c                >    g | ]}t          j                    j        S rE   r   r   s     r&   r   z(Cassandra.aadd_texts.<locals>.<listcomp>  r   r(   Nrl   r6   r   r   List[float]rJ   dictr   r;   c                   K   4 d {V  j                             | |||pi            d {V  d d d           d {V  d S # 1 d {V swxY w Y   d S )Nr   rA   aput)rl   r   r   rJ   r%   semr7   s       r&   send_concurrentlyz/Cassandra.aadd_texts.<locals>.send_concurrently  s              joo!"+%^ + &                                      s   (A
AAr   )
rl   r6   r   r6   r   r   rJ   r   r   r;   )
r   r!   r7   r"   aembed_documentsasyncio	Semaphorer   create_taskgather)r%   r   r   rs   r   r7   rS   r   
_metadatasr   r   r   tasksr   s   `    `       @r&   
aadd_textszCassandra.aadd_textsk  s?     , e777777!*!@rdS[[.@
!5T%5"&."A"A&"I"IIIIIII,,
	 
	 
	 
	 
	 
	 
	 
	 q#f++&& 	) 	)A#%%Aq	+<Q+?A  E .%(((((((((
r(   id_to_metadatadict[str, dict]c                    t          |                                          }t          dt          |          |          D ]6}||||z            } fd|D             }|D ]}|                                 7dS )aj  Replace the metadata of documents.

        For each document to update, identified by its ID, the new metadata
        dictionary completely replaces what is on the store. This includes
        passing empty metadata `{}` to erase the currently-stored information.

        Args:
            id_to_metadata: map from the Document IDs to modify to the
                new metadata for updating.
                Keys in this dictionary that do not correspond to an existing
                document will not cause an error, rather will result in new
                rows being written into the Cassandra table but without an
                associated vector: hence unreachable through vector search.
            batch_size: Number of concurrent requests to send to the server.

        Returns:
            None if the writes succeed (otherwise an error is raised).
        r   c                N    g | ]!\  }}j                             ||           "S )rl   rJ   r   )r   doc_iddoc_mdr%   s      r&   r   z.Cassandra.replace_metadata.<locals>.<listcomp>  sL       
 #FF	 
$$!# %    r(   N)r   itemsr   r!   r   )r%   r   r{   ids_and_metadatasr   	batch_i_mr   r   s   `       r&   replace_metadatazCassandra.replace_metadata  s    0 !!5!5!7!788q#/00*== 
	  
	 A)!a*n*<=I   
 '0  G "     r(   )r   c                   K   t          |                                          }t          j        |          d	 fd}|D ]8\  }}t          j         |||                    g}t          j        |  d{V  9dS )
a  Replace the metadata of documents.

        For each document to update, identified by its ID, the new metadata
        dictionary completely replaces what is on the store. This includes
        passing empty metadata `{}` to erase the currently-stored information.

        Args:
            id_to_metadata: map from the Document IDs to modify to the
                new metadata for updating.
                Keys in this dictionary that do not correspond to an existing
                document will not cause an error, rather will result in new
                rows being written into the Cassandra table but without an
                associated vector: hence unreachable through vector search.
            concurrency: Number of concurrent queries to the database.
                Defaults to 50.

        Returns:
            None if the writes succeed (otherwise an error is raised).
        r   r6   r   r   r   r;   c                   K   4 d {V  j                             | |           d {V  d d d           d {V  d S # 1 d {V swxY w Y   d S )Nr   r   )r   r   r%   r   s     r&   r   z6Cassandra.areplace_metadata.<locals>.send_concurrently  s             joo!# &                                      s   #A
AAN)r   r6   r   r   r   r;   )r   r   r   r   r   r   )	r%   r   r   r   r   r   r   r   r   s	   `       @r&   areplace_metadatazCassandra.areplace_metadata  s      2 !!5!5!7!788,,	 	 	 	 	 	 	 0 	) 	)NFF():):66)J)JKKLE.%(((((((((r(   rowDict[str, Any]r   c                J    t          | d         | d         | d                   S )Nrl   r   rJ   )idpage_contentrJ   r   r   s    r&   _row_to_documentzCassandra._row_to_document  s/    8}[)_
 
 
 	
r(   Document | Nonec                l    | j                             |          }|dS |                     |          S zRetrieve a single document from the store, given its document ID.

        Args:
            document_id: The document ID

        Returns:
            The the document if it exists. Otherwise None.
        rk   Nr   )rA   getr   r%   rh   r   s      r&   get_by_document_idzCassandra.get_by_document_id  s:     jnnKn00;4$$$---r(   c                |   K   | j                             |           d{V }|dS |                     |          S r   )rA   agetr   r   s      r&   aget_by_document_idzCassandra.aget_by_document_id  sP       JOO;O77777777;4$$$---r(      nIterable[Document]c                X      j                             ||          } fd|D             S )Get documents via a metadata search.

        Args:
            filter: the metadata to query for.
            n: the maximum number of documents to return.
        rJ   r   c                @    g | ]}|                     |           S r   r   r   r   r%   s     r&   r   z-Cassandra.metadata_search.<locals>.<listcomp>   s/    FFF3#F%%#%..FFFr(   )rA   find_entriesr%   r|   r   rowss   `   r&   metadata_searchzCassandra.metadata_search  s9     z&&!&<<FFFF$FFFFr(   c                h    K    j                             ||           d{V } fd|D             S )r   r   Nc                <    g | ]}                     |           S r   r   r   s     r&   r   z.Cassandra.ametadata_search.<locals>.<listcomp>.  s*    ???3%%#%..???r(   )rA   afind_entriesr   s   `   r&   ametadata_searchzCassandra.ametadata_search"  sO       Z--v-CCCCCCCC????$????r(      r   kOptional[Dict[str, str]]body_searchOptional[Union[str, List[str]]]'List[Tuple[Document, List[float], str]]c                z    K   i }|||d<   |||d<     j         j        d||d| d{V } fd|D             S )a  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.
            filter: Filter on the metadata to apply.
            body_search: Document textual search terms to apply.
                Only supported by Astra DB at the moment.
        Returns:
            List of (Document, embedding, id), the most similar to the query vector.
        NrJ   r   )r   r   c                Z    g | ]'}                     |           |d         |d         f(S )r   r   rl   r   )r   hitr%   s     r&   r   zLCassandra.asimilarity_search_with_embedding_id_by_vector.<locals>.<listcomp>M  sO     
 
 
 	 %%#%..HH
 
 
r(   rE   )rA   aann_searchr%   r"   r   r|   r   rS   hitss   `      r&   .asimilarity_search_with_embedding_id_by_vectorz8Cassandra.asimilarity_search_with_embedding_id_by_vector0  s      $ "$!'F:"$/F=!+TZ+ 

 
 
 
 
 
 
 
 
 


 
 
 
 
 
 
 	
r(   r   Iterable[Dict[str, Any]]!List[Tuple[Document, float, str]]c                    d | D             S )Nc                n    g | ]2}t                               |           dd|d         z  z   |d         f3S )r         ?distancerl   r   r   r   r   s     r&   r   z2Cassandra._search_to_documents.<locals>.<listcomp>\  sX     
 
 
 	 **s*33cC
O++H
 
 
r(   rE   )r   s    r&   _search_to_documentszCassandra._search_to_documentsV  s%    
 
 
 
 
 	
r(   c                x    i }|||d<   |||d<    | j         j        d||dd|}|                     |          S a  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.
            filter: Filter on the metadata to apply.
            body_search: Document textual search terms to apply.
                Only supported by Astra DB at the moment.
        Returns:
            List of (Document, score, id), the most similar to the query vector.
        NrJ   r   cosr   r   metricrE   )rA   metric_ann_searchr  r   s          r&   )similarity_search_with_score_id_by_vectorz3Cassandra.similarity_search_with_score_id_by_vectorf  sr    $ "$!'F:"$/F=!+tz+ 

 
 	
 
 ((...r(   c                   K   i }|||d<   |||d<    | j         j        d||dd| d{V }|                     |          S r
  )rA   ametric_ann_searchr  r   s          r&   *asimilarity_search_with_score_id_by_vectorz4Cassandra.asimilarity_search_with_score_id_by_vector  s      $ "$!'F:"$/F=!2TZ2 

 
 	
 
 
 
 
 
 
 
 ((...r(   queryc                h    | j                             |          }|                     ||||          S )  Return docs most similar to query.

        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            filter: Filter on the metadata to apply.
            body_search: Document textual search terms to apply.
                Only supported by Astra DB at the moment.
        Returns:
            List of (Document, score, id), the most similar to the query vector.
        r"   r   r|   r   )r"   r#   r  r%   r  r   r|   r   r   s         r&   similarity_search_with_score_idz)Cassandra.similarity_search_with_score_id  sC    $  >55e<<==&#	 > 
 
 	
r(   c                   K   | j                             |           d{V }|                     ||||           d{V S )r  Nr  )r"   r*   r  r  s         r&    asimilarity_search_with_score_idz*Cassandra.asimilarity_search_with_score_id  sx      $ "&!<!<U!C!CCCCCCCDD&#	 E 
 
 
 
 
 
 
 
 	
r(   List[Tuple[Document, float]]c                H    d |                      ||||          D             S )  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.
            filter: Filter on the metadata to apply.
            body_search: Document textual search terms to apply.
                Only supported by Astra DB at the moment.
        Returns:
            List of (Document, score), the most similar to the query vector.
        c                    g | ]
\  }}}||fS rE   rE   )r   docr\   docIds       r&   r   zDCassandra.similarity_search_with_score_by_vector.<locals>.<listcomp>  s2     
 
 
#eU %L
 
 
r(   r  )r  r%   r"   r   r|   r   s        r&   &similarity_search_with_score_by_vectorz0Cassandra.similarity_search_with_score_by_vector  sE    $
 
'+'U'U#'	 (V ( (
 
 
 	
r(   c                X   K   d |                      ||||           d{V D             S )r  c                    g | ]
\  }}}||fS rE   rE   )r   r  r\   r   s       r&   r   zECassandra.asimilarity_search_with_score_by_vector.<locals>.<listcomp>  s7     
 
 
	 %L
 
 
r(   r  N)r  r!  s        r&   'asimilarity_search_with_score_by_vectorz1Cassandra.asimilarity_search_with_score_by_vector  si      $
 
 FF#'	 G        
 
 
 	
r(   List[Document]c                h    | j                             |          }|                     ||||          S )  Return docs most similar to query.

        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            filter: Filter on the metadata to apply.
            body_search: Document textual search terms to apply.
                Only supported by Astra DB at the moment.
        Returns:
            List of Document, the most similar to the query vector.
        r|   r   )r"   r#   similarity_search_by_vectorr%   r  r   r|   r   rS   r   s          r&   similarity_searchzCassandra.similarity_search  sC    &  >55e<<//#	 0 
 
 	
r(   c                   K   | j                             |           d{V }|                     ||||           d{V S )r(  Nr)  )r"   r*   asimilarity_search_by_vectorr+  s          r&   asimilarity_searchzCassandra.asimilarity_search1  sw      & "&!<!<U!C!CCCCCCC66#	 7 
 
 
 
 
 
 
 
 	
r(   c                H    d |                      ||||          D             S )  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.
            filter: Filter on the metadata to apply.
            body_search: Document textual search terms to apply.
                Only supported by Astra DB at the moment.
        Returns:
            List of Document, the most similar to the query vector.
        c                    g | ]\  }}|S rE   rE   r   r  r   s      r&   r   z9Cassandra.similarity_search_by_vector.<locals>.<listcomp>_  ,     
 
 
Q 
 
 
r(   r)  )r"  r%   r"   r   r|   r   rS   s         r&   r*  z%Cassandra.similarity_search_by_vectorL  sE    &
 
EE'	 F  
 
 
 	
r(   c                X   K   d |                      ||||           d{V D             S )r1  c                    g | ]\  }}|S rE   rE   r3  s      r&   r   z:Cassandra.asimilarity_search_by_vector.<locals>.<listcomp>|  r4  r(   r)  N)r%  r5  s         r&   r.  z&Cassandra.asimilarity_search_by_vectori  sg      &
 
 $ L L'	 !M ! !      
 
 
 	
r(   c                h    | j                             |          }|                     ||||          S )  Return docs most similar to query.

        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            filter: Filter on the metadata to apply.
            body_search: Document textual search terms to apply.
                Only supported by Astra DB at the moment.
        Returns:
            List of (Document, score), the most similar to the query vector.
        r)  )r"   r#   r"  r  s         r&   similarity_search_with_scorez&Cassandra.similarity_search_with_score  sC    $  >55e<<::#	 ; 
 
 	
r(   c                   K   | j                             |           d{V }|                     ||||           d{V S )r9  Nr)  )r"   r*   r%  r  s         r&   asimilarity_search_with_scorez'Cassandra.asimilarity_search_with_score  sx      $ "&!<!<U!C!CCCCCCCAA#	 B 
 
 
 
 
 
 
 
 	
r(   prefetch_hitsList[Dict[str, Any]]lambda_multfloatc                    t          t          j        |t          j                  d | D             ||          fdt	          |           D             }d |D             S )N)dtypec                    g | ]
}|d          S )r   rE   )r   pf_hits     r&   r   z6Cassandra._mmr_search_to_documents.<locals>.<listcomp>  s    :::&VH:::r(   )r   r?  c                "    g | ]\  }}|v 	|S rE   rE   )r   pf_indexrD  mmr_chosen_indicess      r&   r   z6Cassandra._mmr_search_to_documents.<locals>.<listcomp>  s3     
 
 
 &--- ---r(   c                D    g | ]}t                               |           S r   r  r  s     r&   r   z6Cassandra._mmr_search_to_documents.<locals>.<listcomp>  s)    HHH	**s*33HHHr(   )r   nparrayfloat32	enumerate)r=  r"   r   r?  mmr_hitsrG  s        @r&   _mmr_search_to_documentsz"Cassandra._mmr_search_to_documents  s     8HYbj111::M:::#	
 
 

 
 
 
$-m$<$<
 
 

 IHxHHHHr(      r  fetch_kc           	         i }|||d<   |||d<   t           | j        j        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.
                Defaults to 20.
            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.
            filter: Filter on the metadata to apply.
            body_search: Document textual search terms to apply.
                Only supported by Astra DB at the moment.
        Returns:
            List of Documents selected by maximal marginal relevance.
        NrJ   r   r  r  rE   )r   rA   r  rN  
r%   r"   r   rP  r?  r|   r   rS   _kwargsr=  s
             r&   'max_marginal_relevance_search_by_vectorz1Cassandra.max_marginal_relevance_search_by_vector  s    8 #%"(GJ"%0GM"(DJ(    	 
 
 ,,]Iq+VVVr(   c           	        K   i }|||d<   |||d<   t           | j        j        d||dd| d{V           }	|                     |	|||          S rR  )r   rA   r  rN  rS  s
             r&   (amax_marginal_relevance_search_by_vectorz2Cassandra.amax_marginal_relevance_search_by_vector  s      8 #%"(GJ"%0GM"/$*/    	       
 
 ,,]Iq+VVVr(   c                l    | j                             |          }|                     ||||||          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.
                Defaults to 20.
            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.
            filter: Filter on the metadata to apply.
            body_search: Document textual search terms to apply.
                Only supported by Astra DB at the moment.
        Returns:
            List of Documents selected by maximal marginal relevance.
        r?  r|   r   )r"   r#   rU  	r%   r  r   rP  r?  r|   r   rS   r   s	            r&   max_marginal_relevance_searchz'Cassandra.max_marginal_relevance_search'  sI    8  >55e<<;;## < 
 
 	
r(   c                   K   | j                             |           d{V }|                     ||||||           d{V S )aq  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.
            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.
            filter: Filter on the metadata to apply.
            body_search: Document textual search terms to apply.
                Only supported by Astra DB at the moment.
        Returns:
            List of Documents selected by maximal marginal relevance.
        NrY  )r"   r*   rW  rZ  s	            r&   amax_marginal_relevance_searchz(Cassandra.amax_marginal_relevance_searchM  s~      6 "&!<!<U!C!CCCCCCCBB## C 
 
 
 
 
 
 
 
 	
r(   c                    g }t          |           D ]H\  }}t          |          }|||         |_        |||         |_        |                    |           I|S )N)r   )rL  r   rJ   r   append)r   r   rs   docsr   r   r  s          r&   _build_docs_from_textsz Cassandra._build_docs_from_textsr  sx      " '' 	 	GAt!  C $(|QKKr(   )r1   r3   r5   rs   r7   r.   r0   cls
Type[CVST]r   c               ^    |                      |||          } | j        d|||||||	|
d|S )  Create a Cassandra vector store from raw texts.

        Args:
            texts: Texts to add to the vectorstore.
            embedding: Embedding function to use.
            metadatas: Optional list of metadatas associated with the texts.
            session: Cassandra driver session.
                If not provided, it is resolved from cassio.
            keyspace: Cassandra key space.
                If not provided, it is resolved from cassio.
            table_name: Cassandra table (required).
            ids: Optional list of IDs associated with the texts.
            ttl_seconds: Optional time-to-live for the added texts.
            body_index_options: Optional options used to create the body index.
                Eg. body_index_options = [cassio.table.cql.STANDARD_ANALYZER]
            metadata_indexing: Optional specification of a metadata indexing policy,
                i.e. to fine-tune which of the metadata fields are indexed.
                It can be a string ("all" or "none"), or a 2-tuple. The following
                means that all fields except 'f1', 'f2' ... are NOT indexed:
                    metadata_indexing=("allowlist", ["f1", "f2", ...])
                The following means all fields EXCEPT 'g1', 'g2', ... are indexed:
                    metadata_indexing("denylist", ["g1", "g2", ...])
                The default is to index every metadata field.
                Note: if you plan to have massive unique text metadata entries,
                consider not indexing them for performance
                (and to overcome max-length limitations).

        Returns:
            a Cassandra vector store.
        r   r   rs   	documentsr"   r1   r3   r5   r7   r.   r0   rE   )ra  from_documentsrb  r   r"   r   r1   r3   r5   rs   r7   r.   r0   rS   r`  s                r&   
from_textszCassandra.from_texts  sm    \ )) * 
 
 "s! 

!#1/

 

 

 

 
	
r(   c               n   K   |                      |||          } | j        d|||||||	|
d| d{V S )re  rf  rg  NrE   )ra  afrom_documentsrj  s                r&   afrom_textszCassandra.afrom_texts  s      \ )) * 
 
 )S( 

!#1/

 

 

 

 

 

 

 

 

 

 
	
r(   r`  c                D    |t          | |          D ]\  }}||_        | S rW   )r   r   )r`  rs   r  r   s       r&   _add_ids_to_docszCassandra._add_ids_to_docs  s2    
 ?"4~~    Vr(   rh  c                   |t          j        dt          d            | d|||||||	d|
}|                    |                     ||                     |S )	H  Create a Cassandra vector store from a document list.

        Args:
            documents: Documents to add to the vectorstore.
            embedding: Embedding function to use.
            session: Cassandra driver session.
                If not provided, it is resolved from cassio.
            keyspace: Cassandra key space.
                If not provided, it is resolved from cassio.
            table_name: Cassandra table (required).
            ids: Optional list of IDs associated with the documents.
            ttl_seconds: Optional time-to-live for the added documents.
            body_index_options: Optional options used to create the body index.
                Eg. body_index_options = [cassio.table.cql.STANDARD_ANALYZER]
            metadata_indexing: Optional specification of a metadata indexing policy,
                i.e. to fine-tune which of the metadata fields are indexed.
                It can be a string ("all" or "none"), or a 2-tuple. The following
                means that all fields except 'f1', 'f2' ... are NOT indexed:
                    metadata_indexing=("allowlist", ["f1", "f2", ...])
                The following means all fields EXCEPT 'g1', 'g2', ... are indexed:
                    metadata_indexing("denylist", ["g1", "g2", ...])
                The default is to index every metadata field.
                Note: if you plan to have massive unique text metadata entries,
                consider not indexing them for performance
                (and to overcome max-length limitations).

        Returns:
            a Cassandra vector store.
        NzParameter `ids` to Cassandra's `from_documents` method is deprecated. Please set the supplied documents' `.id` attribute instead. The id attribute of Document is ignored as long as the `ids` parameter is passed.   
stacklevel)r"   r1   r3   r5   r7   r.   r0   r`  rs   rh  rE   )warningswarnDeprecationWarningadd_documentsrp  rb  rh  r"   r1   r3   r5   rs   r7   r.   r0   rS   stores               r&   ri  zCassandra.from_documents  s    X ?MK
 #	 	 	 	  	
!#1/	
 	
 	
 	
 	c&:&:	s&:&S&STTTr(   c                  K   |t          j        dt          d            | d|||||t          j        ||	d|
}|                    |                     ||                     d{V  |S )	rr  NzParameter `ids` to Cassandra's `afrom_documents` method is deprecated. Please set the supplied documents' `.id` attribute instead. The id attribute of Document is ignored as long as the `ids` parameter is passed.rs  rt  )r"   r1   r3   r5   r7   r/   r.   r0   rv  rw  rE   )rx  ry  rz  r   rN   aadd_documentsrp  r|  s               r&   rm  zCassandra.afrom_documentsS  s      X ?MK
 #	 	 	 	  

!# 1/

 

 

 

 ""**	s*CC # 
 
 	
 	
 	
 	
 	
 	
 	
 r(   
similaritysearch_typesearch_kwargsOptional[Dict[str, Any]]tagsrJ   r   c           	     \    |pg |                                  z   }t          d| ||pi ||d|S )a	  Return VectorStoreRetriever initialized from this VectorStore.

        Args:
            search_type: Defines the type of search that
                the Retriever should perform.
                Can be "similarity" (default), "mmr", or
                "similarity_score_threshold".
            search_kwargs: Keyword arguments to pass to the
                search function. Can include things like:
                    k: Amount of documents to return (Default: 4)
                    score_threshold: Minimum relevance threshold
                        for similarity_score_threshold
                    fetch_k: Amount of documents to pass to MMR algorithm (Default: 20)
                    lambda_mult: Diversity of results returned by MMR;
                        1 for minimum diversity and 0 for maximum. (Default: 0.5)
                    filter: Filter by document metadata
            tags: List of tags associated with the retriever.
            metadata: Metadata associated with the retriever.
            kwargs: Other arguments passed to the VectorStoreRetriever init.

        Returns:
            Retriever for VectorStore.

        Examples:

        .. code-block:: python

            # Retrieve more documents with higher diversity
            # Useful if your dataset has many similar documents
            docsearch.as_retriever(
                search_type="mmr",
                search_kwargs={'k': 6, 'lambda_mult': 0.25}
            )

            # Fetch more documents for the MMR algorithm to consider
            # But only return the top 5
            docsearch.as_retriever(
                search_type="mmr",
                search_kwargs={'k': 5, 'fetch_k': 50}
            )

            # Only retrieve documents that have a relevance score
            # Above a certain threshold
            docsearch.as_retriever(
                search_type="similarity_score_threshold",
                search_kwargs={'score_threshold': 0.8}
            )

            # Only get the single most similar document from the dataset
            docsearch.as_retriever(search_kwargs={'k': 1})

            # Use a filter to only retrieve documents from a specific paper
            docsearch.as_retriever(
                search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}
            )
        )vectorstorer  r  r  rJ   rE   )_get_retriever_tagsr   )r%   r  r  r  rJ   rS   _tagss          r&   as_retrieverzCassandra.as_retriever  sZ    @ 7T55777# 
#'-2
 
 
 
 	
r(   )r   r   )NNr,   N)r"   r   r1   r2   r3   r4   r5   r6   r7   r8   r.   r9   r/   r   r0   r:   r   r;   )r   r   )r   rY   )r   r;   )rh   r6   r   r;   rW   )rs   rt   rS   r   r   ru   )r|   r}   r{   r   r   r   )NNr   N)r   r   r   r   rs   rt   r{   r   r7   r8   rS   r   r   r   )r   r   r   r   rs   rt   r   r   r7   r8   rS   r   r   r   )r   r   r{   r   r   r;   )r   r   r   r   r   r;   )r   r   r   r   )rh   r6   r   r   )r|   r}   r   r   r   r   )r   NN)
r"   r   r   r   r|   r   r   r   r   r   )r   r   r   r  )
r"   r   r   r   r|   r   r   r   r   r  )
r  r6   r   r   r|   r   r   r   r   r  )
r"   r   r   r   r|   r   r   r   r   r  )r  r6   r   r   r|   r   r   r   rS   r   r   r&  )r"   r   r   r   r|   r   r   r   rS   r   r   r&  )
r  r6   r   r   r|   r   r   r   r   r  )
r=  r>  r"   r   r   r   r?  r@  r   r&  )r   rO  r  NN)r"   r   r   r   rP  r   r?  r@  r|   r   r   r   rS   r   r   r&  )r  r6   r   r   rP  r   r?  r@  r|   r   r   r   rS   r   r   r&  )NN)r   r   r   r   rs   rt   r   r&  )rb  rc  r   r   r"   r   r   r   r1   r2   r3   r4   r5   r6   rs   rt   r7   r8   r.   r9   r0   r:   rS   r   r   r   )r`  r&  rs   rt   r   r&  )rb  rc  rh  r&  r"   r   r1   r2   r3   r4   r5   r6   rs   rt   r7   r8   r.   r9   r0   r:   rS   r   r   r   )r  NNN)r  r6   r  r  r  rt   rJ   r  rS   r   r   r   );__name__
__module____qualname____annotations__r'   r+   r   rO   rU   propertyrX   r^   ra   rd   r`   rc   ro   rr   rm   rq   r   r   r   r   r   r   staticmethodr   r   r   r   r   r   r  r  r  r  r  r"  r%  r,  r/  r*  r.  r:  r<  rN  rU  rW  r[  r]  ra  classmethodrk  rn  rp  ri  rm  r  rE   r(   r&   r   r   '   si        ****) ) ) )) ) ) ) &*"&%)h. ?C )CHh. h. h. h. h. h.T    X# # # #         " " " "5 5 5 5< < < <    & *.    0 	
 
 
 
 
 
H 	
 
 
 
 
 
F +/#'%)/ / / / /h +/#'%)3 3 3 3 3r 	$ $ $ $ $ $T 	( ( ( ( ( (T 
 
 
 \
. . . .. . . .  "$G G G G G  "$@ @ @ @ @" +/7;$
 $
 $
 $
 $
L 
 
 
 \
$ +/7;/ / / / /D +/7;/ / / / /F +/7;
 
 
 
 
: +/7;
 
 
 
 
< +/7;
 
 
 
 
> +/7;
 
 
 
 
F +/7;
 
 
 
 
< +/7;
 
 
 
 
< +/7;
 
 
 
 
@ +/7;
 
 
 
 
@ +/7;
 
 
 
 
: +/7;
 
 
 
 
4 I I I \I.  +/7;*W *W *W *W *W^  +/7;*W *W *W *W *W^  +/7;$
 $
 $
 $
 $
R  +/7;#
 #
 #
 #
 #
J  +/#'    \" 
 +/	=
 &*"&#'%)>BCH=
 =
 =
 =
 =
 [=
~ 
 +/	=
 &*"&#'%)>BCH=
 =
 =
 =
 =
 [=
~  $(    \  &*"&#'%)>BCHB B B B B [BH  &*"&#'%)>BCHE E E E E [ER (26$(-1H
 H
 H
 H
 H
 H
 H
r(   )(
__future__r   r   importlib.metadatarI   typingr   rx  r   r   r   r   r   r	   r
   r   r   r   r   numpyrI  packaging.versionr   TYPE_CHECKINGcassandra.clusterr   langchain_core.documentsr   langchain_core.embeddingsr   langchain_core.vectorstoresr   r   'langchain_community.utilities.cassandrar   &langchain_community.vectorstores.utilsr   r   rL   r   rE   r(   r&   <module>r     s   " " " " " "                                      % % % % % %	 *)))))) - - - - - - 0 0 0 0 0 0 I I I I I I I I = = = = = = M M M M M Mwv[)))WX&& |
 |
 |
 |
 |
 |
 |
 |
 |
 |
r(   