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

deepset-ai / haystack / 15276913207

27 May 2025 01:41PM UTC coverage: 90.41% (+0.02%) from 90.388%
15276913207

Pull #9449

github

web-flow
Merge f55ee47c3 into 3deaa20cb
Pull Request #9449: refactor: Refactor hf api chat generator

11464 of 12680 relevant lines covered (90.41%)

0.9 hits per line

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

96.3
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
        :param token: The Hugging Face token to use as HTTP bearer authorization.
99
            Check your HF token in your [account settings](https://huggingface.co/settings/tokens).
100
        :param generation_kwargs:
101
            A dictionary with keyword arguments to customize text generation. Some examples: `max_new_tokens`,
102
            `temperature`, `top_k`, `top_p`.
103
            For details, see [Hugging Face documentation](https://huggingface.co/docs/huggingface_hub/en/package_reference/inference_client#huggingface_hub.InferenceClient.text_generation)
104
            for more information.
105
        :param stop_words: An optional list of strings representing the stop words.
106
        :param streaming_callback: An optional callable for handling streaming responses.
107
        """
108

109
        huggingface_hub_import.check()
1✔
110

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

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

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

143
        self.api_type = api_type
1✔
144
        self.api_params = api_params
1✔
145
        self.token = token
1✔
146
        self.generation_kwargs = generation_kwargs
1✔
147
        self.streaming_callback = streaming_callback
1✔
148
        self._client = InferenceClient(model_or_url, token=token.resolve_value() if token else None)
1✔
149

150
    def to_dict(self) -> Dict[str, Any]:
1✔
151
        """
152
        Serialize this component to a dictionary.
153

154
        :returns:
155
            A dictionary containing the serialized component.
156
        """
157
        callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None
1✔
158
        return default_to_dict(
1✔
159
            self,
160
            api_type=str(self.api_type),
161
            api_params=self.api_params,
162
            token=self.token.to_dict() if self.token else None,
163
            generation_kwargs=self.generation_kwargs,
164
            streaming_callback=callback_name,
165
        )
166

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

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

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

202
        # check if streaming_callback is passed
203
        streaming_callback = select_streaming_callback(
1✔
204
            init_callback=self.streaming_callback, runtime_callback=streaming_callback, requires_async=False
205
        )
206

207
        hf_output = self._client.text_generation(
1✔
208
            prompt, details=True, stream=streaming_callback is not None, **generation_kwargs
209
        )
210

211
        if streaming_callback is not None:
1✔
212
            return self._stream_and_build_response(hf_output, streaming_callback)
1✔
213

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

217
    def _stream_and_build_response(
1✔
218
        self, hf_output: Iterable["TextGenerationStreamOutput"], streaming_callback: StreamingCallbackT
219
    ):
220
        chunks: List[StreamingChunk] = []
1✔
221
        first_chunk_time = None
1✔
222

223
        component_info = ComponentInfo.from_component(self)
1✔
224
        for chunk in hf_output:
1✔
225
            token: TextGenerationStreamOutputToken = chunk.token
1✔
226
            if token.special:
1✔
227
                continue
×
228

229
            chunk_metadata = {**asdict(token), **(asdict(chunk.details) if chunk.details else {})}
1✔
230
            if first_chunk_time is None:
1✔
231
                first_chunk_time = datetime.now().isoformat()
1✔
232

233
            stream_chunk = StreamingChunk(content=token.text, meta=chunk_metadata, component_info=component_info)
1✔
234
            chunks.append(stream_chunk)
1✔
235
            streaming_callback(stream_chunk)
1✔
236

237
        metadata = {
1✔
238
            "finish_reason": chunks[-1].meta.get("finish_reason", None),
239
            "model": self._client.model,
240
            "usage": {"completion_tokens": chunks[-1].meta.get("generated_tokens", 0)},
241
            "completion_start_time": first_chunk_time,
242
        }
243
        return {"replies": ["".join([chunk.content for chunk in chunks])], "meta": [metadata]}
1✔
244

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