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

deepset-ai / haystack / 13972131258

20 Mar 2025 02:43PM UTC coverage: 90.021% (-0.03%) from 90.054%
13972131258

Pull #9069

github

web-flow
Merge 8371761b0 into 67ab3788e
Pull Request #9069: refactor!: `ChatMessage` serialization-deserialization updates

9833 of 10923 relevant lines covered (90.02%)

0.9 hits per line

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

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

5
import os
1✔
6
from typing import Any, Callable, Dict, Optional
1✔
7

8
from openai.lib.azure import AzureADTokenProvider, AzureOpenAI
1✔
9

10
from haystack import component, default_from_dict, default_to_dict
1✔
11
from haystack.components.generators import OpenAIGenerator
1✔
12
from haystack.dataclasses import StreamingChunk
1✔
13
from haystack.utils import Secret, deserialize_callable, deserialize_secrets_inplace, serialize_callable
1✔
14

15

16
@component
1✔
17
class AzureOpenAIGenerator(OpenAIGenerator):
1✔
18
    """
19
    Generates text using OpenAI's large language models (LLMs).
20

21
    It works with the gpt-4 - type models and supports streaming responses
22
    from OpenAI API.
23

24
    You can customize how the text is generated by passing parameters to the
25
    OpenAI API. Use the `**generation_kwargs` argument when you initialize
26
    the component or when you run it. Any parameter that works with
27
    `openai.ChatCompletion.create` will work here too.
28

29

30
    For details on OpenAI API parameters, see
31
    [OpenAI documentation](https://platform.openai.com/docs/api-reference/chat).
32

33

34
    ### Usage example
35

36
    ```python
37
    from haystack.components.generators import AzureOpenAIGenerator
38
    from haystack.utils import Secret
39
    client = AzureOpenAIGenerator(
40
        azure_endpoint="<Your Azure endpoint e.g. `https://your-company.azure.openai.com/>",
41
        api_key=Secret.from_token("<your-api-key>"),
42
        azure_deployment="<this a model name, e.g.  gpt-4o-mini>")
43
    response = client.run("What's Natural Language Processing? Be brief.")
44
    print(response)
45
    ```
46

47
    ```
48
    >> {'replies': ['Natural Language Processing (NLP) is a branch of artificial intelligence that focuses on
49
    >> the interaction between computers and human language. It involves enabling computers to understand, interpret,
50
    >> and respond to natural human language in a way that is both meaningful and useful.'], 'meta': [{'model':
51
    >> 'gpt-4o-mini', 'index': 0, 'finish_reason': 'stop', 'usage': {'prompt_tokens': 16,
52
    >> 'completion_tokens': 49, 'total_tokens': 65}}]}
53
    ```
54
    """
55

56
    # pylint: disable=super-init-not-called
57
    def __init__(  # pylint: disable=too-many-positional-arguments
1✔
58
        self,
59
        azure_endpoint: Optional[str] = None,
60
        api_version: Optional[str] = "2023-05-15",
61
        azure_deployment: Optional[str] = "gpt-4o-mini",
62
        api_key: Optional[Secret] = Secret.from_env_var("AZURE_OPENAI_API_KEY", strict=False),
63
        azure_ad_token: Optional[Secret] = Secret.from_env_var("AZURE_OPENAI_AD_TOKEN", strict=False),
64
        organization: Optional[str] = None,
65
        streaming_callback: Optional[Callable[[StreamingChunk], None]] = None,
66
        system_prompt: Optional[str] = None,
67
        timeout: Optional[float] = None,
68
        max_retries: Optional[int] = None,
69
        generation_kwargs: Optional[Dict[str, Any]] = None,
70
        default_headers: Optional[Dict[str, str]] = None,
71
        *,
72
        azure_ad_token_provider: Optional[AzureADTokenProvider] = None,
73
    ):
74
        """
75
        Initialize the Azure OpenAI Generator.
76

77
        :param azure_endpoint: The endpoint of the deployed model, for example `https://example-resource.azure.openai.com/`.
78
        :param api_version: The version of the API to use. Defaults to 2023-05-15.
79
        :param azure_deployment: The deployment of the model, usually the model name.
80
        :param api_key: The API key to use for authentication.
81
        :param azure_ad_token: [Azure Active Directory token](https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id).
82
        :param organization: Your organization ID, defaults to `None`. For help, see
83
        [Setting up your organization](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization).
84
        :param streaming_callback: A callback function called when a new token is received from the stream.
85
            It accepts [StreamingChunk](https://docs.haystack.deepset.ai/docs/data-classes#streamingchunk)
86
            as an argument.
87
        :param system_prompt: The system prompt to use for text generation. If not provided, the Generator
88
        omits the system prompt and uses the default system prompt.
89
        :param timeout: Timeout for AzureOpenAI client. If not set, it is inferred from the
90
            `OPENAI_TIMEOUT` environment variable or set to 30.
91
        :param max_retries: Maximum retries to establish contact with AzureOpenAI if it returns an internal error.
92
            If not set, it is inferred from the `OPENAI_MAX_RETRIES` environment variable or set to 5.
93
        :param generation_kwargs: Other parameters to use for the model, sent directly to
94
            the OpenAI endpoint. See [OpenAI documentation](https://platform.openai.com/docs/api-reference/chat) for
95
            more details.
96
            Some of the supported parameters:
97
            - `max_tokens`: The maximum number of tokens the output text can have.
98
            - `temperature`: The sampling temperature to use. Higher values mean the model takes more risks.
99
                Try 0.9 for more creative applications and 0 (argmax sampling) for ones with a well-defined answer.
100
            - `top_p`: An alternative to sampling with temperature, called nucleus sampling, where the model
101
                considers the results of the tokens with top_p probability mass. For example, 0.1 means only the tokens
102
                comprising the top 10% probability mass are considered.
103
            - `n`: The number of completions to generate for each prompt. For example, with 3 prompts and n=2,
104
                the LLM will generate two completions per prompt, resulting in 6 completions total.
105
            - `stop`: One or more sequences after which the LLM should stop generating tokens.
106
            - `presence_penalty`: The penalty applied if a token is already present.
107
                Higher values make the model less likely to repeat the token.
108
            - `frequency_penalty`: Penalty applied if a token has already been generated.
109
                Higher values make the model less likely to repeat the token.
110
            - `logit_bias`: Adds a logit bias to specific tokens. The keys of the dictionary are tokens, and the
111
                values are the bias to add to that token.
112
        :param default_headers: Default headers to use for the AzureOpenAI client.
113
        :param azure_ad_token_provider: A function that returns an Azure Active Directory token, will be invoked on
114
            every request.
115
        """
116
        # We intentionally do not call super().__init__ here because we only need to instantiate the client to interact
117
        # with the API.
118

119
        # Why is this here?
120
        # AzureOpenAI init is forcing us to use an init method that takes either base_url or azure_endpoint as not
121
        # None init parameters. This way we accommodate the use case where env var AZURE_OPENAI_ENDPOINT is set instead
122
        # of passing it as a parameter.
123
        azure_endpoint = azure_endpoint or os.environ.get("AZURE_OPENAI_ENDPOINT")
1✔
124
        if not azure_endpoint:
1✔
125
            raise ValueError("Please provide an Azure endpoint or set the environment variable AZURE_OPENAI_ENDPOINT.")
×
126

127
        if api_key is None and azure_ad_token is None:
1✔
128
            raise ValueError("Please provide an API key or an Azure Active Directory token.")
×
129

130
        # The check above makes mypy incorrectly infer that api_key is never None,
131
        # which propagates the incorrect type.
132
        self.api_key = api_key  # type: ignore
1✔
133
        self.azure_ad_token = azure_ad_token
1✔
134
        self.generation_kwargs = generation_kwargs or {}
1✔
135
        self.system_prompt = system_prompt
1✔
136
        self.streaming_callback = streaming_callback
1✔
137
        self.api_version = api_version
1✔
138
        self.azure_endpoint = azure_endpoint
1✔
139
        self.azure_deployment = azure_deployment
1✔
140
        self.organization = organization
1✔
141
        self.model: str = azure_deployment or "gpt-4o-mini"
1✔
142
        self.timeout = timeout or float(os.environ.get("OPENAI_TIMEOUT", "30.0"))
1✔
143
        self.max_retries = max_retries or int(os.environ.get("OPENAI_MAX_RETRIES", "5"))
1✔
144
        self.default_headers = default_headers or {}
1✔
145
        self.azure_ad_token_provider = azure_ad_token_provider
1✔
146

147
        self.client = AzureOpenAI(
1✔
148
            api_version=api_version,
149
            azure_endpoint=azure_endpoint,
150
            azure_deployment=azure_deployment,
151
            azure_ad_token_provider=azure_ad_token_provider,
152
            api_key=api_key.resolve_value() if api_key is not None else None,
153
            azure_ad_token=azure_ad_token.resolve_value() if azure_ad_token is not None else None,
154
            organization=organization,
155
            timeout=self.timeout,
156
            max_retries=self.max_retries,
157
            default_headers=self.default_headers,
158
        )
159

160
    def to_dict(self) -> Dict[str, Any]:
1✔
161
        """
162
        Serialize this component to a dictionary.
163

164
        :returns:
165
            The serialized component as a dictionary.
166
        """
167
        callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None
1✔
168
        azure_ad_token_provider_name = None
1✔
169
        if self.azure_ad_token_provider:
1✔
170
            azure_ad_token_provider_name = serialize_callable(self.azure_ad_token_provider)
1✔
171
        return default_to_dict(
1✔
172
            self,
173
            azure_endpoint=self.azure_endpoint,
174
            azure_deployment=self.azure_deployment,
175
            organization=self.organization,
176
            api_version=self.api_version,
177
            streaming_callback=callback_name,
178
            generation_kwargs=self.generation_kwargs,
179
            system_prompt=self.system_prompt,
180
            api_key=self.api_key.to_dict() if self.api_key is not None else None,
181
            azure_ad_token=self.azure_ad_token.to_dict() if self.azure_ad_token is not None else None,
182
            timeout=self.timeout,
183
            max_retries=self.max_retries,
184
            default_headers=self.default_headers,
185
            azure_ad_token_provider=azure_ad_token_provider_name,
186
        )
187

188
    @classmethod
1✔
189
    def from_dict(cls, data: Dict[str, Any]) -> "AzureOpenAIGenerator":
1✔
190
        """
191
        Deserialize this component from a dictionary.
192

193
        :param data:
194
            The dictionary representation of this component.
195
        :returns:
196
            The deserialized component instance.
197
        """
198
        deserialize_secrets_inplace(data["init_parameters"], keys=["api_key", "azure_ad_token"])
1✔
199
        init_params = data.get("init_parameters", {})
1✔
200
        serialized_callback_handler = init_params.get("streaming_callback")
1✔
201
        if serialized_callback_handler:
1✔
202
            data["init_parameters"]["streaming_callback"] = deserialize_callable(serialized_callback_handler)
×
203
        serialized_azure_ad_token_provider = init_params.get("azure_ad_token_provider")
1✔
204
        if serialized_azure_ad_token_provider:
1✔
205
            data["init_parameters"]["azure_ad_token_provider"] = deserialize_callable(
×
206
                serialized_azure_ad_token_provider
207
            )
208
        return default_from_dict(cls, data)
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