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

deepset-ai / haystack / 15343971673

30 May 2025 09:44AM UTC coverage: 90.371% (+0.03%) from 90.346%
15343971673

Pull #9457

github

web-flow
Merge 7c781dea6 into 25c8d7ef9
Pull Request #9457: feat: Allow passing of additional parameters to HF Inference clients in `HuggingFaceAPIChatGenerator` and `HuggingFaceAPIGenerator`

11460 of 12681 relevant lines covered (90.37%)

0.9 hits per line

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

96.34
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
1✔
10
from haystack.dataclasses import ComponentInfo, StreamingCallbackT, StreamingChunk, select_streaming_callback
1✔
11
from haystack.lazy_imports import LazyImport
1✔
12
from haystack.utils import Secret, deserialize_callable, deserialize_secrets_inplace, serialize_callable
1✔
13
from haystack.utils.hf import HFGenerationAPIType, 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 (
1✔
18
        InferenceClient,
19
        TextGenerationOutput,
20
        TextGenerationStreamOutput,
21
        TextGenerationStreamOutputToken,
22
    )
23

24

25
@component
1✔
26
class HuggingFaceAPIGenerator:
1✔
27
    """
28
    Generates text using Hugging Face APIs.
29

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

35
    ### Usage examples
36

37
    #### With the free serverless inference API
38

39
    ```python
40
    from haystack.components.generators import HuggingFaceAPIGenerator
41
    from haystack.utils import Secret
42

43
    generator = HuggingFaceAPIGenerator(api_type="serverless_inference_api",
44
                                        api_params={"model": "HuggingFaceH4/zephyr-7b-beta"},
45
                                        token=Secret.from_token("<your-api-key>"))
46

47
    result = generator.run(prompt="What's Natural Language Processing?")
48
    print(result)
49
    ```
50

51
    #### With paid 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

76
    def __init__(  # pylint: disable=too-many-positional-arguments
1✔
77
        self,
78
        api_type: Union[HFGenerationAPIType, str],
79
        api_params: Dict[str, str],
80
        token: Optional[Secret] = Secret.from_env_var(["HF_API_TOKEN", "HF_TOKEN"], strict=False),
81
        generation_kwargs: Optional[Dict[str, Any]] = None,
82
        stop_words: Optional[List[str]] = None,
83
        streaming_callback: Optional[StreamingCallbackT] = None,
84
    ):
85
        """
86
        Initialize the HuggingFaceAPIGenerator instance.
87

88
        :param api_type:
89
            The type of Hugging Face API to use. Available types:
90
            - `text_generation_inference`: See [TGI](https://github.com/huggingface/text-generation-inference).
91
            - `inference_endpoints`: See [Inference Endpoints](https://huggingface.co/inference-endpoints).
92
            - `serverless_inference_api`: See [Serverless Inference API](https://huggingface.co/inference-api).
93
        :param api_params:
94
            A dictionary with the following keys:
95
            - `model`: Hugging Face model ID. Required when `api_type` is `SERVERLESS_INFERENCE_API`.
96
            - `url`: URL of the inference endpoint. Required when `api_type` is `INFERENCE_ENDPOINTS` or
97
            `TEXT_GENERATION_INFERENCE`.
98
            - Other parameters specific to the chosen API type, such as `timeout`, `headers`, `provider` etc.
99
        :param token: The Hugging Face token to use as HTTP bearer authorization.
100
            Check your HF token in your [account settings](https://huggingface.co/settings/tokens).
101
        :param generation_kwargs:
102
            A dictionary with keyword arguments to customize text generation. Some examples: `max_new_tokens`,
103
            `temperature`, `top_k`, `top_p`.
104
            For details, see [Hugging Face documentation](https://huggingface.co/docs/huggingface_hub/en/package_reference/inference_client#huggingface_hub.InferenceClient.text_generation)
105
            for more information.
106
        :param stop_words: An optional list of strings representing the stop words.
107
        :param streaming_callback: An optional callable for handling streaming responses.
108
        """
109

110
        huggingface_hub_import.check()
1✔
111

112
        if isinstance(api_type, str):
1✔
113
            api_type = HFGenerationAPIType.from_str(api_type)
1✔
114

115
        if api_type == HFGenerationAPIType.SERVERLESS_INFERENCE_API:
1✔
116
            model = api_params.get("model")
1✔
117
            if model is None:
1✔
118
                raise ValueError(
1✔
119
                    "To use the Serverless Inference API, you need to specify the `model` parameter in `api_params`."
120
                )
121
            check_valid_model(model, HFModelType.GENERATION, token)
1✔
122
            model_or_url = model
1✔
123
        elif api_type in [HFGenerationAPIType.INFERENCE_ENDPOINTS, HFGenerationAPIType.TEXT_GENERATION_INFERENCE]:
1✔
124
            url = api_params.get("url")
1✔
125
            if url is None:
1✔
126
                msg = (
1✔
127
                    "To use Text Generation Inference or Inference Endpoints, you need to specify the `url` "
128
                    "parameter in `api_params`."
129
                )
130
                raise ValueError(msg)
1✔
131
            if not is_valid_http_url(url):
1✔
132
                raise ValueError(f"Invalid URL: {url}")
1✔
133
            model_or_url = url
1✔
134
        else:
135
            msg = f"Unknown api_type {api_type}"
×
136
            raise ValueError(msg)
×
137

138
        # handle generation kwargs setup
139
        generation_kwargs = generation_kwargs.copy() if generation_kwargs else {}
1✔
140
        generation_kwargs["stop_sequences"] = generation_kwargs.get("stop_sequences", [])
1✔
141
        generation_kwargs["stop_sequences"].extend(stop_words or [])
1✔
142
        generation_kwargs.setdefault("max_new_tokens", 512)
1✔
143

144
        self.api_type = api_type
1✔
145
        self.api_params = api_params
1✔
146
        self.token = token
1✔
147
        self.generation_kwargs = generation_kwargs
1✔
148
        self.streaming_callback = streaming_callback
1✔
149

150
        resolved_api_params: Dict[str, Any] = {k: v for k, v in api_params.items() if k != "model" and k != "url"}
1✔
151
        self._client = InferenceClient(
1✔
152
            model_or_url, token=token.resolve_value() if token else None, **resolved_api_params
153
        )
154

155
    def to_dict(self) -> Dict[str, Any]:
1✔
156
        """
157
        Serialize this component to a dictionary.
158

159
        :returns:
160
            A dictionary containing the serialized component.
161
        """
162
        callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None
1✔
163
        return default_to_dict(
1✔
164
            self,
165
            api_type=str(self.api_type),
166
            api_params=self.api_params,
167
            token=self.token.to_dict() if self.token else None,
168
            generation_kwargs=self.generation_kwargs,
169
            streaming_callback=callback_name,
170
        )
171

172
    @classmethod
1✔
173
    def from_dict(cls, data: Dict[str, Any]) -> "HuggingFaceAPIGenerator":
1✔
174
        """
175
        Deserialize this component from a dictionary.
176
        """
177
        deserialize_secrets_inplace(data["init_parameters"], keys=["token"])
1✔
178
        init_params = data["init_parameters"]
1✔
179
        serialized_callback_handler = init_params.get("streaming_callback")
1✔
180
        if serialized_callback_handler:
1✔
181
            init_params["streaming_callback"] = deserialize_callable(serialized_callback_handler)
1✔
182
        return default_from_dict(cls, data)
1✔
183

184
    @component.output_types(replies=List[str], meta=List[Dict[str, Any]])
1✔
185
    def run(
1✔
186
        self,
187
        prompt: str,
188
        streaming_callback: Optional[StreamingCallbackT] = None,
189
        generation_kwargs: Optional[Dict[str, Any]] = None,
190
    ):
191
        """
192
        Invoke the text generation inference for the given prompt and generation parameters.
193

194
        :param prompt:
195
            A string representing the prompt.
196
        :param streaming_callback:
197
            A callback function that is called when a new token is received from the stream.
198
        :param generation_kwargs:
199
            Additional keyword arguments for text generation.
200
        :returns:
201
            A dictionary with the generated replies and metadata. Both are lists of length n.
202
            - replies: A list of strings representing the generated replies.
203
        """
204
        # update generation kwargs by merging with the default ones
205
        generation_kwargs = {**self.generation_kwargs, **(generation_kwargs or {})}
1✔
206

207
        # check if streaming_callback is passed
208
        streaming_callback = select_streaming_callback(
1✔
209
            init_callback=self.streaming_callback, runtime_callback=streaming_callback, requires_async=False
210
        )
211

212
        hf_output = self._client.text_generation(
1✔
213
            prompt, details=True, stream=streaming_callback is not None, **generation_kwargs
214
        )
215

216
        if streaming_callback is not None:
1✔
217
            return self._stream_and_build_response(hf_output, streaming_callback)
1✔
218

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

222
    def _stream_and_build_response(
1✔
223
        self, hf_output: Iterable["TextGenerationStreamOutput"], streaming_callback: StreamingCallbackT
224
    ):
225
        chunks: List[StreamingChunk] = []
1✔
226
        first_chunk_time = None
1✔
227

228
        component_info = ComponentInfo.from_component(self)
1✔
229
        for chunk in hf_output:
1✔
230
            token: TextGenerationStreamOutputToken = chunk.token
1✔
231
            if token.special:
1✔
232
                continue
×
233

234
            chunk_metadata = {**asdict(token), **(asdict(chunk.details) if chunk.details else {})}
1✔
235
            if first_chunk_time is None:
1✔
236
                first_chunk_time = datetime.now().isoformat()
1✔
237

238
            stream_chunk = StreamingChunk(content=token.text, meta=chunk_metadata, component_info=component_info)
1✔
239
            chunks.append(stream_chunk)
1✔
240
            streaming_callback(stream_chunk)
1✔
241

242
        metadata = {
1✔
243
            "finish_reason": chunks[-1].meta.get("finish_reason", None),
244
            "model": self._client.model,
245
            "usage": {"completion_tokens": chunks[-1].meta.get("generated_tokens", 0)},
246
            "completion_start_time": first_chunk_time,
247
        }
248
        return {"replies": ["".join([chunk.content for chunk in chunks])], "meta": [metadata]}
1✔
249

250
    def _build_non_streaming_response(self, hf_output: "TextGenerationOutput"):
1✔
251
        meta = [
1✔
252
            {
253
                "model": self._client.model,
254
                "finish_reason": hf_output.details.finish_reason if hf_output.details else None,
255
                "usage": {"completion_tokens": len(hf_output.details.tokens) if hf_output.details else 0},
256
            }
257
        ]
258
        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

© 2026 Coveralls, Inc