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

deepset-ai / haystack / 11591697173

30 Oct 2024 10:51AM UTC coverage: 90.104%. Remained the same
11591697173

push

github

web-flow
fix: `HuggingFaceAPIGenerator` - use forward references (#8502)

* hf API generator: forward references + refactor

* release note

7712 of 8559 relevant lines covered (90.1%)

0.9 hits per line

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

96.1
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 typing import Any, Callable, Dict, Iterable, List, Optional, Union
1✔
7

8
from haystack import component, default_from_dict, default_to_dict, logging
1✔
9
from haystack.dataclasses import StreamingChunk
1✔
10
from haystack.lazy_imports import LazyImport
1✔
11
from haystack.utils import Secret, deserialize_callable, deserialize_secrets_inplace, serialize_callable
1✔
12
from haystack.utils.hf import HFGenerationAPIType, HFModelType, check_valid_model
1✔
13
from haystack.utils.url_validation import is_valid_http_url
1✔
14

15
with LazyImport(message="Run 'pip install \"huggingface_hub>=0.23.0\"'") as huggingface_hub_import:
1✔
16
    from huggingface_hub import (
1✔
17
        InferenceClient,
18
        TextGenerationOutput,
19
        TextGenerationOutputToken,
20
        TextGenerationStreamOutput,
21
    )
22

23

24
logger = logging.getLogger(__name__)
1✔
25

26

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

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

37
    ### Usage examples
38

39
    #### With the free serverless inference API
40

41
    ```python
42
    from haystack.components.generators import HuggingFaceAPIGenerator
43
    from haystack.utils import Secret
44

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

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

53
    #### With paid inference endpoints
54

55
    ```python
56
    from haystack.components.generators import HuggingFaceAPIGenerator
57
    from haystack.utils import Secret
58

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

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

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

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

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

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

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

111
        huggingface_hub_import.check()
1✔
112

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

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

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

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

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

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

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

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

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

204
        # check if streaming_callback is passed
205
        streaming_callback = streaming_callback or self.streaming_callback
1✔
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
        return self._build_non_streaming_response(hf_output)
1✔
215

216
    def _stream_and_build_response(
1✔
217
        self, hf_output: Iterable["TextGenerationStreamOutput"], streaming_callback: Callable[[StreamingChunk], None]
218
    ):
219
        chunks: List[StreamingChunk] = []
1✔
220
        for chunk in hf_output:
1✔
221
            token: TextGenerationOutputToken = chunk.token
1✔
222
            if token.special:
1✔
223
                continue
×
224
            chunk_metadata = {**asdict(token), **(asdict(chunk.details) if chunk.details else {})}
1✔
225
            stream_chunk = StreamingChunk(token.text, chunk_metadata)
1✔
226
            chunks.append(stream_chunk)
1✔
227
            streaming_callback(stream_chunk)
1✔
228
        metadata = {
1✔
229
            "finish_reason": chunks[-1].meta.get("finish_reason", None),
230
            "model": self._client.model,
231
            "usage": {"completion_tokens": chunks[-1].meta.get("generated_tokens", 0)},
232
        }
233
        return {"replies": ["".join([chunk.content for chunk in chunks])], "meta": [metadata]}
1✔
234

235
    def _build_non_streaming_response(self, hf_output: "TextGenerationOutput"):
1✔
236
        meta = [
1✔
237
            {
238
                "model": self._client.model,
239
                "finish_reason": hf_output.details.finish_reason if hf_output.details else None,
240
                "usage": {"completion_tokens": len(hf_output.details.tokens) if hf_output.details else 0},
241
            }
242
        ]
243
        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