|
| 1 | +from typing import List, Any |
| 2 | +from llama_index.embeddings.base import BaseEmbedding |
| 3 | +from llama_index.bridge.pydantic import PrivateAttr |
| 4 | + |
| 5 | + |
| 6 | +class ElasticsearchEmbeddings(BaseEmbedding): |
| 7 | + """Elasticsearch embedding models. |
| 8 | +
|
| 9 | + This class provides an interface to generate embeddings using a model deployed |
| 10 | + in an Elasticsearch cluster. It requires an Elasticsearch connection object |
| 11 | + and the model_id of the model deployed in the cluster. |
| 12 | +
|
| 13 | + In Elasticsearch you need to have an embedding model loaded and deployed. |
| 14 | + - https://www.elastic.co |
| 15 | + /guide/en/elasticsearch/reference/current/infer-trained-model.html |
| 16 | + - https://www.elastic.co |
| 17 | + /guide/en/machine-learning/current/ml-nlp-deploy-models.html |
| 18 | + """ # |
| 19 | + |
| 20 | + _client: Any = PrivateAttr() |
| 21 | + model_id: str |
| 22 | + input_field: str |
| 23 | + |
| 24 | + @classmethod |
| 25 | + def class_name(self) -> str: |
| 26 | + return "ElasticsearchEmbeddings" |
| 27 | + |
| 28 | + def __init__( |
| 29 | + self, |
| 30 | + client: Any, |
| 31 | + model_id: str, |
| 32 | + input_field: str = "text_field", |
| 33 | + **kwargs: Any, |
| 34 | + ): |
| 35 | + self._client = client |
| 36 | + super().__init__(model_id=model_id, input_field=input_field, **kwargs) |
| 37 | + |
| 38 | + @classmethod |
| 39 | + def from_es_connection( |
| 40 | + cls, |
| 41 | + model_id: str, |
| 42 | + es_connection: Any, |
| 43 | + input_field: str = "text_field", |
| 44 | + ) -> BaseEmbedding: |
| 45 | + """ |
| 46 | + Instantiate embeddings from an existing Elasticsearch connection. |
| 47 | +
|
| 48 | + This method provides a way to create an instance of the ElasticsearchEmbeddings |
| 49 | + class using an existing Elasticsearch connection. The connection object is used |
| 50 | + to create an MlClient, which is then used to initialize the |
| 51 | + ElasticsearchEmbeddings instance. |
| 52 | +
|
| 53 | + Args: |
| 54 | + model_id (str): The model_id of the model deployed in the Elasticsearch cluster. |
| 55 | + es_connection (elasticsearch.Elasticsearch): An existing Elasticsearch |
| 56 | + connection object. |
| 57 | + input_field (str, optional): The name of the key for the input text field |
| 58 | + in the document. Defaults to 'text_field'. |
| 59 | +
|
| 60 | + Returns: |
| 61 | + ElasticsearchEmbeddings: An instance of the ElasticsearchEmbeddings class. |
| 62 | +
|
| 63 | + Example: |
| 64 | + .. code-block:: python |
| 65 | +
|
| 66 | + from elasticsearch import Elasticsearch |
| 67 | +
|
| 68 | + from llama_index.embeddings import ElasticsearchEmbeddings |
| 69 | +
|
| 70 | + # Define the model ID and input field name (if different from default) |
| 71 | + model_id = "your_model_id" |
| 72 | + # Optional, only if different from 'text_field' |
| 73 | + input_field = "your_input_field" |
| 74 | +
|
| 75 | + # Create Elasticsearch connection |
| 76 | + es_connection = Elasticsearch( |
| 77 | + hosts=["localhost:9200"], basic_auth=("user", "password") |
| 78 | + ) |
| 79 | +
|
| 80 | + # Instantiate ElasticsearchEmbeddings using the existing connection |
| 81 | + embeddings = ElasticsearchEmbeddings.from_es_connection( |
| 82 | + model_id, |
| 83 | + es_connection, |
| 84 | + input_field=input_field, |
| 85 | + ) |
| 86 | + """ |
| 87 | + |
| 88 | + try: |
| 89 | + from elasticsearch.client import MlClient |
| 90 | + except ImportError: |
| 91 | + raise ImportError( |
| 92 | + "elasticsearch package not found, install with" |
| 93 | + "'pip install elasticsearch'" |
| 94 | + ) |
| 95 | + |
| 96 | + client = MlClient(es_connection) |
| 97 | + return cls(client, model_id, input_field=input_field) |
| 98 | + |
| 99 | + @classmethod |
| 100 | + def from_credentials( |
| 101 | + cls, |
| 102 | + model_id: str, |
| 103 | + es_url: str, |
| 104 | + es_username: str, |
| 105 | + es_password: str, |
| 106 | + input_field: str = "text_field", |
| 107 | + ) -> BaseEmbedding: |
| 108 | + """Instantiate embeddings from Elasticsearch credentials. |
| 109 | +
|
| 110 | + Args: |
| 111 | + model_id (str): The model_id of the model deployed in the Elasticsearch |
| 112 | + cluster. |
| 113 | + input_field (str): The name of the key for the input text field in the |
| 114 | + document. Defaults to 'text_field'. |
| 115 | + es_url: (str): The Elasticsearch url to connect to. |
| 116 | + es_username: (str): Elasticsearch username. |
| 117 | + es_password: (str): Elasticsearch password. |
| 118 | +
|
| 119 | + Example: |
| 120 | + .. code-block:: python |
| 121 | +
|
| 122 | + from llama_index.embeddings import ElasticsearchEmbeddings |
| 123 | +
|
| 124 | + # Define the model ID and input field name (if different from default) |
| 125 | + model_id = "your_model_id" |
| 126 | + # Optional, only if different from 'text_field' |
| 127 | + input_field = "your_input_field" |
| 128 | +
|
| 129 | + embeddings = ElasticsearchEmbeddings.from_credentials( |
| 130 | + model_id, |
| 131 | + input_field=input_field, |
| 132 | + es_url="foo", |
| 133 | + es_username="bar", |
| 134 | + es_password="baz", |
| 135 | + ) |
| 136 | + """ |
| 137 | + |
| 138 | + try: |
| 139 | + from elasticsearch import Elasticsearch |
| 140 | + from elasticsearch.client import MlClient |
| 141 | + except ImportError: |
| 142 | + raise ImportError( |
| 143 | + "elasticsearch package not found, install with" |
| 144 | + "'pip install elasticsearch'" |
| 145 | + ) |
| 146 | + |
| 147 | + es_connection = Elasticsearch( |
| 148 | + hosts=[es_url], |
| 149 | + basic_auth=(es_username, es_password), |
| 150 | + ) |
| 151 | + |
| 152 | + client = MlClient(es_connection) |
| 153 | + return cls(client, model_id, input_field=input_field) |
| 154 | + |
| 155 | + def _get_embedding(self, text: str) -> List[float]: |
| 156 | + """ |
| 157 | + Generate an embedding for a single query text. |
| 158 | +
|
| 159 | + Args: |
| 160 | + text (str): The query text to generate an embedding for. |
| 161 | +
|
| 162 | + Returns: |
| 163 | + List[float]: The embedding for the input query text. |
| 164 | + """ |
| 165 | + |
| 166 | + response = self._client.infer_trained_model( |
| 167 | + model_id=self.model_id, |
| 168 | + docs=[{self.input_field: text}], |
| 169 | + ) |
| 170 | + |
| 171 | + embedding = response["inference_results"][0]["predicted_value"] |
| 172 | + return embedding |
| 173 | + |
| 174 | + def _get_text_embedding(self, text: str) -> List[float]: |
| 175 | + return self._get_embedding(text) |
| 176 | + |
| 177 | + def _get_query_embedding(self, query: str) -> List[float]: |
| 178 | + return self._get_embedding(query) |
| 179 | + |
| 180 | + async def _aget_query_embedding(self, query: str) -> List[float]: |
| 181 | + return self._get_query_embedding(query) |
0 commit comments