a
    bg3K                     @  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m	Z	m
Z
mZmZ d dl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rd dlZd	d	d
dddZddddddddZdddddZdddddZG dd deZdS )    )annotationsN)TYPE_CHECKINGAnyCallableDictIterableListOptionalTupleuuid4)Document)
Embeddings)VectorStore)maximal_marginal_relevancestrr   )
index_nametext_keyreturnc                 C  s   | |dgdgdS )Ntext)nameZdataType)class
properties )r   r   r   r   w/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain_community/vectorstores/weaviate.py_default_schema   s    r   Optional[str]r   zweaviate.Client)urlapi_keykwargsr   c                 K  st   zdd l }W n ty&   tdY n0 | p6tjd} |pFtjd}|rZ|jj|dnd }|jf | |d|S )Nr   _Could not import weaviate python  package. Please install it with `pip install weaviate-client`ZWEAVIATE_URLZWEAVIATE_API_KEY)r   )r   Zauth_client_secret)weaviateImportErrorosenvirongetauthZ
AuthApiKeyClient)r   r   r   r!   r&   r   r   r   _create_weaviate_client(   s    
r(   float)valr   c                 C  s   dddt |    S )N   )npexp)r*   r   r   r   _default_score_normalizer:   s    r.   )valuer   c                 C  s   t | tjr|  S | S N)
isinstancedatetime	isoformat)r/   r   r   r   _json_serializable>   s    r4   c                   @  sJ  e Zd ZdZddedfddddddd	d
ddZeddddZddddZ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(d)d*ZdDd!ddd'ddd+d,d-ZdEdddd.dd/d0ZedFdddddd1d2ed3dd4dd5d6d6d7d6dd	ddd d8d9d:ZdGddd;d<d=d>ZdS )HWeaviatea  `Weaviate` vector store.

    To use, you should have the ``weaviate-client`` python package installed.

    Example:
        .. code-block:: python

            import weaviate
            from langchain_community.vectorstores import Weaviate

            client = weaviate.Client(url=os.environ["WEAVIATE_URL"], ...)
            weaviate = Weaviate(client, index_name, text_key)

    NTr   r   zOptional[Embeddings]zOptional[List[str]]z"Optional[Callable[[float], float]]bool)clientr   r   	embedding
attributesrelevance_score_fnby_textc           	      C  s   zddl }W n ty&   tdY n0 t||jsFtdt| || _|| _|| _|| _	| j	g| _
|| _|| _|dur| j
| dS )z Initialize with Weaviate client.r   Nz_Could not import weaviate python package. Please install it with `pip install weaviate-client`.z5client should be an instance of weaviate.Client, got )r!   r"   r1   r'   
ValueErrortype_client_index_name
_embedding	_text_key_query_attrsr:   _by_textextend)	selfr7   r   r   r8   r9   r:   r;   r!   r   r   r   __init__T   s&    

zWeaviate.__init__)r   c                 C  s   | j S r0   )r@   rE   r   r   r   
embeddingsv   s    zWeaviate.embeddingszCallable[[float], float]c                 C  s   | j r| j S tS r0   )r:   r.   rG   r   r   r   _select_relevance_score_fnz   s    z#Weaviate._select_relevance_score_fnzIterable[str]zOptional[List[dict]]z	List[str])texts	metadatasr   r   c              
   K  s  ddl m} g }d}| jr8t|ts,t|}| j|}| jj}t|D ]\}}	| j	|	i}
|dur|| 
 D ]\}}t||
|< qp|t }d|v r|d | }nd|v r|d | }|j|
| j||r|| nd|dd || qJW d   n1 s0    Y  |S )z4Upload texts with metadata (properties) to Weaviate.r   get_valid_uuidNuuidsidstenant)data_object
class_nameuuidvectorrP   )weaviate.utilrM   r@   r1   listembed_documentsr>   batch	enumeraterA   itemsr4   r   add_data_objectr?   r%   append)rE   rJ   rK   r   rM   rO   rH   rX   ir   data_propertieskeyr*   _idr   r   r   	add_texts   s6    



,zWeaviate.add_texts   intzList[Document])querykr   r   c                 K  sP   | j r| j||fi |S | jdu r,td| j|}| j||fi |S dS )Return docs most similar to query.

        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.

        Returns:
            List of Documents most similar to the query.
        NzC_embedding cannot be None for similarity_search when _by_text=False)rC   similarity_search_by_textr@   r<   embed_querysimilarity_search_by_vector)rE   rd   re   r   r8   r   r   r   similarity_search   s    
zWeaviate.similarity_searchc           
      K  s   d|gi}| dr"| d|d< | jj | j| j}| drP|| d}| drj|| d}| dr|| d}||	|
 }d|v rtd|d  g }|d	 d
 | j D ]"}|| j}	|t|	|d q|S )rf   conceptssearch_distance	certaintywhere_filterrP   
additionalerrorsError during query: dataGetZpage_contentmetadata)r%   r>   rd   r?   rB   
with_wherewith_tenantwith_additionalwith_near_text
with_limitdor<   poprA   r\   r   )
rE   rd   re   r   content	query_objresultdocsresr   r   r   r   rg      s$    




z"Weaviate.similarity_search_by_textzList[float])r8   re   r   r   c           
      K  s   d|i}| j j| j| j}|dr6||d}|drP||d}|drj||d}||	|
 }d|v rtd|d  g }|d d | j D ]"}|| j}	|t|	|d	 q|S )
z:Look up similar documents by embedding vector in Weaviate.rT   rn   rP   ro   rp   rq   rr   rs   rt   )r>   rd   r%   r?   rB   rv   rw   rx   with_near_vectorrz   r{   r<   r|   rA   r\   r   )
rE   r8   re   r   rT   r~   r   r   r   r   r   r   r   ri      s     


z$Weaviate.similarity_search_by_vector         ?r)   )rd   re   fetch_klambda_multr   r   c                 K  s:   | j dur| j |}ntd| j|f|||d|S )a  Return docs selected using the maximal marginal relevance.

        Maximal marginal relevance optimizes for similarity to query AND diversity
        among selected documents.

        Args:
            query: Text to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            fetch_k: Number of Documents to fetch to pass to MMR algorithm.
            lambda_mult: Number between 0 and 1 that determines the degree
                        of diversity among the results with 0 corresponding
                        to maximum diversity and 1 to minimum diversity.
                        Defaults to 0.5.

        Returns:
            List of Documents selected by maximal marginal relevance.
        NzCmax_marginal_relevance_search requires a suitable Embeddings object)re   r   r   )r@   rh   r<   'max_marginal_relevance_search_by_vector)rE   rd   re   r   r   r   r8   r   r   r   max_marginal_relevance_search   s    
z&Weaviate.max_marginal_relevance_search)r8   re   r   r   r   r   c                 K  s   d|i}| j j| j| j}|dr6||d}|drP||d}|d|	|
 }|d d | j }	dd |	D }
tt||
||d}g }|D ]<}|	| | j}|	| d	 |	| }|t||d
 q|S )a  Return docs selected using the maximal marginal relevance.

        Maximal marginal relevance optimizes for similarity to query AND diversity
        among selected documents.

        Args:
            embedding: Embedding to look up documents similar to.
            k: Number of Documents to return. Defaults to 4.
            fetch_k: Number of Documents to fetch to pass to MMR algorithm.
            lambda_mult: Number between 0 and 1 that determines the degree
                        of diversity among the results with 0 corresponding
                        to maximum diversity and 1 to minimum diversity.
                        Defaults to 0.5.

        Returns:
            List of Documents selected by maximal marginal relevance.
        rT   rn   rP   rr   rs   c                 S  s   g | ]}|d  d qS )_additionalrT   r   ).0r   r   r   r   
<listcomp>B      zDWeaviate.max_marginal_relevance_search_by_vector.<locals>.<listcomp>)re   r   r   rt   )r>   rd   r%   r?   rB   rv   rw   rx   r   rz   r{   r   r,   arrayr|   rA   r\   r   )rE   r8   re   r   r   r   rT   r~   resultspayloadrH   Zmmr_selectedr   idxr   metar   r   r   r     s0    


z0Weaviate.max_marginal_relevance_search_by_vectorzList[Tuple[Document, float]]c                 K  s<  | j du rtdd|gi}|dr4|d|d< | jj| j| j}|drb||d}|dr|||d}| j 	|}| j
sd|i}|||d }n|||d }d	|v rtd
|d	  g }	|d d | j D ]:}
|
| j}t|
d d |}|	t||
d|f q|	S )z
        Return list of documents most similar to the query
        text and cosine distance in float for each.
        Lower score represents more similarity.
        Nz:_embedding cannot be None for similarity_search_with_scorerk   rl   rm   rn   rP   rT   rp   rq   rr   rs   r   rt   )r@   r<   r%   r>   rd   r?   rB   rv   rw   rh   rC   r   rz   rx   r{   ry   r|   rA   r,   dotr\   r   )rE   rd   re   r   r}   r~   Zembedded_queryrT   r   Zdocs_and_scoresr   r   Zscorer   r   r   similarity_search_with_scoreO  sF    






z%Weaviate.similarity_search_with_scorer   F)r7   weaviate_urlweaviate_api_key
batch_sizer   r   r;   r:   r   zOptional[weaviate.Client]r   zOptional[int])rJ   r8   rK   r7   r   r   r   r   r   r;   r:   r   r   c             
     s  zddl m  W n. ty> } ztd|W Y d}~n
d}~0 0 |pNt||d}|rb|jj|d |prdt j }t||	}|j	
|s|j	| |r||nd}|rt|d  nd}d|v r|d}n fd	d
tt|D }|j}t|D ]x\}}|	|i}|dur<||  D ]}|| | ||< q$|| }|||d}|durf|| |d< |jf i | q|  W d   n1 s0    Y  | |||	f||||
d|S )av  Construct Weaviate wrapper from raw documents.

        This is a user-friendly interface that:
            1. Embeds documents.
            2. Creates a new index for the embeddings in the Weaviate instance.
            3. Adds the documents to the newly created Weaviate index.

        This is intended to be a quick way to get started.

        Args:
            texts: Texts to add to vector store.
            embedding: Text embedding model to use.
            metadatas: Metadata associated with each text.
            client: weaviate.Client to use.
            weaviate_url: The Weaviate URL. If using Weaviate Cloud Services get it
                from the ``Details`` tab. Can be passed in as a named param or by
                setting the environment variable ``WEAVIATE_URL``. Should not be
                specified if client is provided.
            weaviate_api_key: The Weaviate API key. If enabled and using Weaviate Cloud
                Services, get it from ``Details`` tab. Can be passed in as a named param
                or by setting the environment variable ``WEAVIATE_API_KEY``. Should
                not be specified if client is provided.
            batch_size: Size of batch operations.
            index_name: Index name.
            text_key: Key to use for uploading/retrieving text to/from vectorstore.
            by_text: Whether to search by text or by embedding.
            relevance_score_fn: Function for converting whatever distance function the
                vector store uses to a relevance score, which is a normalized similarity
                score (0 means dissimilar, 1 means similar).
            kwargs: Additional named parameters to pass to ``Weaviate.__init__()``.

        Example:
            .. code-block:: python

                from langchain_community.embeddings import OpenAIEmbeddings
                from langchain_community.vectorstores import Weaviate

                embeddings = OpenAIEmbeddings()
                weaviate = Weaviate.from_texts(
                    texts,
                    embeddings,
                    weaviate_url="http://localhost:8080"
                )
        r   rL   r    N)r   r   )r   Z
LangChain_rN   c                   s   g | ]} t  qS r   r   )r   _rL   r   r   r     r   z'Weaviate.from_texts.<locals>.<listcomp>)rS   rQ   rR   rT   )r8   r9   r:   r;   )rU   rM   r"   r(   rX   	configurer   hexr   schemaexistsZcreate_classrW   rV   keysr|   rangelenrY   r[   flush)clsrJ   r8   rK   r7   r   r   r   r   r   r;   r:   r   er   rH   r9   rN   rX   r]   r   r^   r_   r`   paramsr   rL   r   
from_texts  sf    @


(zWeaviate.from_textsNone)rO   r   r   c                 K  s.   |du rt d|D ]}| jjj|d qdS )zUDelete by vector IDs.

        Args:
            ids: List of ids to delete.
        NzNo ids provided to delete.)rS   )r<   r>   rQ   delete)rE   rO   r   idr   r   r   r     s    zWeaviate.delete)N)rb   )rb   )rb   )rb   r   r   )rb   r   r   )rb   )N)N)__name__
__module____qualname____doc__r.   rF   propertyrH   rI   ra   rj   rg   ri   r   r   r   classmethodr   r   r   r   r   r   r5   D   sR   "
 ,       '   5 0 , r5   )NN)
__future__r   r2   r#   typingr   r   r   r   r   r   r	   r
   rS   r   numpyr,   Zlangchain_core.documentsr   Zlangchain_core.embeddingsr   Zlangchain_core.vectorstoresr   Z&langchain_community.vectorstores.utilsr   r!   r   r(   r.   r4   r5   r   r   r   r   <module>   s$   (
  