
    dh$                        S SK Jr  S SKrS SKrS SKJr  S SKJrJrJ	r	J
r
JrJr  S SKJr  S SKJr  S SKJr  S SKJrJrJr  S S	KJrJr   " S
 S\5      rg)    )annotationsN)Path)AnyDictListOptionalTupleUnion)CallbackManagerForRetrieverRun)Document)BaseRetriever)convert_to_secret_strget_from_dict_or_envpre_init)
ConfigDict	SecretStrc                  0   \ rS rSr% SrS\S'    SrS\S'    \" SS	9r\	SSS
 jj5       r
\ S     SS jj5       r\ S     SS jj5       r\SS j5       r  S         SS jjrSS jrSS jrS S jrS!S jrS"S jr        S#S jrS$S jrSrg)%NeuralDBRetriever   z0Document retriever that uses ThirdAI's NeuralDB.r   thirdai_keyNr   dbforbid)extrac                     SSK Jn  [        R                  R	                  S5        UR                  U =(       d    [        R                  " S5      5        g ! [         a    [        S5      ef = f)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     g/var/www/html/shao/venv/lib/python3.13/site-packages/langchain_community/retrievers/thirdai_neuraldb.py_verify_thirdai_library)NeuralDBRetriever._verify_thirdai_library   s[    
	)NN$$%89{Fbii.FG 	K 	s   AA A,c                d    [         R                  U5        SSKJn  U " XR                  " S0 UD6S9$ )aH  
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   model_kwargsndbs       r%   from_scratchNeuralDBRetriever.from_scratch*   s,    : 	11+>,{||/Kl/KLL    c                v    [         R                  U5        SSKJn  U " X#R                  R                  U5      S9$ )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*   r-   from_checkpoint)r.   
checkpointr   r0   s       r%   r5   !NeuralDBRetriever.from_checkpointL   s/    < 	11+>,{||/K/KJ/WXXr3   c                8    [        [        USS5      5      US'   U$ )z'Validate ThirdAI environment variables.r   r   )r   r   )r.   valuess     r%   validate_environments'NeuralDBRetriever.validate_environmentso   s+     !6 !
} r3   c                f    U R                  U5      nU R                  R                  " SUUUS.UD6  g)a;  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.
)sourcestrainfast_approximationNr,   )_preprocess_sourcesr   insert)selfr=   r>   	fast_modekwargss        r%   rA   NeuralDBRetriever.insert{   s<      **73 	
(	
 		
r3   c                J   SSK Jn  U(       d  U$ / nU GH
  n[        U[        5      (       d  UR	                  U5        M,  UR                  5       R                  S5      (       a"  UR	                  UR                  U5      5        Mr  UR                  5       R                  S5      (       a"  UR	                  UR                  U5      5        M  UR                  5       R                  S5      (       a"  UR	                  UR                  U5      5        M  [        SU S35      e   U$ )zChecks 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)rB   r=   r0   preprocessed_sourcesdocs        r%   r@   %NeuralDBRetriever._preprocess_sources   s     	-N!Cc3''$++C099;''//(//=YY[))'22(//>YY[))&11(//=&7u =P P  " $#r3   c                :    U R                   R                  X5        g)zThe 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)rB   querydocument_ids      r%   upvoteNeuralDBRetriever.upvote   s     	u2r3   c                :    U R                   R                  U5        g)aT  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)rB   query_id_pairss     r%   upvote_batchNeuralDBRetriever.upvote_batch   s     	$$^4r3   c                :    U R                   R                  X5        g)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)rB   sourcetargets      r%   r_   NeuralDBRetriever.associate   s     	&)r3   c                :    U R                   R                  U5        g)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)rB   
text_pairss     r%   rd   !NeuralDBRetriever.associate_batch   s     	
+r3   c                z    SU;  a  SUS'   U R                   R                  " S	SU0UD6nU Vs/ sH_  n[        UR                  UR                  UR
                  UR                  UR                  UR                  UR                  S5      S.S9PMa     sn$ s  snf ! [         a  n[        SU 35      UeSnAff = f)
zRetrieve {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
   rU      )id
upvote_idsr`   metadatascorecontext)page_contentrm   z"Error while retrieving documents: Nr,   )r   searchr   textrk   rl   r`   rm   rn   ro   	Exception
ValueError)rB   rU   run_managerrD   
referencesrefes          r%   _get_relevant_documents)NeuralDBRetriever._get_relevant_documents   s    	Nf$"$w>e>v>J & &C !$!ff&)nn"%**$'LL!$#&;;q>
 &    	NA!EFAM	Ns)   -B A%BB B 
B:&B55B:c                :    U R                   R                  U5        g)zSaves 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)rB   paths     r%   r|   NeuralDBRetriever.save   s     	Tr3   r,   )N)r   Optional[str]returnNone)r   r   r/   dictr   r   )r6   zUnion[str, Path]r   r   r   r   )r9   r   r   r   )TT)
r=   z	List[Any]r>   boolrC   r   rD   r   r   r   )r=   listr   r   )rU   rH   rV   intr   r   )r[   zList[Tuple[str, int]]r   r   )r`   rH   ra   rH   r   r   )re   zList[Tuple[str, str]]r   r   )rU   rH   ru   r   rD   r   r   zList[Document])r}   rH   r   r   )__name__
__module____qualname____firstlineno____doc____annotations__r   r   model_configstaticmethodr&   classmethodr1   r5   r   r:   rA   r@   rW   r\   r_   rd   ry   r|   __static_attributes__r,   r3   r%   r   r      sK   :BNL    &*M"M M 
	M MB  &* Y$ Y # Y 
	 Y  YD 	 	 	

 
 	

 
 

0$@3	5	*,NN'ENQTN	N<r3   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,   r3   r%   <module>r      s7    "  	  : : C - 3 V V *s sr3   