
    Ng                       d dl mZ d dlZd dlZd dlZd dlZd dlmZmZ d dl	m
Z
 d dl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mZ d d
lmZmZ d dl m!Z!  ej"        e#          Z$dZ%dZ&dZ'e G d d                      Z(e G d d                      Z)e G d d                      Z*e G d d                      Z+ G d de          Z, G d de          Z- G d de          Z.dS )    )annotationsN)	dataclassfield)md5)AnyIterableIteratorListOptionalTupleType)CallbackManagerForRetrieverRunDocument)
Embeddings)RunnableRunnableConfig)VectorStoreVectorStoreRetriever)
ConfigDictivAivAivAc                  Z    e Zd ZU dZdZded<   dZded<   dZd	ed
<   dZd	ed<   dZ	ded<   dS )SummaryConfigaj  Configuration for summary generation.

    is_enabled: True if summary is enabled, False otherwise
    max_results: maximum number of results to summarize
    response_lang: requested language for the summary
    prompt_name: name of the prompt to use for summarization
      (see https://docs.vectara.com/docs/learn/grounded-generation/select-a-summarizer)
    Fbool
is_enabled   intmax_resultsengstrresponse_langz"vectara-summary-ext-24-05-med-omniprompt_namestreamN)
__name__
__module____qualname____doc__r   __annotations__r   r    r!   r"        d/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/vectorstores/vectara.pyr   r      ss           JKM;K;;;;Fr)   r   c                  >    e Zd ZU dZdZded<   dZded<   dZd	ed
<   dS )	MMRConfiga  Configuration for Maximal Marginal Relevance (MMR) search.
       This will soon be deprated in favor of RerankConfig.

    is_enabled: True if MMR is enabled, False otherwise
    mmr_k: number of results to fetch for MMR, defaults to 50
    diversity_bias: number between 0 and 1 that determines the degree
        of diversity among the results with 0 corresponding
        to minimum diversity and 1 to maximum diversity.
        Defaults to 0.3.
        Note: diversity_bias is equivalent 1-lambda_mult
        where lambda_mult is the value often used in max_marginal_relevance_search()
        We chose to use that since we believe it's more intuitive to the user.
    Fr   r   2   r   mmr_k333333?floatdiversity_biasN)r#   r$   r%   r&   r   r'   r.   r1   r(   r)   r*   r,   r,   .   sM           JEOOOONr)   r,   c                  L    e Zd ZU dZdZded<   dZded<   dZd	ed
<   dZded<   dS )RerankConfiga  Configuration for Reranker.

    reranker: "mmr", "rerank_multilingual_v1", "udf" or "none"
    rerank_k: number of results to fetch before reranking, defaults to 50
    mmr_diversity_bias: for MMR only - a number between 0 and 1 that determines
        the degree of diversity among the results with 0 corresponding
        to minimum diversity and 1 to maximum diversity.
        Defaults to 0.3.
        Note: mmr_diversity_bias is equivalent 1-lambda_mult
        where lambda_mult is the value often used in max_marginal_relevance_search()
        We chose to use that since we believe it's more intuitive to the user.
    user_function: for UDF only - the user function to use for reranking.
    noner   rerankerr-   r   rerank_kr/   r0   mmr_diversity_bias user_functionN)	r#   r$   r%   r&   r5   r'   r6   r7   r9   r(   r)   r*   r3   r3   C   sc           HH #####Mr)   r3   c                      e Zd ZU dZdZded<   dZded<   dZd	ed
<   dZded<   dZ	ded<   dZ
ded<    ee          Zded<    ee          Zded<   	 	 	 	 	 	 	 	 	 	 dddZdS )VectaraQueryConfigaW  Configuration for Vectara query.

    k: Number of Documents to return. Defaults to 10.
    lambda_val: lexical match parameter for hybrid search.
    filter Dictionary of argument(s) to filter on metadata. For example a
        filter can be "doc.rating > 3.0 and part.lang = 'deu'"} see
        https://docs.vectara.com/docs/search-apis/sql/filter-overview
        for more details.
    score_threshold: minimal score threshold for the result.
        If defined, results with score less than this value will be
        filtered out.
    n_sentence_before: number of sentences before the matching segment
        to add, defaults to 2
    n_sentence_after: number of sentences before the matching segment
        to add, defaults to 2
    rerank_config: RerankConfig configuration dataclass
    summary_config: SummaryConfig configuration dataclass
    
   r   k        r0   
lambda_valr8   r   filterNOptional[float]score_threshold   n_sentence_beforen_sentence_after)default_factoryr3   rerank_configr   summary_confign_sentence_contextOptional[int]
mmr_configOptional[MMRConfig]Optional[SummaryConfig]Optional[RerankConfig]c                   || _         || _        || _        || _        |	r|	| _        nt                      | _        |r)|| _        || _        t          j	        dt                     n|| _        || _        |
r	|
| _        d S |r=t          d|j        |j                  | _        t          j	        dt                     d S t                      | _        d S )Nz[n_sentence_context is deprecated. Please use n_sentence_before and n_sentence_after insteadmmrr5   r6   r7   z9MMRConfig is deprecated. Please use RerankConfig instead.)r=   r?   r@   rB   rH   r   rD   rE   warningswarnDeprecationWarningrG   r3   r.   r1   )selfr=   r?   r@   rB   rD   rE   rI   rK   rH   rG   s              r*   __init__zVectaraQueryConfig.__init__w   s    $. 	2"0D"///D  
	5%7D"$6D!ML"    &7D"$4D!  	0!.D 	0!-#)#-#<" " "D
 MK"    
 ".Dr)   )
r<   r>   r8   NrC   rC   NNNN)r=   r   r?   r0   r@   r   rB   rA   rD   r   rE   r   rI   rJ   rK   rL   rH   rM   rG   rN   )r#   r$   r%   r&   r=   r'   r?   r@   rB   rD   rE   r   r3   rG   r   rH   rV   r(   r)   r*   r;   r;   Y   s          & AKKKKJF'+O++++"'%"E"E"EMEEEE$)E-$H$H$HNHHHH +/!" !,0*.260420 20 20 20 20 20 20r)   r;   c                     e Zd ZdZ	 	 	 	 	 dFdGdZedHd            ZdIdZdJdZdKdLdZ	dMdNdZ
	 dMdOd%Z	 	 dPdQd)Z	 	 dRdSd/ZdTd1ZdUd2ZdVd4Z	 	 dWdXd:Ze	 	 dPdYd>            Ze	 	 dPdZd@            Zd[dBZd[dCZd\dEZdS )]Vectaraa  `Vectara API` vector store.

     See (https://vectara.com).

    Example:
        .. code-block:: python

            from langchain_community.vectorstores import Vectara

            vectorstore = Vectara(
                vectara_customer_id=vectara_customer_id,
                vectara_corpus_id=vectara_corpus_id,
                vectara_api_key=vectara_api_key
            )
    Nx   	langchainvectara_customer_idOptional[str]vectara_corpus_idvectara_api_keyvectara_api_timeoutr   sourcer   c                P   |pt           j                            d          | _        |pt           j                            d          | _        |pt           j                            d          | _        | j        | j        | j        t                              d           n"t                              d| j                    || _	        t          j                    | _        t          j                            d          }| j                            d	|           || _        dS )
zInitialize with Vectara API.VECTARA_CUSTOMER_IDVECTARA_CORPUS_IDVECTARA_API_KEYNzHCan't find Vectara credentials, customer_id or corpus_id in environment.zUsing corpus id    )max_retrieszhttp://)osenvironget_vectara_customer_id_vectara_corpus_id_vectara_api_keyloggerwarningdebug_sourcerequestsSession_sessionadaptersHTTPAdaptermountr_   )rU   r[   r]   r^   r_   r`   adapters          r*   rV   zVectara.__init__   s    %8 %
2:>>!<
 <
! #4 #
rz~~8
 8
 !0 T2:>>BS3T3T%-&.$,NN   
 LLED,CEEFFF (**#//A/>>Iw///#6   r)   returnOptional[Embeddings]c                    d S Nr(   rU   s    r*   
embeddingszVectara.embeddings   s    tr)   dictc                .    | j         | j        d| j        dS )z=Returns headers that should be attached to each post request.zapplication/json)z	x-api-keyzcustomer-idContent-TypezX-Source)rl   rj   rp   r|   s    r*   _get_post_headerszVectara._get_post_headers   s'     .4.	
 
 	
r)   doc_idr   c           
     :   | j         | j        |d}| j                            dt	          j        |          d|                                 | j                  }|j        dk    r7t          
                    d| d|j         d|j         d	|j                    d
S dS )z
        Delete a document from the Vectara corpus.

        Args:
            doc_id (str): ID of the document to delete.
        Returns:
            bool: True if deletion was successful, False otherwise.
        )customer_id	corpus_iddocument_idz$https://api.vectara.io/v1/delete-docT)dataverifyheaderstimeout   z#Delete request failed for doc_id = z with status code 	, reason z, text F)rj   rk   rs   postjsondumpsr   r_   status_coderm   errorreasontext)rU   r   bodyresponses       r*   _delete_doczVectara._delete_doc   s      40!
 

 =%%2D!!**,,, & 
 
 3&&LL#f # #'# #2:/# #=# #  
 5tr)   Fdocuse_core_apic                j   i }| j         |d<   | j        |d<   ||d<   |rdnd}| j                            |                                 |t          j        |          | j        d          }|j        }|                                }d|v r|d         d	         nd }|d
k    s|r|dk    rdS |r|dk    rdS dS )Nr   r   documentz$https://api.vectara.io/v1/core/indexzhttps://api.vectara.io/v1/indexT)r   urlr   r   r   statuscode  ALREADY_EXISTSE_ALREADY_EXISTS	FORBIDDENE_NO_PERMISSIONSE_SUCCEEDED)	rj   rk   rs   r   r   r   r   r_   r   )	rU   r   r   requestapi_endpointr   r   result
status_strs	            r*   
_index_doczVectara._index_doc
  s    "$!%!:#6!
 3222 	
 =%%**,,G$$, & 
 
 *19V1C1CVH%f--
#?O1O1O%% 	!Z;66%% =r)   idsOptional[List[str]]kwargsr   Optional[bool]c                F     |r fd|D             }t          |          S dS )zDelete by vector ID or other criteria.
        Args:
            ids: List of ids to delete.

        Returns:
            Optional[bool]: True if deletion is successful,
            False otherwise, None if not implemented.
        c                :    g | ]}                     |          S r(   )r   ).0idrU   s     r*   
<listcomp>z"Vectara.delete.<locals>.<listcomp>2  s'    :::t''++:::r)   T)all)rU   r   r   successs   `   r*   deletezVectara.delete(  s7      	::::c:::Gw<<4r)   
files_listIterable[str]	metadatasOptional[List[dict]]	List[str]c                Z   g }t          |          D ]\  }}t          j                            |          st                              d| d           D|r||         ni }|t          |d          ft          j        |          d}| 	                                }	|	
                    d           | j                            d| j         d| j         d|d	|	| j        
          }
|
j        dk    rC|
                                d         d         }t                              d| d| d           #|
j        dk    r7|
                                d         d         }|                    |           et                              d| d|
                                            |S )ac  
        Vectara provides a way to add documents directly via our API where
        pre-processing and chunking occurs internally in an optimal way
        This method provides a way to use that API in LangChain

        Args:
            files_list: Iterable of strings, each representing a local file path.
                    Files could be text, HTML, PDF, markdown, doc/docx, ppt/pptx, etc.
                    see API docs for full list
            metadatas: Optional list of metadatas associated with each file

        Returns:
            List of ids associated with each of the files indexed
        zFile z does not exist, skippingrb)filedoc_metadatar   z https://api.vectara.io/upload?c=z&o=z&d=TrueT)filesr   r   r   r   r   
documentIdz# already exists on Vectara (doc_id=z), skippingr   zError indexing file z: )	enumeraterg   pathexistsrm   r   openr   r   r   poprs   r   rj   rk   r_   r   infoappend)rU   r   r   r   doc_idsinxr   mdr   r   r   r   s               r*   	add_fileszVectara.add_files7  s   ( ":.. 	N 	NIC7>>$'' DTDDDEEE#,43"BtD$//0 $
2 E ,,..GKK'''}))q43LqqQUQhqqq0 *  H #s**!4\BXDXXVXXX    %,,!4\Bv&&&&L4LL8==??LLMMMMr)   textsr   Optional[dict]c           
     .   t                      }|D ])}|                    |                                           *|                                }|d |D             }|rd|d<   nddi}|                    dd          }|rdnd}	d	|d
t          j        |          |	d t          ||          D             i}
|                     |
|          }|dk    r+| 	                    |           |                     |
           n|dk    rt          d           |gS )a  Run more texts through the embeddings and add to the vectorstore.

        Args:
            texts: Iterable of strings to add to the vectorstore.
            metadatas: Optional list of metadatas associated with the texts.
            doc_metadata: optional metadata for the document

        This function indexes all the input text strings in the Vectara corpus as a
        single Vectara document, where each input text is considered a "section" and the
        metadata are associated with each section.
        if 'doc_metadata' is provided, it is associated with the Vectara document.

        Returns:
            document ID of the document added

        Nc                    g | ]}i S r(   r(   )r   _s     r*   r   z%Vectara.add_texts.<locals>.<listcomp>  s    ++++++r)   rZ   r`   r   Fpartssectionr   metadataJsonc                B    g | ]\  }}|t          j        |          d S ))r   r   )r   r   )r   r   r   s      r*   r   z%Vectara.add_texts.<locals>.<listcomp>  s<       D" tz"~~>>  r)   )r   r   r   ziNo permissions to add document to Vectara. 
                Check your corpus ID, customer ID and API key)r   updateencode	hexdigestri   r   r   zipr   r   print)rU   r   r   r   r   doc_hashtr   r   section_keyr   success_strs               r*   	add_textszVectara.add_textsl  s`   . 55 	( 	(AOOAHHJJ''''##%%++U+++I 	3%0L""$k2Lzz.%88!-<gg96DJ|44   #E9 5 5  
 oocoEE,,,V$$$OOC    ...A   xr)   queryconfigr;   chatchat_conv_idc                   t          |j        t                    rt          di |j        |_        t          |j        t                    rt          di |j        |_        d|d|j        j        dv r|j        j        n|j        |j	        |j
        d| j        |j        dgdgi}|j        dk    r$d|j        i|d         d         d         d         d	<   |j        j        d
k    r&t          d|j        j        id|d         d         d<   n\|j        j        dk    r$t           |j        j        d|d         d         d<   n(|j        j        dk    rdt$          i|d         d         d<   |j        j        rV|j        j        |j        j        |j        j        dg|d         d         d<   |r d|d|d         d         d         d         d<   |S )zBuild the body for the API

        Args:
            query: Text to look up documents similar to.
            config: VectaraQueryConfig object
        Returns:
            A dictionary with the body of the query
        r   r   )rP   udfrerank_multilingual_v1)sentencesBeforesentencesAfter)corpusIdmetadataFilter)r   start
numResultscontextConfig	corpusKeylambdar   lexicalInterpolationConfigrP   diversityBias)
rerankerId	mmrConfigrerankingConfigr   )r   userFunctionr   r   )maxSummarizedResultsresponseLangsummarizerPromptNamesummaryT)storeconversationIdr   r(   )
isinstancerG   r~   r3   rH   r   r5   r6   r=   rD   rE   rk   r@   r?   MMR_RERANKER_IDr7   UDF_RERANKER_IDr9   RERANKER_MULTILINGUAL_V1_IDr   r   r    r!   )rU   r   r   r   r   r   r   s          r*   _get_query_bodyzVectara._get_query_body  sU     f*D11 	H#/#G#G&2F#G#GF f+T22 	K$1$J$JF4I$J$JF! " #09GH H ,55
 $X ,2+C*0*A& & )-(?.4m " 
6 q  &+NDM![)!,-IJ (E11--v/C/VW3 3DM!.// !*e33- & 4 B3 3DM!.// !*.FFF93DM!./  + 	 -3,A,M$*$9$G,2,A,M +DM!Y'  !&2: :Wa +A.v6 r)   List[Tuple[Document, float]]c           
     :    | j         |fi |}| j                            |                                 dt	          j        |          | j                  }|j        dk    r6t          	                    dd|j         d|j
         d|j         d           g S |                                }j        r!fd	|d
         d         d         D             }n|d
         d         d         }|d
         d         d         }g }	|D ]g}
d |
d         D             }|
d         }d ||         d         D             }d|vrd|d<   |                    |           |	                    |           hd t          ||	          D             }j        j        dv r|dj                 }j        j        ro|d
         d         d         d         d         }|d
         d         d         d         d         d         }|                    t+          |d|d          df           |S )a7  Run a Vectara query

        Args:
            query: Text to look up documents similar to.
            config: VectaraQueryConfig object
        Returns:
            A list of k Documents matching the given query
            If summary is enabled, last document is the summary text with 'summary'=True
        zhttps://api.vectara.io/v1/query)r   r   r   r   r   Query failed %s(code r   
, details )c                6    g | ]}|d          j         k    |S score)rB   )r   rr   s     r*   r   z)Vectara.vectara_query.<locals>.<listcomp>  s5       W: 666 666r)   responseSetr   r   r   c                ,    i | ]}|d          |d         S namevaluer(   r   ms     r*   
<dictcomp>z)Vectara.vectara_query.<locals>.<dictcomp>%  s"    ???A!F)QwZ???r)   metadatadocumentIndexc                ,    i | ]}|d          |d         S r  r(   r  s     r*   r  z)Vectara.vectara_query.<locals>.<dictcomp>'  s"    TTTai7TTTr)   r`   vectarac                R    g | ]$\  }}t          |d          |          |d         f%S r   page_contentr  r  r   r   xr   s      r*   r   z)Vectara.vectara_query.<locals>.<listcomp>-  sU     	
 	
 	
 2 !"6   '
	
 	
 	
r)   rP   r   Nr   r   factualConsistencyr  T)r   fcsr  r>   )r   rs   r   r   r   r   r_   r   rm   r   r   r   rB   r   r   r   rG   r5   r=   rH   r   r   )rU   r   r   r   r   r   r   	responses	documentsr   r  r   doc_numdoc_mdresr   r  s     `              r*   vectara_queryzVectara.vectara_query  s    $t#E6<<V<<=%%**,,1D!!,	 & 
 
 3&&LL!$- $ $ $ $=$ $ $  
 I! 	=   .q1*=  II }-a0<I=)!,Z8		 	! 	!A??:???B(GTTYw5G
5STTTFv%%#,x IIfR    	
 	
 Y	22	
 	
 	
 (,MMMjj/C + 
	]+A.y9!<VDG'*95a89MNwWCJJ%,4PS7T7T   	   
r)   c                J    t          di |}|                     ||          }|S )a  Return Vectara documents most similar to query, along with scores.

        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return. Defaults to 10.

            any other querying variable in VectaraQueryConfig like:
            - lambda_val: lexical match parameter for hybrid search.
            - filter: filter string
            - score_threshold: minimal score threshold for the result.
            - n_sentence_before: number of sentences before the matching segment
            - n_sentence_after: number of sentences after the matching segment
            - rerank_config: optional configuration for Reranking
              (see RerankConfig dataclass)
            - summary_config: optional configuration for summary
              (see SummaryConfig dataclass)
        Returns:
            List of Documents most similar to the query and score for each.
        r(   )r;   r#  )rU   r   r   r   docss        r*   similarity_search_with_scorez$Vectara.similarity_search_with_scoreG  s1    0 $--f--!!%00r)   List[Document]c                6     | j         |fi |}d |D             S )a  Return Vectara documents most similar to query, along with scores.

        Args:
            query: Text to look up documents similar to.
            any other querying variable in VectaraQueryConfig

        Returns:
            List of Documents most similar to the query
        c                    g | ]\  }}|S r(   r(   r   r   r   s      r*   r   z-Vectara.similarity_search.<locals>.<listcomp>u      222Q222r)   )r&  )rU   r   r   docs_and_scoress       r*   similarity_searchzVectara.similarity_searchc  s>     <$;
 

 
 32/2222r)   r-         ?fetch_klambda_multr0   c                N    t          d|d|z
            |d<    | j        |fi |S )aS  Return docs selected using the maximal marginal relevance.
        Maximal marginal relevance optimizes for similarity to query AND diversity
        among selected documents.

        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return. Defaults to 5.
            fetch_k: Number of Documents to fetch to pass to MMR algorithm.
                     Defaults to 50
            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.
                        Defaults to 0.5.
            kwargs: any other querying variable in VectaraQueryConfig
        Returns:
            List of Documents selected by maximal marginal relevance.
        rP      rQ   rG   )r3   r-  )rU   r   r/  r0  r   s        r*   max_marginal_relevance_searchz%Vectara.max_marginal_relevance_searchw  sE    0 #/W[#
 #
 #
 &t%e66v666r)   clsType[Vectara]	embeddingc                d    |                     di           } | di |} |j        ||fd|i| |S )a  Construct Vectara wrapper from raw documents.
        This is intended to be a quick way to get started.
        Example:
            .. code-block:: python

                from langchain_community.vectorstores import Vectara
                vectara = Vectara.from_texts(
                    texts,
                    vectara_customer_id=customer_id,
                    vectara_corpus_id=corpus_id,
                    vectara_api_key=api_key,
                )
        r   r(   )r   r   )r4  r   r6  r   r   r   r  s          r*   
from_textszVectara.from_texts  sO    6 zz."55#----%PPPPPPr)   r   c                B     | di |}|                     ||           |S )a  Construct Vectara wrapper from raw documents.
        This is intended to be a quick way to get started.
        Example:
            .. code-block:: python

                from langchain_community.vectorstores import Vectara
                vectara = Vectara.from_files(
                    files_list,
                    vectara_customer_id=customer_id,
                    vectara_corpus_id=corpus_id,
                    vectara_api_key=api_key,
                )
        r(   )r   )r4  r   r6  r   r   r  s         r*   
from_fileszVectara.from_files  s0    . #----%+++r)   
VectaraRAGc                "    t          | |          S )zReturn a Vectara RAG runnable.r;  rU   r   s     r*   as_ragzVectara.as_rag  s    $'''r)   c                &    t          | |d          S )z'Return a Vectara RAG runnable for chat.T)r   r=  r>  s     r*   as_chatzVectara.as_chat  s    $T2222r)   VectaraRetrieverc                d    t          | |                    dt                                          S )zreturn a retriever object.r   )vectorstorer   )rB  ri   r;   )rU   r   s     r*   as_retrieverzVectara.as_retriever  s3    VZZ:L:N:N%O%O
 
 
 	
r)   )NNNrY   rZ   )
r[   r\   r]   r\   r^   r\   r_   r   r`   r   )rx   ry   )rx   r~   )r   r   rx   r   F)r   r~   r   r   rx   r   r{   )r   r   r   r   rx   r   )r   r   r   r   r   r   rx   r   )NN)
r   r   r   r   r   r   r   r   rx   r   )FN)r   r   r   r;   r   r   r   r\   r   r   rx   r~   )r   r   r   r;   r   r   rx   r   )r   r   r   r   rx   r   )r   r   r   r   rx   r'  )r-   r.  )
r   r   r/  r   r0  r0   r   r   rx   r'  )r4  r5  r   r   r6  ry   r   r   r   r   rx   rX   )r4  r5  r   r   r6  ry   r   r   r   r   rx   rX   )r   r;   rx   r;  )r   r   rx   rB  )r#   r$   r%   r&   rV   propertyr}   r   r   r   r   r   r   r   r#  r&  r-  r3  classmethodr8  r:  r?  rA  rE  r(   r)   r*   rX   rX      s#        $ .2+/)-#&! 7  7  7  7  7D    X
 
 
 
   <! ! ! ! !<    $ +/3 3 3 3 3p +/'+	7 7 7 7 7z  %&*Q Q Q Q QfM M M M^   83 3 3 3.  	7 7 7 7 7:  +/*.	    [>  +/*.	    [4( ( ( (3 3 3 3
 
 
 
 
 
r)   rX   c                  T    e Zd ZU dZded<   	 ded<   	  ed          ZddZddZdS )rB  zVectara Retriever class.rX   rD  r;   r   T)arbitrary_types_allowedr   r   run_managerr   rx   r'  c               Z    | j                             || j                  }d |D             S )Nc                    g | ]\  }}|S r(   r(   r*  s      r*   r   z<VectaraRetriever._get_relevant_documents.<locals>.<listcomp>  r+  r)   )rD  r#  r   )rU   r   rK  r,  s       r*   _get_relevant_documentsz(VectaraRetriever._get_relevant_documents  s2     *88LL22/2222r)   r  r   r   r   c                (     | j         j        |fi |S )zAdd documents to vectorstore.)rD  add_documents)rU   r  r   s      r*   rP  zVectaraRetriever.add_documents  s     -t-iBB6BBBr)   N)r   r   rK  r   rx   r'  )r  r'  r   r   rx   r   )	r#   r$   r%   r&   r'   r   model_configrN  rP  r(   r)   r*   rB  rB    s         ""++: $  L3 3 3 3C C C C C Cr)   rB  c                  6    e Zd ZdZ	 ddd	Z	 dddZ	 dddZd
S )r;  zVectara RAG runnable.

    Parameters:
        vectara: Vectara object
        config: VectaraQueryConfig object
        chat: bool, default False
    Fr  rX   r   r;   r   r   c                >    || _         || _        || _        d | _        d S r{   )r  r   r   conv_id)rU   r  r   r   s       r*   rV   zVectaraRAG.__init__  s$     	r)   Ninputr   Optional[RunnableConfig]r   r   rx   Iterator[dict]c           
   +  6   K    j                             | j         j         j                  } j         j                             j                                         dt          j	        |           j         j
        d          }|j        dk    r6t                              dd|j         d|j         d|j         d	           d
S g }g }d|iV  |                                D ]}|rt          j        |                    d                    }	|	d         }
|
d         }||
                    dd
          }|Yt)          |                    d                    dk    rJt                              d|                    d          d                             d                      |                    dd
          }|rd|                    dd
          rN|d         }t                              d|            |dk    r#d
 _        t                              d           E|r|                    dd
          nd
}|r| _        |                    dd
          r2|                    di                               dd
          }d|iV  t-          |d                   }d|iV  ͉ j        j        r fd|d         D             }n|d         }|d          }g }|D ]g}d! |d"         D             }|d#         }d$ ||         d"         D             }d%|vrd&|d%<   |                    |           |                    |           hd' t5          ||          D             } j        j        j        d(v r|d
 j        j                 }d)|iV  d
S )*a  Get streaming output from Vectara RAG.

        Args:
            input: The input query
            config: RunnableConfig object
            kwargs: Any additional arguments

        Returns:
            The output dictionary with question, answer and context
        z&https://api.vectara.io/v1/stream-queryT)r   r   r   r   r"   r   r  r  r   r  r  Nquestionzutf-8r   r	  r   r   r   z&Summary generation failed with status statusDetailr   zChat query failed with code RESOURCE_EXHAUSTEDz-Sorry, Vectara chat turns exceeds plan limit.r   r  r  r  r   answerc                @    g | ]}|d          j         j        k    |S r  )r   rB   )r   r  rU   s     r*   r   z%VectaraRAG.stream.<locals>.<listcomp>Y  s7     % % % ! zDK,GGG GGGr)   r   r   c                ,    i | ]}|d          |d         S r  r(   r  s     r*   r  z%VectaraRAG.stream.<locals>.<dictcomp>c  s"    KKKai7KKKr)   r  r  c                ,    i | ]}|d          |d         S r  r(   r  s     r*   r  z%VectaraRAG.stream.<locals>.<dictcomp>e  s2     " " " ! fIqz" " "r)   r`   r  c                R    g | ]$\  }}t          |d          |          |d         f%S r  r   r  s      r*   r   z%VectaraRAG.stream.<locals>.<listcomp>m  sU     	 	 	 "Ar %-.vY)+   gJ	 	 	r)   r  context)r  r   r   r   rT  rs   r   r   r   r   r_   r   rm   r   r   r   
iter_linesloadsdecoderi   lenr   r   rB   r   r   r   rG   r5   r=   )rU   rU  r   r   r   r   r  r  liner   r   response_setr   r   st_coderT  r  chunkr   r  r   r   r!  r"  s   `                       r*   r"   zVectaraRAG.stream  se       |++E4;	4<XX<(--L22448D!!L4 . 
 
 3&&LL!$- $ $ $ $=$ $ $  
 F		5!!!!'')) N	+ N	+D M+z$++g"6"677h%m4'$jjD99G 7;;x0011A55N&{{844Q7;;NKKN N   ! #;;vt44D %4 8 8 %"&x.$L7$L$LMMM"&:::+/DL"LL O   %BFPdhh'7>>>DG /'. {{#7>> !%kk*>CCGGQUVV$cl***   00E#U+++++{2 =% % % %%1*%=% % %		 %1$<	 ,Z 8I "I& 
- 
-KKQz]KKK"#O"4" "%.w%7
%C" " " $611/8F8,		&)))!((,,,,	 	 &)I%>%>	 	 	C {09 >   "/DKM/2$c****r)   r~   c                   ddi}|                      |          D ]j}d|v r|d         |d<   d|v r|d         |d<   "d|v r|dxx         |d         z  cc<   =d|v r|d         |d<   Mt                              d|            k|S )Nr\  r8   ra  rY  r  zUnknown chunk type: )r"   rm   r   )rU   rU  r   r   r"  ri  s         r*   invokezVectaraRAG.invoke  s     n[['' 
	= 
	=EE!!!&y!1Iu$$"'
"3JU""Hx0%"5\E

;E;;<<<<
r)   rF  )r  rX   r   r;   r   r   r{   )rU  r   r   rV  r   r   rx   rW  )rU  r   r   rV  r   r   rx   r~   )r#   r$   r%   r&   rV   r"   rk  r(   r)   r*   r;  r;    s          JO     ,0v v v v vv ,0      r)   r;  )/
__future__r   r   loggingrg   rR   dataclassesr   r   hashlibr   typingr   r   r	   r
   r   r   r   rq    langchain_core.callbacks.managerr   langchain_core.documentsr   langchain_core.embeddingsr   langchain_core.runnablesr   r   langchain_core.vectorstoresr   r   pydanticr   	getLoggerr#   rm   r   r   r   r   r,   r3   r;   rX   rB  r;  r(   r)   r*   <module>rx     s   " " " " " "   				  ( ( ( ( ( ( ( (       G G G G G G G G G G G G G G G G G G       . - - - - - 0 0 0 0 0 0 = = = = = = = = I I I I I I I I      		8	$	$'         "                (        * O0 O0 O0 O0 O0 O0 O0 O0do
 o
 o
 o
 o
k o
 o
 o
dC C C C C+ C C C0[ [ [ [ [ [ [ [ [ [r)   