Ë
    µŒj^0  ã                  óø   — d dl m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 d dlmZ d dlmZ erd dlmZ d dlmZ  G d	„ d
ee«      Z edeeef   ¬«      Z ej4                  e«      ZdZ G d„ de«      Zy)é    )ÚannotationsN)ÚEnum)	ÚTYPE_CHECKINGÚAnyÚDictÚ	GeneratorÚIterableÚListÚOptionalÚTypeVarÚUnion)ÚDocument)ÚVectorStore)Ú
Embeddings)Ú
Collectionc                  ó    — e Zd ZdZdZ	 dZ	 dZy)ÚDocumentDBSimilarityTypez)DocumentDB Similarity Type as enumerator.ÚcosineÚ
dotProductÚ	euclideanN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚCOSÚDOTÚEUC© ó    úu/var/www/html/Fitness-lenito-AI-main/venv/lib/python3.12/site-packages/langchain_community/vectorstores/documentdb.pyr   r      s   „ Ù3à
€CØØ
€CØØ
€CØr   r   ÚDocumentDBDocumentType)Úboundé€   c                  ól  — e Zd ZdZddddœ	 	 	 	 	 	 	 	 	 dd„Zedd„«       Zdd„Ze	 	 	 	 	 	 	 	 	 	 dd	„«       Z	dd
„Z
dd„Zdej                  ddf	 	 	 	 	 	 	 	 	 dd„Z	 d 	 	 	 	 	 	 	 d!d„Zd"d„Ze	 	 d#	 	 	 	 	 	 	 	 	 	 	 d$d„«       Zd d%d„Zd d&d„Z	 	 	 d'	 	 	 	 	 	 	 	 	 d(d„Z	 	 d)ddœ	 	 	 	 	 	 	 	 	 	 	 d*d„Zy)+ÚDocumentDBVectorSearcha€  `Amazon DocumentDB (with MongoDB compatibility)` vector store.
    Please refer to the official Vector Search documentation for more details:
    https://docs.aws.amazon.com/documentdb/latest/developerguide/vector-search.html

    To use, you should have both:
    - the ``pymongo`` python package installed
    - a connection string and credentials associated with a DocumentDB cluster

    Example:
        . code-block:: python

            from langchain_community.vectorstores import DocumentDBVectorSearch
            from langchain_community.embeddings.openai import OpenAIEmbeddings
            from pymongo import MongoClient

            mongo_client = MongoClient("<YOUR-CONNECTION-STRING>")
            collection = mongo_client["<db_name>"]["<collection_name>"]
            embeddings = OpenAIEmbeddings()
            vectorstore = DocumentDBVectorSearch(collection, embeddings)
    ÚvectorSearchIndexÚtextContentÚvectorContent)Ú
index_nameÚtext_keyÚembedding_keyc               ót   — || _         || _        || _        || _        || _        t
        j                  | _        y)a¹  Constructor for DocumentDBVectorSearch

        Args:
            collection: MongoDB collection to add the texts to.
            embedding: Text embedding model to use.
            index_name: Name of the Vector Search index.
            text_key: MongoDB field that will contain the text
                for each document.
            embedding_key: MongoDB field that will contain the embedding
                for each document.
        N)Ú_collectionÚ
_embeddingÚ_index_nameÚ	_text_keyÚ_embedding_keyr   r   Ú_similarity_type)ÚselfÚ
collectionÚ	embeddingr)   r*   r+   s         r    Ú__init__zDocumentDBVectorSearch.__init__B   s8   € ð( &ˆÔØ#ˆŒØ%ˆÔØ!ˆŒØ+ˆÔÜ 8× <Ñ <ˆÕr   c                ó   — | j                   S ©N)r.   ©r3   s    r    Ú
embeddingsz!DocumentDBVectorSearch.embeddings]   s   € à�‰Ðr   c                ó   — | j                   S )zUReturns the index name

        Returns:
            Returns the index name

        )r/   r9   s    r    Úget_index_namez%DocumentDBVectorSearch.get_index_namea   s   € ð ×ÑÐr   c                óœ   — 	 ddl m}  ||«      }|j                  d«      \  }}||   |   }	 | |	|fi |¤ŽS # t        $ r t        d«      ‚w xY w)a†  Creates an Instance of DocumentDBVectorSearch from a Connection String

        Args:
            connection_string: The DocumentDB cluster endpoint connection string
            namespace: The namespace (database.collection)
            embedding: The embedding utility
            **kwargs: Dynamic keyword arguments

        Returns:
            an instance of the vector store

        r   )ÚMongoClientzGCould not import pymongo, please install it with `pip install pymongo`.Ú.)Úpymongor>   ÚImportErrorÚsplit)
ÚclsÚconnection_stringÚ	namespacer5   Úkwargsr>   ÚclientÚdb_nameÚcollection_namer4   s
             r    Úfrom_connection_stringz-DocumentDBVectorSearch.from_connection_stringj   sm   € ð(	Ý+ñ *Ð*;Ó<ˆØ#,§?¡?°3Ó#7Ñ ˆ�Ø˜G‘_ _Ñ5ˆ
Ù�:˜yÑ3¨FÑ3Ð3øô ò 	Üð)óð ð	ús	   ‚6 ¶Ac                óŽ   — | j                   j                  «       }| j                  }|D ]  }|j                  d«      }||k(  sŒ y y)zãVerifies if the specified index name during instance
            construction exists on the collection

        Returns:
          Returns True on success and False if no such index exists
            on the collection
        ÚnameTF)r-   Úlist_indexesr/   Úpop)r3   Úcursorr)   ÚresÚcurrent_index_names        r    Úindex_existsz#DocumentDBVectorSearch.index_existsŠ   sK   € ð ×!Ñ!×.Ñ.Ó0ˆØ×%Ñ%ˆ
ãˆCØ!$§¡¨£ÐØ! ZÓ/Ùð ð
 r   c                óp   — | j                  «       r&| j                  j                  | j                  «       yy)zEDeletes the index specified during instance construction if it existsN)rR   r-   Ú
drop_indexr/   r9   s    r    Údelete_indexz#DocumentDBVectorSearch.delete_indexœ   s-   € à×ÑÔØ×Ñ×'Ñ'¨×(8Ñ(8Õ9ð r   i   é   é@   c           	     óÖ   — || _         | j                  j                  | j                  | j                  did||||dœdœgdœ}| j                  j
                  }|j                  |«      }|S )aà  Creates an index using the index name specified at
            instance construction

        Args:
            dimensions: Number of dimensions for vector similarity.
                The maximum number of supported dimensions is 2000

            similarity: Similarity algorithm to use with the HNSW index.
                 Possible options are:
                    - DocumentDBSimilarityType.COS (cosine distance),
                    - DocumentDBSimilarityType.EUC (Euclidean distance), and
                    - DocumentDBSimilarityType.DOT (dot product).

            m: Specifies the max number of connections for an HNSW index.
                Large impact on memory consumption.

            ef_construction: Specifies the size of the dynamic candidate list
                for constructing the graph for HNSW index. Higher values lead
                to more accurate results but slower indexing speed.


        Returns:
            An object describing the created index

        ÚvectorÚhnsw)ÚtypeÚ
similarityÚ
dimensionsÚmÚefConstruction)rL   ÚkeyÚvectorOptions)ÚcreateIndexesÚindexes)r2   r-   rL   r/   r1   ÚdatabaseÚcommand)r3   r]   r\   r^   Úef_constructionÚcreate_index_commandsÚcurrent_databaseÚcreate_index_responsess           r    Úcreate_indexz#DocumentDBVectorSearch.create_index£   s�   € ð@ !+ˆÔð "×-Ñ-×2Ñ2ð !×,Ñ,Ø ×/Ñ/°Ð:à &Ø&0Ø&0ØØ*9ñ&ñ
ðñ!
Ðð$  ×+Ñ+×4Ñ4Ðð 2B×1IÑ1IØ!ó2
Ðð &Ð%r   Nc                ó„  — |j                  dt        «      }|xs	 d„ |D «       }g }g }g }t        t        ||«      «      D ][  \  }	\  }
}|j	                  |
«       |j	                  |«       |	dz   |z  dk(  sŒ7|j                  | j                  ||«      «       g }g }Œ] |r!|j                  | j                  ||«      «       |S )NÚ
batch_sizec              3  ó    K  — | ]  }i –— Œ y ­wr8   r   )Ú.0Ú_s     r    Ú	<genexpr>z3DocumentDBVectorSearch.add_texts.<locals>.<genexpr>è   s   è ø€ Ð:MÁuÀ!¼2Áuùs   ‚é   r   )ÚgetÚDEFAULT_INSERT_BATCH_SIZEÚ	enumerateÚzipÚappendÚextendÚ_insert_texts)r3   ÚtextsÚ	metadatasrF   rl   Ú
_metadatasÚtexts_batchÚmetadatas_batchÚ
result_idsÚiÚtextÚmetadatas               r    Ú	add_textsz DocumentDBVectorSearch.add_textsá   sÍ   € ð —Z‘Z Ô.GÓHˆ
Ø-6Ò-MÑ:MÁuÓ:Mˆ
ØˆØˆØˆ
Ü#,¬S°¸
Ó-CÖ#DÑˆAÑ��hØ×Ñ˜tÔ$Ø×"Ñ" 8Ô,Ø�A‘˜Ñ# qÓ(Ø×!Ñ! $×"4Ñ"4°[À/Ó"RÔSØ �Ø"$‘ð $Eñ Ø×Ñ˜d×0Ñ0°¸oÓNÔOØÐr   c           	     ó  — |sg S | j                   j                  |«      }t        |||«      D ���cg c]"  \  }}}| j                  || j                  |i|¥‘Œ$ }}}}| j
                  j                  |«      }|j                  S c c}}}w )zàUsed to Load Documents into the collection

        Args:
            texts: The list of documents strings to load
            metadatas: The list of metadata objects associated with each document

        Returns:

        )r.   Úembed_documentsru   r0   r1   r-   Úinsert_manyÚinserted_ids)	r3   ry   rz   r:   Útr^   r5   Ú	to_insertÚinsert_results	            r    rx   z$DocumentDBVectorSearch._insert_texts÷   s”   € ñ ØˆIð —_‘_×4Ñ4°UÓ;ˆ
ô $' u¨i¸Ô#Dõ
á#D‘��1�ið �^‰^˜Q × 3Ñ 3°YÐDÀ!ÒDØ#Dð 	ò 
ð
 ×(Ñ(×4Ñ4°YÓ?ˆØ×)Ñ)Ð)ùô
s   ±'Bc                óZ   — |€t        d«      ‚ | ||fi |¤Ž}|j                  ||¬«       |S )Nz*Must provide 'collection' named parameter.)rz   )Ú
ValueErrorr‚   )rC   ry   r5   rz   r4   rF   Úvectorstores          r    Ú
from_textsz!DocumentDBVectorSearch.from_texts  s@   € ð ÐÜÐIÓJÐJÙ˜* iÑ:°6Ñ:ˆØ×Ñ˜e¨yÐÔ9ØÐr   c                óN   — |€t        d«      ‚|D ]  }| j                  |«       Œ y)Nz#No document ids provided to delete.T)r‹   Údelete_document_by_id)r3   ÚidsrF   Údocument_ids       r    ÚdeletezDocumentDBVectorSearch.delete  s.   € Øˆ;ÜÐBÓCÐCãˆKØ×&Ñ& {Õ3ð àr   c                ó¬   — 	 ddl m} |€t        d«      ‚| j                  j                  d ||«      i«       y# t        $ r}t        d«      |‚d}~ww xY w)zjRemoves a Specific Document by Id

        Args:
            document_id: The document identifier
        r   )ÚObjectIdz>Unable to import bson, please install with `pip install bson`.Nz"No document id provided to delete.Ú_id)Úbson.objectidr”   rA   r‹   r-   Ú
delete_one)r3   r‘   r”   Úes       r    r�   z,DocumentDBVectorSearch.delete_document_by_id&  sa   € ð	Ý.ð
 ÐÜÐAÓBÐBà×Ñ×#Ñ# U©H°[Ó,AÐ$BÕCøô ò 	ÜØPóàðûð	ús   ‚9 ¹	AÁAÁAc           	     ó  — |si }d|idd|| j                   | j                  ||dœiig}| j                  j                  |«      }g }|D ]9  }|j	                  | j
                  «      }	|j                  t        |	|¬«      «       Œ; |S )a   Returns a list of documents.

        Args:
            embeddings: The query vector
            k: the number of documents to return
            ef_search: Specifies the size of the dynamic candidate list
                that HNSW index uses during search. A higher value of
                efSearch provides better recall at cost of speed.
            filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
        Returns:
            A list of documents closest to the query vector
        z$matchz$searchÚvectorSearch)rY   Úpathr\   ÚkÚefSearch)Úpage_contentr�   )r1   r2   r-   Ú	aggregaterN   r0   rv   r   )
r3   r:   rœ   Ú	ef_searchÚfilterÚpipelinerO   ÚdocsrP   r€   s
             r    Ú _similarity_search_without_scorez7DocumentDBVectorSearch._similarity_search_without_score7  sž   € ñ* ØˆFà�vÐàØ"Ø",Ø $× 3Ñ 3Ø&*×&;Ñ&;ØØ$-ñ%ðð
ð*
ˆð ×!Ñ!×+Ñ+¨HÓ5ˆàˆãˆCØ—7‘7˜4Ÿ>™>Ó*ˆDØ�K‰Kœ¨d¸SÔAÕBð ð ˆr   )r¡   c               óŒ   — | j                   j                  |«      }| j                  ||||¬«      }|D �cg c]  }|‘Œ c}S c c}w )N)r:   rœ   r    r¡   )r.   Úembed_queryr¤   )	r3   Úqueryrœ   r    r¡   rF   r:   r£   Údocs	            r    Úsimilarity_searchz(DocumentDBVectorSearch.similarity_searchg  sP   € ð —_‘_×0Ñ0°Ó7ˆ
Ø×4Ñ4Ø! Q°)ÀFð 5ó 
ˆñ  $Ó$™t˜’˜tÑ$Ð$ùÒ$s   µ	A)
r4   z"Collection[DocumentDBDocumentType]r5   r   r)   Ústrr*   rª   r+   rª   )Úreturnr   )r«   rª   )
rD   rª   rE   rª   r5   r   rF   r   r«   r%   )r«   Úbool)r«   ÚNone)
r]   Úintr\   r   r^   r®   rf   r®   r«   zdict[str, Any]r8   )ry   zIterable[str]rz   zOptional[List[Dict[str, Any]]]rF   r   r«   r
   )ry   ú	List[str]rz   zList[Dict[str, Any]]r«   r
   )NN)ry   r¯   r5   r   rz   zOptional[List[dict]]r4   z,Optional[Collection[DocumentDBDocumentType]]rF   r   r«   r%   )r�   zOptional[List[str]]rF   r   r«   zOptional[bool])r‘   zOptional[str]r«   r­   )é   é(   N)
r:   zList[float]rœ   r®   r    r®   r¡   úOptional[Dict[str, Any]]r«   úList[Document])r°   r±   )r§   rª   rœ   r®   r    r®   r¡   r²   rF   r   r«   r³   )r   r   r   r   r6   Úpropertyr:   r<   ÚclassmethodrJ   rR   rU   r   r   rj   r‚   rx   r�   r’   r�   r¤   r©   r   r   r    r%   r%   ,   s!  „ ñð4 .Ø%Ø,ñ=à6ð=ð ð=ð
 ð=ð ð=ð ó=ð6 òó ðó ð ð4àð4ð ð4ð ð	4ð
 ð4ð 
 ò4ó ð4ó>ó$:ð Ø/G×/KÑ/KØØ!ð<&àð<&ð -ð<&ð ð	<&ð
 ð<&ð 
ó<&ðB 59ðàðð 2ðð ð	ð
 
óó,*ð0 ð
 +/ØCGðàðð ðð (ð	ð
 Aðð ðð 
 òó ðôôDð( ØØ+/ð.àð.ð ð.ð ð	.ð
 )ð.ð 
ó.ðf Øð	%ð ,0ñ%àð%ð ð%ð ð	%ð )ð%ð ð%ð 
ô%r   r%   )Ú
__future__r   ÚloggingÚenumr   Útypingr   r   r   r   r	   r
   r   r   r   Úlangchain_core.documentsr   Úlangchain_core.vectorstoresr   Úlangchain_core.embeddingsr   Úpymongo.collectionr   rª   r   r!   Ú	getLoggerr   Úloggerrs   r%   r   r   r    Ú<module>rÀ      sz   ðÝ "ã Ý ÷
÷ 
õ 
õ .Ý 3áÝ4Ý-ô˜s Dô ñ !Ð!9ÀÀcÈ3ÀhÁÔPÐ à	ˆ×	Ñ	˜8Ó	$€àÐ ôH%˜[õ H%r   