a
    bg<                     @  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   w/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/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                   @  s8  e Zd ZdZd=ddddd	d
dddZeddddZd>ddddddZddddZd?dddd
ddddZ	d@ddd
dd d!d"Z
dAddd
d#d d$d%ZdBd&dd
dd'd(d)ZdCd&dd
d#d'd*d+ZdDddd.dd
dd/d0d1ZdEd&dd.dd
dd2d3d4ZdFd5d
dd6d7d8ZedGddddddd9d
d:d;d<ZdS )H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
    LangChainCollectionNFr   strzOptional[VikingDBConfig]zOptional[dict]zOptional[bool]r   )embedding_functioncollection_nameconnection_argsindex_paramsdrop_oldkwargsc                 K  s  zddl m}m} W n ty.   tdY n0 || _|| _d| _|| _|| _|| _	||j
|j|j|j|j| _z| j|}	W n ty   d }	Y n0 |	| _d | _| jd ur| j| j| j| _|rt| j|r| j|}
|
D ]}| j||j q| j| d | _d | _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indexesr.   r   r   r   r   2   sD    	


zVikingDB.__init__)returnc                 C  s   | j S r   )r)   r   r   r   r   
embeddingsa   s    zVikingDB.embeddingsr   zOptional[List[dict]]None)r3   	metadatasr1   c           	      C  s  zddl m}m} W n ty.   tdY n0 t|d }g }|rB|d  D ]\}}t|trx||||j	 qRt|t
r||||j qRt|tr||||j qRt|trtdd |D r||||j qRt|trtdd |D r||||j qRt|tr8||||j qRtdqR||d|j ||d	|j	d
d ||d|j|d | j| j|| _d S )Nr   )Field	FieldTyper&   c                 s  s   | ]}t |tV  qd S r   )r/   r   .0itemr   r   r   	<genexpr>z   s   z.VikingDB._create_collection.<locals>.<genexpr>c                 s  s   | ]}t |tV  qd S r   )r/   intr8   r   r   r   r;   ~   s   z>metadatas value is invalidplease change the type of metadatas.textprimary_keyT)Zis_primary_keyvector)dim)r'   r6   r7   r(   lenitemsr/   r   appendStringr<   ZInt64boolZBoollistallZList_StringZ
List_Int64bytesText
ValueErrorZVectorr+   Zcreate_collectionr   r-   )	r   r3   r5   r6   r7   r@   fieldskeyvaluer   r   r   _create_collectione   sB    




zVikingDB._create_collectionc                 C  s   zddl m} W n ty*   tdY n0 d}| }d}d }| jd ur| jdd urb| jd }| jdd ur|| jd }| jdd ur| jd }| jd	d ur| jd	 }| jj| j| j||||d
| _	d S )Nr   )VectorIndexParamsr&       	cpu_quotavector_indexpartition_byscalar_index)rS   rR   rT   rU   )
r'   rO   r(   r!   getr+   Zcreate_indexr   r*   r.   )r   rO   rR   rS   rT   rU   r   r   r   _create_index   s6    





zVikingDB._create_index  z	List[str]r<   )textsr5   
batch_sizer#   r1   c                   s  zddl m} W n ty*   tdY n0 t|}z j|}W n$ tyh    fdd|D }Y n0 t|dkrt	d g S  j
du r ||    g }g }tt|D ]}	tt }
||
 ||	 |
||	 d}|dur*|	t|k r*t||	  }|D ]}||	 |||< q||| qt|}td||D ],}t|| |}||| } j
| qN|S )	zInsert text data into VikingDB.r   )Datar&   c                   s   g | ]} j |qS r   )r)   embed_query)r9   xr2   r   r   
<listcomp>       z&VikingDB.add_texts.<locals>.<listcomp>zNothing to insert, skipping.N)r=   r>   r?   )r'   r[   r(   rF   r)   Zembed_documentsNotImplementedErrorrA   loggerdebugr-   rN   rW   ranger   uuiduuid4rC   keysrV   minZupsert_data)r   rY   r5   rZ   r#   r[   r3   dataZpksr.   r>   fieldnamesnameZtotal_countiendZinsert_datar   r2   r   	add_texts   sJ    



zVikingDB.add_textszList[Document])queryparamsr#   r1   c                 K  s$   | j f ||d|}dd |D S )5Perform a similarity search against the query string.)ro   rp   c                 S  s   g | ]\}}|qS r   r   r9   doc_r   r   r   r^      r_   z.VikingDB.similarity_search.<locals>.<listcomp>)similarity_search_with_score)r   ro   rp   r#   resr   r   r   similarity_search   s    zVikingDB.similarity_searchzList[Tuple[Document, float]]c                 K  s&   | j |}| jf ||d|}|S )APerform a search on a query string and return results with score.	embeddingrp   )r)   r\   &similarity_search_with_score_by_vector)r   ro   rp   r#   rz   rv   r   r   r   ru      s    z%VikingDB.similarity_search_with_scorezList[float])rz   rp   r#   r1   c                 K  s$   | j f ||d|}dd |D S )rq   ry   c                 S  s   g | ]\}}|qS r   r   rr   r   r   r   r^     r_   z8VikingDB.similarity_search_by_vector.<locals>.<listcomp>)r{   )r   rz   rp   r#   rv   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r|ddurF|d }|ddur\|d }|ddurr|d }|ddur|d }| jj|||||d	}g }	|D ]l}
d
|
jv r|
jd
 d|
jv r|
jd d}d|
jv r|
jd}t||
jd}||
j	f}|	
| q|	S )rx   N!No existing collection to search.
   defaultfilterlimitoutput_fields	partitionr   r   r   r   r>   r?   rQ   r=   page_contentmetadata)r-   ra   rb   rV   r.   search_by_vectorrK   popr   ZscorerC   )r   rz   rp   r#   r   r   r   r   rv   retr:   r   rs   pairr   r   r   r{   	  sH    





z/VikingDB.similarity_search_with_score_by_vector         ?float)ro   klambda_multrp   r#   r1   c                 K  s&   | j |}| jf ||||d|S )>Perform a search and return results that are reordered by MMR.)rz   r   r   rp   )r)   r\   'max_marginal_relevance_search_by_vector)r   ro   r   r   rp   r#   rz   r   r   r   max_marginal_relevance_search8  s    	z&VikingDB.max_marginal_relevance_search)rz   r   r   rp   r#   r1   c                 K  s\  | j du rtd g S d}d}d}d}	|dur|ddurF|d }|ddur\|d }|ddurr|d }|ddur|d }	| jj|||||	d	}
g }g }|
D ]f}d
|jvsd|jvsd|jvrq||jd
 |jd |jd}t	||jd}|| qt
t||||d}g }|D ]&}|dkrF qXn|||  q0|S )r   Nr}   r~   r   r   r   r   r   r   r?   r>   r=   r   )r   r   )r-   ra   rb   rV   r.   r   rK   rC   r   r   r
   nparray)r   rz   r   r   rp   r#   r   r   r   r   rv   Z	documentsZordered_result_embeddingsr:   r   rs   Znew_orderingr   r]   r   r   r   r   J  s^    	


z0VikingDB.max_marginal_relevance_search_by_vectorzOptional[List[str]])idsr#   r1   c                 K  s$   | j d u rtd | j | d S )Nr}   )r-   ra   rb   Zdelete_data)r   r   r#   r   r   r   delete  s    

zVikingDB.deleterE   )rY   rz   r    r5   r   r!   r"   r#   c           
      K  s<   |du rt d| f |||||d|}	|	j||d |	S )z0Create a collection, indexes it and insert data.NzVikingDBConfig does not exists)r   r   r    r!   r"   )rY   r5   )r,   rn   )
clsrY   rz   r    r5   r   r!   r"   r#   Z	vector_dbr   r   r   
from_texts  s    zVikingDB.from_texts)r   NNF)N)NrX   )N)N)N)N)r   r   N)r   r   N)N)NNr   NF)r   r   r   r   r   propertyr3   rN   rW   rn   rw   ru   r|   r{   r   r   r   classmethodr   r   r   r   r   r   *   sN   
    / -"  7    2      ? 	     r   )
__future__r   loggingrd   typingr   r   r   r   numpyr   Zlangchain_core.documentsr   Zlangchain_core.embeddingsr   Zlangchain_core.vectorstoresr	   Z&langchain_community.vectorstores.utilsr
   	getLoggerr   ra   objectr   r   r   r   r   r   <module>   s   
