§
    šŠtjù#  ã                  ó²   — 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 d dlmZ d dlmZ d dlmZ d dlmZmZmZ d d	lmZmZ  G d
„ de¦  «        ZdS )é    )ÚannotationsN)ÚPath)ÚAnyÚDictÚListÚOptionalÚTupleÚUnion)ÚCallbackManagerForRetrieverRun)ÚDocument)ÚBaseRetriever)Úconvert_to_secret_strÚget_from_dict_or_envÚpre_init)Ú
ConfigDictÚ	SecretStrc                  óø   — e Zd ZU dZded<   	 dZded<   	  ed¬¦  «        Zed4d5d„¦   «         Z	e
	 d4d6d„¦   «         Ze
	 d4d7d„¦   «         Zed8d„¦   «         Z	 	 d9d:d„Zd;d„Zd<d$„Zd=d'„Zd>d*„Zd?d-„Zd@d1„ZdAd3„ZdS )BÚNeuralDBRetrieverz0Document retriever that uses ThirdAI's NeuralDB.r   Úthirdai_keyNr   ÚdbÚforbid)ÚextraúOptional[str]ÚreturnÚNonec                óÞ   — 	 ddl m} t          j                             d¦  «         |                     | pt          j        d¦  «        ¦  «         d S # t          $ r t          d¦  «        ‚w xY w)Nr   )Ú	licensingzthirdai.neural_dbÚTHIRDAI_KEYz{Could not import thirdai python package and neuraldb dependencies. Please install it with `pip install thirdai[neural_db]`.)	Úthirdair   Ú	importlibÚutilÚ	find_specÚactivateÚosÚgetenvÚImportError)r   r   s     úm/var/www/html/CA-Chatbot/venv/lib/python3.11/site-packages/langchain_community/retrievers/thirdai_neuraldb.pyÚ_verify_thirdai_libraryz)NeuralDBRetriever._verify_thirdai_library   sŒ   € ð
	Ø)Ð)Ð)Ð)Ð)Ð)åŒN×$Ò$Ð%8Ñ9Ô9Ð9à×Ò˜{ÐF­b¬i¸Ñ.FÔ.FÑGÔGÐGÐGÐGøÝð 	ð 	ð 	ÝðKñô ð ð	øøøs   ‚AA ÁA,Úmodel_kwargsÚdictc                ór   — t                                |¦  «         ddlm}  | | |j        di |¤Ž¬¦  «        S )aÈ  
        Create a NeuralDBRetriever from scratch.

        To use, set the ``THIRDAI_KEY`` environment variable with your ThirdAI
        API key, or pass ``thirdai_key`` as a named parameter.

        Example:
            .. code-block:: python

                from langchain_community.retrievers import NeuralDBRetriever

                retriever = NeuralDBRetriever.from_scratch(
                    thirdai_key="your-thirdai-key",
                )

                retriever.insert([
                    "/path/to/doc.pdf",
                    "/path/to/doc.docx",
                    "/path/to/doc.csv",
                ])

                documents = retriever.invoke("AI-driven music therapy")
        r   ©Ú	neural_db©r   r   © )r   r(   r   r-   ÚNeuralDB)Úclsr   r)   Úndbs       r'   Úfrom_scratchzNeuralDBRetriever.from_scratch*   sQ   € õ: 	×1Ò1°+Ñ>Ô>Ð>Ø,Ð,Ð,Ð,Ð,Ð,àˆs˜{¨|¨s¬|Ð/KÐ/K¸lÐ/KÐ/KÐLÑLÔLÐLó    Ú
checkpointúUnion[str, Path]c                óŒ   — t                                |¦  «         ddlm}  | ||j                             |¦  «        ¬¦  «        S )a!  
        Create a NeuralDBRetriever with a base model from a saved checkpoint

        To use, set the ``THIRDAI_KEY`` environment variable with your ThirdAI
        API key, or pass ``thirdai_key`` as a named parameter.

        Example:
            .. code-block:: python

                from langchain_community.retrievers import NeuralDBRetriever

                retriever = NeuralDBRetriever.from_checkpoint(
                    checkpoint="/path/to/checkpoint.ndb",
                    thirdai_key="your-thirdai-key",
                )

                retriever.insert([
                    "/path/to/doc.pdf",
                    "/path/to/doc.docx",
                    "/path/to/doc.csv",
                ])

                documents = retriever.invoke("AI-driven music therapy")
        r   r,   r.   )r   r(   r   r-   r0   Úfrom_checkpoint)r1   r5   r   r2   s       r'   r8   z!NeuralDBRetriever.from_checkpointL   sO   € õ< 	×1Ò1°+Ñ>Ô>Ð>Ø,Ð,Ð,Ð,Ð,Ð,àˆs˜{¨s¬|×/KÒ/KÈJÑ/WÔ/WÐXÑXÔXÐXr4   Úvaluesr   c                óH   — t          t          |dd¦  «        ¦  «        |d<   |S )z'Validate ThirdAI environment variables.r   r   )r   r   )r1   r9   s     r'   Úvalidate_environmentsz'NeuralDBRetriever.validate_environmentso   s5   € õ !6Ý ØØØñô ñ!
ô !
ˆˆ}Ñð ˆr4   TÚsourcesú	List[Any]ÚtrainÚboolÚ	fast_modeÚkwargsc                ó\   — |                       |¦  «        } | j        j        d|||dœ|¤Ž dS )as  Inserts files / document sources into the retriever.

        Args:
            train: When True this means that the underlying model in the
            NeuralDB will undergo unsupervised pretraining on the inserted files.
            Defaults to True.
            fast_mode: Much faster insertion with a slight drop in performance.
            Defaults to True.
        )r<   r>   Úfast_approximationNr/   )Ú_preprocess_sourcesr   Úinsert)Úselfr<   r>   r@   rA   s        r'   rE   zNeuralDBRetriever.insert{   sV   € ð  ×*Ò*¨7Ñ3Ô3ˆØˆŒŒð 	
ØØØ(ð	
ð 	
ð ð		
ð 	
ð 	
ð 	
ð 	
r4   Úlistc                ó†  — ddl m} |s|S g }|D �]0}t          |t          ¦  «        s|                     |¦  «         Œ.|                     ¦   «                              d¦  «        r)|                     |                     |¦  «        ¦  «         Œ~|                     ¦   «                              d¦  «        r)|                     |                     |¦  «        ¦  «         ŒÎ|                     ¦   «                              d¦  «        r*|                     | 	                    |¦  «        ¦  «         �Œt          d|› d�¦  «        ‚|S )zùChecks if the provided sources are string paths. If they are, convert
        to NeuralDB document objects.

        Args:
            sources: list of either string paths to PDF, DOCX or CSV files, or
            NeuralDB document objects.
        r   r,   z.pdfz.docxz.csvzCould not automatically load z¦. Only files with .pdf, .docx, or .csv extensions can be loaded automatically. For other formats, please use the appropriate document object from the ThirdAI library.)r   r-   Ú
isinstanceÚstrÚappendÚlowerÚendswithÚPDFÚDOCXÚCSVÚRuntimeError)rF   r<   r2   Úpreprocessed_sourcesÚdocs        r'   rD   z%NeuralDBRetriever._preprocess_sources“   sR  € ð 	-Ð,Ð,Ð,Ð,Ð,àð 	ØˆNØ!ÐØð 	ñ 	ˆCÝ˜c¥3Ñ'Ô'ð Ø$×+Ò+¨CÑ0Ô0Ð0Ð0à—9’9‘;”;×'Ò'¨Ñ/Ô/ð Ø(×/Ò/°·²¸±´Ñ=Ô=Ð=Ð=Ø—Y’Y‘[”[×)Ò)¨'Ñ2Ô2ð 
Ø(×/Ò/°·²¸±´Ñ>Ô>Ð>Ð>Ø—Y’Y‘[”[×)Ò)¨&Ñ1Ô1ð Ø(×/Ò/°·²¸±´Ñ=Ô=Ð=Ñ=å&ðP¸ð Pð Pð Pñô ð ð $Ð#r4   ÚqueryrJ   Údocument_idÚintc                ó<   — | j                              ||¦  «         dS )a!  The retriever upweights the score of a document for a specific query.
        This is useful for fine-tuning the retriever to user behavior.

        Args:
            query: text to associate with `document_id`
            document_id: id of the document to associate query with.
        N)r   Útext_to_result)rF   rT   rU   s      r'   ÚupvotezNeuralDBRetriever.upvote³   s"   € ð 	Œ×Ò˜u kÑ2Ô2Ð2Ð2Ð2r4   Úquery_id_pairsúList[Tuple[str, int]]c                ó:   — | j                              |¦  «         dS )a„  Given a batch of (query, document id) pairs, the retriever upweights
        the scores of the document for the corresponding queries.
        This is useful for fine-tuning the retriever to user behavior.

        Args:
            query_id_pairs: list of (query, document id) pairs. For each pair in
            this list, the model will upweight the document id for the query.
        N)r   Útext_to_result_batch)rF   rZ   s     r'   Úupvote_batchzNeuralDBRetriever.upvote_batch½   s    € ð 	Œ×$Ò$ ^Ñ4Ô4Ð4Ð4Ð4r4   ÚsourceÚtargetc                ó<   — | j                              ||¦  «         dS )a=  The retriever associates a source phrase with a target phrase.
        When the retriever sees the source phrase, it will also consider results
        that are relevant to the target phrase.

        Args:
            source: text to associate to `target`.
            target: text to associate `source` to.
        N)r   Ú	associate)rF   r_   r`   s      r'   rb   zNeuralDBRetriever.associateÈ   s"   € ð 	Œ×Ò˜& &Ñ)Ô)Ð)Ð)Ð)r4   Ú
text_pairsúList[Tuple[str, str]]c                ó:   — | j                              |¦  «         dS )a.  Given a batch of (source, target) pairs, the retriever associates
        each source phrase with the corresponding target phrase.

        Args:
            text_pairs: list of (source, target) text pairs. For each pair in
            this list, the source will be associated with the target.
        N)r   Úassociate_batch)rF   rc   s     r'   rf   z!NeuralDBRetriever.associate_batchÓ   s    € ð 	Œ×Ò 
Ñ+Ô+Ð+Ð+Ð+r4   Úrun_managerr   úList[Document]c                ó    — 	 d|vrd|d<    | j         j        dd|i|¤Ž}d„ |D ¦   «         S # t          $ r}t          d|› �¦  «        |‚d}~ww xY w)zÙRetrieve {top_k} contexts with your retriever for a given query

        Args:
            query: Query to submit to the model
            top_k: The max number of context results to retrieve. Defaults to 10.
        Útop_ké
   rT   c                ó    — g | ]K}t          |j        |j        |j        |j        |j        |j        |                     d ¦  «        dœ¬¦  «        ‘ŒLS )é   )ÚidÚ
upvote_idsr_   ÚmetadataÚscoreÚcontext)Úpage_contentrp   )r   Útextrn   ro   r_   rp   rq   rr   )Ú.0Úrefs     r'   ú
<listcomp>z=NeuralDBRetriever._get_relevant_documents.<locals>.<listcomp>ê   sn   € ð ð ð ð õ Ø!$¤à!œfØ&)¤nØ"%¤*Ø$'¤LØ!$¤Ø#&§;¢;¨q¡>¤>ðð ð
ñ 
ô 
ðð ð r4   z"Error while retrieving documents: Nr/   )r   ÚsearchÚ	ExceptionÚ
ValueError)rF   rT   rg   rA   Ú
referencesÚes         r'   Ú_get_relevant_documentsz)NeuralDBRetriever._get_relevant_documentsÝ   s›   € ð	NØ˜fÐ$Ð$Ø"$��w‘Ø'˜œœÐ>Ð>¨eÐ>°vÐ>Ð>ˆJðð ð &ðñ ô ð øõ ð 	Nð 	Nð 	NÝÐEÀ!ÐEÐEÑFÔFÈAÐMøøøøð	Nøøøs   ‚(+ «
AµAÁAÚpathc                ó:   — | j                              |¦  «         dS )zÇSaves a NeuralDB instance to disk. Can be loaded into memory by
        calling NeuralDB.from_checkpoint(path)

        Args:
            path: path on disk to save the NeuralDB instance to.
        N)r   Úsave)rF   r~   s     r'   r€   zNeuralDBRetriever.saveû   s   € ð 	Œ�Š�TÑÔÐÐÐr4   )N)r   r   r   r   )r   r   r)   r*   r   r   )r5   r6   r   r   r   r   )r9   r   r   r   )TT)
r<   r=   r>   r?   r@   r?   rA   r*   r   r   )r<   rG   r   rG   )rT   rJ   rU   rV   r   r   )rZ   r[   r   r   )r_   rJ   r`   rJ   r   r   )rc   rd   r   r   )rT   rJ   rg   r   rA   r   r   rh   )r~   rJ   r   r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__r   r   Úmodel_configÚstaticmethodr(   Úclassmethodr3   r8   r   r;   rE   rD   rY   r^   rb   rf   r}   r€   r/   r4   r'   r   r      s«  € € € € € € Ø:Ð:àÐÐÑØà€B€N€N€N�NØà�:Øðñ ô €Lð ðð ð ð ñ „\ðð ð &*ðMð Mð Mð Mñ „[ðMðB ð &*ð Yð  Yð  Yð  Yñ „[ð YðD ð	ð 	ð 	ñ „Xð	ð Øð	
ð 
ð 
ð 
ð 
ð0$ð $ð $ð $ð@3ð 3ð 3ð 3ð	5ð 	5ð 	5ð 	5ð	*ð 	*ð 	*ð 	*ð,ð ,ð ,ð ,ðNð Nð Nð Nð<ð ð ð ð ð r4   r   )Ú
__future__r   r    r$   Úpathlibr   Útypingr   r   r   r   r	   r
   Úlangchain_core.callbacksr   Úlangchain_core.documentsr   Úlangchain_core.retrieversr   Úlangchain_core.utilsr   r   r   Úpydanticr   r   r   r/   r4   r'   ú<module>r‘      s  ðØ "Ð "Ð "Ð "Ð "Ð "à Ð Ð Ð Ø 	€	€	€	Ø Ð Ð Ð Ð Ð Ø :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ð :à CÐ CÐ CÐ CÐ CÐ CØ -Ð -Ð -Ð -Ð -Ð -Ø 3Ð 3Ð 3Ð 3Ð 3Ð 3Ø VÐ VÐ VÐ VÐ VÐ VÐ VÐ VÐ VÐ VØ *Ð *Ð *Ð *Ð *Ð *Ð *Ð *ðsð sð sð sð s˜ñ sô sð sð sð sr4   