
    h<                        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 d dlmZ  ej*                  e      Z G d	 d
e      Z G d de      Zy)    )annotationsN)AnyListOptionalTuple)Document)
Embeddings)VectorStore)Self)maximal_marginal_relevancec                  :    e Zd ZdZ	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZy)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.
    c                J    || _         || _        || _        || _        || _        y N)hostregionakskscheme)selfr   r   r   r   r   s         g/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/langchain_community/vectorstores/vikingdb.py__init__zVikingDBConfig.__init__#   s'     	    N)r   r   r   r   http)r   strr   r   r   r   r   r   r   r   returnNone)__name__
__module____qualname____doc__r    r   r   r   r      sW    $   	
   
r   r   c                     e Zd ZdZ	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZedd       Z	 d	 	 	 	 	 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dZ	 	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZ	 d	 	 	 	 	 ddZe	 	 	 	 	 d 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d!d       Zy)"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
    Nc                0   	 ddl m}m} || _        || _        d| _        || _        || _        || _	         ||j                  |j                  |j                  |j                  |j                        | _        	 | j                  j!                  |      }	|	| _        d | _        | j$                  5| j                  j)                  | j
                  | j                        | _        |rt+        | j$                  |      rr| j                  j-                  |      }
|
D ](  }| j                  j/                  ||j                         * | j                  j1                  |       d | _        d | _        y y y # t        $ r t        d      w xY w# t"        $ r d }	Y w xY w)Nr   )
CollectionVikingDBServicefCould not import volcengine python package. Please install it with `pip install --upgrade volcengine`.LangChainIndex)volcengine.viking_dbr&   r'   ImportErrorembedding_funccollection_name
index_nameconnection_argsindex_paramsdrop_oldr   r   r   r   r   serviceget_collection	Exception
collectionindex	get_index
isinstancelist_indexes
drop_indexdrop_collection)r   embedding_functionr-   r/   r0   r1   kwargsr&   r'   colindexesr6   s               r   r   zVikingDB.__init__:   sx   	H 1.*.( &  """"
	,,--o>C 
??&//0D0DdooVDJ
4??J?ll//@G  K''9I9IJKLL((9"DODJ @89  	M 	*  	C	s   E. 8F .FFFc                    | j                   S r   )r,   )r   s    r   
embeddingszVikingDB.embeddingsi   s    """r   c                   	 ddl m}m} t	        |d         }g }|r~|d   j                         D ]g  \  }}t        |t              r#|j                   |||j                               :t        |t              r#|j                   |||j                               mt        |t              r#|j                   |||j                               t        |t              r5t        d |D              r#|j                   |||j                                t        |t              r6t        d |D              r$|j                   |||j"                               +t        |t$              r$|j                   |||j&                               _t)        d       |j                   |d|j&                               |j                   |d|j                  d	
             |j                   |d|j*                  |             | j,                  j/                  | j0                  |      | _        y # t        $ r t        d      w xY w)Nr   )Field	FieldTyper(   c              3  <   K   | ]  }t        |t                y wr   )r8   r   .0items     r   	<genexpr>z.VikingDB._create_collection.<locals>.<genexpr>         5.2JtS)5   c              3  <   K   | ]  }t        |t                y wr   )r8   intrF   s     r   rI   z.VikingDB._create_collection.<locals>.<genexpr>   rJ   rK   z>metadatas value is invalidplease change the type of metadatas.textprimary_keyT)is_primary_keyvector)dim)r*   rC   rD   r+   lenitemsr8   r   appendStringrM   Int64boolBoollistallList_String
List_Int64bytesText
ValueErrorVectorr2   create_collectionr-   r5   )	r   rA   	metadatasrC   rD   rR   fieldskeyvalues	            r   _create_collectionzVikingDB._create_collectionm   s   	= *Q- 'l002 
UeS)MM%Y-=-=">?s+MM%Y__"=>t,MM%Y^^"<=t, 56;5 2 MM%Y-B-B"CDt, 56;5 2 MM%Y-A-A"BCu-MM%Y^^"<=$X '. 	eFINN34eM9+;+;DQReHi&6&6C@A,,889M9MvVK  	M 	s   H1 1Ic                8   	 ddl m} d} |       }d}d }| j                  | j                  j	                  d      | j                  d   }| j                  j	                  d      | j                  d   }| j                  j	                  d      | j                  d   }| j                  j	                  d	      | j                  d	   }| j
                  j                  | j                  | j                  ||||
      | _	        y # t        $ r t        d      w xY w)Nr   )VectorIndexParamsr(       	cpu_quotavector_indexpartition_byscalar_index)rm   rl   rn   ro   )
r*   ri   r+   r0   getr2   create_indexr-   r.   r6   )r   ri   rl   rm   rn   ro   s         r   _create_indexzVikingDB._create_index   s&   	> 	(*(  $$[1= --k:	  $$^4@#00@  $$^4@#00@  $$^4@#00@\\..  OO%%% / 

'  	M 	s   D Dc                   	 ddl m} t        |      }	 | j                  j                  |      }t        |      dk(  rt        j                  d       g S | j                  "| j                  ||       | j                          g }g }	t        t        |            D ]  }
t        t!        j"                               }|	j%                  |       ||
   |||
   d}|H|
t        |      k  r:t        ||
   j'                               }|D ]  }||
   j)                  |      ||<    |j%                   ||              t        |      }t        d||      D ]1  }t+        ||z   |      }||| }| j                  j-                  |       3 |	S # t        $ r t        d      w xY w# t        $ r2 |D cg c]  }| j                  j                  |       nc c}w }}Y w xY w)zInsert text data into VikingDB.r   )Datar(   zNothing to insert, skipping.)rN   rO   rQ   )r*   rt   r+   rZ   r,   embed_documentsNotImplementedErrorembed_queryrS   loggerdebugr5   rg   rr   ranger   uuiduuid4rU   keysrp   minupsert_data)r   textsrc   
batch_sizer=   rt   rA   xdatapksr6   rO   fieldnamesnametotal_countiendinsert_datas                      r   	add_textszVikingDB.add_texts   s   	1 U	M,,<<UCJ z?aLL78I??"##J	:  3z?+ 	%Edjjl+KJJ{#e*$U+E
 $Y)?Yu-2245! =D"+E"2"6"6t"<E$K=KKU$	% $iq+z2 	5Aa*nk2Cq+KOO''4		5
 
Q  	M 	 # 	MFKL$--99!<LLJL	Ms(   F F  F G-"GGGc                b     | j                   d||d|}|D cg c]  \  }}|	 c}}S c c}}w )5Perform a similarity search against the query string.)queryparamsr"   )similarity_search_with_score)r   r   r   r=   resdoc_s          r   similarity_searchzVikingDB.similarity_search   s8     0d//UeFUfU"%&Q&&&   +c                f    | j                   j                  |      } | j                  d||d|}|S )APerform a search on a query string and return results with score.	embeddingr   r"   )r,   rw   &similarity_search_with_score_by_vector)r   r   r   r=   r   r   s         r   r   z%VikingDB.similarity_search_with_score   sE     ''33E:	9d99 

28
 
r   c                b     | j                   d||d|}|D cg c]  \  }}|	 c}}S c c}}w )r   r   r"   )r   )r   r   r   r=   r   r   r   s          r   similarity_search_by_vectorz$VikingDB.similarity_search_by_vector  sB     :d99 

28
 #&&Q&&&r   c                   | j                   t        j                  d       g S d}d}d}d}|X|j                  d      |d   }|j                  d      |d   }|j                  d      |d   }|j                  d      |d   }| j                  j                  |||||	      }g }	|D ]  }
d
|
j                  v r|
j                  j                  d
       d|
j                  v r|
j                  j                  d       d}d|
j                  v r|
j                  j                  d      }t        ||
j                        }||
j                  f}|	j                  |        |	S )r   N!No existing collection to search.
   defaultfilterlimitoutput_fields	partitionr   r   r   r   rO   rQ   rk   rN   page_contentmetadata)r5   rx   ry   rp   r6   search_by_vectorrd   popr   scorerU   )r   r   r   r=   r   r   r   r   r   retrH   r   r   pairs                 r   r   z/VikingDB.similarity_search_with_score_by_vector  sg    ??"LL<=I	zz(#/)zz'".wzz/*6 & 7zz+&2";/	jj))' * 
  
	D+.4;;&)L$#{{v6t{{KC$DJJt
	 
r   c                f    | j                   j                  |      } | j                  d||||d|S )>Perform a search and return results that are reordered by MMR.)r   klambda_multr   r"   )r,   rw   'max_marginal_relevance_search_by_vector)r   r   r   r   r   r=   r   s          r   max_marginal_relevance_searchz&VikingDB.max_marginal_relevance_search?  sJ     ''33E:	;t;; 
#	

 
 	
r   c                Z   | j                   t        j                  d       g S d}d}d}d}	|X|j                  d      |d   }|j                  d      |d   }|j                  d      |d   }|j                  d      |d   }	| j                  j                  |||||		      }
g }g }|
D ]  }d
|j                  vsd|j                  vsd|j                  vr.|j                  |j                  j                  d
             |j                  j                  d       |j                  j                  d      }t        ||j                        }|j                  |        t        t        j                  |      |||      }g }|D ]  }|dk(  r |S |j                  ||            |S )r   Nr   r   r   r   r   r   r   r   rQ   rO   rN   r   )r   r   )r5   rx   ry   rp   r6   r   rd   rU   r   r   r   nparray)r   r   r   r   r   r=   r   r   r   r   r   	documentsordered_result_embeddingsrH   r   r   new_orderingr   r   s                      r   r   z0VikingDB.max_marginal_relevance_search_by_vectorQ  s    ??"LL<=I	zz(#/)zz'".wzz/*6 & 7zz+&2";/	jj))' * 
 	$&! 	"D+ 3,%,,T[[__X-FGKKOOM*;;??62Lt{{KCS!	" 2HHY!:a[
  	)ABw 
 

9Q<(	) 
r   c                |    | j                   t        j                  d       | j                   j                  |       y )Nr   )r5   rx   ry   delete_data)r   idsr=   s      r   deletezVikingDB.delete  s-    
 ??"LL<=##C(r   c           	     b    |t        d       | d|||||d|}	|	j                  ||       |	S )z0Create a collection, indexes it and insert data.zVikingDBConfig does not exists)r<   r-   r/   r0   r1   )r   rc   r"   )r4   r   )
clsr   r   r/   rc   r-   r0   r1   r=   	vector_dbs
             r   
from_textszVikingDB.from_texts  sY     "<== 
(++%
 
	 	%9=r   )LangChainCollectionNNF)r<   r	   r-   r   r/   Optional[VikingDBConfig]r0   Optional[dict]r1   zOptional[bool]r=   r   )r   r	   r   )rA   r   rc   Optional[List[dict]]r   r   )r   r   )Ni  )
r   	List[str]rc   r   r   rM   r=   r   r   r   )r   r   r   r   r=   r   r   List[Document])r   r   r   r   r=   r   r   List[Tuple[Document, float]])r   List[float]r   r   r=   r   r   r   )r   r   r   r   r=   r   r   r   )   g      ?N)r   r   r   rM   r   floatr   r   r=   r   r   r   )r   r   r   rM   r   r   r   r   r=   r   r   r   )r   zOptional[List[str]]r=   r   r   r   )NNr   NF)r   r   r   r	   r/   r   rc   r   r-   r   r0   r   r1   rX   r=   r   r   r   )r   r   r    r!   r   propertyrA   rg   rr   r   r   r   r   r   r   r   r   classmethodr   r"   r   r   r$   r$   2   s     548'+#(-&- - 2	-
 %- !- -^ # # CG*W*W+?*W	*WX
D +/	22 (2 	2
 2 
2n "&'' ' 	'
 
' "&  	
 
&" "&
'
' 
' 	
'
 

' "&-- - 	-
 
&-d  !%

 
 	

 
 
 

*  !%;; ; 	;
 ; ; 
;~ $() ) ) 
	) 
 59*.4'+  2	
 (  %   
 r   r$   )
__future__r   loggingr{   typingr   r   r   r   numpyr   langchain_core.documentsr   langchain_core.embeddingsr	   langchain_core.vectorstoresr
   typing_extensionsr   &langchain_community.vectorstores.utilsr   	getLoggerr   rx   objectr   r$   r"   r   r   <module>r      sS    "   - -  - 0 3 " M			8	$V @}{ }r   