
    Ng<                        d dl mZ d dlZd dlZd dl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  ej        e          Z G d d	e          Z G d
 de          ZdS )    )annotationsN)AnyListOptionalTuple)Document)
Embeddings)VectorStore)maximal_marginal_relevancec                      e Zd ZdZd	dZdS )
VikingDBConfigaA  vikingdb connection config

    See the following documentation for details:
    https://www.volcengine.com/docs/6459/1167770

    Attribute:
        host(str):The access address of the vector database server
            that the client needs to connect to.
        region(str):"cn-shanghai" or "cn-beijing"
        ak(str):Access Key ID, security credentials for accessing
            Volcano Engine services.
        sk(str):Secret Access Key, security credentials for accessing
            Volcano Engine services.
        scheme(str):http or https, defaulting to http.
    hostregionakskhttpc                L    || _         || _        || _        || _        || _        d S N)r   r   r   r   scheme)selfr   r   r   r   r   s         e/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/vectorstores/vikingdb.py__init__zVikingDBConfig.__init__"   s)    	    N)r   r   r   r   r   )__name__
__module____qualname____doc__r    r   r   r   r      s2               r   r   c                      e Zd ZdZ	 	 	 	 d7d8dZed9d            Z	 d:d;dZd<dZ	 	 d=d>d Z		 d:d?d$Z
	 d:d@d&Z	 d:dAd)Z	 d:dBd*Z	 	 	 dCdDd0Z	 	 	 dCdEd1Z	 d:dFd4Ze	 	 	 	 	 dGdHd6            ZdS )IVikingDBzvikingdb as a vector store

    In order to use this you need to have a database instance.
    See the following documentation for details:
    https://www.volcengine.com/docs/6459/1167774
    LangChainCollectionNFembedding_functionr	   collection_namestrconnection_argsOptional[VikingDBConfig]index_paramsOptional[dict]drop_oldOptional[bool]kwargsr   c                   	 ddl m}m} n# t          $ r t          d          w xY w|| _        || _        d| _        || _        || _        || _	         ||j
        |j        |j        |j        |j                  | _        	 | j                            |          }	n# t"          $ r d }	Y nw xY w|	| _        d | _        | j        *| j                            | j        | j                  | _        |r~t+          | j        |          rk| j                            |          }
|
D ]"}| j                            ||j                   #| j                            |           d | _        d | _        d S d S d S )Nr   )
CollectionVikingDBServicefCould not import volcengine python package. Please install it with `pip install --upgrade volcengine`.LangChainIndex)volcengine.viking_dbr-   r.   ImportErrorembedding_funcr#   
index_namer%   r'   r)   r   r   r   r   r   serviceget_collection	Exception
collectionindex	get_index
isinstancelist_indexes
drop_indexdrop_collection)r   r"   r#   r%   r'   r)   r+   r-   r.   colindexesr9   s               r   r   zVikingDB.__init__2   s   	HHHHHHHHH 	 	 	M  	
 1.*.( & ""
 
	,--o>>CC 	 	 	CCC	
?&//0DdoVVDJ 	
4?J?? 	l//@@G  K K''9IJJJJL((999"DODJJJ	 	 	 	s    % B B*)B*returnc                    | j         S r   )r3   )r   s    r   
embeddingszVikingDB.embeddingsa   s    ""r   rC   r   	metadatasOptional[List[dict]]Nonec                2   	 ddl m}m} n# t          $ r t          d          w xY wt	          |d                   }g }|r|d                                         D ]\  }}t          |t                    r%|                     |||j	                             @t          |t                    r%|                     |||j                             zt          |t                    r%|                     |||j                             t          |t                    r?t          d |D                       r&|                     |||j                             t          |t                    r?t          d |D                       r&|                     |||j                             \t          |t$                    r&|                     |||j                             t)          d          |                     |d|j                             |                     |d|j	        d	
                     |                     |d|j        |                     | j                            | j        |          | _        d S )Nr   )Field	FieldTyper/   c              3  @   K   | ]}t          |t                    V  d S r   )r;   r$   .0items     r   	<genexpr>z.VikingDB._create_collection.<locals>.<genexpr>z   =       5 5.2JtS))5 5 5 5 5 5r   c              3  @   K   | ]}t          |t                    V  d S r   )r;   intrK   s     r   rN   z.VikingDB._create_collection.<locals>.<genexpr>~   rO   r   z>metadatas value is invalidplease change the type of metadatas.textprimary_keyT)is_primary_keyvector)dim)r1   rH   rI   r2   lenitemsr;   r$   appendStringrQ   Int64boolBoollistallList_String
List_Int64bytesText
ValueErrorVectorr5   create_collectionr#   r8   )	r   rC   rD   rH   rI   rV   fieldskeyvalues	            r   _create_collectionzVikingDB._create_collectione   s   	========= 	 	 	M  	
 *Q-   	'l0022  
UeS)) MM%%Y-=">">????s++ MM%%Y_"="=>>>>t,, MM%%Y^"<"<====t,,  5 56;5 5 5 2 2  MM%%Y-B"C"CDDDDt,, 
 5 56;5 5 5 2 2 
 MM%%Y-A"B"BCCCCu-- MM%%Y^"<"<====$?  
 	eeFIN33444eeM9+;DQQQRRReeHi&6C@@@AAA,889MvVVs    %c                   	 ddl m} n# t          $ r t          d          w xY wd} |            }d}d }| j        | j                            d          | j        d         }| j                            d          | j        d         }| j                            d          | j        d         }| j                            d	          | j        d	         }| j                            | j        | j        ||||
          | _	        d S )Nr   )VectorIndexParamsr/       	cpu_quotavector_indexpartition_byscalar_index)rp   ro   rq   rr   )
r1   rl   r2   r'   getr5   create_indexr#   r4   r9   )r   rl   ro   rp   rq   rr   s         r   _create_indexzVikingDB._create_index   s@   	>>>>>>> 	 	 	M  	
 	((**( $$[11= -k:	 $$^44@#0@ $$^44@#0@ $$^44@#0@\.. O%%% / 
 



s   	 #  texts	List[str]
batch_sizerQ   c                &    	 ddl m} n# t          $ r t          d          w xY wt          |          }	  j                            |          }n# t          $ r  fd|D             }Y nw xY wt          |          dk    rt          	                    d           g S  j
        *                     ||                                             g }g }t          t          |                    D ]}	t          t          j                              }
|                    |
           ||	         |
||	         d}|]|	t          |          k     rJt          ||	                                                   }|D ] }||	                             |          ||<   !|                     ||                     t          |          }t          d||          D ]9}t)          ||z   |          }|||         } j
                            |           :|S )zInsert text data into VikingDB.r   )Datar/   c                D    g | ]}j                             |          S r   )r3   embed_query)rL   xr   s     r   
<listcomp>z&VikingDB.add_texts.<locals>.<listcomp>   s*    LLL$-99!<<LLLr   zNothing to insert, skipping.N)rR   rS   rU   )r1   r{   r2   r^   r3   embed_documentsNotImplementedErrorrW   loggerdebugr8   rj   ru   ranger$   uuiduuid4rY   keysrs   minupsert_data)r   rw   rD   ry   r+   r{   rC   datapksr9   rS   fieldnamesnametotal_countiendinsert_datas   `                 r   	add_textszVikingDB.add_texts   s`   	1111111 	 	 	M  	
 U	M,<<UCCJJ" 	M 	M 	MLLLLeLLLJJJ	Mz??aLL7888I?"##J	:::    3z??++ 	% 	%Edjll++KJJ{###e*$U+ E
 $Y)?)?Yu-224455! = =D"+E"2"6"6t"<"<E$KKKKU$$$$$iiq+z22 	5 	5Aa*nk22Cqu+KO''4444
s   
 $A A-,A-queryparamsList[Document]c                :     | j         d||d|}d |D             S )5Perform a similarity search against the query string.)r   r   c                    g | ]\  }}|S r   r   rL   doc_s      r   r   z.VikingDB.similarity_search.<locals>.<listcomp>       &&&Q&&&r   r   )similarity_search_with_score)r   r   r   r+   ress        r   similarity_searchzVikingDB.similarity_search   s7     0d/UeFUUfUU&&#&&&&r   List[Tuple[Document, float]]c                Z    | j                             |          } | j        d||d|}|S )APerform a search on a query string and return results with score.	embeddingr   r   )r3   r}   &similarity_search_with_score_by_vector)r   r   r   r+   r   r   s         r   r   z%VikingDB.similarity_search_with_score   sL     '33E::	9d9 

 
28
 
 
r   r   List[float]c                :     | j         d||d|}d |D             S )r   r   c                    g | ]\  }}|S r   r   r   s      r   r   z8VikingDB.similarity_search_by_vector.<locals>.<listcomp>  r   r   r   )r   )r   r   r   r+   r   s        r   similarity_search_by_vectorz$VikingDB.similarity_search_by_vector   sE     :d9 

 
28
 
 '&#&&&&r   c                   | j         t                              d           g S d}d}d}d}|t|                    d          |d         }|                    d          |d         }|                    d          |d         }|                    d          |d         }| j                            |||||	          }g }	|D ]}
d
|
j        v r|
j                            d
           d|
j        v r|
j                            d           d}d|
j        v r|
j                            d          }t          ||
j                  }||
j	        f}|	
                    |           |	S )r   N!No existing collection to search.
   defaultfilterlimitoutput_fields	partitionr   r   r   r   rS   rU   rn   rR   page_contentmetadata)r8   r   r   rs   r9   search_by_vectorrg   popr   scorerY   )r   r   r   r+   r   r   r   r   r   retrM   r   r   pairs                 r   r   z/VikingDB.similarity_search_with_score_by_vector	  s    ?"LL<===I	zz(##/)zz'"".wzz/**6 & 7zz+&&2";/	j))' * 
 
  
	 
	D++...4;&&)))L$$#{v66t{KKKC$DJJt
r            ?klambda_multfloatc                Z    | j                             |          } | j        d||||d|S )>Perform a search and return results that are reordered by MMR.)r   r   r   r   r   )r3   r}   'max_marginal_relevance_search_by_vector)r   r   r   r   r   r+   r   s          r   max_marginal_relevance_searchz&VikingDB.max_marginal_relevance_search8  sQ     '33E::	;t; 
#	
 

 
 
 	
r   c                   | j         t                              d           g S d}d}d}d}	|t|                    d          |d         }|                    d          |d         }|                    d          |d         }|                    d          |d         }	| j                            |||||		          }
g }g }|
D ]}d
|j        vsd|j        vs	d|j        vr|                    |j                            d
                     |j                            d           |j                            d          }t          ||j                  }|                    |           t          t          j        |          |||          }g }|D ]%}|dk    r n|                    ||                    &|S )r   Nr   r   r   r   r   r   r   r   rU   rS   rR   r   )r   r   )r8   r   r   rs   r9   r   rg   rY   r   r   r   nparray)r   r   r   r   r   r+   r   r   r   r   r   	documentsordered_result_embeddingsrM   r   r   new_orderingr   r~   s                      r   r   z0VikingDB.max_marginal_relevance_search_by_vectorJ  s    ?"LL<===I	zz(##/)zz'"".wzz/**6 & 7zz+&&2";/	j))' * 
 
 	$&! 	" 	"D++ 33,,%,,T[__X-F-FGGGKOOM***;??622Lt{KKKCS!!!!1HY!:a[
 
 
  	) 	)ABww

9Q<((((
r   idsOptional[List[str]]c                |    | j         t                              d           | j                             |           d S )Nr   )r8   r   r   delete_data)r   r   r+   s      r   deletezVikingDB.delete  s;    
 ?"LL<===##C(((((r   r\   c           	     r    |t          d           | d|||||d|}	|	                    ||           |	S )z0Create a collection, indexes it and insert data.NzVikingDBConfig does not exists)r"   r#   r%   r'   r)   )rw   rD   r   )r7   r   )
clsrw   r   r%   rD   r#   r'   r)   r+   	vector_dbs
             r   
from_textszVikingDB.from_texts  sn     "<===C 
(++%
 
 
 
	 	%9===r   )r!   NNF)r"   r	   r#   r$   r%   r&   r'   r(   r)   r*   r+   r   )rA   r	   r   )rC   r   rD   rE   rA   rF   )rA   rF   )Nrv   )
rw   rx   rD   rE   ry   rQ   r+   r   rA   rx   )r   r$   r   r(   r+   r   rA   r   )r   r$   r   r(   r+   r   rA   r   )r   r   r   r(   r+   r   rA   r   )r   r   r   r(   r+   r   rA   r   )r   r   N)r   r$   r   rQ   r   r   r   r(   r+   r   rA   r   )r   r   r   rQ   r   r   r   r(   r+   r   rA   r   )r   r   r+   r   rA   rF   )NNr!   NF)rw   rx   r   r	   r%   r&   rD   rE   r#   r$   r'   r(   r)   r\   r+   r   )r   r   r   r   r   propertyrC   rj   ru   r   r   r   r   r   r   r   r   classmethodr   r   r   r   r    r    *   s          548'+#(- - - - -^ # # # X# CG+W +W +W +W +WZ
 
 
 
D +/	2 2 2 2 2n "&' ' ' ' ' "&    " "&
' 
' 
' 
' 
' "&- - - - -d  !%
 
 
 
 
*  !%; ; ; ; ;~ $() ) ) ) ) 
 59*.4'+    [  r   r    )
__future__r   loggingr   typingr   r   r   r   numpyr   langchain_core.documentsr   langchain_core.embeddingsr	   langchain_core.vectorstoresr
   &langchain_community.vectorstores.utilsr   	getLoggerr   r   objectr   r    r   r   r   <module>r      s   " " " " " "   - - - - - - - - - - - -     - - - - - - 0 0 0 0 0 0 3 3 3 3 3 3 M M M M M M		8	$	$    V   2~ ~ ~ ~ ~{ ~ ~ ~ ~ ~r   