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

deepset-ai / haystack / 16075800688

04 Jul 2025 02:18PM UTC coverage: 90.433% (+0.001%) from 90.432%
16075800688

Pull #9590

github

web-flow
Merge 58856ccb0 into 646eedf26
Pull Request #9590: docs: discourage usage of `HuggingFaceAPIGenerator` with the HF Inference API

11684 of 12920 relevant lines covered (90.43%)

0.9 hits per line

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

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

5
from dataclasses import asdict
1✔
6
from datetime import datetime
1✔
7
from typing import Any, Dict, Iterable, List, Optional, Union, cast
1✔
8

9
from haystack import component, default_from_dict, default_to_dict, logging
1✔
10
from haystack.dataclasses import (
1✔
11
    ComponentInfo,
12
    FinishReason,
13
    StreamingCallbackT,
14
    StreamingChunk,
15
    SyncStreamingCallbackT,
16
    select_streaming_callback,
17
)
18
from haystack.lazy_imports import LazyImport
1✔
19
from haystack.utils import Secret, deserialize_callable, deserialize_secrets_inplace, serialize_callable
1✔
20
from haystack.utils.hf import HFGenerationAPIType, HFModelType, check_valid_model
1✔
21
from haystack.utils.url_validation import is_valid_http_url
1✔
22

23
with LazyImport(message="Run 'pip install \"huggingface_hub>=0.27.0\"'") as huggingface_hub_import:
1✔
24
    from huggingface_hub import (
1✔
25
        InferenceClient,
26
        TextGenerationOutput,
27
        TextGenerationStreamOutput,
28
        TextGenerationStreamOutputToken,
29
    )
30

31

32
logger = logging.getLogger(__name__)
1✔
33

34

35
@component
1✔
36
class HuggingFaceAPIGenerator:
1✔
37
    """
38
    Generates text using Hugging Face APIs.
39

40
    Use it with the following Hugging Face APIs:
41
    - [Paid Inference Endpoints](https://huggingface.co/inference-endpoints)
42
    - [Self-hosted Text Generation Inference](https://github.com/huggingface/text-generation-inference)
43

44
    **Note:** As of July 2025, the Hugging Face Inference API no longer offers generative models through the
45
    `text_generation` endpoint. Generative models are now only available through providers supporting the
46
    `chat_completion` endpoint. As a result, this component might no longer work with the Hugging Face Inference API.
47
    Use the `HuggingFaceAPIChatGenerator` component, which supports the `chat_completion` endpoint.
48

49
    ### Usage examples
50

51
    #### With Hugging Face Inference Endpoints
52

53
    ```python
54
    from haystack.components.generators import HuggingFaceAPIGenerator
55
    from haystack.utils import Secret
56

57
    generator = HuggingFaceAPIGenerator(api_type="inference_endpoints",
58
                                        api_params={"url": "<your-inference-endpoint-url>"},
59
                                        token=Secret.from_token("<your-api-key>"))
60

61
    result = generator.run(prompt="What's Natural Language Processing?")
62
    print(result)
63

64
    #### With self-hosted text generation inference
65
    ```python
66
    from haystack.components.generators import HuggingFaceAPIGenerator
67

68
    generator = HuggingFaceAPIGenerator(api_type="text_generation_inference",
69
                                        api_params={"url": "http://localhost:8080"})
70

71
    result = generator.run(prompt="What's Natural Language Processing?")
72
    print(result)
73
    ```
74

75
    #### With the free serverless inference API
76

77
    Be aware that this example might not work as the Hugging Face Inference API no longer offer models that support the
78
    `text_generation` endpoint. Use the `HuggingFaceAPIChatGenerator` for generative models through the
79
    `chat_completion` endpoint.
80

81
    ```python
82
    from haystack.components.generators import HuggingFaceAPIGenerator
83
    from haystack.utils import Secret
84

85
    generator = HuggingFaceAPIGenerator(api_type="serverless_inference_api",
86
                                        api_params={"model": "HuggingFaceH4/zephyr-7b-beta"},
87
                                        token=Secret.from_token("<your-api-key>"))
88

89
    result = generator.run(prompt="What's Natural Language Processing?")
90
    print(result)
91
    ```
92
    """
93

94
    def __init__(  # pylint: disable=too-many-positional-arguments
1✔
95
        self,
96
        api_type: Union[HFGenerationAPIType, str],
97
        api_params: Dict[str, str],
98
        token: Optional[Secret] = Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False),
99
        generation_kwargs: Optional[Dict[str, Any]] = None,
100
        stop_words: Optional[List[str]] = None,
101
        streaming_callback: Optional[StreamingCallbackT] = None,
102
    ):
103
        """
104
        Initialize the HuggingFaceAPIGenerator instance.
105

106
        :param api_type:
107
            The type of Hugging Face API to use. Available types:
108
            - `text_generation_inference`: See [TGI](https://github.com/huggingface/text-generation-inference).
109
            - `inference_endpoints`: See [Inference Endpoints](https://huggingface.co/inference-endpoints).
110
            - `serverless_inference_api`: See [Serverless Inference API](https://huggingface.co/inference-api).
111
              This might no longer work due to changes in the models offered in the Hugging Face Inference API.
112
              Please use the `HuggingFaceAPIChatGenerator` component instead.
113
        :param api_params:
114
            A dictionary with the following keys:
115
            - `model`: Hugging Face model ID. Required when `api_type` is `SERVERLESS_INFERENCE_API`.
116
            - `url`: URL of the inference endpoint. Required when `api_type` is `INFERENCE_ENDPOINTS` or
117
            `TEXT_GENERATION_INFERENCE`.
118
            - Other parameters specific to the chosen API type, such as `timeout`, `headers`, `provider` etc.
119
        :param token: The Hugging Face token to use as HTTP bearer authorization.
120
            Check your HF token in your [account settings](https://huggingface.co/settings/tokens).
121
        :param generation_kwargs:
122
            A dictionary with keyword arguments to customize text generation. Some examples: `max_new_tokens`,
123
            `temperature`, `top_k`, `top_p`.
124
            For details, see [Hugging Face documentation](https://huggingface.co/docs/huggingface_hub/en/package_reference/inference_client#huggingface_hub.InferenceClient.text_generation)
125
            for more information.
126
        :param stop_words: An optional list of strings representing the stop words.
127
        :param streaming_callback: An optional callable for handling streaming responses.
128
        """
129

130
        huggingface_hub_import.check()
1✔
131

132
        if isinstance(api_type, str):
1✔
133
            api_type = HFGenerationAPIType.from_str(api_type)
1✔
134

135
        if api_type == HFGenerationAPIType.SERVERLESS_INFERENCE_API:
1✔
136
            logger.warning(
1✔
137
                "Due to changes in the models offered in Hugging Face Inference API, using this component with the "
138
                "Serverless Inference API might no longer work. "
139
                "Please use the `HuggingFaceAPIChatGenerator` component instead."
140
            )
141
            model = api_params.get("model")
1✔
142
            if model is None:
1✔
143
                raise ValueError(
1✔
144
                    "To use the Serverless Inference API, you need to specify the `model` parameter in `api_params`."
145
                )
146
            check_valid_model(model, HFModelType.GENERATION, token)
1✔
147
            model_or_url = model
1✔
148
        elif api_type in [HFGenerationAPIType.INFERENCE_ENDPOINTS, HFGenerationAPIType.TEXT_GENERATION_INFERENCE]:
1✔
149
            url = api_params.get("url")
1✔
150
            if url is None:
1✔
151
                msg = (
1✔
152
                    "To use Text Generation Inference or Inference Endpoints, you need to specify the `url` "
153
                    "parameter in `api_params`."
154
                )
155
                raise ValueError(msg)
1✔
156
            if not is_valid_http_url(url):
1✔
157
                raise ValueError(f"Invalid URL: {url}")
1✔
158
            model_or_url = url
1✔
159
        else:
160
            msg = f"Unknown api_type {api_type}"
×
161
            raise ValueError(msg)
×
162

163
        # handle generation kwargs setup
164
        generation_kwargs = generation_kwargs.copy() if generation_kwargs else {}
1✔
165
        generation_kwargs["stop_sequences"] = generation_kwargs.get("stop_sequences", [])
1✔
166
        generation_kwargs["stop_sequences"].extend(stop_words or [])
1✔
167
        generation_kwargs.setdefault("max_new_tokens", 512)
1✔
168

169
        self.api_type = api_type
1✔
170
        self.api_params = api_params
1✔
171
        self.token = token
1✔
172
        self.generation_kwargs = generation_kwargs
1✔
173
        self.streaming_callback = streaming_callback
1✔
174

175
        resolved_api_params: Dict[str, Any] = {k: v for k, v in api_params.items() if k != "model" and k != "url"}
1✔
176
        self._client = InferenceClient(
1✔
177
            model_or_url, token=token.resolve_value() if token else None, **resolved_api_params
178
        )
179

180
    def to_dict(self) -> Dict[str, Any]:
1✔
181
        """
182
        Serialize this component to a dictionary.
183

184
        :returns:
185
            A dictionary containing the serialized component.
186
        """
187
        callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None
1✔
188
        return default_to_dict(
1✔
189
            self,
190
            api_type=str(self.api_type),
191
            api_params=self.api_params,
192
            token=self.token.to_dict() if self.token else None,
193
            generation_kwargs=self.generation_kwargs,
194
            streaming_callback=callback_name,
195
        )
196

197
    @classmethod
1✔
198
    def from_dict(cls, data: Dict[str, Any]) -> "HuggingFaceAPIGenerator":
1✔
199
        """
200
        Deserialize this component from a dictionary.
201
        """
202
        deserialize_secrets_inplace(data["init_parameters"], keys=["token"])
1✔
203
        init_params = data["init_parameters"]
1✔
204
        serialized_callback_handler = init_params.get("streaming_callback")
1✔
205
        if serialized_callback_handler:
1✔
206
            init_params["streaming_callback"] = deserialize_callable(serialized_callback_handler)
1✔
207
        return default_from_dict(cls, data)
1✔
208

209
    @component.output_types(replies=List[str], meta=List[Dict[str, Any]])
1✔
210
    def run(
1✔
211
        self,
212
        prompt: str,
213
        streaming_callback: Optional[StreamingCallbackT] = None,
214
        generation_kwargs: Optional[Dict[str, Any]] = None,
215
    ):
216
        """
217
        Invoke the text generation inference for the given prompt and generation parameters.
218

219
        :param prompt:
220
            A string representing the prompt.
221
        :param streaming_callback:
222
            A callback function that is called when a new token is received from the stream.
223
        :param generation_kwargs:
224
            Additional keyword arguments for text generation.
225
        :returns:
226
            A dictionary with the generated replies and metadata. Both are lists of length n.
227
            - replies: A list of strings representing the generated replies.
228
        """
229
        # update generation kwargs by merging with the default ones
230
        generation_kwargs = {**self.generation_kwargs, **(generation_kwargs or {})}
1✔
231

232
        # check if streaming_callback is passed
233
        streaming_callback = select_streaming_callback(
1✔
234
            init_callback=self.streaming_callback, runtime_callback=streaming_callback, requires_async=False
235
        )
236

237
        hf_output = self._client.text_generation(
1✔
238
            prompt, details=True, stream=streaming_callback is not None, **generation_kwargs
239
        )
240

241
        if streaming_callback is not None:
1✔
242
            return self._stream_and_build_response(hf_output=hf_output, streaming_callback=streaming_callback)
1✔
243

244
        # mypy doesn't know that hf_output is a TextGenerationOutput, so we cast it
245
        return self._build_non_streaming_response(cast(TextGenerationOutput, hf_output))
1✔
246

247
    def _stream_and_build_response(
1✔
248
        self, hf_output: Iterable["TextGenerationStreamOutput"], streaming_callback: SyncStreamingCallbackT
249
    ):
250
        chunks: List[StreamingChunk] = []
1✔
251
        first_chunk_time = None
1✔
252

253
        component_info = ComponentInfo.from_component(self)
1✔
254
        for chunk in hf_output:
1✔
255
            token: TextGenerationStreamOutputToken = chunk.token
1✔
256
            if token.special:
1✔
257
                continue
×
258

259
            chunk_metadata = {**asdict(token), **(asdict(chunk.details) if chunk.details else {})}
1✔
260
            if first_chunk_time is None:
1✔
261
                first_chunk_time = datetime.now().isoformat()
1✔
262

263
            mapping: Dict[str, FinishReason] = {
1✔
264
                "length": "length",  # Direct match
265
                "eos_token": "stop",  # EOS token means natural stop
266
                "stop_sequence": "stop",  # Stop sequence means natural stop
267
            }
268
            mapped_finish_reason = (
1✔
269
                mapping.get(chunk_metadata["finish_reason"], "stop") if chunk_metadata.get("finish_reason") else None
270
            )
271
            stream_chunk = StreamingChunk(
1✔
272
                content=token.text,
273
                meta=chunk_metadata,
274
                component_info=component_info,
275
                index=0,
276
                start=len(chunks) == 0,
277
                finish_reason=mapped_finish_reason,
278
            )
279
            chunks.append(stream_chunk)
1✔
280
            streaming_callback(stream_chunk)
1✔
281

282
        metadata = {
1✔
283
            "finish_reason": chunks[-1].meta.get("finish_reason", None),
284
            "model": self._client.model,
285
            "usage": {"completion_tokens": chunks[-1].meta.get("generated_tokens", 0)},
286
            "completion_start_time": first_chunk_time,
287
        }
288
        return {"replies": ["".join([chunk.content for chunk in chunks])], "meta": [metadata]}
1✔
289

290
    def _build_non_streaming_response(self, hf_output: "TextGenerationOutput"):
1✔
291
        meta = [
1✔
292
            {
293
                "model": self._client.model,
294
                "finish_reason": hf_output.details.finish_reason if hf_output.details else None,
295
                "usage": {"completion_tokens": len(hf_output.details.tokens) if hf_output.details else 0},
296
            }
297
        ]
298
        return {"replies": [hf_output.generated_text], "meta": meta}
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