
    h                       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jD                  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.y)    )annotationsN)	dataclassfield)md5)AnyIterableIteratorListOptionalTupleType)CallbackManagerForRetrieverRun)Document)
Embeddings)RunnableRunnableConfig)VectorStoreVectorStoreRetriever)
ConfigDictivAivAivAc                  X    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<   y)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!        f/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/langchain_community/vectorstores/vectara.pyr   r      s;     JKM3;K;FD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
<   y)	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-   r0   r'   r(   r)   r+   r+   .   s&     JE3ONEr(   r+   c                  J    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<   y)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.   r/   mmr_diversity_bias user_functionN)	r"   r#   r$   r%   r4   r&   r5   r6   r8   r'   r(   r)   r2   r2   C   s2     HcHc ##M3r(   r2   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y)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        r/   
lambda_valr7   r   filterNOptional[float]score_threshold   n_sentence_beforen_sentence_after)default_factoryr2   rerank_configr   summary_configc                   || _         || _        || _        || _        |	r|	| _        nt               | _        |r)|| _        || _        t        j                  dt               n|| _        || _        |
r|
| _        y |rBt        d|j                  |j                        | _        t        j                  dt               y t               | _        y )Nz[n_sentence_context is deprecated. Please use n_sentence_before and n_sentence_after insteadmmrr4   r5   r6   z9MMRConfig is deprecated. Please use RerankConfig instead.)r<   r>   r?   rA   rG   r   rC   rD   warningswarnDeprecationWarningrF   r2   r-   r0   )selfr<   r>   r?   rA   rC   rD   n_sentence_context
mmr_configrG   rF   s              r)   __init__zVectaraQueryConfig.__init__w   s     $."0D"//D %7D"$6D!MML" &7D"$4D! !.D!-#))#-#<#<"D
 MMK"
 ".Dr(   )
r;   r=   r7   NrB   rB   NNNN)r<   r   r>   r/   r?   r   rA   r@   rC   r   rD   r   rO   zOptional[int]rP   zOptional[MMRConfig]rG   zOptional[SummaryConfig]rF   zOptional[RerankConfig])r"   r#   r$   r%   r<   r&   r>   r?   rA   rC   rD   r   r2   rF   r   rG   rQ   r'   r(   r)   r:   r:   Y   s    & AsKJFC'+O_+sc"'"EM<E$)-$HNMH +/!" !,0*.26042020 20 	20
 )20 20 20 *20 (20 020 .20r(   r:   c                     e Zd ZdZ	 	 	 	 	 d	 	 	 	 	 	 	 	 	 ddZedd       ZddZddZdddZ	dddZ
	 d	 	 	 	 	 	 	 dd	Z	 	 d	 	 	 	 	 	 	 	 	 d d
Z	 	 d!	 	 	 	 	 	 	 	 	 	 	 d"dZ	 	 	 	 	 	 	 	 d#dZ	 	 	 	 	 	 d$dZ	 	 	 	 	 	 d%dZ	 	 d&	 	 	 	 	 	 	 	 	 d'dZe	 	 d	 	 	 	 	 	 	 	 	 	 	 d(d       Ze	 	 d	 	 	 	 	 	 	 	 	 	 	 d)d       Zd*dZd*dZd+dZy),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
            )
    Nc                r   |xs t         j                  j                  d      | _        |xs t         j                  j                  d      | _        |xs t         j                  j                  d      | _        | j                  | j                  | j
                  t        j                  d       n"t        j                  d| j                          || _	        t        j                         | _        t        j                  j                  d      }| j                  j                  d	|       || _        y)
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mountvectara_api_timeout)rN   vectara_customer_idvectara_corpus_idvectara_api_keyrj   sourceadapters          r)   rQ   zVectara.__init__   s     %8 %
2::>>!<
! #4 #
rzz~~8
 !0 T2::>>BS3T%%-&&.$$,NN
 LL+D,C,C+DEF ((*##//A/>Iw/#6 r(   c                     y Nr'   rN   s    r)   
embeddingszVectara.embeddings   s    r(   c                L    | 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)r_   r]   rc   rr   s    r)   _get_post_headerszVectara._get_post_headers   s*     ..44.	
 	
r(   c           
     l   | j                   | j                  |d}| j                  j                  dt	        j
                  |      d| j                         | j                        }|j                  dk7  r@t        j                  d| d|j                   d|j                   d	|j                          y
y)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)r]   r^   rf   postjsondumpsrv   rj   status_coder`   errorreasontext)rN   doc_idbodyresponses       r)   _delete_doczVectara._delete_doc   s      4400!

 ==%%2D!**,,, & 
 3&LL5fX=O''(	(//1B'==/#
 r(   c                n   i }| j                   |d<   | j                  |d<   ||d<   |rdnd}| j                  j                  | j	                         |t        j                  |      | j                  d      }|j                  }|j                         }d|v r|d   d	   nd }|d
k(  s|r|dk(  ry|r|dk(  ryy)Nrx   ry   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)	r]   r^   rf   r   rv   r   r   rj   r   )	rN   docuse_core_apirequestapi_endpointr   r   result
status_strs	            r)   
_index_doczVectara._index_doc
  s    "$!%!:!:#66!
  32 	
 ==%%**,G$,, & 
 **19V1CVH%f-
#?O1O%Z;6% r(   c                d    |r)|D cg c]  }| j                  |       }}t        |      S yc c}w )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.
        T)r   all)rN   idskwargsidsuccesss        r)   deletezVectara.delete(  s7     69:t''+:G:w< ;s   -c                   g }t        |      D ]v  \  }}t        j                  j                  |      st        j                  d| d       @|r||   ni }|t        |d      ft        j                  |      d}| j                         }	|	j                  d       | j                  j                  d| j                   d| j                   d|d	|	| j                  
      }
|
j                   dk(  r4|
j                         d   d   }t        j#                  d| d| d       |
j                   dk(  r)|
j                         d   d   }|j%                  |       Nt        j#                  d| d|
j                                 y |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_metadataru   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: )	enumeraterZ   pathexistsr`   r   openr   r   rv   poprf   r   r]   r^   rj   r   infoappend)rN   
files_list	metadatasr   doc_idsinxr   mdr   r}   r   r   s               r)   	add_fileszVectara.add_files7  s   ( ":. 	NIC77>>$'uTF*CDE#,3"BtD$/0 $

2E ,,.GKK'}}))243L3L2MSQUQhQhPiipq00 * H ##s*!4\BD6!DVHKX %%,!4\Bv&24&8==?:KLM9	N< r(   c                >   t               }|D ]!  }|j                  |j                                # |j                         }||D cg c]  }i  }}|rd|d<   nddi}|j	                  dd      }	|	rdnd}
d|dt        j                  |      |
t        ||      D cg c]  \  }}|t        j                  |      d	 c}}i}| j                  ||	
      }|dk(  r%| j                  |       | j                  |       |gS |dk(  rt        d       |gS c c}w c c}}w )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

        	langchainrn   r   Fpartssectionrz   metadataJson)r   r   )r   r   r   ziNo permissions to add document to Vectara. 
                Check your corpus ID, customer ID and API key)r   updateencode	hexdigestr\   r   r   zipr   r   print)rN   textsr   r   r   doc_hashtr   _r   section_keyr   r   r   success_strs                  r)   	add_textszVectara.add_textsl  s:   . 5 	(AOOAHHJ'	(##%%*++I+%0L"$k2Lzz.%8!-g96DJJ|4 #E9 5D" tzz"~>
 oocoE,,V$OOC  x ..A x7 ,s   	D"Dc                Z   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kD  rd|j                  i|d   d   d   d   d	<   |j                  j                  d
k(  r)t        d|j                  j                  id|d   d   d<   nj|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&                  rb|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
        queryr   )rI   udfrerank_multilingual_v1)sentencesBeforesentencesAfter)corpusIdmetadataFilter)r   start
numResultscontextConfig	corpusKeylambdar   lexicalInterpolationConfigrI   diversityBias)
rerankerId	mmrConfigrerankingConfigr   )r   userFunctionr   r   )maxSummarizedResultsresponseLangsummarizerPromptNamesummaryT)storeconversationIdchatr'   )
isinstancerF   dictr2   rG   r   r4   r5   r<   rC   rD   r^   r?   r>   MMR_RERANKER_IDr6   UDF_RERANKER_IDr8   RERANKER_MULTILINGUAL_V1_IDr   r   r   r    )rN   r   configr   chat_conv_idr   r   s          r)   _get_query_bodyzVectara._get_query_body  sP     f**D1#/#G&2F2F#GF f++T2$1$JF4I4I$JF! " #0099GH ,,55
 $XX ,2+C+C*0*A*A& )-(?(?.4mm"
6 q &++NDM![)!,-IJ ((E1--v/C/C/V/VW3DM!./ !!**e3- & 4 4 B B3DM!./ !!**.FF93DM!./   ++ -3,A,A,M,M$*$9$9$G$G,2,A,A,M,M+DM!Y' !&2:Wa +A.v6 r(   c           
         | j                   ||fi |}| j                  j                  | j                         dt	        j
                  |      | j                        }|j                  dk7  r@t        j                  dd|j                   d|j                   d|j                   d       g S |j	                         }|j                  r+|d	   d
   d   D cg c]  }|d   |j                  kD  r| }}n|d	   d
   d   }|d	   d
   d   }	g }
|D ]g  }|d   D ci c]  }|d   |d    }}|d   }|	|   d   D ci c]  }|d   |d    }}d|vrd|d<   |j                  |       |
j                  |       i t        ||
      D cg c]  \  }}t!        |d   |      |d   f }}}|j"                  j$                  dv r|d|j&                   }|j(                  j*                  rF|d	   d
   d   d
   d   }|d	   d
   d   d
   d   d   }|j                  t!        |d|d      df       |S c c}w c c}w c c}w c c}}w )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 )responseSetr   r   scorer   metadatanamevaluedocumentIndexrn   vectarar   page_contentr   rI   r   Nr   factualConsistencyT)r   fcsr=   )r   rf   r   rv   r   r   rj   r   r`   r   r   r   rA   r   r   r   r   rF   r4   r<   rG   r   )rN   r   r   r   r   r   r   r	responses	documentsr   xmr   doc_numdoc_mdresr   r   s                      r)   vectara_queryzVectara.vectara_query  s    $t##E6<V<==%%**,1D!,,	 & 
 3&LL!--.i7H
==/$
 I!!  .q1*=W: 6 66 I  }-a0<I=)!,Z8		 	!A12:?A!F)QwZ'?B?(G5>w5G
5STai7+TFTv%#,x IIfR 	!" Y	2	
 2 !"6 '
	
 	
 ((,MMj/C  ++]+A.y9!<VDG'*95a89MNwWCJJ%,4PS7T 	 
W @T	
s   H/H4:H9H>c                @    t        di |}| j                  ||      }|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  )rN   r   r   r   docss        r)   similarity_search_with_scorez$Vectara.similarity_search_with_scoreG  s(    0 $-f-!!%0r(   c                ^     | j                   |fi |}|D cg c]  \  }}|	 c}}S c c}}w )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
        )r  )rN   r   r   docs_and_scoresr   r   s         r)   similarity_searchzVectara.similarity_searchc  s;     <$;;

 #22Q222s   )c                P    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.
        rI      rJ   rF   )r2   r
  )rN   r   fetch_klambda_multr   s        r)   max_marginal_relevance_searchz%Vectara.max_marginal_relevance_searchw  s8    0 #/W[#
 &t%%e6v66r(   c                f    |j                  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   )clsr   	embeddingr   r   r   r   s          r)   
from_textszVectara.from_texts  s@    6 zz."5--%PPPr(   c                :     | di |}|j                  ||       |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   )r  r   r  r   r   r   s         r)   
from_fileszVectara.from_files  s$    . --%+r(   c                    t        | |      S )zReturn a Vectara RAG runnable.
VectaraRAGrN   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2r(   c                L    t        | |j                  dt                           S )zreturn a retriever object.r   )vectorstorer   )VectaraRetrieverr\   r:   )rN   r   s     r)   as_retrieverzVectara.as_retriever  s#    VZZ:L:N%O
 	
r(   )NNNx   r   )
rk   Optional[str]rl   r"  rm   r"  rj   r   rn   r   )returnOptional[Embeddings])r#  r   )r   r   r#  r   F)r   r   r   r   r#  r   rq   )r   zOptional[List[str]]r   r   r#  Optional[bool])r   Iterable[str]r   Optional[List[dict]]r   r   r#  	List[str])NN)
r   r'  r   r(  r   zOptional[dict]r   r   r#  r)  )FN)r   r   r   r:   r   r&  r   r"  r   r   r#  r   )r   r   r   r:   r   r   r#  List[Tuple[Document, float]])r   r   r   r   r#  r*  )r   r   r   r   r#  List[Document])r,   g      ?)
r   r   r  r   r  r/   r   r   r#  r+  )r  Type[Vectara]r   r)  r  r$  r   r(  r   r   r#  rS   )r  r,  r   r)  r  r$  r   r(  r   r   r#  rS   )r   r:   r#  r  )r   r   r#  r  )r"   r#   r$   r%   rQ   propertyrs   rv   r   r   r   r   r   r   r  r  r
  r  classmethodr  r  r  r  r   r'   r(   r)   rS   rS      s   $ .2+/)-#&! 7* 7 ) 7 '	 7
 ! 7  7D  
<!<$ +/3!3 (3 	3
 
3p +/'+	77 (7 %	7
 7 
7z  %&*QQ #Q 	Q
 $Q Q 
QfMM #M 	M
 
&M^  
&	833 3 
	3.  	77 7 	7
 7 
7:  +/*.	 ( (	
  
 >  +/*.	 ( (	
  
 4(3
r(   rS   c                  \    e Zd ZU dZded<   	 ded<   	  ed      Z	 	 	 	 	 	 	 	 ddZdd	Zy
)r  zVectara Retriever class.rS   r  r:   r   T)arbitrary_types_allowedc                    | j                   j                  || j                  fi |}|D cg c]  \  }}|	 c}}S c c}}w rq   )r  r  r   )rN   r   run_managerr   r	  r   r   s          r)   _get_relevant_documentsz(VectaraRetriever._get_relevant_documents  s?     9$**88VvV"12Q222s   >c                <     | j                   j                  |fi |S )zAdd documents to vectorstore.)r  add_documents)rN   r   r   s      r)   r5  zVectaraRetriever.add_documents  s     -t--iB6BBr(   N)r   r   r2  r   r   r   r#  r+  )r   r+  r   r   r#  r)  )	r"   r#   r$   r%   r&   r   model_configr3  r5  r'   r(   r)   r  r    sO    "++ $L33*H3TW3	3Cr(   r  c                  Z    e Zd ZdZ	 d	 	 	 	 	 ddZ	 d	 	 	 	 	 	 	 d	dZ	 d	 	 	 	 	 	 	 d
dZy)r  zVectara RAG runnable.

    Parameters:
        vectara: Vectara object
        config: VectaraQueryConfig object
        chat: bool, default False
    c                <    || _         || _        || _        d | _        y rq   )r   r   r   conv_id)rN   r   r   r   s       r)   rQ   zVectaraRAG.__init__  s      	r(   Nc           
   +    K   | j                   j                  || j                  | j                  | j                        }| j                   j
                  j                  | j                   j                         dt        j                  |      | j                   j                  d      }|j                  dk7  r?t        j                  dd|j                   d|j                   d|j                   d	       y
g }g }d|i |j!                         D ]  }|st        j"                  |j%                  d            }	|	d   }
|
d   }|C|
j'                  dd
      }|Mt)        |j'                  d            dkD  r:t        j                  d|j'                  d      d   j'                  d              |j'                  dd
      }|rR|j'                  dd
      r@|d   }t        j+                  d|        |dk(  rd
| _        t        j                  d       
|r|j'                  dd
      nd
}|r|| _        |j'                  dd
      r*|j'                  di       j'                  dd
      }d|i et-        |d         }d|i {| j                  j.                  r/|d   D cg c]   }|d   | j                  j.                  kD  r|" }}n|d   }|d   }g }|D ]g  }|d    D ci c]  }|d!   |d"    }}|d#   }||   d    D ci c]  }|d!   |d"    }}d$|vrd%|d$<   |j1                  |       |j3                  |       i t5        ||      D cg c]  \  }}t7        |d   |&      |d   f }}}| j                  j8                  j:                  d'v r|d
| j                  j<                   }d(|i  y
c c}w c c}w c c}w c c}}w w))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   answerr   r   r   r   r   r   rn   r   r   r   context)r   r   r   r   r9  rf   r   rv   r   r   rj   r   r`   r   r   r   
iter_linesloadsdecoder\   lenr   r   rA   r   r   r   r   rF   r4   r<   )rN   inputr   r   r   r   r   r   liner{   r   response_setr   r   st_coder9  r   chunkr   r   r   r   r   r  r  r  s                             r)   r!   zVectaraRAG.stream  s      ||++E4;;		4<<X<<((--LL2248D!LL44 . 
 3&LL!--.i7H
==/$
 		5!!'') N	+Dzz$++g"67h%m4'$jjD9G 7;;x01A5D&{{84Q7;;NKLN ! #;;vt4D4 8"&x.&B7)$LM"&::+/DL"LL O %BFdhh'7>DG'. {{#7>%kk*>CGGQUV$cl*   0E#U++{{22 &2*%=% ! zDKK,G,GG %	 % %1$<	 ,Z 8I "I& 
-=>z]Kai73KK"#O"4 &/w%7
%C" ! fIqz1" " $61/8F8,		&)!((,
-& &)I%>	 "Ar %-.vY)+ gJ	C 	 {{0099 >  "/DKKMM2$c**]N	+^ 	I% L"	s>   DOFO(%N>O(O8O	O>OO6AOc                    ddi}| j                  |      D ]V  }d|v r	|d   |d<   d|v r	|d   |d<   d|v r|dxx   |d   z  cc<   2d|v r	|d   |d<   ?t        j                  d|        X |S )Nr>  r7   r?  r;  r   zUnknown chunk type: )r!   r`   r   )rN   rD  r   r   r  rH  s         r)   invokezVectaraRAG.invoke  s     n[[' 
	=EE!!&y!1Iu$"'
"3JU"Hx0%"5\E
3E7;<
	= 
r(   r%  )r   rS   r   r:   r   r   rq   )rD  r   r   Optional[RunnableConfig]r   r   r#  zIterator[dict])rD  r   r   rK  r   r   r#  r   )r"   r#   r$   r%   rQ   r!   rJ  r'   r(   r)   r  r    s     JO(:BF ,0vv )v 	v
 
vv ,0 ) 	
 
r(   r  )/
__future__r   r   loggingrZ   rK   dataclassesr   r   hashlibr   typingr   r   r	   r
   r   r   r   rd    langchain_core.callbacks.managerr   langchain_core.documentsr   langchain_core.embeddingsr   langchain_core.runnablesr   r   langchain_core.vectorstoresr   r   pydanticr   	getLoggerr"   r`   r   r   r   r   r+   r2   r:   rS   r  r  r'   r(   r)   <module>rX     s    "   	  (  G G G  . 0 = I 			8	$'    "      (   * O0 O0 O0do
k o
dC+ C0[ [r(   