
    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  S SK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  \R*                  " \5      r " S S	\5      rg)
    )annotationsN)ThreadPoolExecutor)AnyIterableListOptionalTuple)Document)
Embeddings)VectorStorec                  D   \ 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       SS jjr\	       S                   SS jj5       r
\	      S                 SS	 jj5       rS
rg)Clarifai   a  `Clarifai AI` vector store.

To use, you should have the ``clarifai`` python SDK package installed.

Example:
    .. code-block:: python

            from langchain_community.vectorstores import Clarifai

            clarifai_vector_db = Clarifai(
                    user_id=USER_ID,
                    app_id=APP_ID,
                    number_of_docs=NUMBER_OF_DOCS,
                    )
Nc           	     P   U=(       d    [         R                  R                  S5      nU=(       d    [         R                  R                  S5      nUb  Uc  [        S5      eX0l         SSKJn	  U	" UUUUUUS9R                  U l	        g! [         a  n
[        S5      U
eSn
A
ff = f)	aN  Initialize with Clarifai client.

Args:
    user_id (Optional[str], optional): User ID. Defaults to None.
    app_id (Optional[str], optional): App ID. Defaults to None.
    pat (Optional[str], optional): Personal access token. Defaults to None.
    token (Optional[str], optional): Session token. Defaults to None.
    number_of_docs (Optional[int], optional): Number of documents to return
    during vector search. Defaults to None.
    api_base (Optional[str], optional): API base. Defaults to None.

Raises:
    ValueError: If user ID, app ID or personal access token is not provided.
CLARIFAI_USER_IDCLARIFAI_APP_IDNzCould not find CLARIFAI_USER_ID or CLARIFAI_APP_ID in your environment. Please set those env variables with a valid user ID, app IDr   SearchXCould not import clarifai python package. Please install it with `pip install clarifai`.)user_idapp_idtop_kpattokenbase_url)
osenvironget
ValueError_number_of_docsclarifai.client.searchr   ImportErrorauth_helper_auth)selfr   r   number_of_docsr   r   api_base_user_id_app_idr   es              a/var/www/html/shao/venv/lib/python3.13/site-packages/langchain_community/vectorstores/clarifai.py__init__Clarifai.__init__#   s    . @bjjnn-?@=BJJNN+<=wN 
  .	5  
 + 	
  	A 	s   )B
 

B%B  B%c                0    SSK Jn  SSKJn  [        U5      n[        U5      n	U	S:  d   S5       eUb  U	[        U5      :X  d   S5       eUb  [        U5      [        U5      :X  d   S5       eUR                  U R                  S	9n
S
n/ n[        SX5       GH  n XX-    nU(       a  X-X-    OSnUcA  [        [        U5      5       Vs/ sH"  n[        R                  " 5       R                  PM$     nnOX=X-    nUb4  / nU H,  nU" 5       nUR                  U5        UR                  U5        M.     [        U5       VVs/ sH&  u  nnU
R!                  UU   UU(       a  WU   OSS9PM(     nnnU
R#                  US9nUR%                  U5        [&        R)                  S5        GM     U$ ! [         a  n[	        S5      UeSnAff = fs  snf s  snnf ! [*         a9  n[&        R-                  SU 35        [.        R0                  " 5          SnAGM{  SnAff = f)a  Add texts to the Clarifai vectorstore. This will push the text
to a Clarifai application.
Application use a base workflow that create and store embedding for each text.
Make sure you are using a base workflow that is compatible with text
(such as Language Understanding).

Args:
    texts (Iterable[str]): Texts to add to the vectorstore.
    metadatas (Optional[List[dict]], optional): Optional list of metadatas.
    ids (Optional[List[str]], optional): Optional list of IDs.

r   )Inputs)Structr   Nz,No texts provided to add to the vectorstore.z1Number of texts and metadatas should be the same.z7Number of text inputs and input ids should be the same.)auth    )input_idraw_textmetadata)inputszInput posted successfully.zPost inputs failed: )clarifai.client.inputr/   google.protobuf.struct_pb2r0   r"   listlenfrom_auth_helperr$   rangeuuiduuid4hexupdateappend	enumerateget_text_inputupload_inputsextendloggerdebug	Exceptionwarning	traceback	print_exc)r%   texts	metadatasidskwargsr/   r0   r*   ltextslength	input_obj
batch_sizeinput_job_idsidxbatch_textsbatch_metadatas_	batch_ids	meta_listmetameta_structitextinput_batch	result_iderrors                             r+   	add_textsClarifai.add_textsU   sG   &	49 eVzIIIz S^+ C+ ?v;#c(* I* +++<	
F/C&$3+;<9BIC$45   ;;@[AQ;R S;Ra!1!1;RI SI ##*: ;I". "I /&,h#**40!((5 !0 $-[#9 $:4 ,,!*1!%1@1d - 
 $:   &33;3G	$$Y/9:5 0@ o  	A 	< !T  &!5eW=>##%%&sN   F) .G(G0AG>,G*8G)
G3F??GG
H-HHc                .  ^ ^  SSK Jn  SSKJn  SSKJm  U=(       d    T R                  nUR                  T R                  US9n	SU0/n
Ub  S	U0nU	R                  X/S
9nOU	R                  U
S9nU VVs/ sH  oR                   H  oPM     M     nnn[        SS9nSUU 4S jjnU Vs/ sH  nUR                  UU5      PM     nnU Vs/ sH  nUR                  5       PM     nnU$ ! [         a  n[        S5      UeSnAff = fs  snnf s  snf s  snf )av  Run similarity search with score using Clarifai.

Args:
    query (str): Query text to search for.
    k (Optional[int]): Number of results to return. If not set,
    it'll take _number_of_docs. Defaults to None.
    filter (Optional[Dict[str, str]]): Filter by metadata.
    Defaults to None.

Returns:
    List[Document]: List of documents most similar to the query text.
r   r   )resources_pb2)json_formatr   N)r1   r   text_rawr5   )ranksfilters)rh   
   )max_workersc                ,  > TR                  U R                  R                  R                  5      n[	        TR
                  R                  5      n[        R                  " U R                  R                  R                  R                  US9nUR                  Ul        UR                  n[        R                  SU R                  S SU R                  R                    SU R                  R                    SUS S  35        [#        XAS9U R                  4$ )	N)headersz	Score z.2fz for annotation: z                off input: z, text: }   )page_contentr5   )MessageToDictinputdatar5   dictr$   requestsr   r^   urlapparent_encodingencodingrF   rG   score
annotationidr
   )hitr5   hrequestrequested_textrf   r%   s        r+   hit_to_document>Clarifai.similarity_search_with_score.<locals>.hit_to_document   s    "001H1HIHTZZ(()All399>>#6#6#:#:AFG  '88G$\\NLL399S/):3>>;L;L:M NIILL>.#2F1GI .LciiXX    )r{   zresources_pb2.HitreturnzTuple[Document, float])r!   r   clarifai_grpc.grpc.apire   google.protobufrf   r"   r    r;   r$   queryhitsr   submitresult)r%   r   kri   rO   r   re   r*   r   
search_objranksearch_metadatasearch_responserr   r{   r   executorr   futuresfuturedocs_and_scoresrf   s   `                    @r+   similarity_search_with_score%Clarifai.similarity_search_with_score   s4   &	5<3 )T)),,$**E,J
U#$)73O(..TCT.UO(..T.:O !0E99C9E%"5	Y 	Y  EIIDS8???C8DI9@Av6==?AS  	A 	& F& JAs)   C) 6D+DD)
D3C??Dc                d    U R                   " U4SU0UD6nU VVs/ sH  u  pVUPM	     snn$ s  snnf )a  Run similarity search using Clarifai.

Args:
    query: Text to look up documents similar to.
    k: Number of Documents to return.
    If not set, it'll take _number_of_docs. Defaults to None.

Returns:
    List of Documents most similar to the query and score for each
r   )r   )r%   r   r   rO   r   docrX   s          r+   similarity_searchClarifai.similarity_search   s8      ;;EQQQ&Q"12//222s   ,c	           	     @    U " SUUUUUS.U	D6n
U
R                  XS9  U
$ )am  Create a Clarifai vectorstore from a list of texts.

Args:
    user_id (str): User ID.
    app_id (str): App ID.
    texts (List[str]): List of texts to add.
    number_of_docs (Optional[int]): Number of documents
    to return during vector search. Defaults to None.
    pat (Optional[str], optional): Personal access token.
    Defaults to None.
    token (Optional[str], optional): Session token. Defaults to None.
    metadatas (Optional[List[dict]]): Optional list
    of metadatas. Defaults to None.
    kwargs: Additional keyword arguments to be passed to the Search.

Returns:
    Clarifai: Clarifai vectorstore.
)r   r   r&   r   r   )rL   rM    )rb   )clsrL   	embeddingrM   r   r   r&   r   r   rO   clarifai_vector_dbs              r+   
from_textsClarifai.from_texts   sF    > ! 
)
 
 	$$5$F!!r   c                    U V	s/ sH  oR                   PM     n
n	U V	s/ sH  oR                  PM     nn	U R                  " SUUU
UUUUS.UD6$ s  sn	f s  sn	f )a"  Create a Clarifai vectorstore from a list of documents.

Args:
    user_id (str): User ID.
    app_id (str): App ID.
    documents (List[Document]): List of documents to add.
    number_of_docs (Optional[int]): Number of documents
    to return during vector search. Defaults to None.
    pat (Optional[str], optional): Personal access token. Defaults to None.
    token (Optional[str], optional): Session token. Defaults to None.
    kwargs: Additional keyword arguments to be passed to the Search.

Returns:
    Clarifai: Clarifai vectorstore.
)r   r   rL   r&   r   rM   r   r   )ro   r5   r   )r   	documentsr   r   r   r&   r   r   rO   r   rL   rM   s               r+   from_documentsClarifai.from_documents#  so    6 .77Yc!!Y7-67Yc\\Y	7~~ 	
)	
 	
 		
 87s
   AA)r$   r    )NN   NNzhttps://api.clarifai.com)r   Optional[str]r   r   r&   Optional[int]r   r   r   r   r'   r   r   None)NN)
rL   zIterable[str]rM   Optional[List[dict]]rN   zOptional[List[str]]rO   r   r   	List[str])
r   strr   r   ri   zOptional[dict]rO   r   r   zList[Tuple[Document, float]])N)r   r   r   r   rO   r   r   List[Document])NNNNNNN)rL   r   r   Optional[Embeddings]rM   r   r   r   r   r   r&   r   r   r   r   r   rO   r   r   r   )NNNNNN)r   r   r   r   r   r   r   r   r&   r   r   r   r   r   rO   r   r   r   )__name__
__module____qualname____firstlineno____doc__r,   rb   r   r   classmethodr   r   __static_attributes__r   r   r+   r   r      s+   $ "& $()!#"<00 0 &	0
 0 0  0 
0j +/#'	MM (M !	M
 M 
Md  "&	@@ @  	@
 @ 
&@J  33 3 	3
 
3&  +/*.!% $(,!#'"'" ('" (	'"
 '" '" &'" '" '" '" 
'" '"R  +/!% $(,!#%
!%
 (%
 	%

 %
 &%
 %
 %
 %
 
%
 %
r   r   )
__future__r   loggingr   rJ   r=   concurrent.futuresr   typingr   r   r   r   r	   rt   langchain_core.documentsr
   langchain_core.embeddingsr   langchain_core.vectorstoresr   	getLoggerr   rF   r   r   r   r+   <module>r      sG    "  	   1 7 7  - 0 3			8	$w
{ w
r   