
    Ng                       d dl mZ d dlZd dlZd dlm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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 d d	lmZ d d
l m!Z! d dl"m#Z#m$Z$ d dl%m&Z& erd dl'm(Z) d dl'm*Z*  edd          Z+ ed          Z, ed          Z-ee.ef         Z/dZ0dZ1dZ2dZ3d"dZ4 eddd            G d! de!                      Z(dS )#    )annotationsN)ThreadPoolExecutor)TYPE_CHECKINGAny	AwaitableCallableDictIterableListOptionalSetTupleTypeTypeVarUnion)
deprecatedDocument)
Embeddings)gather_with_concurrency)batch_iterate)VectorStore)	SetupMode_AstraDBCollectionEnvironment)maximal_marginal_relevance)AstraDB)AsyncAstraDBADBVSTr   )boundTU      
   lstList[T]keyCallable[[T], U]returnc                    t                      }g }| D ];} ||          }||vr*|                    |           |                    |           <|S N)setaddappend)r%   r'   visited_keysnew_lstitemitem_keys         d/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/vectorstores/astradb.py_unique_listr4   9   sc    55LG ! !3t99<''X&&&NN4   N    z0.0.21z1.0z$langchain_astradb.AstraDBVectorStore)sinceremovalalternative_importc                      e Zd Zedqd            Zddddddddddej        dddrd Zdsd"Zdsd#Z	e
dtd$            Zedud'            Zdvd)Zdwd*Zdwd+Zdxd-Zdxd.Z	 	 dydzd5Z	 	 dydzd6Zdwd7Zdwd8Ze	 	 dyd{d@            Zed|dD            Z	 	 dyddddEd}dIZ	 	 dyddddEd}dJZ	 	 d~ddPZ	 	 d~ddQZ	 	 d~ddSZ	 	 d~ddTZ	 	 d~ddVZ	 	 d~ddWZ	 	 d~ddYZ 	 	 d~ddZZ!	 	 d~dd[Z"	 	 d~dd\Z#	 	 d~dd]Z$	 	 d~dd^Z%edda            Z&	 	 	 	 dddeZ'	 	 	 	 dddfZ(	 	 	 	 dddgZ)	 	 	 	 dddhZ*e+ddl            Z,e+	 	 dyddm            Z-e+	 	 dyddn            Z.e+d fdp            Z/ xZ0S )r   filter_dictOptional[Dict[str, Any]]r)   Dict[str, Any]c                    | i S i }|                                  D ]^\  }}|rO|d         dk    rCt          |t                    rd |D             ||<   8t                              |          ||<   V||d| <   _|S )Nr   $c                B    g | ]}t                               |          S  )r   _filter_to_metadata).0fs     r3   
<listcomp>z/AstraDB._filter_to_metadata.<locals>.<listcomp>S   s'    -X-X-XQRg.I.I!.L.L-X-X-Xr5   z	metadata.)items
isinstancelistr   rA   )r:   metadata_filterkvs       r3   rA   zAstraDB._filter_to_metadataJ   s    I O#))++ 9 91 91!!T** L-X-XVW-X-X-X**-4-H-H-K-K**78OOOO44""r5   NF)tokenapi_endpointastra_db_clientasync_astra_db_client	namespacemetric
batch_sizebulk_insert_batch_concurrency!bulk_insert_overwrite_concurrencybulk_delete_concurrency
setup_modepre_delete_collection	embeddingr   collection_namestrrK   Optional[str]rL   rM   Optional[LibAstraDB]rN   Optional[AsyncAstraDB]rO   rP   rQ   Optional[int]rR   rS   rT   rU   r   rV   boolNonec               $   || _         || _        || _        || _        || _        |	pt
          | _        |
pt          | _        |pt          | _
        |pt          | _        || _        d}|t          j        k    r|                                 }n$|t          j        k    r|                                 }t'          ||||||||||
  
        | _        | j        j        | _        | j        j        | _        | j        j        | _        | j        j        | _        dS )a  Wrapper around DataStax Astra DB for vector-store workloads.

        For quickstart and details, visit
        https://docs.datastax.com/en/astra/astra-db-vector/

        Example:
            .. code-block:: python

                from langchain_community.vectorstores import AstraDB
                from langchain_openai.embeddings import OpenAIEmbeddings

                embeddings = OpenAIEmbeddings()
                vectorstore = AstraDB(
                    embedding=embeddings,
                    collection_name="my_store",
                    token="AstraCS:...",
                    api_endpoint="https://<DB-ID>-<REGION>.apps.astra.datastax.com"
                )

                vectorstore.add_texts(["Giraffes", "All good here"])
                results = vectorstore.similarity_search("Everything's ok", k=1)

        Args:
            embedding: embedding function to use.
            collection_name: name of the Astra DB collection to create/use.
            token: API token for Astra DB usage.
            api_endpoint: full URL to the API endpoint, such as
                `https://<DB-ID>-us-east1.apps.astra.datastax.com`.
            astra_db_client: *alternative to token+api_endpoint*,
                you can pass an already-created 'astrapy.db.AstraDB' instance.
            async_astra_db_client: *alternative to token+api_endpoint*,
                you can pass an already-created 'astrapy.db.AsyncAstraDB' instance.
            namespace: namespace (aka keyspace) where the collection is created.
                Defaults to the database's "default namespace".
            metric: similarity function to use out of those available in Astra DB.
                If left out, it will use Astra DB API's defaults (i.e. "cosine" - but,
                for performance reasons, "dot_product" is suggested if embeddings are
                normalized to one).
            batch_size: Size of batches for bulk insertions.
            bulk_insert_batch_concurrency: Number of threads or coroutines to insert
                batches concurrently.
            bulk_insert_overwrite_concurrency: Number of threads  or coroutines in a
                batch to insert pre-existing entries.
            bulk_delete_concurrency: Number of threads (for deleting multiple rows
                concurrently).
            pre_delete_collection: whether to delete the collection before creating it.
                If False and the collection already exists, the collection will be used
                as is.

        Note:
            For concurrency in synchronous :meth:`~add_texts`:, as a rule of thumb, on a
            typical client machine it is suggested to keep the quantity
            bulk_insert_batch_concurrency * bulk_insert_overwrite_concurrency
            much below 1000 to avoid exhausting the client multithreading/networking
            resources. The hardcoded defaults are somewhat conservative to meet
            most machines' specs, but a sensible choice to test may be:

            - bulk_insert_batch_concurrency = 80
            - bulk_insert_overwrite_concurrency = 10

            A bit of experimentation is required to nail the best results here,
            depending on both the machine/network specs and the expected workload
            (specifically, how often a write is an update of an existing id).
            Remember you can pass concurrency settings to individual calls to
            :meth:`~add_texts` and :meth:`~add_documents` as well.
        N)
rX   rK   rL   rM   rN   rO   rU   rV   embedding_dimensionrP   )rW   rX   rK   rL   rO   DEFAULT_BATCH_SIZErQ   %DEFAULT_BULK_INSERT_BATCH_CONCURRENCYrR   )DEFAULT_BULK_INSERT_OVERWRITE_CONCURRENCYrS   DEFAULT_BULK_DELETE_CONCURRENCYrT   rP   r   ASYNC_aget_embedding_dimensionSYNC_get_embedding_dimensionr   	astra_envastra_dbasync_astra_db
collectionasync_collection)selfrW   rX   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   ra   s                   r3   __init__zAstraDB.__init__[   s.   h #.
(")?-?)R-R 	* . 98 	.
 $F'F 	$ @D(("&"@"@"B"B9>))"&"?"?"A"A6+%+"7!"7 3
 
 
 /"n;.3 $ ?r5   intc                R    t          | j                            d                    S NzThis is a sample sentence.)text)lenrW   embed_queryro   s    r3   ri   z AstraDB._get_embedding_dimension   s$    4>--3O-PPQQQr5   c                b   K   t          | j                            d           d {V           S rs   )ru   rW   aembed_queryrw   s    r3   rg   z!AstraDB._aget_embedding_dimension   s:      44:V4WWWWWWWWXXXr5   c                    | j         S r+   )rW   rw   s    r3   
embeddingszAstraDB.embeddings   s
    ~r5   similarity0to1floatc                    | S )z?Keep similarity from client unchanged ad it's in [0:1] already.r@   )r|   s    r3   _dont_flip_the_cos_scorez AstraDB._dont_flip_the_cos_score   s
     r5   Callable[[float], float]c                    | j         S )z
        The underlying API calls 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:
        )r   rw   s    r3   _select_relevance_score_fnz"AstraDB._select_relevance_score_fn   s     ,,r5   c                l    | j                                          | j                            i            dS z/Empty the collection of all its stored entries.N)rj   ensure_db_setuprm   delete_manyrw   s    r3   clearzAstraDB.clear   s2    &&(((##B'''''r5   c                   K   | j                                          d{V  | j                            i            d{V  dS r   )rj   aensure_db_setuprn   r   rw   s    r3   aclearzAstraDB.aclear   s[      n--/////////#//33333333333r5   document_idc                    | j                                          | j                            |          }|pi                     d          pi                     dd          dk    S )
        Remove a single document from the store, given its document ID.

        Args:
            document_id: The document ID

        Returns
            True if a document has indeed been deleted, False if ID not found.
        statusdeletedCountr      )rj   r   rm   
delete_onegetro   r   deletion_responses      r3   delete_by_document_idzAstraDB.delete_by_document_id   sk     	&&((( O66{CC"(b--h77=2BBA
 
 	r5   c                   K   | j                                          d{V  | j                            |           d{V }|pi                     d          pi                     dd          dk    S )r   Nr   r   r   r   )rj   r   rn   r   r   r   s      r3   adelete_by_document_idzAstraDB.adelete_by_document_id
  s       n--/////////"&"7"B"B;"O"OOOOOOO"(b--h77=2BBA
 
 	r5   idsOptional[List[str]]concurrencykwargsr   Optional[bool]c           	     r   |rJt          j        dd                    t          |                                                     d           |t          d          |p| j        }t          |          5 }t          |	                    | j
        |                    }ddd           n# 1 swxY w Y   dS )a+  Delete by vector ids.

        Args:
            ids: List of ids to delete.
            concurrency: max number of threads issuing single-doc delete requests.
                Defaults to instance-level setting.

        Returns:
            True if deletion is successful, False otherwise.
        zLMethod 'delete' of AstraDB vector store invoked with unsupported arguments (, ), which will be ignored.NNo ids provided to delete.max_workersT)warningswarnjoinsortedkeys
ValueErrorrT   r   rG   mapr   )ro   r   r   r   _max_workerstpe_s          r3   deletezAstraDB.delete  s	   "  	M)*.))F6;;==4I4I*J*J) ) )   ;9:::"Bd&BL999 	S.  A	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ts   7)B,,B03B0c           	        K   |rJt          j        dd                    t          |                                                     d           |t          d          t          t          |g fd|D             R   d{V           S )ai  Delete by vector ids.

        Args:
            ids: List of ids to delete.
            concurrency: max concurrency of single-doc delete requests.
                Defaults to instance-level setting.
            **kwargs: Other keyword arguments that subclasses might use.

        Returns:
            True if deletion is successful, False otherwise.
        zMMethod 'adelete' of AstraDB vector store invoked with unsupported arguments (r   r   Nr   c                :    g | ]}                     |          S r@   )r   )rB   doc_idro   s     r3   rD   z#AstraDB.adelete.<locals>.<listcomp>\  s'    UUUvt::6BBUUUr5   )r   r   r   r   r   r   allr   )ro   r   r   r   s   `   r3   adeletezAstraDB.adelete?  s      "  	M)*.))F6;;==4I4I*J*J) ) )   ;9:::)UUUUQTUUU        
 
 	
r5   c                x    | j                                          | j                            | j                   dS )z
        Completely delete the collection from the database (as opposed
        to :meth:`~clear`, which empties it only).
        Stored data is lost and unrecoverable, resources are freed.
        Use with caution.
        rX   N)rj   r   rk   delete_collectionrX   rw   s    r3   r   zAstraDB.delete_collection`  sG     	&&((('' 0 	( 	
 	
 	
 	
 	
r5   c                   K   | j                                          d{V  | j                            | j                   d{V  dS )z
        Completely delete the collection from the database (as opposed
        to :meth:`~aclear`, which empties it only).
        Stored data is lost and unrecoverable, resources are freed.
        Use with caution.
        Nr   )rj   r   rl   r   rX   rw   s    r3   adelete_collectionzAstraDB.adelete_collectionl  s|       n--/////////!33 0 4 
 
 	
 	
 	
 	
 	
 	
 	
 	
 	
r5   textsIterable[str]embedding_vectorsList[List[float]]	metadatasOptional[List[dict]]List[DocDict]c                    |d | D             }|d | D             }d t          | |||          D             }t          |d d d         d           d d d         }|S )Nc                >    g | ]}t          j                    j        S r@   )uuiduuid4hexrB   r   s     r3   rD   z4AstraDB._get_documents_to_insert.<locals>.<listcomp>  s!    3334:<<#333r5   c                    g | ]}i S r@   r@   r   s     r3   rD   z4AstraDB._get_documents_to_insert.<locals>.<listcomp>  s    ++++++r5   c                &    g | ]\  }}}}||||d S ))content_id$vectormetadatar@   )rB   b_txtb_embb_idb_mds        r3   rD   z4AstraDB._get_documents_to_insert.<locals>.<listcomp>  sE     
 
 
 )udD !  	 
 
 
r5   c                    | d         S )Nr   r@   )documents    r3   <lambda>z2AstraDB._get_documents_to_insert.<locals>.<lambda>  s
    Xe_ r5   )zipr4   )r   r   r   r   documents_to_insertuniqued_documents_to_inserts         r3   _get_documents_to_insertz AstraDB._get_documents_to_insertx  s     ;33U333C++U+++I
 
 -0!	- -
 
 
 '3"%,,'
 '
 $B$'# +*r5   document_batchinsert_resultTuple[List[str], List[DocDict]]c                   d|vrt          dt          |                     |d         d         }d | D             t          |          z
  |                    dg           }t	          |          }t          d |D                       }|t	                    k    s|rt          dt          |                     fd| D             }||fS )Nr   z,API Exception while running bulk insertion: insertedIdsc                    h | ]
}|d          S r   r@   )rB   r   s     r3   	<setcomp>z2AstraDB._get_missing_from_batch.<locals>.<setcomp>  s    NNN8xNNNr5   errorsc              3  H   K   | ]}|                     d           dk    V  dS )	errorCodeDOCUMENT_ALREADY_EXISTSN)r   )rB   errors     r3   	<genexpr>z2AstraDB._get_missing_from_batch.<locals>.<genexpr>  sE        
  
DIEIIk""&?? 
  
  
  
  
  
r5   c                (    g | ]}|d          v |S r   r@   )rB   r   missed_inserted_idss     r3   rD   z3AstraDB._get_missing_from_batch.<locals>.<listcomp>  s3     
 
 
"555 555r5   )r   rY   r,   r   ru   any)r   r   batch_insertedr   
num_errorsunexpected_errorsmissing_from_batchr   s          @r3   _get_missing_from_batchzAstraDB._get_missing_from_batch  s5    =((Ss=?Q?QSS   'x0?NN~NNNQTR
 R
 
 ""8R00[[
  
  
MS 
  
  
 
 
 011115F1Ls6{{LL  
 
 
 
*
 
 

 111r5   )rQ   batch_concurrencyoverwrite_concurrencyr   r   	List[str]c          	     ,    |rJt          j        dd                    t          |                                                     d            j                                          j                            t          |                    } 
                    ||||          }	d fd}
|p j        }t          |	          5 }|                    |
t          |p j        |	                    }d
d
d
           n# 1 swxY w Y   d |D             S )  Run texts through the embeddings and add them to the vectorstore.

        If passing explicit ids, those entries whose id is in the store already
        will be replaced.

        Args:
            texts: Texts to add to the vectorstore.
            metadatas: Optional list of metadatas.
            ids: Optional list of ids.
            batch_size: Number of documents in each API call.
                Check the underlying Astra DB HTTP API specs for the max value
                (20 at the time of writing this). If not provided, defaults
                to the instance-level setting.
            batch_concurrency: number of threads to process
                insertion batches concurrently. Defaults to instance-level
                setting if not provided.
            overwrite_concurrency:  number of threads to process
                pre-existing documents in each batch (which require individual
                API calls). Defaults to instance-level setting if not provided.

        Note:
            There are constraints on the allowed field names
            in the metadata dictionaries, coming from the underlying Astra DB API.
            For instance, the `$` (dollar sign) cannot be used in the dict keys.
            See this document for details:
            https://docs.datastax.com/en/astra/astra-db-vector/api-reference/data-api.html

        Returns:
            The list of ids of the added texts.
        zOMethod 'add_texts' of AstraDB vector store invoked with unsupported arguments (r   r   r   r   r)   r   c                2   	j                             | ddid          }	                    | |          \  }}d	fd	}p	j        }t	          |
          5 }t          |                    ||                    }d d d            n# 1 swxY w Y   ||z   S )NorderedFT	documentsoptionspartial_failures_allowedmissing_documentDocDictr)   rY   c                t    j                             d| d         i|           }|d         d         d         S Nr   )filterreplacementdatar   )rm   find_one_and_replacer   replacement_resultro   s     r3   _handle_missing_documentzJAstraDB.add_texts.<locals>._handle_batch.<locals>._handle_missing_document  sI    %)_%I%I!#3E#:; 0 &J & &" *&1*=eDDr5   r   r   r   r)   rY   )rm   insert_manyr   rS   r   rG   r   )
r   	im_resultr   r   r  _u_max_workerstpe2batch_replacedr   ro   s
           r3   _handle_batchz(AstraDB.add_texts.<locals>._handle_batch  s   33("E*)- 4  I
 261M1M	2 2.N.E E E E E E &O)O  $??? 4!%HH0* " "               "N22s   $B		BBr   Nc                    g | ]	}|D ]}|
S r@   r@   rB   id_listiids      r3   rD   z%AstraDB.add_texts.<locals>.<listcomp>  %    EEEWEEcEEEEr5   r   r   r)   r   )r   r   r   r   r   rj   r   rW   embed_documentsrG   r   rR   r   r   r   rQ   )ro   r   r   r   rQ   r   r   r   r   r   r	  _b_max_workersr   all_ids_nesteds   `     `       r3   	add_textszAstraDB.add_texts  s   T  	M)*.))F6;;==4I4I*J*J) ) )  
 	&&((( N::4;;GG";;$i
 
	3 	3 	3 	3 	3 	3 	3: +Pd.PN;;; 	s WW1$/'  N	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 FE>EEEEs   ,C??DDc          	        K   |rJt          j        dd                    t          |                                                     d            j                                         d{V   j                            t          |                     d{V } 
                    ||||          }	d fd	|p j        }
t          |
gfd
t          |p j        |	          D             R   d{V }d |D             S )r   zPMethod 'aadd_texts' of AstraDB vector store invoked with unsupported arguments (r   r   Nr   r   r)   r   c                   K   j                             | ddid           d {V }                    | |          \  }}dfd	pj        }t	          |gfd
|D             R   d {V }||z   S )Nr   FTr   r   r   r)   rY   c                   K   j                             d| d         i|            d {V }|d         d         d         S r   )rn   r   r   s     r3   r  zKAstraDB.aadd_texts.<locals>._handle_batch.<locals>._handle_missing_documentW  sl      +/+@+U+U!#3E#:; 0 ,V , , & & & & & &" *&1*=eDDr5   c                &    g | ]} |          S r@   r@   )rB   docr  s     r3   rD   z=AstraDB.aadd_texts.<locals>._handle_batch.<locals>.<listcomp>c  s%    NNNC**3//NNNr5   r  )rn   r  r   rS   r   )	r   r  r   r   r  r  r  r   ro   s	         @r3   r	  z)AstraDB.aadd_texts.<locals>._handle_batchM  s     "3??("E*)- @        I
 261M1M	2 2.N.E E E E E E &O)O  $;$NNNN;MNNN$ $ $      N "N22r5   c                &    g | ]} |          S r@   r@   )rB   batchr	  s     r3   rD   z&AstraDB.aadd_texts.<locals>.<listcomp>j  s3        e$$  r5   c                    g | ]	}|D ]}|
S r@   r@   r  s      r3   rD   z&AstraDB.aadd_texts.<locals>.<listcomp>s  r  r5   r  )r   r   r   r   r   rj   r   rW   aembed_documentsrG   r   rR   r   r   rQ   )ro   r   r   r   rQ   r   r   r   r   r   r  r  r	  s   `     `     @r3   
aadd_textszAstraDB.aadd_texts  s     R  	M)*.))F6;;==4I4I*J*J) ) )  
 n--/////////"&."A"A$u++"N"NNNNNNN";;$i
 
	3 	3 	3 	3 	3 	3 	34 +Pd.P6	 
   *1$/'   	 
 	 
 	 
 	
 	
 	
 	
 	
 	
 FE>EEEEr5      List[float]rI   r   !List[Tuple[Document, float, str]]c                    | j                                          |                     |          }t          | j                            |d|i|dddddd                    }d |D             S )r  Return docs most similar to embedding vector with score and id.

        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.

        Returns:
            The list of (Document, score, id), the most similar to the query vector.
        r   TlimitincludeSimilarityr   r   r   r   r   sortr   
projectionc                f    g | ].}t          |d          |d                   |d         |d         f/S )r   r   page_contentr   $similarityr   r   rB   hits     r3   rD   zEAstraDB.similarity_search_with_score_id_by_vector.<locals>.<listcomp>  s]     

 

 

  !$Y _   M"E


 

 

r5   )rj   r   rA   rG   rm   paginated_find)ro   rW   rI   r   metadata_parameterhitss         r3   )similarity_search_with_score_id_by_vectorz1AstraDB.similarity_search_with_score_id_by_vectoru  s      	&&(((!55f==O**)+"#$??  ! 	 + 	 	
 


 

 

 

 

 
	
r5   c           
        K   | j                                          d{V  |                     |          }d | j                            |d|i|dddddd          2              d{V S )	r"  Nc                x   K   g | 3 d {V 	 }t          |d         |d                   |d         |d         f56 S )Nr   r   r+  r-  r   r   r.  s     r3   rD   zFAstraDB.asimilarity_search_with_score_id_by_vector.<locals>.<listcomp>  s       
 
 
 
 
 
 
 
 
  !$Y _   M"E

 
 
 
s   :r   Tr#  r   r&  r'  )rj   r   rA   rn   r0  )ro   rW   rI   r   r1  s        r3   *asimilarity_search_with_score_id_by_vectorz2AstraDB.asimilarity_search_with_score_id_by_vector  s        n--/////////!55f==
 
 "2AA)+"#$??  ! 	 B 	 	
 
 
 
 
 
 
 
 
 	
r5   queryc                f    | j                             |          }|                     |||          S )\  Return docs most similar to the query with score and id.

        Args:
            query: Query to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            filter: Filter on the metadata to apply.

        Returns:
            The list of (Document, score, id), the most similar to the query.
        rW   rI   r   )rW   rv   r3  ro   r7  rI   r   embedding_vectors        r3   similarity_search_with_score_idz'AstraDB.similarity_search_with_score_id  s@       >55e<<==& > 
 
 	
r5   c                   K   | j                             |           d{V }|                     |||           d{V S )r9  Nr:  )rW   ry   r6  r;  s        r3    asimilarity_search_with_score_idz(AstraDB.asimilarity_search_with_score_id  su        "&!<!<U!C!CCCCCCCDD& E 
 
 
 
 
 
 
 
 	
r5   List[Tuple[Document, float]]c                F    d |                      |||          D             S )g  Return docs most similar to embedding vector with score.

        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.

        Returns:
            The list of (Document, score), the most similar to the query vector.
        c                    g | ]
\  }}}||fS r@   r@   rB   r  scorer   s       r3   rD   zBAstraDB.similarity_search_with_score_by_vector.<locals>.<listcomp>  s2     
 
 
$eV %L
 
 
r5   r:  )r3  ro   rW   rI   r   s       r3   &similarity_search_with_score_by_vectorz.AstraDB.similarity_search_with_score_by_vector  sB     
 
(,(V(V# )W ) )
 
 
 	
r5   c                V   K   d |                      |||           d{V D             S )rB  c                    g | ]
\  }}}||fS r@   r@   rD  s       r3   rD   zCAstraDB.asimilarity_search_with_score_by_vector.<locals>.<listcomp>   s7     
 
 
	 %L
 
 
r5   r:  N)r6  rF  s       r3   'asimilarity_search_with_score_by_vectorz/AstraDB.asimilarity_search_with_score_by_vector  sf       
 
 FF# G        
 
 
 	
r5   List[Document]c                f    | j                             |          }|                     |||          S )5  Return docs most similar to query.

        Args:
            query: Query to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            filter: Filter on the metadata to apply.

        Returns:
            The list of Documents most similar to the query.
        r   )rW   rv   similarity_search_by_vectorro   r7  rI   r   r   r<  s         r3   similarity_searchzAstraDB.similarity_search-  s@    "  >55e<<// 0 
 
 	
r5   c                   K   | j                             |           d{V }|                     |||           d{V S )rM  NrN  )rW   ry   asimilarity_search_by_vectorrP  s         r3   asimilarity_searchzAstraDB.asimilarity_searchE  st      " "&!<!<U!C!CCCCCCC66 7 
 
 
 
 
 
 
 
 	
r5   c                F    d |                      |||          D             S )O  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.

        Returns:
            The list of Documents most similar to the query vector.
        c                    g | ]\  }}|S r@   r@   rB   r  r   s      r3   rD   z7AstraDB.similarity_search_by_vector.<locals>.<listcomp>n  ,     
 
 
Q 
 
 
r5   rN  )rG  ro   rW   rI   r   r   s        r3   rO  z#AstraDB.similarity_search_by_vector]  sB    "
 
EE F  
 
 
 	
r5   c                V   K   d |                      |||           d{V D             S )rV  c                    g | ]\  }}|S r@   r@   rX  s      r3   rD   z8AstraDB.asimilarity_search_by_vector.<locals>.<listcomp>  rY  r5   rN  N)rJ  rZ  s        r3   rS  z$AstraDB.asimilarity_search_by_vectorw  sd      "
 
 $ L L !M ! !      
 
 
 	
r5   c                f    | j                             |          }|                     |||          S )T  Return docs most similar to query with score.

        Args:
            query: Query to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            filter: Filter on the metadata to apply.

        Returns:
            The list of (Document, score), the most similar to the query vector.
        rN  )rW   rv   rG  r;  s        r3   similarity_search_with_scorez$AstraDB.similarity_search_with_score  s@       >55e<<:: ; 
 
 	
r5   c                   K   | j                             |           d{V }|                     |||           d{V S )r^  NrN  )rW   ry   rJ  r;  s        r3   asimilarity_search_with_scorez%AstraDB.asimilarity_search_with_score  su        "&!<!<U!C!CCCCCCCAA B 
 
 
 
 
 
 
 
 	
r5   lambda_multprefetch_hitsc                    t          t          j        | t          j                  d |D             ||          fdt	          |          D             }d |D             S )N)dtypec                    g | ]
}|d          S )r   r@   )rB   prefetch_hits     r3   rD   z)AstraDB._get_mmr_hits.<locals>.<listcomp>  s    GGG\)$GGGr5   )rI   rb  c                "    g | ]\  }}|v 	|S r@   r@   )rB   prefetch_indexrg  mmr_chosen_indicess      r3   rD   z)AstraDB._get_mmr_hits.<locals>.<listcomp>  s3     
 
 
,!333 333r5   c                H    g | ]}t          |d          |d                    S )r   r   r+  r   r.  s     r3   rD   z)AstraDB._get_mmr_hits.<locals>.<listcomp>  sG     
 
 

 	  ^Z  
 
 
r5   )r   nparrayfloat32	enumerate)rW   rI   rb  rc  mmr_hitsrj  s        @r3   _get_mmr_hitszAstraDB._get_mmr_hits  s     8HYbj111GGGGG#	
 
 

 
 
 
09-0H0H
 
 


 

  
 
 
 	
r5   r"         ?fetch_kc                    | j                                          |                     |          }t          | j                            |d|i|ddddddd                    }|                     ||||          S )  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.
            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.
            filter: Filter on the metadata to apply.

        Returns:
            The list of Documents selected by maximal marginal relevance.
        r   Tr#  r   r   r   r   r   r'  )rj   r   rA   rG   rm   r0  rq  	ro   rW   rI   rs  rb  r   r   r1  rc  s	            r3   'max_marginal_relevance_search_by_vectorz/AstraDB.max_marginal_relevance_search_by_vector  s    4 	&&(((!55f==O**)+")EE  ! 	 	 + 
 

 
 !!)Q]KKKr5   c                  K   | j                                          d{V  |                     |          }d | j                            |d|i|ddddddd          2              d{V }|                     ||||          S )	ru  Nc                $   K   g | 3 d {V 	 }|6 S r+   r@   r.  s     r3   rD   zDAstraDB.amax_marginal_relevance_search_by_vector.<locals>.<listcomp>   sO       
 
 
 
 
 
 
 
 
 
 
 
 
s   r   Tr#  r   rv  r'  )rj   r   rA   rn   r0  rq  rw  s	            r3   (amax_marginal_relevance_search_by_vectorz0AstraDB.amax_marginal_relevance_search_by_vector  s      4 n--/////////!55f==
 
!2AA)+")EE  ! 	 	 B 
 

 
 
 
 
 
 
 
 
 !!)Q]KKKr5   c                j    | j                             |          }|                     |||||          S )  Return docs selected using the maximal marginal relevance.

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

        Args:
            query: Query 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.
            filter: Filter on the metadata to apply.

        Returns:
            The list of Documents selected by maximal marginal relevance.
        rb  r   )rW   rv   rx  ro   r7  rI   rs  rb  r   r   r<  s           r3   max_marginal_relevance_searchz%AstraDB.max_marginal_relevance_search1  sF    4  >55e<<;;# < 
 
 	
r5   c                   K   | j                             |           d{V }|                     |||||           d{V S )r}  Nr~  )rW   ry   r{  r  s           r3   amax_marginal_relevance_searchz&AstraDB.amax_marginal_relevance_searchT  s{      4 "&!<!<U!C!CCCCCCCBB# C 
 
 
 
 
 
 
 
 	
r5   clsType[ADBVST]r   c                   h d}|r^t          |                                          |z
  }|r8t          j        dd                    t          |                     d           |d         }|                    d          }|                    d          }|                    d          }|                    d	          }	|                    d
          }
|                    d          } | ||||||	|
||                    d          |                    d          |                    d          |                    d                    S )N>   rK   rP   rO   rQ   rL   rM   rX   r   rN   r   rT   rR   rS   zPMethod 'from_texts' of AstraDB vector store invoked with unsupported arguments (r   r   rX   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   )rW   rX   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   )r,   r   r   r   r   r   r   )r  rW   r   known_kwargsunknown_kwargsrX   rK   rL   rM   rN   rO   rP   s               r3   _from_kwargszAstraDB._from_kwargsw  sj   
 
 
  	 //,>N -.2ii~8N8N.O.O- - -    &&78

7##zz.11 **%677 &

+B C CJJ{++	H%%s+%+"7zz,//*0**5T*U*U.4jj3/ / %+JJ/H$I$I
 
 
 	
r5   c           
         t          j        |fi |}|                    ||||                    d          |                    d          |                    d                     |S )^  Create an Astra DB vectorstore from raw texts.

        Args:
            texts: the texts to insert.
            embedding: the embedding function to use in the store.
            metadatas: metadata dicts for the texts.
            ids: ids to associate to the texts.
            **kwargs: you can pass any argument that you would
                to :meth:`~add_texts` and/or to the 'AstraDB' constructor
                (see these methods for details). These arguments will be
                routed to the respective methods as they are.

        Returns:
            an `AstraDb` vectorstore.
        rQ   r   r   r   r   r   rQ   r   r   )r   r  r  r   r  r   rW   r   r   r   astra_db_stores          r3   
from_textszAstraDB.from_texts  sy    0 !-iBB6BB  zz,//$jj)<=="(**-D"E"E 	! 	
 	
 	
 r5   c           
        K   t          j        |fi |}|                    ||||                    d          |                    d          |                    d                     d{V  |S )r  rQ   r   r   r  N)r   r  r  r   r  s          r3   afrom_textszAstraDB.afrom_texts  s      0 !-iBB6BB''zz,//$jj)<=="(**-D"E"E ( 
 
 	
 	
 	
 	
 	
 	
 	
 r5   r   c                :     t                      j        ||fi |S )a6  Create an Astra DB vectorstore from a document list.

        Utility method that defers to 'from_texts' (see that one).

        Args: see 'from_texts', except here you have to supply 'documents'
            in place of 'texts' and 'metadatas'.

        Returns:
            an `AstraDB` vectorstore.
        )superfrom_documents)r  r   rW   r   	__class__s       r3   r  zAstraDB.from_documents  s&    " &uww%iEEfEEEr5   )r:   r;   r)   r<   )rW   r   rX   rY   rK   rZ   rL   rZ   rM   r[   rN   r\   rO   rZ   rP   rZ   rQ   r]   rR   r]   rS   r]   rT   r]   rU   r   rV   r^   r)   r_   )r)   rq   )r)   r   )r|   r}   r)   r}   )r)   r   )r)   r_   )r   rY   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   r   r   r   r   r   rQ   r]   r   r]   r   r]   r   r   r)   r   )r  N)rW   r  rI   rq   r   r;   r)   r   )r7  rY   rI   rq   r   r;   r)   r   )rW   r  rI   rq   r   r;   r)   r@  )
r7  rY   rI   rq   r   r;   r   r   r)   rK  )
rW   r  rI   rq   r   r;   r   r   r)   rK  )r7  rY   rI   rq   r   r;   r)   r@  )
rW   r  rI   rq   rb  r}   rc  r   r)   rK  )r  r"   rr  N)rW   r  rI   rq   rs  rq   rb  r}   r   r;   r   r   r)   rK  )r7  rY   rI   rq   rs  rq   rb  r}   r   r;   r   r   r)   rK  )r  r  rW   r   r   r   r)   r   )r  r  r   r   rW   r   r   r   r   r   r   r   r)   r   )
r  r  r   rK  rW   r   r   r   r)   r   )1__name__
__module____qualname__staticmethodrA   r   rh   rp   ri   rg   propertyr{   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r3  r6  r=  r?  rG  rJ  rQ  rT  rO  rS  r_  ra  rq  rx  r{  r  r  classmethodr  r  r  r  __classcell__)r  s   @r3   r   r   D   s        # # # \#*  $&*048<#' $$(7;;?15 )&+!|@ |@ |@ |@ |@ |@|R R R RY Y Y Y    X    \- - - -( ( ( (
4 4 4 4
       $ $(%)# # # # #N $(%)
 
 
 
 
B

 

 

 



 

 

 

  +/#'	+ + + + \+@ 2 2 2 \2B +/#'	]F %)+//3]F ]F ]F ]F ]F ]FD +/#'	\F %)+//3\F \F \F \F \F \FB +/	*
 *
 *
 *
 *
^ +/	&
 &
 &
 &
 &
V +/	
 
 
 
 
4 +/	
 
 
 
 
4 +/	
 
 
 
 
8 +/	
 
 
 
 
@ +/	
 
 
 
 
6 +/	
 
 
 
 
6 +/	
 
 
 
 
: +/	
 
 
 
 
: +/	
 
 
 
 
4 +/	
 
 
 
 
. 
 
 
 \
2  +/+L +L +L +L +L`  +/,L ,L ,L ,L ,Lb  +/!
 !
 !
 !
 !
L  +/!
 !
 !
 !
 !
F 4
 4
 4
 [4
l 
 +/#'        [ D 
 +/#'        [ D F F F F F [F F F F Fr5   )r%   r&   r'   r(   r)   r&   )5
__future__r   r   r   concurrent.futuresr   typingr   r   r   r   r	   r
   r   r   r   r   r   r   r   numpyrl  langchain_core._api.deprecationr   langchain_core.documentsr   langchain_core.embeddingsr   langchain_core.runnables.utilsr   langchain_core.utils.iterr   langchain_core.vectorstoresr   %langchain_community.utilities.astradbr   r   &langchain_community.vectorstores.utilsr   
astrapy.dbr   
LibAstraDBr   r   r    r!   rY   r   rb   rc   rd   re   r4   r@   r5   r3   <module>r     s   " " " " " "   1 1 1 1 1 1                                   6 6 6 6 6 6 - - - - - - 0 0 0 0 0 0 B B B B B B 3 3 3 3 3 3 3 3 3 3 3 3        N M M M M M (000000''''''		+	+	+GCLLGCLL
sCx.
  (* %,. )"$     
=  
|F |F |F |F |Fk |F |F 
|F |F |Fr5   