
    _jT                         d dl mZmZmZmZ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mZmZmZmZmZmZmZ d dlmZ d dlmZ d dlm Z  erd dl!m"Z"  G d ded	                   Z#d
S )    )TYPE_CHECKINGOptionalUnionListcast)URICollectionMetadata	EmbeddingPyEmbeddingIncludeIndexingStatusMetadataDocumentImageWhereIDs	GetResultQueryResultID	OneOrMany	ReadLevelWhereDocumentSearchResultDeleteResultmaybe_cast_one_to_many)CollectionCommon)UpdateCollectionConfiguration)Search)AsyncServerAPIc                      e Zd Z	 	 	 	 	 d(dee         deeee         ee         f                  deee	                  deee
                  deee                  deee                  ddfd	Zej        fd
edefdZdefdZdddddddgfdeee                  dee         dee         dee         dee         dedefdZd)dedefdZddddddddg df	deeee         ee         f                  deee
                  deee                  deee                  deee                  dedee         dee         dedefdZ	 	 	 d*dee         dee         dee         ddfdZd edd fd!Z defd"Z!ej        fd#ee"         d
ede#fd$Z$	 	 	 	 	 d(dee         deeee         ee         f                  deee	                  deee
                  deee                  deee                  ddfd%Z%	 	 	 	 	 d(dee         deeee         ee         f                  deee	                  deee
                  deee                  deee                  ddfd&Z&	 	 	 	 d+dee'         dee         dee         dee         de(f
d'Z)dS ),AsyncCollectionNids
embeddings	metadatas	documentsimagesurisreturnc           
         K   |                      ||||||          }| j                            | j        |d         |d         |d         |d         |d         | j        | j                   d{V  dS )	a]  Add embeddings to the data store.
        Args:
            ids: The ids of the embeddings you wish to add
            embeddings: The embeddings to add. If None, embeddings will be computed based on the documents or images using the embedding_function set for the Collection. Optional.
            metadatas: The metadata to associate with the embeddings. When querying, you can filter on this metadata. Optional.
            documents: The documents to associate with the embeddings. Optional.
            images: The images to associate with the embeddings. Optional.
            uris: The uris of the images to associate with the embeddings. Optional.

        Returns:
            None

        Raises:
            ValueError: If you don't provide either embeddings or documents
            ValueError: If the length of ids, embeddings, metadatas, or documents don't match
            ValueError: If you don't provide an embedding function and don't provide embeddings
            ValueError: If you provide both embeddings and documents
            ValueError: If you provide an id that already exists

        r"   r#   r$   r%   r&   r'   r"   r#   r$   r%   r'   collection_idr"   r#   r$   r%   r'   tenantdatabaseN)!_validate_and_prepare_add_request_client_addidr-   r.   )selfr"   r#   r$   r%   r&   r'   add_requests           `/var/www/FlaskApp/flask-venv/lib/python3.11/site-packages/chromadb/api/models/AsyncCollection.pyaddzAsyncCollection.add#   s      D <<! = 
 
 l'E""<0!+.!+.V$;]   	
 	
 		
 		
 		
 		
 		
 		
 		
 		
 		
    
read_levelc                 l   K   | j                             | j        | j        | j        |           d{V S )a  Return the number of records in the collection.

        Args:
            read_level: Controls whether to read from the write-ahead log (WAL):
                - ReadLevel.INDEX_AND_WAL: Read from both the compacted index and WAL (default).
                  All committed writes will be visible.
                - ReadLevel.INDEX_ONLY: Read only from the compacted index, skipping the WAL.
                  Faster, but recent writes that haven't been compacted may not be visible.
                - ReadLevel.INDEX_AND_BOUNDED_WAL: Read from the index and up to a
                  server-configured number of WAL entries for bounded query latency.

        Returns:
            int: The total number of embeddings added to the database
        )r,   r-   r.   r8   N)r0   _countr2   r-   r.   )r3   r8   s     r5   countzAsyncCollection.countY   sW       \((';]!	 ) 
 
 
 
 
 
 
 
 	
r7   c                 j   K   | j                             | j        | j        | j                   d{V S )a  Get the indexing status of this collection.

        Returns:
            IndexingStatus: An object containing:
                - num_indexed_ops: Number of user operations that have been indexed
                - num_unindexed_ops: Number of user operations pending indexing
                - total_ops: Total number of user operations in collection
                - op_indexing_progress: Proportion of user operations that have been indexed as a float between 0 and 1
        r,   r-   r.   N)r0   _get_indexing_statusr2   r-   r.   r3   s    r5   get_indexing_statusz#AsyncCollection.get_indexing_statuso   sT       \66';] 7 
 
 
 
 
 
 
 
 	
r7   wherelimitoffsetwhere_documentincludec                   K   |                      ||||          }| j                            | j        |d         |d         |d         |d         ||| j        | j        	  	         d{V }|                     ||d                   S )	a  Get embeddings and their associate data from the data store. If no ids or where filter is provided returns
        all embeddings up to limit starting at offset.

        Args:
            ids: The ids of the embeddings to get. Optional.
            where: A Where type dict used to filter results by. E.g. `{"$and": [{"color" : "red"}, {"price": {"$gte": 4.20}}]}`. Optional.
            limit: The number of documents to return. Optional.
            offset: The offset to start returning results from. Useful for paging results with limit. Optional.
            where_document: A WhereDocument type dict used to filter by the documents. E.g. `{"$contains": "hello"}`. Optional.
            include: A list of what to include in the results. Can contain `"embeddings"`, `"metadatas"`, `"documents"`. Ids are always included. Defaults to `["metadatas", "documents"]`. Optional.

        Returns:
            GetResult: A GetResult object containing the results.

        )r"   rA   rD   rE   r"   rA   rD   rE   )	r,   r"   rA   rD   rE   rB   rC   r-   r.   NresponserE   )!_validate_and_prepare_get_requestr0   _getr2   r-   r.   _transform_get_response)	r3   r"   rA   rB   rC   rD   rE   get_requestget_resultss	            r5   getzAsyncCollection.get   s      0 <<)	 = 
 
 !L--'E"g&&'78	*;] . 

 

 

 

 

 

 

 

 ++ +i*@ , 
 
 	
r7   
   c                    K   |                      | j                            | j        || j        | j                   d{V           S )zGet the first few results in the database up to limit

        Args:
            limit: The number of results to return.

        Returns:
            GetResult: A GetResult object containing the results.
        )r,   nr-   r.   N)_transform_peek_responser0   _peekr2   r-   r.   )r3   rB   s     r5   peekzAsyncCollection.peek   sj       ,,,$$"g{	 %        
 
 	
r7   )r$   r%   	distancesquery_embeddingsquery_textsquery_images
query_uris	n_resultsc
                 4  K   |                      |||||||||		  	        }
| j                            | j        |
d         |
d         |
d         |
d         |
d         |
d         | j        | j        	  	         d	{V }|                     ||
d         
          S )a  Get the n_results nearest neighbor embeddings for provided query_embeddings or query_texts.

        Args:
            query_embeddings: The embeddings to get the closes neighbors of. Optional.
            query_texts: The document texts to get the closes neighbors of. Optional.
            query_images: The images to get the closes neighbors of. Optional.
            ids: A subset of ids to search within. Optional.
            n_results: The number of neighbors to return for each query_embedding or query_texts. Optional.
            where: A Where type dict used to filter results by. E.g. `{"$and": [{"color" : "red"}, {"price": {"$gte": 4.20}}]}`. Optional.
            where_document: A WhereDocument type dict used to filter by the documents. E.g. `{"$contains": "hello"}`. Optional.
            include: A list of what to include in the results. Can contain `"embeddings"`, `"metadatas"`, `"documents"`, `"distances"`. Ids are always included. Defaults to `["metadatas", "documents", "distances"]`. Optional.

        Returns:
            QueryResult: A QueryResult object containing the results.

        Raises:
            ValueError: If you don't provide either query_embeddings, query_texts, or query_images
            ValueError: If you provide both query_embeddings and query_texts
            ValueError: If you provide both query_embeddings and query_images
            ValueError: If you provide both query_texts and query_images

        )	rV   rW   rX   rY   r"   rZ   rA   rD   rE   r"   r#   rZ   rA   rD   rE   )	r,   r"   rV   rZ   rA   rD   rE   r-   r.   NrG   )#_validate_and_prepare_query_requestr0   _queryr2   r-   r.   _transform_query_response)r3   rV   rW   rX   rY   r"   rZ   rA   rD   rE   query_requestquery_resultss               r5   queryzAsyncCollection.query   s      X @@-#%!) A 

 

 #l11'e$*<8#K0(()9:!),;] 2 

 

 

 

 

 

 

 

 --"M),D . 
 
 	
r7   namemetadataconfigurationc                    K   |                      |           | j                            | j        |||| j        | j                   d{V  |                     |||           dS )zModify the collection name or metadata

        Args:
            name: The updated name for the collection. Optional.
            metadata: The updated metadata for the collection. Optional.

        Returns:
            None
        )r2   new_namenew_metadatanew_configurationr-   r.   N)_validate_modify_requestr0   _modifyr2   r-   r.   "_update_model_after_modify_success)r3   rb   rc   rd   s       r5   modifyzAsyncCollection.modify  s        	%%h///
 l""w!+;] # 
 
 	
 	
 	
 	
 	
 	
 	
 	//hNNNNNr7   rf   c                    K   | j                             | j        || j        | j                   d{V }t          | j         || j        | j                  S )a  Fork the current collection under a new name. The returning collection should contain identical data to the current collection.
        This only works for Hosted Chroma for now.

        Args:
            new_name: The name of the new collection.

        Returns:
            Collection: A new collection with the specified name and containing identical data to the current collection.
        )r,   rf   r-   r.   N)clientmodelembedding_functiondata_loader)r0   _forkr2   r-   r.   r!   _embedding_function_data_loader)r3   rf   ro   s      r5   forkzAsyncCollection.fork(  s       l((';]	 ) 
 
 
 
 
 
 
 
 <#7)	
 
 
 	
r7   c                 j   K   | j                             | j        | j        | j                   d{V S )zGet the number of forks that exist for this collection.
        This only works for Hosted Chroma for now.

        Returns:
            int: The number of forks for this collection.
        r=   N)r0   _fork_countr2   r-   r.   r?   s    r5   
fork_countzAsyncCollection.fork_countB  sT       \--';] . 
 
 
 
 
 
 
 
 	
r7   searchesc                     K   t          |          }|g } fd|D             } j                             j        t	          t
          t                   |           j         j        |           d{V S )a  Perform hybrid search on the collection.
        This is an experimental API that only works for Hosted Chroma for now.

        Args:
            searches: A single Search object or a list of Search objects, each containing:
                - where: Where expression for filtering
                - rank: Ranking expression for hybrid search (defaults to Val(0.0))
                - limit: Limit configuration for pagination (defaults to no limit)
                - select: Select configuration for keys to return (defaults to empty)
            read_level: Controls whether to read from the write-ahead log (WAL):
                - ReadLevel.INDEX_AND_WAL: Read from both the compacted index and WAL (default).
                  All committed writes will be visible.
                - ReadLevel.INDEX_ONLY: Read only from the compacted index, skipping the WAL.
                  Faster, but recent writes that haven't been compacted may not be visible.
                - ReadLevel.INDEX_AND_BOUNDED_WAL: Read from the index and up to a
                  server-configured number of WAL entries for bounded query latency.

        Returns:
            SearchResult: Column-major format response with:
                - ids: List of result IDs for each search payload
                - documents: Optional documents for each payload
                - embeddings: Optional embeddings for each payload
                - metadatas: Optional metadata for each payload
                - scores: Optional scores for each payload
                - select: List of selected keys for each payload

        Raises:
            NotImplementedError: For local/segment API implementations

        Examples:
            # Using builder pattern with Key constants
            from chromadb.execution.expression import (
                Search, Key, K, Knn, Val
            )

            # Note: K is an alias for Key, so K.DOCUMENT == Key.DOCUMENT
            search = (Search()
                .where((K("category") == "science") & (K("score") > 0.5))
                .rank(Knn(query=[0.1, 0.2, 0.3]) * 0.8 + Val(0.5) * 0.2)
                .limit(10, offset=0)
                .select(K.DOCUMENT, K.SCORE, "title"))

            # Direct construction
            from chromadb.execution.expression import (
                Search, Eq, And, Gt, Knn, Limit, Select, Key
            )

            search = Search(
                where=And([Eq("category", "science"), Gt("score", 0.5)]),
                rank=Knn(query=[0.1, 0.2, 0.3]),
                limit=Limit(offset=0, limit=10),
                select=Select(keys={Key.DOCUMENT, Key.SCORE, "title"})
            )

            # Single search
            result = await collection.search(search)

            # Multiple searches at once
            searches = [
                Search().where(K("type") == "article").rank(Knn(query=[0.1, 0.2])),
                Search().where(K("type") == "paper").rank(Knn(query=[0.3, 0.4]))
            ]
            results = await collection.search(searches)

            # Skip WAL for faster queries (may miss recent uncommitted writes)
            from chromadb.api.types import ReadLevel
            result = await collection.search(search, read_level=ReadLevel.INDEX_ONLY)
        Nc                 :    g | ]}                     |          S  )_embed_search_string_queries).0searchr3   s     r5   
<listcomp>z*AsyncCollection.search.<locals>.<listcomp>  s4     
 
 
:@D--f55
 
 
r7   )r,   ry   r-   r.   r8   )	r   r0   _searchr2   r   r   r   r-   r.   )r3   ry   r8   searches_listembedded_searchess   `    r5   r   zAsyncCollection.searchO  s      T /x88 M
 
 
 
DQ
 
 
 \))'$v,(9::;]! * 
 
 
 
 
 
 
 
 	
r7   c           
         K   |                      ||||||          }| j                            | j        |d         |d         |d         |d         |d         | j        | j                   d{V  dS )	a  Update the embeddings, metadatas or documents for provided ids.

        Args:
            ids: The ids of the embeddings to update
            embeddings: The embeddings to update. If None, embeddings will be computed based on the documents or images using the embedding_function set for the Collection. Optional.
            metadatas:  The metadata to associate with the embeddings. When querying, you can filter on this metadata. Optional.
            documents: The documents to associate with the embeddings. Optional.
            images: The images to associate with the embeddings. Optional.
        Returns:
            None
        r*   r"   r#   r$   r%   r'   r+   N)$_validate_and_prepare_update_requestr0   _updater2   r-   r.   )r3   r"   r#   r$   r%   r&   r'   update_requests           r5   updatezAsyncCollection.update        2 BB! C 
 
 l""'u%%l3$[1$[1';] # 	
 	
 		
 		
 		
 		
 		
 		
 		
 		
 		
r7   c           
         K   |                      ||||||          }| j                            | j        |d         |d         |d         |d         |d         | j        | j                   d{V  dS )	aO  Update the embeddings, metadatas or documents for provided ids, or create them if they don't exist.

        Args:
            ids: The ids of the embeddings to update
            embeddings: The embeddings to add. If None, embeddings will be computed based on the documents using the embedding_function set for the Collection. Optional.
            metadatas:  The metadata to associate with the embeddings. When querying, you can filter on this metadata. Optional.
            documents: The documents to associate with the embeddings. Optional.

        Returns:
            None
        r*   r"   r#   r$   r%   r'   r+   N)$_validate_and_prepare_upsert_requestr0   _upsertr2   r-   r.   )r3   r"   r#   r$   r%   r&   r'   upsert_requests           r5   upsertzAsyncCollection.upsert  r   r7   c           	         K   |                      ||||          }| j                            | j        |d         |d         |d         |d         | j        | j                   d{V S )a1  Delete the embeddings based on ids and/or a where filter

        Args:
            ids: The ids of the embeddings to delete
            where: A Where type dict used to filter the delection by. E.g. `{"$and": [{"color" : "red"}, {"price": {"$gte": 4.20}}]}`. Optional.
            where_document: A WhereDocument type dict used to filter the deletion by the document content. E.g. `{"$contains": "hello"}`. Optional.
            limit: Maximum number of records to delete. Can only be used with where or where_document filters.

        Returns:
            DeleteResult: A dict containing the number of records deleted.

        Raises:
            ValueError: If you don't provide either ids, where, or where_document
            ValueError: If limit is specified without a where or where_document clause.
        )rB   r"   rA   rD   rB   )r,   r"   rA   rD   rB   r-   r.   N)$_validate_and_prepare_delete_requestr0   _deleter2   r-   r.   )r3   r"   rA   rD   rB   delete_requests         r5   deletezAsyncCollection.delete  s      , BBe C 
 
 \))'u% ))*:; );] * 
 
 
 
 
 
 
 
 	
r7   )NNNNN)rO   )NNN)NNNN)*__name__
__module____qualname__r   r   r   r   r
   r   r   r   r   r   r6   r   INDEX_AND_WALintr;   r   r@   r   r   r   r   rN   rT   r   ra   strr	   r   rl   ru   rx   r   r   r   r   r   r   r   r   r|   r7   r5   r!   r!   "   s        3737-1)-4
 4
r]4
 )$+&(
4
 Ih/04
 Ih/04
 5)*4
 y~&4
 
4
 4
 4
 4
l 3<2I 
 
i 
c 
 
 
 
,
> 
 
 
 
$ (,!%# $26'5-
 -
im$-
 -
 }	-

 -
 !/-
 -
 
-
 -
 -
 -
^
 
 
Y 
 
 
 
2 5937/3'+!%26
 
 
F
 F
")$+&(
F
 i12F
 y/0F
 Ys^,F
 im$F
 F
 F
 !/F
 F
( 
)F
 F
 F
 F
T #15AE	O OsmO -.O   =>	O
 
O O O O@

 

 
 
 
4
# 
 
 
 
  !* 7Y
 Y
F#Y
 Y
 
	Y
 Y
 Y
 Y
F 3737-1)-+
 +
r]+
 )$+&(
+
 Ih/0+
 Ih/0+
 5)*+
 y~&+
 
+
 +
 +
 +
j 3737-1)-+
 +
r]+
 )$+&(
+
 Ih/0+
 Ih/0+
 5)*+
 y~&+
 
+
 +
 +
 +
^ "!%26#"
 "
c]"
 "
 !/	"

 }"
 
"
 "
 "
 "
 "
 "
r7   r!   r   N)$typingr   r   r   r   r   chromadb.api.typesr   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   $chromadb.api.models.CollectionCommonr   %chromadb.api.collection_configurationr   "chromadb.execution.expression.planr   chromadb.apir   r!   r|   r7   r5   <module>r      s   = = = = = = = = = = = = = =                                           . B A A A A A O O O O O O 5 5 5 5 5 5 ,++++++D
 D
 D
 D
 D
&'78 D
 D
 D
 D
 D
r7   