o
    ZhK                     @  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 d d	lmZ erPd dlZd&ddZ		d'd(ddZd)ddZd*ddZed d!d"d#G d$d% d%eZ dS )+    )annotationsN)TYPE_CHECKINGAnyCallableDictIterableListOptionalTupleuuid4)
deprecated)Document)
Embeddings)VectorStore)maximal_marginal_relevance
index_namestrtext_keyreturnr   c                 C  s   | |dgdgdS )Ntext)nameZdataType)class
properties )r   r   r   r   `/var/www/html/lang_env/lib/python3.10/site-packages/langchain_community/vectorstores/weaviate.py_default_schema   s   r   urlOptional[str]api_keykwargsr   weaviate.Clientc                 K  sp   zdd l }W n ty   tdw | ptjd} |p!tjd}|r+|jj|dnd }|jd| |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_secretr   )weaviateImportErrorosenvirongetauthZ
AuthApiKeyClient)r   r   r    r#   r(   r   r   r   _create_weaviate_client)   s   r*   valfloatc                 C  s   dddt |    S )N   )npexp)r+   r   r   r   _default_score_normalizer;   s   r0   valuec                 C  s   t | tjr
|  S | S N)
isinstancedatetime	isoformat)r1   r   r   r   _json_serializable?   s   r6   z0.3.18z1.0z&langchain_weaviate.WeaviateVectorStore)ZsinceZremovalZalternative_importc                   @  s   e Zd ZdZddedfdIddZedJddZdKddZ	dLdMdd Z		!dNdOd&d'Z
	!dNdOd(d)Z	!dNdPd+d,Z	!	-	.dQdRd2d3Z	!	-	.dQdSd4d5Z	!dNdTd7d8Ze	dLdddddd9d:ed;dUdCdDZdLdVdGdHZdS )W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)

    NTclientr   r   r   r   	embeddingOptional[Embeddings]
attributesOptional[List[str]]relevance_score_fn"Optional[Callable[[float], float]]by_textboolc           	      C  s   zddl }W n ty   tdw t||js!tdt| || _|| _|| _|| _	| j	g| _
|| _|| _|durD| j
| dS 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$   r3   r)   
ValueErrortype_client_index_name
_embedding	_text_key_query_attrsr=   _by_textextend)	selfr8   r   r   r9   r;   r=   r?   r#   r   r   r   __init__Z   s*   
zWeaviate.__init__r   c                 C  s   | j S r2   )rE   rJ   r   r   r   
embeddings|   s   zWeaviate.embeddingsCallable[[float], float]c                 C  s   | j r| j S tS r2   )r=   r0   rL   r   r   r   _select_relevance_score_fn   s
   z#Weaviate._select_relevance_score_fntextsIterable[str]	metadatasOptional[List[dict]]r    	List[str]c              
   K  s  ddl m} g }d}| jrt|tst|}| j|}| jj_}t|D ]Q\}}	| j	|	i}
|durC|| 
 D ]
\}}t||
|< q8|t }d|v rS|d | }n
d|v r]|d | }|j|
| j||ri|| nd|dd || q%W d   |S 1 sw   Y  |S )z4Upload texts with metadata (properties) to Weaviate.r   get_valid_uuidNuuidsidstenant)data_object
class_nameuuidvectorrY   )weaviate.utilrV   rE   r3   listembed_documentsrC   batch	enumeraterF   itemsr6   r   add_data_objectrD   r'   append)rJ   rP   rR   r    rV   rX   rM   ra   ir   data_propertieskeyr+   _idr   r   r   	add_texts   s>   




zWeaviate.add_texts   querykintList[Document]c                 K  sL   | j r| j||fi |S | jdu rtd| j|}| j||fi |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)rH   similarity_search_by_textrE   rA   embed_querysimilarity_search_by_vector)rJ   rl   rm   r    r9   r   r   r   similarity_search   s   
zWeaviate.similarity_searchc           
      K  s   d|gi}| dr| d|d< | jj | j| j}| dr(|| d}| dr5|| d}| drB|| d}||	|
 }d|v rYtd|d  g }|d	 d
 | j D ]}|| j}	|t|	|d qd|S )rp   conceptssearch_distance	certaintywhere_filterrY   
additionalerrorsError during query: dataGetZpage_contentmetadata)r'   rC   rl   rD   rG   
with_wherewith_tenantwith_additionalwith_near_text
with_limitdorA   poprF   re   r   )
rJ   rl   rm   r    content	query_objresultdocsresr   r   r   r   rq      s$   




z"Weaviate.similarity_search_by_textList[float]c           
      K  s   d|i}| j j| j| j}|dr||d}|dr(||d}|dr5||d}||	|
 }d|v rLtd|d  g }|d d | j D ]}|| j}	|t|	|d	 qW|S )
z:Look up similar documents by embedding vector in Weaviate.r]   rx   rY   ry   rz   r{   r|   r}   r~   )rC   rl   r'   rD   rG   r   r   r   with_near_vectorr   r   rA   r   rF   re   r   )
rJ   r9   rm   r    r]   r   r   r   r   r   r   r   r   rs      s    


z$Weaviate.similarity_search_by_vector         ?fetch_klambda_multr,   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)rm   r   r   )rE   rr   rA   'max_marginal_relevance_search_by_vector)rJ   rl   rm   r   r   r    r9   r   r   r   max_marginal_relevance_search   s   
z&Weaviate.max_marginal_relevance_searchc                 K  s   d|i}| j j| j| j}|dr||d}|dr(||d}|d|	|
 }|d d | j }	dd |	D }
tt||
||d}g }|D ]}|	| | j}|	| d	 |	| }|t||d
 qT|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.
        r]   rx   rY   r|   r}   c                 S  s   g | ]}|d  d qS )_additionalr]   r   ).0r   r   r   r   
<listcomp>H  s    zDWeaviate.max_marginal_relevance_search_by_vector.<locals>.<listcomp>)rm   r   r   r~   )rC   rl   r'   rD   rG   r   r   r   r   r   r   r   r.   arrayr   rF   re   r   )rJ   r9   rm   r   r   r    r]   r   resultspayloadrM   Zmmr_selectedr   idxr   metar   r   r   r   !  s.   

z0Weaviate.max_marginal_relevance_search_by_vectorList[Tuple[Document, float]]c                 K  s<  | j du r	tdd|gi}|dr|d|d< | jj| j| j}|dr1||d}|dr>||d}| j 	|}| j
sYd|i}|||d }n|||d }d	|v rst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_scoreru   rv   rw   rx   rY   r]   rz   r{   r|   r}   r   r~   )rE   rA   r'   rC   rl   rD   rG   r   r   rr   rH   r   r   r   r   r   r   rF   r.   dotre   r   )rJ   rl   rm   r    r   r   Zembedded_queryr]   r   Zdocs_and_scoresr   r   Zscorer   r   r   similarity_search_with_scoreU  sB   




z%Weaviate.similarity_search_with_scorer   F)r8   weaviate_urlweaviate_api_key
batch_sizer   r   r?   r=   r   Optional[weaviate.Client]r   r   r   r   Optional[int]c             
     s  zddl m  W n ty } ztd|d}~ww |p!t||d}|r+|jj|d |p3dt j }t||	}|j	
|sE|j	| |rL||nd}|rXt|d  nd}d|v rd|d}n fd	d
tt|D }|jJ}t|D ]9\}}|	|i}|dur||  D ]
}|| | ||< q|| }|||d}|dur|| |d< |jdi | qy|  W d   n1 sw   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   rU   r"   N)r   r   )r   Z
LangChain_rW   c                   s   g | ]} t  qS r   r   )r   _rU   r   r   r     s    z'Weaviate.from_texts.<locals>.<listcomp>)r\   rZ   r[   r]   )r9   r;   r=   r?   r   )r^   rV   r$   r*   ra   	configurer   hexr   schemaexistsZcreate_classr`   r_   keysr   rangelenrb   rd   flush)clsrP   r9   rR   r8   r   r   r   r   r   r?   r=   r    er   rM   r;   rW   ra   rf   r   rg   rh   ri   paramsr   rU   r   
from_texts  sl   @

zWeaviate.from_textsrX   Nonec                 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.)r\   )rA   rC   rZ   delete)rJ   rX   r    idr   r   r   r   
  s
   zWeaviate.delete)r8   r   r   r   r   r   r9   r:   r;   r<   r=   r>   r?   r@   )r   r:   )r   rN   r2   )rP   rQ   rR   rS   r    r   r   rT   )rk   )rl   r   rm   rn   r    r   r   ro   )r9   r   rm   rn   r    r   r   ro   )rk   r   r   )rl   r   rm   rn   r   rn   r   r,   r    r   r   ro   )r9   r   rm   rn   r   rn   r   r,   r    r   r   ro   )rl   r   rm   rn   r    r   r   r   )rP   rT   r9   r   rR   rS   r8   r   r   r   r   r   r   r   r   r   r   r   r?   r@   r=   r>   r    r   r   r7   )rX   r<   r    r   r   r   )__name__
__module____qualname____doc__r0   rK   propertyrM   rO   rj   rt   rq   rs   r   r   r   classmethodr   r   r   r   r   r   r7   E   sT    "

, '50 r7   )r   r   r   r   r   r   )NN)r   r   r   r   r    r   r   r!   )r+   r,   r   r,   )r1   r   r   r   )!
__future__r   r4   r%   typingr   r   r   r   r   r   r	   r
   r\   r   numpyr.   Zlangchain_core._apir   Zlangchain_core.documentsr   Zlangchain_core.embeddingsr   Zlangchain_core.vectorstoresr   Z&langchain_community.vectorstores.utilsr   r#   r   r*   r0   r6   r7   r   r   r   r   <module>   s2    (



