o
    Zh{<                     @  s   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eZG dd	 d	eZG d
d deZdS )    )annotationsN)AnyListOptionalTuple)Document)
Embeddings)VectorStore)maximal_marginal_relevancec                   @  s   e Zd ZdZd
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                 C  s"   || _ || _|| _|| _|| _d S N)r   r   r   r   scheme)selfr   r   r   r   r    r   `/var/www/html/lang_env/lib/python3.10/site-packages/langchain_community/vectorstores/vikingdb.py__init__"   s
   
zVikingDBConfig.__init__N)r   r   r   r   r   )__name__
__module____qualname____doc__r   r   r   r   r   r      s    r   c                   @  s   e Zd ZdZ				dDdEddZedFddZ	dGdHddZdIddZ		dJdKd$d%Z		dGdLd)d*Z
	dGdMd,d-Z	dGdNd0d1Z	dGdOd2d3Z	4	5	dPdQd9d:Z	4	5	dPdRd;d<Z	dGdSd?d@Ze					dTdUdBdCZdS )V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                 K  s  z
ddl m}m} W n ty   tdw || _|| _d| _|| _|| _|| _	||j
|j|j|j|j| _z| j|}	W n tyI   d }	Y nw |	| _d | _| jd ur_| j| j| j| _|rt| j|r| j|}
|
D ]
}| j||j qo| 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`.ZLangChainIndex)volcengine.viking_dbr'   r(   ImportErrorembedding_funcr   
index_namer    r"   r$   r   r   r   r   r   serviceZget_collection	Exception
collectionindexZ	get_index
isinstanceZlist_indexesZ
drop_indexZdrop_collection)r   r   r   r    r"   r$   r&   r'   r(   colZindexesr1   r   r   r   r   2   sJ   	

zVikingDB.__init__returnc                 C  s   | j S r   )r,   r   r   r   r   
embeddingsa   s   zVikingDB.embeddingsr6   r   	metadatasOptional[List[dict]]Nonec           	      C  s  z
ddl m}m} W n ty   tdw t|d }g }|r|d  D ]s\}}t|tr9||||j	 q&t|t
rH||||j q&t|trW||||j q&t|trotdd |D ro||||j q&t|trtdd |D r||||j q&t|tr||||j q&td||d|j ||d	|j	d
d ||d|j|d | j| j|| _d S )Nr   )Field	FieldTyper)   c                 s      | ]}t |tV  qd S r   )r2   r   .0itemr   r   r   	<genexpr>z       

z.VikingDB._create_collection.<locals>.<genexpr>c                 s  r<   r   )r2   intr=   r   r   r   r@   ~   rA   z>metadatas value is invalidplease change the type of metadatas.textprimary_keyT)Zis_primary_keyvector)dim)r*   r:   r;   r+   lenitemsr2   r   appendStringrB   ZInt64boolZBoollistallZList_StringZ
List_Int64bytesText
ValueErrorZVectorr.   Zcreate_collectionr   r0   )	r   r6   r7   r:   r;   rF   fieldskeyvaluer   r   r   _create_collectione   sD   



zVikingDB._create_collectionc                 C  s   zddl m} W n ty   tdw d}| }d}d }| jd urV| jdd ur/| jd }| jdd ur<| jd }| jdd urI| jd }| jd	d urV| jd	 }| jj| j| j||||d
| _	d S )Nr   )VectorIndexParamsr)       	cpu_quotavector_indexpartition_byscalar_index)rY   rX   rZ   r[   )
r*   rU   r+   r"   getr.   Zcreate_indexr   r-   r1   )r   rU   rX   rY   rZ   r[   r   r   r   _create_index   s8   




zVikingDB._create_index  texts	List[str]
batch_sizerB   c                   st  zddl m} W n ty   tdw t|}z j|}W n ty2    fdd|D }Y nw t|dkr@t	d g S  j
du rO ||    g }g }tt|D ]>}	tt }
||
 ||	 |
||	 d}|dur|	t|k rt||	  }|D ]}||	 |||< q||| qYt|}td||D ]}t|| |}||| } j
| q|S )	zInsert text data into VikingDB.r   )Datar)   c                   s   g | ]} j |qS r   )r,   embed_query)r>   xr5   r   r   
<listcomp>   s    z&VikingDB.add_texts.<locals>.<listcomp>zNothing to insert, skipping.N)rC   rD   rE   )r*   rb   r+   rL   r,   Zembed_documentsNotImplementedErrorrG   loggerdebugr0   rT   r]   ranger   uuiduuid4rI   keysr\   minZupsert_data)r   r_   r7   ra   r&   rb   r6   dataZpksr1   rD   fieldnamesnameZtotal_countiendZinsert_datar   r5   r   	add_texts   sN   


zVikingDB.add_textsqueryparamsList[Document]c                 K  $   | j d||d|}dd |D S )5Perform a similarity search against the query string.)ru   rv   c                 S     g | ]\}}|qS r   r   r>   doc_r   r   r   re          z.VikingDB.similarity_search.<locals>.<listcomp>Nr   )similarity_search_with_score)r   ru   rv   r&   resr   r   r   similarity_search   s   zVikingDB.similarity_searchList[Tuple[Document, float]]c                 K  s&   | j |}| jd||d|}|S )APerform a search on a query string and return results with score.	embeddingrv   Nr   )r,   rc   &similarity_search_with_score_by_vector)r   ru   rv   r&   r   r   r   r   r   r      s   z%VikingDB.similarity_search_with_scorer   List[float]c                 K  rx   )ry   r   c                 S  rz   r   r   r{   r   r   r   re     r~   z8VikingDB.similarity_search_by_vector.<locals>.<listcomp>Nr   )r   )r   r   rv   r&   r   r   r   r   similarity_search_by_vector   s   z$VikingDB.similarity_search_by_vectorc                 K  s  | j du rtd g S d}d}d}d}|durD|ddur#|d }|ddur.|d }|ddur9|d }|ddurD|d }| jj|||||d	}g }	|D ]6}
d
|
jv r`|
jd
 d|
jv rk|
jd d}d|
jv rx|
jd}t||
jd}||
j	f}|	
| qS|	S )r   N!No existing collection to search.
   defaultfilterlimitoutput_fields	partitionr   r   r   r   rD   rE   rW   rC   page_contentmetadata)r0   rg   rh   r\   r1   search_by_vectorrQ   popr   ZscorerI   )r   r   rv   r&   r   r   r   r   r   retr?   r   r|   pairr   r   r   r     sH   





z/VikingDB.similarity_search_with_score_by_vector         ?klambda_multfloatc                 K  s&   | j |}| jd||||d|S )>Perform a search and return results that are reordered by MMR.)r   r   r   rv   Nr   )r,   rc   'max_marginal_relevance_search_by_vector)r   ru   r   r   rv   r&   r   r   r   r   max_marginal_relevance_search7  s   	z&VikingDB.max_marginal_relevance_searchc                 K  sV  | j du rtd g S d}d}d}d}	|durD|ddur#|d }|ddur.|d }|ddur9|d }|ddurD|d }	| jj|||||	d	}
g }g }|
D ]3}d
|jvsfd|jvsfd|jvrgqU||jd
 |jd |jd}t	||jd}|| qUt
t||||d}g }|D ]}|dkr |S |||  q|S )r   Nr   r   r   r   r   r   r   r   rE   rD   rC   r   )r   r   )r0   rg   rh   r\   r1   r   rQ   rI   r   r   r
   nparray)r   r   r   r   rv   r&   r   r   r   r   r   Z	documentsZordered_result_embeddingsr?   r   r|   Znew_orderingr   rd   r   r   r   r   I  sZ   
	



z0VikingDB.max_marginal_relevance_search_by_vectoridsOptional[List[str]]c                 K  s$   | j d u r
td | j | d S )Nr   )r0   rg   rh   Zdelete_data)r   r   r&   r   r   r   delete  s   

zVikingDB.deleterK   c           
      K  s<   |du rt d| d|||||d|}	|	j||d |	S )z0Create a collection, indexes it and insert data.NzVikingDBConfig does not exists)r   r   r    r"   r$   )r_   r7   r   )r/   rt   )
clsr_   r   r    r7   r   r"   r$   r&   Z	vector_dbr   r   r   
from_texts  s   zVikingDB.from_texts)r   NNF)r   r   r   r   r    r!   r"   r#   r$   r%   r&   r   )r4   r   r   )r6   r   r7   r8   r4   r9   )r4   r9   )Nr^   )
r_   r`   r7   r8   ra   rB   r&   r   r4   r`   )ru   r   rv   r#   r&   r   r4   rw   )ru   r   rv   r#   r&   r   r4   r   )r   r   rv   r#   r&   r   r4   rw   )r   r   rv   r#   r&   r   r4   r   )r   r   N)ru   r   r   rB   r   r   rv   r#   r&   r   r4   rw   )r   r   r   rB   r   r   rv   r#   r&   r   r4   rw   )r   r   r&   r   r4   r9   )NNr   NF)r_   r`   r   r   r    r!   r7   r8   r   r   r"   r#   r$   rK   r&   r   )r   r   r   r   r   propertyr6   rT   r]   rt   r   r   r   r   r   r   r   classmethodr   r   r   r   r   r   *   sP    
/
,"72?	r   )
__future__r   loggingrj   typingr   r   r   r   numpyr   Zlangchain_core.documentsr   Zlangchain_core.embeddingsr   Zlangchain_core.vectorstoresr	   Z&langchain_community.vectorstores.utilsr
   	getLoggerr   rg   objectr   r   r   r   r   r   <module>   s    
