
    Ng3K                        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rd dlZddZ	 	 dddZd dZd!dZ G d de          ZdS )"    )annotationsN)TYPE_CHECKINGAnyCallableDictIterableListOptionalTupleuuid4)Document)
Embeddings)VectorStore)maximal_marginal_relevance
index_namestrtext_keyreturnr   c                    | |dgdgdS )Ntext)namedataType)class
properties )r   r   s     e/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/vectorstores/weaviate.py_default_schemar      s-     !#H 
      urlOptional[str]api_keykwargsr   weaviate.Clientc                *   	 dd l }n# t          $ r t          d          w xY w| pt          j                            d          } |pt          j                            d          }|r|j                            |          nd } |j        d| |d|S )Nr   _Could not import weaviate python  package. Please install it with `pip install weaviate-client`WEAVIATE_URLWEAVIATE_API_KEY)r"   )r    auth_client_secretr   )weaviateImportErrorosenvirongetauth
AuthApiKeyClient)r    r"   r#   r*   r/   s        r   _create_weaviate_clientr2   (   s    

 
 
 
C
 
 	


 
///C;(:;;G8?I8=##G#444TD8?FstFFvFFF    !valfloatc                <    dddt          j        |           z   z  z
  S )N   )npexp)r4   s    r   _default_score_normalizerr:   :   s    qAsO$$$r   valuec                b    t          | t          j                  r|                                 S | S N)
isinstancedatetime	isoformat)r;   s    r   _json_serializablerA   >   s,    %*++ !   Lr   c                      e Zd ZdZddedfd=dZed>d            Zd?dZ	 d@dAdZ		 dBdCd"Z
	 dBdCd#Z	 dBdDd%Z	 	 	 dEdFd+Z	 	 	 dEdGd,Z	 dBdHd.Ze	 d@dddddd/d0ed1dId9            Zd@dJd<ZdS )K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                ^   	 ddl }n# t          $ r t          d          w xY wt          ||j                  st	          dt          |                     || _        || _        || _        || _	        | j	        g| _
        || _        || _        || 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+   r>   r1   
ValueErrortype_client_index_name
_embedding	_text_key_query_attrsrI   _by_textextend)	selfrD   r   r   rE   rG   rI   rK   r*   s	            r   __init__zWeaviate.__init__T   s    	OOOO 	 	 	H  	
 &(/22 	VVVV   %#!!^,"4!$$Z00000 "!r3   r   c                    | j         S r=   )rR   rW   s    r   
embeddingszWeaviate.embeddingsv   s
    r   Callable[[float], float]c                ,    | j         r| j         nt          S r=   )rI   r:   rZ   s    r   _select_relevance_score_fnz#Weaviate._select_relevance_score_fnz   s     &+D##*	
r   textsIterable[str]	metadatasOptional[List[dict]]r#   	List[str]c                   ddl m} g }d}| j        r>t          |t                    st	          |          }| j                            |          }| j        j        5 }t          |          D ]\  }}	| j	        |	i}
|2||         
                                D ]\  }}t          |          |
|<    |t                                }d|v r|d         |         }nd|v r|d         |         }|                    |
| j        ||r||         nd|                    d                     |                    |           	 ddd           n# 1 swxY w Y   |S )z4Upload texts with metadata (properties) to Weaviate.r   get_valid_uuidNuuidsidstenant)data_object
class_nameuuidvectorri   )weaviate.utilrf   rR   r>   listembed_documentsrP   batch	enumeraterS   itemsrA   r   add_data_objectrQ   r.   append)rW   r_   ra   r#   rf   rh   r[   rq   ir   data_propertieskeyr4   _ids                 r   	add_textszWeaviate.add_texts   s    	10000026
? 	@eT** $U88??J\ 	 5$U++    4#'>4"8($-aL$6$6$8$8 G GS/A#/F/F,, %nUWW--f$$ /!,CCf__ -*C%% /#/,6@:a==D!::h// &    

3/ 	  	  	  	  	  	  	  	  	  	  	  	  	  	  	 2 
s   C E		EE   querykintList[Document]c                    | j         r | j        ||fi |S | j        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)rU   similarity_search_by_textrR   rN   embed_querysimilarity_search_by_vector)rW   r|   r}   r#   rE   s        r   similarity_searchzWeaviate.similarity_search   s     = 		L141%EEfEEE& %   33E::I343IqKKFKKKr   c                   d|gi}|                     d          r|                     d          |d<   | j        j                             | j        | j                  }|                     d          r(|                    |                     d                    }|                     d          r(|                    |                     d                    }|                     d          r(|                    |                     d                    }|                    |          	                    |          
                                }d|v rt          d|d                    g }|d	         d
         | j                 D ]@}|                    | j                  }	|                    t          |	|                     A|S )r   conceptssearch_distance	certaintywhere_filterri   
additionalerrorsError during query: dataGetpage_contentmetadata)r.   rP   r|   rQ   rT   
with_wherewith_tenantwith_additionalwith_near_text
with_limitdorN   poprS   ru   r   )
rW   r|   r}   r#   content	query_objresultdocsresr   s
             r   r   z"Weaviate.similarity_search_by_text   s    $.w"7::'(( 	A#)::.?#@#@GK L&**4+;T=NOO	::n%% 	I!,,VZZ-G-GHHI::h 	D!--fjj.B.BCCI::l## 	L!11&**\2J2JKKI))'22==a@@CCEEvFF84DFFGGG&>%()9: 	C 	CC774>**DKKdSAAABBBBr   List[float]c                4   d|i}| j         j                            | j        | j                  }|                    d          r(|                    |                    d                    }|                    d          r(|                    |                    d                    }|                    d          r(|                    |                    d                    }|                    |          	                    |          
                                }d|v rt          d|d                    g }|d         d         | j                 D ]@}|                    | j                  }	|                    t          |	|	                     A|S )
z:Look up similar documents by embedding vector in Weaviate.rm   r   ri   r   r   r   r   r   r   )rP   r|   r.   rQ   rT   r   r   r   with_near_vectorr   r   rN   r   rS   ru   r   )
rW   rE   r}   r#   rm   r   r   r   r   r   s
             r   r   z$Weaviate.similarity_search_by_vector   s    I&L&**4+;T=NOO	::n%% 	I!,,VZZ-G-GHHI::h 	D!--fjj.B.BCCI::l## 	L!11&**\2J2JKKI++F33>>qAADDFFvFF84DFFGGG&>%()9: 	C 	CC774>**DKKdSAAABBBBr            ?fetch_klambda_multr5   c                    | j         | 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)r}   r   r   )rR   r   rN   'max_marginal_relevance_search_by_vector)rW   r|   r}   r   r   r#   rE   s          r   max_marginal_relevance_searchz&Weaviate.max_marginal_relevance_search   sm    2 ?&33E::IIU   <t;
G
 
HN
 
 	
r   c                `   d|i}| j         j                            | j        | j                  }|                    d          r(|                    |                    d                    }|                    d          r(|                    |                    d                    }|                    d                              |          	                    |          
                                }|d         d         | j                 }	d |	D             }
t          t          j        |          |
||          }g }|D ]i}|	|                             | j                  }|	|                             d           |	|         }|                    t#          ||	                     j|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.
        rm   r   ri   r   r   c                *    g | ]}|d          d         S )_additionalrm   r   ).0r   s     r   
<listcomp>zDWeaviate.max_marginal_relevance_search_by_vector.<locals>.<listcomp>B  s"    LLL&f]+H5LLLr   )r}   r   r   r   )rP   r|   r.   rQ   rT   r   r   r   r   r   r   r   r8   arrayr   rS   ru   r   )rW   rE   r}   r   r   r#   rm   r   resultspayloadr[   mmr_selectedr   idxr   metas                   r   r   z0Weaviate.max_marginal_relevance_search_by_vector  s   2 I&L&**4+;T=NOO	::n%% 	I!,,VZZ-G-GHHI::h 	D!--fjj.B.BCCI%%h//f%%Z  RTT	 	 &/%()9:LLGLLL
1HYqk
 
 
  	D 	DC3<##DN33DCL]+++3<DKKdTBBBCCCCr   List[Tuple[Document, float]]c                   | j         t          d          d|gi}|                    d          r|                    d          |d<   | j        j                            | j        | j                  }|                    d          r(|                    |                    d                    }|                    d          r(|                    |                    d                    }| j         	                    |          }| j
        sRd|i}|                    |                              |                              d                                          }nM|                    |                              |                              d                                          }d	|v rt          d
|d	                    g }	|d         d         | j                 D ]c}
|
                    | j                  }t%          j        |
d         d         |          }|	                    t+          ||
          |f           d|	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_scorer   r   r   r   ri   rm   r   r   r   r   r   r   )rR   rN   r.   rP   r|   rQ   rT   r   r   r   rU   r   r   r   r   r   r   rS   r8   dotru   r   )rW   r|   r}   r#   r   r   embedded_queryrm   r   docs_and_scoresr   r   scores                r   similarity_search_with_scorez%Weaviate.similarity_search_with_scoreO  s,    ?"L   $.w"7::'(( 	A#)::.?#@#@GK L&**4+;T=NOO	::n%% 	I!,,VZZ-G-GHHI::h 	D!--fjj.B.BCCI44U;;} 	/F**622A **	 F ((11A **	  vFF84DFFGGG&>%()9: 	W 	WC774>**DF3}-h7HHE""H$$M$M$Mu#UVVVVr   r   F)rD   weaviate_urlweaviate_api_key
batch_sizer   r   rK   rI   r   Optional[weaviate.Client]r   r!   r   r   Optional[int]c                  	 ddl m n"# t          $ r}t          d          |d}~ww xY w|pt          ||          }|r|j                            |           |pdt                      j         }t          ||	          }|j	        
                    |          s|j	                            |           |r|                    |          nd}|r't          |d                                                   nd}d|v r|                    d          }n(fd	t!          t#          |                    D             }|j        5 }t%          |          D ]a\  }}|	|i}|.||                                         D ]}||         |         ||<   ||         }|||d
}|||         |d<    |j        di | b|                                 ddd           n# 1 swxY w 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   re   r&   N)r    r"   )r   
LangChain_rg   c                >    g | ]} t                                S r   r   )r   _rf   s     r   r   z'Weaviate.from_texts.<locals>.<listcomp>  s'    HHH^^EGG,,HHHr   )rl   rj   rk   rm   )rE   rG   rI   rK   r   )rn   rf   r+   r2   rq   	configurer   hexr   schemaexistscreate_classrp   ro   keysr   rangelenrr   rt   flush)clsr_   rE   ra   rD   r   r   r   r   r   rK   rI   r#   er   r[   rG   rg   rq   rv   r   rw   rx   ry   paramsrf   s                            @r   
from_textszWeaviate.from_texts  s   @	4444444 	 	 	G  	  
2$
 
 
  	:L""j"999=#=#=#=
 X66}##J// 	/M&&v...9BLY..u555
2;ET)A,++--...
 fJJw''EEHHHHeCJJ6G6GHHHE\ 	U$U++ 0 04d# ((|0022 A A/8|C/@,,Ah  #2", 
 )'1!}F8$%%//////KKMMM3	 	 	 	 	 	 	 	 	 	 	 	 	 	 	6 s	
  !1	
 	
 	
 	
 		
s#   
 
)$)BGGGrh   Nonec                r    |t          d          |D ]"}| j        j                            |           #dS )zUDelete by vector IDs.

        Args:
            ids: List of ids to delete.
        NzNo ids provided to delete.)rl   )rN   rP   rj   delete)rW   rh   r#   ids       r   r   zWeaviate.delete  sR     ;9:::  	5 	5BL$+++4444	5 	5r   )rD   r   r   r   r   r   rE   rF   rG   rH   rI   rJ   rK   rL   )r   rF   )r   r\   r=   )r_   r`   ra   rb   r#   r   r   rc   )r{   )r|   r   r}   r~   r#   r   r   r   )rE   r   r}   r~   r#   r   r   r   )r{   r   r   )r|   r   r}   r~   r   r~   r   r5   r#   r   r   r   )rE   r   r}   r~   r   r~   r   r5   r#   r   r   r   )r|   r   r}   r~   r#   r   r   r   )r_   rc   rE   r   ra   rb   rD   r   r   r!   r   r!   r   r   r   r!   r   r   rK   rL   rI   rJ   r#   r   r   rC   )rh   rH   r#   r   r   r   )__name__
__module____qualname____doc__r:   rX   propertyr[   r^   rz   r   r   r   r   r   r   classmethodr   r   r   r   r   rC   rC   D   s        ( +/*. & 1  1  1  1  1D    X
 
 
 
 +/) ) ) ) )X $%L L L L L0 $%    @ 01    0  "
 "
 "
 "
 "
N  2 2 2 2 2j $%. . . . .` 
 +/	B
 -1&**.$($( &B
 B
 B
 B
 B
 [B
H5 5 5 5 5 5 5r   rC   )r   r   r   r   r   r   )NN)r    r!   r"   r!   r#   r   r   r$   )r4   r5   r   r5   )r;   r   r   r   )
__future__r   r?   r,   typingr   r   r   r   r   r	   r
   r   rl   r   numpyr8   langchain_core.documentsr   langchain_core.embeddingsr   langchain_core.vectorstoresr   &langchain_community.vectorstores.utilsr   r*   r   r2   r:   rA   rC   r   r   r   <module>r      s   " " " " " "  					 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	           - - - - - - 0 0 0 0 0 0 3 3 3 3 3 3 M M M M M M OOO	 	 	 	 !G G G G G$% % % %   L5 L5 L5 L5 L5{ L5 L5 L5 L5 L5r   