
    Ng_/                        d dl m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mZ d dlmZ d dlmZ erd dlmZ 	 	 	 dddZ G d de          ZdS )    )annotationsN)TYPE_CHECKINGAnyDictIterableListOptionalTupleType)Document)
Embeddings)get_from_env)VectorStore)ClientclientOptional[Client]urlOptional[str]api_keyreturnr   c                   	 dd l }n# t          $ r t          d          w xY w| sN|pt          dd          }	 |pt          dd          }n# t          $ r Y nw xY w|                    ||          } n4t          | |j                  st          dt          |                      	 |                                  n$# t          $ r}t          d	|           d }~ww xY w| S )
Nr   z^Could not import meilisearch python package. Please install it with `pip install meilisearch`.r   MEILI_HTTP_ADDRr   MEILI_MASTER_KEY)r   r   z8client should be an instance of meilisearch.Client, got z"Failed to connect to Meilisearch: )	meilisearchImportErrorr   	Exceptionr   
isinstance
ValueErrortypeversion)r   r   r   r   es        h/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/vectorstores/meilisearch.py_create_clientr#      sU   

 
 
 
@
 
 	


  
;\%):;;	Li9K!L!LGG 	 	 	D	##W#== 233 
"<<" "
 
 	
C C C CAaAABBBCMs1    !A 
AA)B> >
CCCc                      e Zd ZdZ	 	 	 	 	 	 d3ddd4dZ	 	 	 d5d6d!Z	 	 	 d7d8d)Z	 	 	 d7d9d+Z	 	 	 d:d;d-Z	 	 	 d7d<d.Z	e
ddddddddi df
d=d2            ZdS )>Meilisearcha  `Meilisearch` vector store.

    To use this, you need to have `meilisearch` python package installed,
    and a running Meilisearch instance.

    To learn more about Meilisearch Python, refer to the in-depth
    Meilisearch Python documentation: https://meilisearch.github.io/meilisearch-python/.

    See the following documentation for how to run a Meilisearch instance:
    https://www.meilisearch.com/docs/learn/getting_started/quick_start.

    Example:
        .. code-block:: python

            from langchain_community.vectorstores import Meilisearch
            from langchain_community.embeddings.openai import OpenAIEmbeddings
            import meilisearch

            # api_key is optional; provide it if your meilisearch instance requires it
            client = meilisearch.Client(url='http://127.0.0.1:7700', api_key='***')
            embeddings = OpenAIEmbeddings()
            embedders = {
                "theEmbedderName": {
                    "source": "userProvided",
                    "dimensions": "1536"
                }
            }
            vectorstore = Meilisearch(
                embedding=embeddings,
                embedders=embedders,
                client=client,
                index_name='langchain_demo',
                text_key='text')
    Nlangchain-demotextmetadata)	embedders	embeddingr   r   r   r   r   r   
index_namestrtext_keymetadata_keyr)   Optional[Dict[str, Any]]c                  t          |||          }|| _        || _        || _        || _        || _        || _        | j                            t          | j                            	                    |          | _
        dS )z#Initialize with Meilisearch client.r   r   r   N)r#   _client_index_name
_embedding	_text_key_metadata_key
_embeddersindexr,   update_embedders_embedders_settings)	selfr*   r   r   r   r+   r-   r.   r)   s	            r"   __init__zMeilisearch.__init__R   s      v3HHH%#!)##'<#5#5 !!$
 $


9
%
% 	       defaulttextsIterable[str]	metadatasOptional[List[dict]]idsOptional[List[str]]embedder_namekwargsr   r   	List[str]c           	        t          |          }g }|d |D             }|d |D             }| j                            |          }t          |          D ]K\  }}	||         }
||         }|	|| j        <   ||         }|                    d|
d| |i| j         |i           L| j                            t          | j
                                                |           |S )a!  Run more texts through the embedding and add them to the vector store.

        Args:
            texts (Iterable[str]): Iterable of strings/text to add to the vectorstore.
            embedder_name: Name of the embedder. Defaults to "default".
            metadatas (Optional[List[dict]]): Optional list of metadata.
                Defaults to None.
            ids Optional[List[str]]: Optional list of IDs.
                Defaults to None.

        Returns:
            List[str]: List of IDs of the texts added to the vectorstore.
        Nc                >    g | ]}t          j                    j        S  )uuiduuid4hex.0_s     r"   
<listcomp>z)Meilisearch.add_texts.<locals>.<listcomp>   s!    3334:<<#333r=   c                    g | ]}i S rJ   rJ   rN   s     r"   rQ   z)Meilisearch.add_texts.<locals>.<listcomp>   s    ++++++r=   id_vectors)listr4   embed_documents	enumerater5   appendr6   r2   r8   r,   r3   add_documents)r;   r?   rA   rC   rE   rF   docsembedding_vectorsir'   rS   r(   r*   s                r"   	add_textszMeilisearch.add_textsk   s   * U ;33U333C++U+++I O;;EBB '' 	 	GAtQB |H'+HT^$)!,IKK"M!3Y ?)+X    	3t/0011??EEE
r=      querykintfilterOptional[Dict[str, str]]List[Document]c                N    |                      |||||          }d |D             S )a  Return meilisearch documents most similar to the query.

        Args:
            query (str): Query text for which to find similar documents.
            embedder_name: Name of the embedder to be used. Defaults to "default".
            k (int): Number of documents to return. Defaults to 4.
            filter (Optional[Dict[str, str]]): Filter by metadata.
                Defaults to None.

        Returns:
            List[Document]: List of Documents most similar to the query
            text and score for each.
        )r_   rE   r`   rb   rF   c                    g | ]\  }}|S rJ   rJ   rO   docrP   s      r"   rQ   z1Meilisearch.similarity_search.<locals>.<listcomp>   s    222Q222r=   )similarity_search_with_score)r;   r_   r`   rb   rE   rF   docs_and_scoress          r"   similarity_searchzMeilisearch.similarity_search   sC    * ;;' < 
 
 32/2222r=   List[Tuple[Document, float]]c                n    | j                             |          }|                     |||||          }|S )a%  Return meilisearch documents most similar to the query, along with scores.

        Args:
            query (str): Query text for which to find similar documents.
            embedder_name: Name of the embedder to be used. Defaults to "default".
            k (int): Number of documents to return. Defaults to 4.
            filter (Optional[Dict[str, str]]): Filter by metadata.
                Defaults to None.

        Returns:
            List[Document]: List of Documents most similar to the query
            text and score for each.
        r*   rE   r`   rb   rF   )r4   embed_query'similarity_search_by_vector_with_scores)r;   r_   r`   rb   rE   rF   _queryrZ   s           r"   ri   z(Meilisearch.similarity_search_with_score   sI    * ,,U33;;' < 
 
 r=   List[float]c           	     n   g }| j                             t          | j                                                d|d|d||dd          }|d         D ]`}|| j                 }	| j        |	v rH|	                    | j                  }
|d         }|                    t          |
|	          |f           a|S )	#  Return meilisearch documents most similar to embedding vector.

        Args:
            embedding (List[float]): Embedding to look up similar documents.
            embedder_name: Name of the embedder to be used. Defaults to "default".
            k (int): Number of documents to return. Defaults to 4.
            filter (Optional[Dict[str, str]]): Filter by metadata.
                Defaults to None.

        Returns:
            List[Document]: List of Documents most similar to the query
                vector and score for each.
         g      ?)semanticRatioembedderT)vectorhybridlimitrb   showRankingScorehits_rankingScore)page_contentr(   )
r2   r8   r,   r3   searchr6   r5   poprX   r   )r;   r*   rE   r`   rb   rF   rZ   resultsresultr(   r'   semantic_scores               r"   rp   z3Meilisearch.similarity_search_by_vector_with_scores   s    * ,$$S)9%:%:;;BB#,/]KK $( 	
 	
 fo 	 	Fd01H~))||DN33!'!84(CCC^T   r=   c                N    |                      |||||          }d |D             S )rt   rn   c                    g | ]\  }}|S rJ   rJ   rg   s      r"   rQ   z;Meilisearch.similarity_search_by_vector.<locals>.<listcomp>!  s    '''Q'''r=   )rp   )r;   r*   r`   rb   rE   rF   rZ   s          r"   similarity_search_by_vectorz'Meilisearch.similarity_search_by_vector  sC    * ;;' < 
 
 ('$''''r=   clsType[Meilisearch]Dict[str, Any]c                ~    t          |||          } | ||||          }|                    |||||	|
           |S )a  Construct Meilisearch wrapper from raw documents.

        This is a user-friendly interface that:
            1. Embeds documents.
            2. Adds the documents to a provided Meilisearch index.

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

        Example:
            .. code-block:: python

                from langchain_community.vectorstores import Meilisearch
                from langchain_community.embeddings import OpenAIEmbeddings
                import meilisearch

                # The environment should be the one specified next to the API key
                # in your Meilisearch console
                client = meilisearch.Client(url='http://127.0.0.1:7700', api_key='***')
                embedding = OpenAIEmbeddings()
                embedders: Embedders index setting.
                embedder_name: Name of the embedder. Defaults to "default".
                docsearch = Meilisearch.from_texts(
                    client=client,
                    embedding=embedding,
                )
        r1   )r*   r)   r   r+   )r?   rE   rA   rC   r-   r.   )r#   r]   )r   r?   r*   rA   r   r   r   r+   rC   r-   r.   r)   rE   rF   vectorstores                  r"   
from_textszMeilisearch.from_texts#  st    V  v3HHHc!	
 
 
 	'% 	 	
 	
 	
 r=   )NNNr&   r'   r(   )r*   r   r   r   r   r   r   r   r+   r,   r-   r,   r.   r,   r)   r/   )NNr>   )r?   r@   rA   rB   rC   rD   rE   r   rF   r   r   rG   )r^   Nr>   )r_   r,   r`   ra   rb   rc   rE   r   rF   r   r   rd   )r_   r,   r`   ra   rb   rc   rE   r   rF   r   r   rl   )r>   r^   N)r*   rr   rE   r   r`   ra   rb   r/   rF   r   r   rl   )r*   rr   r`   ra   rb   rc   rE   r   rF   r   r   rd   )r   r   r?   rG   r*   r   rA   rB   r   r   r   r   r   r   r+   r,   rC   rD   r-   r   r.   r   r)   r   rE   r   rF   r   r   r%   )__name__
__module____qualname____doc__r<   r]   rk   ri   rp   r   classmethodr   rJ   r=   r"   r%   r%   .   sX       ! !L $(!!%*&& /3& & & & & &8 +/#''0. . . . .f +/'03 3 3 3 3B +/'0    F (1+/* * * * *^ +/'0( ( ( ( (< 
 +/#'!!%*#'"(&0$&'0: : : : [: : :r=   r%   )NNN)r   r   r   r   r   r   r   r   )
__future__r   rK   typingr   r   r   r   r   r	   r
   r   langchain_core.documentsr   langchain_core.embeddingsr   langchain_core.utilsr   langchain_core.vectorstoresr   r   r   r#   r%   rJ   r=   r"   <module>r      s    " " " " " "  R R R R R R R R R R R R R R R R R R R R - - - - - - 0 0 0 0 0 0 - - - - - - 3 3 3 3 3 3 #""""""  $!    >p p p p p+ p p p p pr=   