• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

deepset-ai / haystack / 13115725275

03 Feb 2025 02:28PM UTC coverage: 91.383% (+0.02%) from 91.359%
13115725275

Pull #8794

github

web-flow
Merge f9479e038 into 503d275ad
Pull Request #8794: refactor: HF API Embedders - use `InferenceClient.feature_extraction` instead of `InferenceClient.post`

8898 of 9737 relevant lines covered (91.38%)

0.91 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.63
haystack/components/embedders/hugging_face_api_document_embedder.py
1
# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
#
3
# SPDX-License-Identifier: Apache-2.0
4

5
import warnings
1✔
6
from typing import Any, Dict, List, Optional, Union
1✔
7

8
from tqdm import tqdm
1✔
9

10
from haystack import component, default_from_dict, default_to_dict, logging
1✔
11
from haystack.dataclasses import Document
1✔
12
from haystack.lazy_imports import LazyImport
1✔
13
from haystack.utils import Secret, deserialize_secrets_inplace
1✔
14
from haystack.utils.hf import HFEmbeddingAPIType, HFModelType, check_valid_model
1✔
15
from haystack.utils.url_validation import is_valid_http_url
1✔
16

17
with LazyImport(message="Run 'pip install \"huggingface_hub>=0.27.0\"'") as huggingface_hub_import:
1✔
18
    from huggingface_hub import InferenceClient
1✔
19

20
logger = logging.getLogger(__name__)
1✔
21

22

23
@component
1✔
24
class HuggingFaceAPIDocumentEmbedder:
1✔
25
    """
26
    Embeds documents using Hugging Face APIs.
27

28
    Use it with the following Hugging Face APIs:
29
    - [Free Serverless Inference API](https://huggingface.co/inference-api)
30
    - [Paid Inference Endpoints](https://huggingface.co/inference-endpoints)
31
    - [Self-hosted Text Embeddings Inference](https://github.com/huggingface/text-embeddings-inference)
32

33

34
    ### Usage examples
35

36
    #### With free serverless inference API
37

38
    ```python
39
    from haystack.components.embedders import HuggingFaceAPIDocumentEmbedder
40
    from haystack.utils import Secret
41
    from haystack.dataclasses import Document
42

43
    doc = Document(content="I love pizza!")
44

45
    doc_embedder = HuggingFaceAPIDocumentEmbedder(api_type="serverless_inference_api",
46
                                                  api_params={"model": "BAAI/bge-small-en-v1.5"},
47
                                                  token=Secret.from_token("<your-api-key>"))
48

49
    result = document_embedder.run([doc])
50
    print(result["documents"][0].embedding)
51

52
    # [0.017020374536514282, -0.023255806416273117, ...]
53
    ```
54

55
    #### With paid inference endpoints
56

57
    ```python
58
    from haystack.components.embedders import HuggingFaceAPIDocumentEmbedder
59
    from haystack.utils import Secret
60
    from haystack.dataclasses import Document
61

62
    doc = Document(content="I love pizza!")
63

64
    doc_embedder = HuggingFaceAPIDocumentEmbedder(api_type="inference_endpoints",
65
                                                  api_params={"url": "<your-inference-endpoint-url>"},
66
                                                  token=Secret.from_token("<your-api-key>"))
67

68
    result = document_embedder.run([doc])
69
    print(result["documents"][0].embedding)
70

71
    # [0.017020374536514282, -0.023255806416273117, ...]
72
    ```
73

74
    #### With self-hosted text embeddings inference
75

76
    ```python
77
    from haystack.components.embedders import HuggingFaceAPIDocumentEmbedder
78
    from haystack.dataclasses import Document
79

80
    doc = Document(content="I love pizza!")
81

82
    doc_embedder = HuggingFaceAPIDocumentEmbedder(api_type="text_embeddings_inference",
83
                                                  api_params={"url": "http://localhost:8080"})
84

85
    result = document_embedder.run([doc])
86
    print(result["documents"][0].embedding)
87

88
    # [0.017020374536514282, -0.023255806416273117, ...]
89
    ```
90
    """
91

92
    def __init__(
1✔
93
        self,
94
        api_type: Union[HFEmbeddingAPIType, str],
95
        api_params: Dict[str, str],
96
        token: Optional[Secret] = Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False),
97
        prefix: str = "",
98
        suffix: str = "",
99
        truncate: Optional[bool] = True,
100
        normalize: Optional[bool] = False,
101
        batch_size: int = 32,
102
        progress_bar: bool = True,
103
        meta_fields_to_embed: Optional[List[str]] = None,
104
        embedding_separator: str = "\n",
105
    ):  # pylint: disable=too-many-positional-arguments
106
        """
107
        Creates a HuggingFaceAPIDocumentEmbedder component.
108

109
        :param api_type:
110
            The type of Hugging Face API to use.
111
        :param api_params:
112
            A dictionary with the following keys:
113
            - `model`: Hugging Face model ID. Required when `api_type` is `SERVERLESS_INFERENCE_API`.
114
            - `url`: URL of the inference endpoint. Required when `api_type` is `INFERENCE_ENDPOINTS` or
115
            `TEXT_EMBEDDINGS_INFERENCE`.
116
        :param token: The Hugging Face token to use as HTTP bearer authorization.
117
            Check your HF token in your [account settings](https://huggingface.co/settings/tokens).
118
        :param prefix:
119
            A string to add at the beginning of each text.
120
        :param suffix:
121
            A string to add at the end of each text.
122
        :param truncate:
123
            Truncates the input text to the maximum length supported by the model.
124
            Applicable when `api_type` is `TEXT_EMBEDDINGS_INFERENCE`, or `INFERENCE_ENDPOINTS`
125
            if the backend uses Text Embeddings Inference.
126
            If `api_type` is `SERVERLESS_INFERENCE_API`, this parameter is ignored.
127
        :param normalize:
128
            Normalizes the embeddings to unit length.
129
            Applicable when `api_type` is `TEXT_EMBEDDINGS_INFERENCE`, or `INFERENCE_ENDPOINTS`
130
            if the backend uses Text Embeddings Inference.
131
            If `api_type` is `SERVERLESS_INFERENCE_API`, this parameter is ignored.
132
        :param batch_size:
133
            Number of documents to process at once.
134
        :param progress_bar:
135
            If `True`, shows a progress bar when running.
136
        :param meta_fields_to_embed:
137
            List of metadata fields to embed along with the document text.
138
        :param embedding_separator:
139
            Separator used to concatenate the metadata fields to the document text.
140
        """
141
        huggingface_hub_import.check()
1✔
142

143
        if isinstance(api_type, str):
1✔
144
            api_type = HFEmbeddingAPIType.from_str(api_type)
1✔
145

146
        api_params = api_params or {}
1✔
147

148
        if api_type == HFEmbeddingAPIType.SERVERLESS_INFERENCE_API:
1✔
149
            model = api_params.get("model")
1✔
150
            if model is None:
1✔
151
                raise ValueError(
1✔
152
                    "To use the Serverless Inference API, you need to specify the `model` parameter in `api_params`."
153
                )
154
            check_valid_model(model, HFModelType.EMBEDDING, token)
1✔
155
            model_or_url = model
1✔
156
        elif api_type in [HFEmbeddingAPIType.INFERENCE_ENDPOINTS, HFEmbeddingAPIType.TEXT_EMBEDDINGS_INFERENCE]:
1✔
157
            url = api_params.get("url")
1✔
158
            if url is None:
1✔
159
                msg = (
1✔
160
                    "To use Text Embeddings Inference or Inference Endpoints, you need to specify the `url` "
161
                    "parameter in `api_params`."
162
                )
163
                raise ValueError(msg)
1✔
164
            if not is_valid_http_url(url):
1✔
165
                raise ValueError(f"Invalid URL: {url}")
1✔
166
            model_or_url = url
1✔
167
        else:
168
            msg = f"Unknown api_type {api_type}"
×
169
            raise ValueError(msg)
×
170

171
        self.api_type = api_type
1✔
172
        self.api_params = api_params
1✔
173
        self.token = token
1✔
174
        self.prefix = prefix
1✔
175
        self.suffix = suffix
1✔
176
        self.truncate = truncate
1✔
177
        self.normalize = normalize
1✔
178
        self.batch_size = batch_size
1✔
179
        self.progress_bar = progress_bar
1✔
180
        self.meta_fields_to_embed = meta_fields_to_embed or []
1✔
181
        self.embedding_separator = embedding_separator
1✔
182
        self._client = InferenceClient(model_or_url, token=token.resolve_value() if token else None)
1✔
183

184
    def to_dict(self) -> Dict[str, Any]:
1✔
185
        """
186
        Serializes the component to a dictionary.
187

188
        :returns:
189
            Dictionary with serialized data.
190
        """
191
        return default_to_dict(
1✔
192
            self,
193
            api_type=str(self.api_type),
194
            api_params=self.api_params,
195
            prefix=self.prefix,
196
            suffix=self.suffix,
197
            token=self.token.to_dict() if self.token else None,
198
            truncate=self.truncate,
199
            normalize=self.normalize,
200
            batch_size=self.batch_size,
201
            progress_bar=self.progress_bar,
202
            meta_fields_to_embed=self.meta_fields_to_embed,
203
            embedding_separator=self.embedding_separator,
204
        )
205

206
    @classmethod
1✔
207
    def from_dict(cls, data: Dict[str, Any]) -> "HuggingFaceAPIDocumentEmbedder":
1✔
208
        """
209
        Deserializes the component from a dictionary.
210

211
        :param data:
212
            Dictionary to deserialize from.
213
        :returns:
214
            Deserialized component.
215
        """
216
        deserialize_secrets_inplace(data["init_parameters"], keys=["token"])
1✔
217
        return default_from_dict(cls, data)
1✔
218

219
    def _prepare_texts_to_embed(self, documents: List[Document]) -> List[str]:
1✔
220
        """
221
        Prepare the texts to embed by concatenating the Document text with the metadata fields to embed.
222
        """
223
        texts_to_embed = []
1✔
224
        for doc in documents:
1✔
225
            meta_values_to_embed = [
1✔
226
                str(doc.meta[key]) for key in self.meta_fields_to_embed if key in doc.meta and doc.meta[key] is not None
227
            ]
228

229
            text_to_embed = (
1✔
230
                self.prefix + self.embedding_separator.join(meta_values_to_embed + [doc.content or ""]) + self.suffix
231
            )
232

233
            texts_to_embed.append(text_to_embed)
1✔
234
        return texts_to_embed
1✔
235

236
    def _embed_batch(self, texts_to_embed: List[str], batch_size: int) -> List[List[float]]:
1✔
237
        """
238
        Embed a list of texts in batches.
239
        """
240
        truncate = self.truncate
1✔
241
        normalize = self.normalize
1✔
242

243
        if self.api_type == HFEmbeddingAPIType.SERVERLESS_INFERENCE_API:
1✔
244
            if truncate is not None:
1✔
245
                msg = "`truncate` parameter is not supported for Serverless Inference API. It will be ignored."
1✔
246
                warnings.warn(msg)
1✔
247
                truncate = None
1✔
248
            if normalize is not None:
1✔
249
                msg = "`normalize` parameter is not supported for Serverless Inference API. It will be ignored."
1✔
250
                warnings.warn(msg)
1✔
251
                normalize = None
1✔
252

253
        all_embeddings = []
1✔
254
        for i in tqdm(
1✔
255
            range(0, len(texts_to_embed), batch_size), disable=not self.progress_bar, desc="Calculating embeddings"
256
        ):
257
            batch = texts_to_embed[i : i + batch_size]
1✔
258

259
            np_embeddings = self._client.feature_extraction(
1✔
260
                # this method does not officially support list of strings, but works as expected
261
                text=batch,  # type: ignore[arg-type]
262
                truncate=truncate,
263
                normalize=normalize,
264
            )
265

266
            if np_embeddings.ndim != 2 or np_embeddings.shape[0] != len(batch):
1✔
267
                raise ValueError(f"Expected embedding shape ({batch_size}, embedding_dim), got {np_embeddings.shape}")
1✔
268

269
            all_embeddings.extend(np_embeddings.tolist())
1✔
270

271
        return all_embeddings
1✔
272

273
    @component.output_types(documents=List[Document])
1✔
274
    def run(self, documents: List[Document]):
1✔
275
        """
276
        Embeds a list of documents.
277

278
        :param documents:
279
            Documents to embed.
280

281
        :returns:
282
            A dictionary with the following keys:
283
            - `documents`: A list of documents with embeddings.
284
        """
285
        if not isinstance(documents, list) or documents and not isinstance(documents[0], Document):
1✔
286
            raise TypeError(
×
287
                "HuggingFaceAPIDocumentEmbedder expects a list of Documents as input."
288
                " In case you want to embed a string, please use the HuggingFaceAPITextEmbedder."
289
            )
290

291
        texts_to_embed = self._prepare_texts_to_embed(documents=documents)
1✔
292

293
        embeddings = self._embed_batch(texts_to_embed=texts_to_embed, batch_size=self.batch_size)
1✔
294

295
        for doc, emb in zip(documents, embeddings):
1✔
296
            doc.embedding = emb
1✔
297

298
        return {"documents": documents}
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc