
    dh                       S SK Jr  S SKrS SKrS SKrS SKrS SKJrJr  S SK	J
r
  S SKJrJrJrJrJrJrJr  S SKrS SKJr  S SKJr  S SKJr  S S	KJrJr  S S
KJrJr  S SK J!r!  \RD                  " \#5      r$Sr%Sr&Sr'\ " S S5      5       r(\ " S S5      5       r)\ " S S5      5       r*\ " S S5      5       r+ " S S\5      r, " S S\5      r- " S S\5      r.g)    )annotationsN)	dataclassfield)md5)AnyIterableIteratorListOptionalTupleType)CallbackManagerForRetrieverRun)Document)
Embeddings)RunnableRunnableConfig)VectorStoreVectorStoreRetriever)
ConfigDictivAivAivAc                  `    \ rS rSr% SrSrS\S'   SrS\S'   S	rS
\S'   Sr	S
\S'   Sr
S\S'   Srg)SummaryConfig   aR  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stream N)__name__
__module____qualname____firstlineno____doc__r   __annotations__r   r    r!   r"   __static_attributes__r#       `/var/www/html/shao/venv/lib/python3.13/site-packages/langchain_community/vectorstores/vectara.pyr   r      s;     JKM3;K;FDr+   r   c                  D    \ rS rSr% SrSrS\S'   SrS\S'   S	rS
\S'   Sr	g)	MMRConfig.   aw  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_biasr#   N)
r$   r%   r&   r'   r(   r   r)   r1   r4   r*   r#   r+   r,   r.   r.   .   s&     JE3ONEr+   r.   c                  R    \ rS rSr% SrSrS\S'   SrS\S'   S	rS
\S'   Sr	S\S'   Sr
g)RerankConfigC   a  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   rerankerr0   r   rerank_kr2   r3   mmr_diversity_bias user_functionr#   N)r$   r%   r&   r'   r(   r9   r)   r:   r;   r=   r*   r#   r+   r,   r6   r6   C   s2     HcHc ##M3r+   r6   c                      \ rS rSr% SrSrS\S'   SrS\S'   S	rS
\S'   Sr	S\S'   Sr
S\S'   SrS\S'   \" \S9rS\S'   \" \S9rS\S'             S                   SS jjrSrg)VectaraQueryConfigY   a  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        r3   
lambda_valr<   r   filterNOptional[float]score_threshold   n_sentence_beforen_sentence_after)default_factoryr6   rerank_configr   summary_configc                   Xl         X l        X0l        X@l        U	(       a  Xl        O[        5       U l        U(       a(  Xpl        Xpl        [        R                  " S[        5        OXPl        X`l        U
(       a  Xl        g U(       a@  [        SUR                  UR                  S9U l        [        R                  " S[        5        g [        5       U l        g )Nz[n_sentence_context is deprecated. Please use n_sentence_before and n_sentence_after insteadmmrr9   r:   r;   z9MMRConfig is deprecated. Please use RerankConfig instead.)rB   rD   rE   rG   rM   r   rI   rJ   warningswarnDeprecationWarningrL   r6   r1   r4   )selfrB   rD   rE   rG   rI   rJ   n_sentence_context
mmr_configrM   rL   s              r,   __init__VectaraQueryConfig.__init__w   s     $."0"//D %7"$6!MML" &7"$4! !.!-#))#-#<#<"D
 MMK"
 ".Dr+   )rE   rB   rD   rJ   rI   rL   rG   rM   )
rA   rC   r<   NrH   rH   NNNN)rB   r   rD   r3   rE   r   rG   rF   rI   r   rJ   r   rU   zOptional[int]rV   zOptional[MMRConfig]rM   zOptional[SummaryConfig]rL   zOptional[RerankConfig])r$   r%   r&   r'   r(   rB   r)   rD   rE   rG   rI   rJ   r   r6   rL   r   rM   rW   r*   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0 20r+   r?   c                     \ rS rSrSr     S         SS jjr\SS j5       rSS jrSS jr	SSS jjr
SSS	 jjr S       S S
 jjr  S!         S"S jjr  S#           S$S jjr        S%S jr      S&S jr      S'S jr  S(         S)S jjr\  S!           S*S jj5       r\  S!           S+S jj5       rS,S jrS,S jrS-S jrSrg).Vectara   aX  `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                   U=(       d    [         R                  R                  S5      U l        U=(       d    [         R                  R                  S5      U l        U=(       d    [         R                  R                  S5      U l        U R                  b  U R                  b  U R
                  c  [        R                  S5        O"[        R                  SU R                   35        XPl	        [        R                  " 5       U l        [        R                  R                  SS9nU R                  R                  S	U5        X@l        g)
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)rT   vectara_customer_idvectara_corpus_idvectara_api_keyrr   sourceadapters          r,   rW   Vectara.__init__   s     %8 %
2::>>!<
! #4 #
rzz~~8
 !0 T2::>>BS3T%%-&&.$$,NN
 LL+D,C,C+DEF ((*##//A/>Iw/#6 r+   c                    g Nr#   rT   s    r,   
embeddingsVectara.embeddings   s    r+   c                L    U R                   U R                  SU R                  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)rg   re   rk   r{   s    r,   _get_post_headersVectara._get_post_headers   s*     ..44.	
 	
r+   c           
     j   U R                   U R                  US.nU R                  R                  S[        R
                  " U5      SU R                  5       U R                  S9nUR                  S:w  a@  [        R                  SU SUR                   SUR                   S	UR                   35        g
g)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)re   rf   rn   postjsondumpsr   rr   status_coderh   errorreasontext)rT   doc_idbodyresponses       r,   _delete_docVectara._delete_doc   s      4400!

 ==%%2D!**,,, & 
 3&LL5fX=O''(	(//1B'==/#
 r+   c                   0 nU R                   US'   U R                  US'   XS'   U(       a  SOSnU R                  R                  U R	                  5       U[
        R                  " U5      U R                  SS9nUR                  nUR                  5       nSU;   a  US   S	   OS nUS
:X  d  U(       a  US:X  a  gU(       a  US:X  a  gg)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)	re   rf   rn   r   r   r   r   rr   r   )	rT   docuse_core_apirequestapi_endpointr   r   result
status_strs	            r,   
_index_docVectara._index_doc
  s    "$!%!:!:#66!
  32 	
 ==%%**,G$,, & 
 **19V1CVH%f-
#?O1O%Z;6% r+   c                p    U(       a*  U Vs/ sH  o0R                  U5      PM     nn[        U5      $ gs  snf )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)rT   idskwargsidsuccesss        r,   deleteVectara.delete(  s6     69:c''+cG:w< ;s   3c           	     .   / n[        U5       GH  u  pV[        R                  R                  U5      (       d  [        R                  SU S35        ME  U(       a  X%   O0 nU[        US5      4[        R                  " U5      S.nU R                  5       n	U	R                  S5        U R                  R                  SU R                   SU R                   S3US	U	U R                  S
9n
U
R                   S:X  a5  U
R                  5       S   S   n[        R#                  SU SU S35        GM  U
R                   S:X  a*  U
R                  5       S   S   nUR%                  U5        GMY  [        R#                  SU SU
R                  5        35        GM     U$ )a  
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: )	enumeraterb   pathexistsrh   r   openr   r   r   poprn   r   re   rf   rr   r   infoappend)rT   
files_list	metadatasr   doc_idsinxr   mdr   r   r   r   s               r,   	add_filesVectara.add_files7  sx   ( ":.IC77>>$''uTF*CDE#,"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 /< r+   c                \   [        5       nU H"  nUR                  UR                  5       5        M$     UR                  5       nUc  U Vs/ sH  n0 PM     nnU(       a  SUS'   OSS0nUR	                  SS5      n	U	(       a  SOSn
SUS[
        R                  " U5      U
[        X5       VVs/ sH  u  pU[
        R                  " U5      S	.PM      snn0nU R                  XS
9nUS:X  a%  U R                  U5        U R                  U5        U/$ US:X  a  [        S5        U/$ s  snf s  snnf )aB  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

	langchainrv   r   Fpartssectionr   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	hexdigestrd   r   r   zipr   r   print)rT   textsr   r   r   doc_hashtr   _r   section_keyr   r   r   success_strs                  r,   	add_textsVectara.add_textsl  s5   . 5AOOAHHJ' ##%%*+UUI+%0L"$k2Lzz.%8!-g96DJJ|4 #E 5 5HD tzz"~> 5
 oocoE,,V$OOC  x ..A x7 ,s   
D#,$D(c                   [        UR                  [        5      (       a  [        S0 UR                  D6Ul        [        UR                  [        5      (       a  [        S0 UR                  D6Ul        SUSUR                  R                  S;   a  UR                  R                  OUR                  UR                  UR                  S.U R                  UR                  S./S./0nUR                  S:  a  SUR                  0US   S   S   S   S	'   UR                  R                  S
:X  a)  [        SUR                  R                  0S.US   S   S'   OlUR                  R                  S:X  a'  [         UR                  R"                  S.US   S   S'   O+UR                  R                  S:X  a  S[$        0US   S   S'   UR                  R&                  (       ag  UR                  R(                  UR                  R*                  UR                  R,                  S./US   S   S'   U(       a  SUS.US   S   S   S   S'   U$ )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   )rO   udfrerank_multilingual_v1)sentencesBeforesentencesAfter)corpusIdmetadataFilter)r   start
numResultscontextConfig	corpusKeylambdar   lexicalInterpolationConfigrO   diversityBias)
rerankerId	mmrConfigrerankingConfigr   )r   userFunctionr   r   )maxSummarizedResultsresponseLangsummarizerPromptNamesummaryT)storeconversationIdchatr#   )
isinstancerL   dictr6   rM   r   r9   r:   rB   rI   rJ   rf   rE   rD   MMR_RERANKER_IDr;   UDF_RERANKER_IDr=   RERANKER_MULTILINGUAL_V1_IDr   r   r    r!   )rT   r   configr   chat_conv_idr   r   s          r,   _get_query_bodyVectara._get_query_body  sV     f**D11#/#G&2F2F#GF f++T2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           
        U R                   " X40 UD6nU R                  R                  U R                  5       S[        R
                  " U5      U R                  S9nUR                  S:w  a@  [        R                  SSUR                   SUR                   SUR                   S35        / $ UR	                  5       nUR                  (       a0  US	   S
   S    Vs/ sH  nUS   UR                  :  d  M  UPM     nnOUS	   S
   S   nUS	   S
   S   n	/ n
U Hk  nUS    Vs0 sH  oS   US   _M     nnUS   nX   S    Vs0 sH  oS   US   _M     nnSU;  a  SUS'   UR                  U5        U
R                  U5        Mm     [        X5       VVs/ sH  u  p[!        US   US9US   4PM     nnnUR"                  R$                  S;   a  USUR&                   nUR(                  R*                  (       aC  US	   S
   S   S
   S   nUS	   S
   S   S
   S   S   nUR                  [!        USUS.S9S45        U$ s  snf s  snf s  snf s  snnf )zRun 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documentIndexrv   vectarar   page_contentr  rO   r   Nr   factualConsistencyT)r   fcsrC   )r   rn   r   r   r   r   rr   r   rh   r   r   r   rG   r   r   r   r   rL   r9   rB   rM   r   )rT   r   r   r   r   r   r   r	responses	documentsr   xmr   doc_numdoc_mdresr   r  s                      r,   vectara_queryVectara.vectara_query  s    ##E<V<==%%**,1D!,,	 & 
 3&LL!--.i7H
==/$
 I!!  .q1*==AW: 6 66 =  I }-a0<I=)!,Z8		A12:?AF)QwZ'B?(G5>5G
5ST5Si7+5SFTv%#,x IIfR  " Y2	
 3 !"6 '
 3 	 	
 ((,MMj/C  ++]+A.y9!<VDG'*95a89MNwWCJJ%,4PS7T 	 
W @T	
s   H=4H=!IIIc                >    [        S0 UD6nU R                  X5      nU$ )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  )rT   r   r   r   docss        r,   similarity_search_with_score$Vectara.similarity_search_with_scoreG  s&    0 $-f-!!%0r+   c                `    U R                   " U40 UD6nU VVs/ sH  u  pEUPM	     snn$ s  snnf )zReturn 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  )rT   r   r   docs_and_scoresr   r   s         r,   similarity_searchVectara.similarity_searchc  s;     ;;

 #22//222s   *c                J    [        SUSU-
  S9US'   U R                  " U40 UD6$ )a  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.
rO      rP   rL   )r6   r  )rT   r   fetch_klambda_multr   s        r,   max_marginal_relevance_search%Vectara.max_marginal_relevance_searchw  s6    0 #/W[#
 %%e6v66r+   c                d    UR                  S0 5      nU " S0 UD6nUR                  " X4SU0UD6  U$ )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_textsVectara.from_texts  s<    6 zz."5--%PPPr+   c                8    U " S0 UD6nUR                  X5        U$ )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_filesVectara.from_files  s"    . --%+r+   c                    [        X5      $ )zReturn a Vectara RAG runnable.
VectaraRAGrT   r   s     r,   as_ragVectara.as_rag  s    $''r+   c                    [        XSS9$ )z'Return a Vectara RAG runnable for chat.T)r   r.  r0  s     r,   as_chatVectara.as_chat  s    $T22r+   c                D    [        XR                  S[        5       5      S9$ )zreturn a retriever object.r   )vectorstorer   )VectaraRetrieverrd   r?   )rT   r   s     r,   as_retrieverVectara.as_retriever  s!    ZZ:L:N%O
 	
r+   )rn   rk   rg   rf   re   rr   )NNNx   r   )
rs   Optional[str]rt   r<  ru   r<  rr   r   rv   r   )returnOptional[Embeddings])r=  r   )r   r   r=  r   F)r   r   r   r   r=  r   rz   )r   zOptional[List[str]]r   r   r=  Optional[bool])r   Iterable[str]r   Optional[List[dict]]r   r   r=  	List[str])NN)
r   rA  r   rB  r   zOptional[dict]r   r   r=  rC  )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=  rD  )r   r   r   r   r=  List[Document])r0   g      ?)
r   r   r!  r   r"  r3   r   r   r=  rE  )r&  Type[Vectara]r   rC  r'  r>  r   rB  r   r   r=  rZ   )r&  rF  r   rC  r'  r>  r   rB  r   r   r=  rZ   )r   r?   r=  r/  )r   r   r=  r8  )r$   r%   r&   r'   r(   rW   propertyr|   r   r   r   r   r   r   r   r  r  r  r#  classmethodr(  r+  r1  r4  r9  r*   r#   r+   r,   rZ   rZ      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+   rZ   c                  b    \ rS rSr% SrS\S'    S\S'    \" SS9r        SS	 jrSS
 jr	Sr
g)r8  i  zVectara Retriever class.rZ   r7  r?   r   T)arbitrary_types_allowedc                   U R                   R                  " XR                  40 UD6nU VVs/ sH  u  pVUPM	     snn$ s  snnf rz   )r7  r  r   )rT   r   run_managerr   r  r   r   s          r,   _get_relevant_documents(VectaraRetriever._get_relevant_documents  s=     **88VvV"12//222s   >c                <    U R                   R                  " U40 UD6$ )zAdd documents to vectorstore.)r7  add_documents)rT   r  r   s      r,   rP  VectaraRetriever.add_documents  s    --iB6BBr+   r#   N)r   r   rL  r   r   r   r=  rE  )r  rE  r   r   r=  rC  )r$   r%   r&   r'   r(   r)   r   model_configrM  rP  r*   r#   r+   r,   r8  r8    sO    "++ $L33*H3TW3	3Cr+   r8  c                  n    \ rS rSrSr S     S	S jjr S
       SS jjr S
       SS jjrSrg)r/  i  zVectara RAG runnable.

Parameters:
    vectara: Vectara object
    config: VectaraQueryConfig object
    chat: bool, default False
c                6    Xl         X l        X0l        S U l        g rz   )r  r   r   conv_id)rT   r  r   r   s       r,   rW   VectaraRAG.__init__  s     	r+   Nc           
   +     #    U R                   R                  XR                  U R                  U R                  5      nU R                   R
                  R                  U R                   R                  5       S[        R                  " U5      U R                   R                  SS9nUR                  S:w  a?  [        R                  SSUR                   SUR                   SUR                   S	35        g
/ n/ nSU0v   UR!                  5        GH  nU(       d  M  [        R"                  " UR%                  S5      5      n	U	S   n
U
S   nUGcc  U
R'                  SS
5      nUc  MW  [)        UR'                  S5      5      S:  a;  [        R                  SUR'                  S5      S   R'                  S5       35        M  UR'                  SS
5      nU(       aY  UR'                  SS
5      (       aB  US   n[        R+                  SU 35        US:X  a  S
U l        [        R                  S5        GM"  U(       a  UR'                  SS
5      OS
nU(       a  Xl        UR'                  SS
5      (       a+  UR'                  S0 5      R'                  SS
5      nSU0v   GM  [-        US   5      nSU0v   GM  U R                  R.                  (       a4  US    Vs/ sH$  nUS   U R                  R.                  :  d  M"  UPM&     nnOUS   nUS   n/ nU Hn  nUS     Vs0 sH  nUS!   US"   _M     nnUS#   nUU   S     Vs0 sH  nUS!   US"   _M     nnS$U;  a  S%US$'   UR1                  U5        UR3                  U5        Mp     [5        UU5       VVs/ sH  u  nn[7        US   US&9US   4PM     nnnU R                  R8                  R:                  S';   a  US
U R                  R<                   nS(U0v   GM     g
s  snf s  snf s  snf s  snnf 7f))zGet 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  rv   r  r  r
  context)r  r   r   r   rU  rn   r   r   r   r   rr   r   rh   r   r   r   
iter_linesloadsdecoderd   lenr   r   rG   r   r   r   r   rL   r9   rB   )rT   inputr   r   r   r   r  r  liner   r   response_setr   r   st_coderU  r  chunkr  r   r  r  r   r  r  r  s                             r,   r"   VectaraRAG.stream  s      ||++E;;		4<<X<<((--LL2248D!LL44 . 
 3&LL!--.i7H
==/$
 		5!!'')Dt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 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"#O"4 &/w%7
%C"%C fIqz1%C  " $61/8F8,		&)!((, '& &)I%>	 &?EAr %-.vY)+ gJ &?  	 {{0099 >  "/DKKMM2$c**] *^ 	I% L"	sE   DPF8P O97O9=PO>*P;PAPP-A!Pc                    SS0nU R                  U5       Hc  nSU;   a
  US   US'   M  SU;   a
  US   US'   M#  SU;   a  US==   US   -  ss'   M;  SU;   a
  US   US'   MK  [        R                  SU 35        Me     U$ )Nr[  r<   r\  rX  r  zUnknown chunk type: )r"   rh   r   )rT   ra  r   r   r  re  s         r,   invokeVectaraRAG.invoke  s     n[['EE!!&y!1Iu$"'
"3JU"Hx0%"5\E
3E7;< ( 
r+   )r   r   rU  r  r?  )r  rZ   r   r?   r   r   rz   )ra  r   r   Optional[RunnableConfig]r   r   r=  zIterator[dict])ra  r   r   rj  r   r   r=  r   )	r$   r%   r&   r'   r(   rW   r"   rh  r*   r#   r+   r,   r/  r/    s     JO(:BF ,0vv )v 	v
 
vv ,0 ) 	
 
 r+   r/  )/
__future__r   r   loggingrb   rQ   dataclassesr   r   hashlibr   typingr   r   r	   r
   r   r   r   rl    langchain_core.callbacks.managerr   langchain_core.documentsr   langchain_core.embeddingsr   langchain_core.runnablesr   r   langchain_core.vectorstoresr   r   pydanticr   	getLoggerr$   rh   r   r   r   r   r.   r6   r?   rZ   r8  r/  r#   r+   r,   <module>rw     s    "   	  (  G G G  . 0 = I 			8	$'    "      (   * O0 O0 O0do
k o
dC+ C0[ [r+   