
    NgT!                        d dl mZ d dlmZmZmZ d dlmZ d dlm	Z	 erd dl
mZ d dlmZ d dlmZ  edd	d
           G d de                      ZdS )    )annotations)TYPE_CHECKINGListOptional)
deprecated)get_from_envElasticsearchMlClient)
Embeddingsz0.1.11z,Use class in langchain-elasticsearch packageT)alternativependingc                  x    e Zd ZdZdddd	Zed
d
d
dddd            Ze	 dd d            Zd!dZd!dZ	d"dZ
d
S )#ElasticsearchEmbeddingsa
  Elasticsearch embedding models.

    This class provides an interface to generate embeddings using a model deployed
    in an Elasticsearch cluster. It requires an Elasticsearch connection object
    and the model_id of the model deployed in the cluster.

    In Elasticsearch you need to have an embedding model loaded and deployed.
    - https://www.elastic.co/guide/en/elasticsearch/reference/current/infer-trained-model.html
    - https://www.elastic.co/guide/en/machine-learning/current/ml-nlp-deploy-models.html
    
text_fieldinput_fieldclientr   model_idstrr   c               0    || _         || _        || _        dS )a  
        Initialize the ElasticsearchEmbeddings instance.

        Args:
            client (MlClient): An Elasticsearch ML client object.
            model_id (str): The model_id of the model deployed in the Elasticsearch
                cluster.
            input_field (str): The name of the key for the input text field in the
                document. Defaults to 'text_field'.
        N)r   r   r   )selfr   r   r   s       h/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/embeddings/elasticsearch.py__init__z ElasticsearchEmbeddings.__init__   s     "  &    N)es_cloud_ides_useres_passwordr   r   Optional[str]r   r   returnc                  	 ddl m} ddlm} n# t          $ r t	          d          w xY w|pt          dd          }|pt          dd          }|pt          d	d
          } ||||f          } ||          }	 | |	||          S )a  Instantiate embeddings from Elasticsearch credentials.

        Args:
            model_id (str): The model_id of the model deployed in the Elasticsearch
                cluster.
            input_field (str): The name of the key for the input text field in the
                document. Defaults to 'text_field'.
            es_cloud_id: (str, optional): The Elasticsearch cloud ID to connect to.
            es_user: (str, optional): Elasticsearch username.
            es_password: (str, optional): Elasticsearch password.

        Example:
            .. code-block:: python

                from langchain_community.embeddings import ElasticsearchEmbeddings

                # Define the model ID and input field name (if different from default)
                model_id = "your_model_id"
                # Optional, only if different from 'text_field'
                input_field = "your_input_field"

                # Credentials can be passed in two ways. Either set the env vars
                # ES_CLOUD_ID, ES_USER, ES_PASSWORD and they will be automatically
                # pulled in, or pass them in directly as kwargs.
                embeddings = ElasticsearchEmbeddings.from_credentials(
                    model_id,
                    input_field=input_field,
                    # es_cloud_id="foo",
                    # es_user="bar",
                    # es_password="baz",
                )

                documents = [
                    "This is an example document.",
                    "Another example document to generate embeddings for.",
                ]
                embeddings_generator.embed_documents(documents)
        r   r	   r   zPelasticsearch package not found, please install with 'pip install elasticsearch'r   ES_CLOUD_IDr   ES_USERr   ES_PASSWORD)cloud_id
basic_authr   )elasticsearchr
   elasticsearch.clientr   ImportErrorr   )
clsr   r   r   r   r   r
   r   es_connectionr   s
             r   from_credentialsz(ElasticsearchEmbeddings.from_credentials3   s    `	3333335555555 	 	 	!  	 "O\-%O%O?\)Y??!O\-%O%O & g{-C
 
 
 -((s68====s    )r,   r
   c                @    ddl m}  ||          } | |||          S )a  
        Instantiate embeddings from an existing Elasticsearch connection.

        This method provides a way to create an instance of the ElasticsearchEmbeddings
        class using an existing Elasticsearch connection. The connection object is used
        to create an MlClient, which is then used to initialize the
        ElasticsearchEmbeddings instance.

        Args:
        model_id (str): The model_id of the model deployed in the Elasticsearch cluster.
        es_connection (elasticsearch.Elasticsearch): An existing Elasticsearch
        connection object. input_field (str, optional): The name of the key for the
        input text field in the document. Defaults to 'text_field'.

        Returns:
        ElasticsearchEmbeddings: An instance of the ElasticsearchEmbeddings class.

        Example:
            .. code-block:: python

                from elasticsearch import Elasticsearch

                from langchain_community.embeddings import ElasticsearchEmbeddings

                # Define the model ID and input field name (if different from default)
                model_id = "your_model_id"
                # Optional, only if different from 'text_field'
                input_field = "your_input_field"

                # Create Elasticsearch connection
                es_connection = Elasticsearch(
                    hosts=["localhost:9200"], http_auth=("user", "password")
                )

                # Instantiate ElasticsearchEmbeddings using the existing connection
                embeddings = ElasticsearchEmbeddings.from_es_connection(
                    model_id,
                    es_connection,
                    input_field=input_field,
                )

                documents = [
                    "This is an example document.",
                    "Another example document to generate embeddings for.",
                ]
                embeddings_generator.embed_documents(documents)
        r   r   r   )r)   r   )r+   r   r,   r   r   r   s         r   from_es_connectionz*ElasticsearchEmbeddings.from_es_connectionw   sA    p 	211111 -(( s68====r   texts	List[str]List[List[float]]c                      j                              j         fd|D                       }d |d         D             }|S )a5  
        Generate embeddings for the given texts using the Elasticsearch model.

        Args:
            texts (List[str]): A list of text strings to generate embeddings for.

        Returns:
            List[List[float]]: A list of embeddings, one for each text in the input
                list.
        c                "    g | ]}j         |iS  r   ).0textr   s     r   
<listcomp>z;ElasticsearchEmbeddings._embedding_func.<locals>.<listcomp>   s!    )U)U)Ut4+;T*B)U)U)Ur   )r   docsc                    g | ]
}|d          S )predicted_valuer5   )r6   docs     r   r8   z;ElasticsearchEmbeddings._embedding_func.<locals>.<listcomp>   s    VVVc+,VVVr   inference_results)r   infer_trained_modelr   )r   r0   response
embeddingss   `   r   _embedding_funcz'ElasticsearchEmbeddings._embedding_func   s_     ;22])U)U)U)Uu)U)U)U 3 
 
 WVAT8UVVV
r   c                ,    |                      |          S )a8  
        Generate embeddings for a list of documents.

        Args:
            texts (List[str]): A list of document text strings to generate embeddings
                for.

        Returns:
            List[List[float]]: A list of embeddings, one for each document in the input
                list.
        rA   )r   r0   s     r   embed_documentsz'ElasticsearchEmbeddings.embed_documents   s     ##E***r   r7   List[float]c                :    |                      |g          d         S )z
        Generate an embedding for a single query text.

        Args:
            text (str): The query text to generate an embedding for.

        Returns:
            List[float]: The embedding for the input query text.
        r   rC   )r   r7   s     r   embed_queryz#ElasticsearchEmbeddings.embed_query   s     ##TF++A..r   )r   r   r   r   r   r   )r   r   r   r    r   r    r   r    r   r   r!   r   )r   )r   r   r,   r
   r   r   r!   r   )r0   r1   r!   r2   )r7   r   r!   rE   )__name__
__module____qualname____doc__r   classmethodr-   r/   rA   rD   rG   r5   r   r   r   r      s        	 	  (' ' ' ' ' '* 
 &*!%%)'A> A> A> A> A> [A>F 
 (	>> >> >> >> [>>@   $+ + + +
/ 
/ 
/ 
/ 
/ 
/r   r   N)
__future__r   typingr   r   r   langchain_core._apir   langchain_core.utilsr   r(   r
   r)   r   langchain_core.embeddingsr   r   r5   r   r   <module>rR      s    " " " " " " 0 0 0 0 0 0 0 0 0 0 * * * * * * - - - - - - .++++++------ 0 0 0 0 0 0 HRV  P/ P/ P/ P/ P/j P/ P/ P/ P/ P/r   