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

deepset-ai / haystack / 13974248160

20 Mar 2025 04:20PM UTC coverage: 90.012% (-0.005%) from 90.017%
13974248160

Pull #9083

github

web-flow
Merge 6dfb09510 into 67ab3788e
Pull Request #9083: chore: make Haystack warnings consistent

9814 of 10903 relevant lines covered (90.01%)

0.9 hits per line

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

96.59
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
from typing import Any, Dict, List, Optional, Union
1✔
6

7
from tqdm import tqdm
1✔
8

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

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

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

21

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

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

32

33
    ### Usage examples
34

35
    #### With free serverless inference API
36

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

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

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

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

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

54
    #### With paid inference endpoints
55

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

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

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

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

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

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

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

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

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

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

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

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

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

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

145
        api_params = api_params or {}
1✔
146

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

270
        return all_embeddings
1✔
271

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

277
        :param documents:
278
            Documents to embed.
279

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

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

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

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

297
        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

© 2025 Coveralls, Inc