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

deepset-ai / haystack / 12709332184

10 Jan 2025 12:11PM UTC coverage: 91.1% (+0.001%) from 91.099%
12709332184

Pull #8702

github

web-flow
Merge 3e4d6bfca into 08cf09f83
Pull Request #8702: fix: `OpenAIChatGenerator` - do not pass tools to the OpenAI client when none are provided

8660 of 9506 relevant lines covered (91.1%)

0.91 hits per line

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

66.67
haystack/components/embedders/azure_text_embedder.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, Dict, List, Optional
1✔
7

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

10
from haystack import Document, component, default_from_dict, default_to_dict
1✔
11
from haystack.utils import Secret, deserialize_secrets_inplace
1✔
12

13

14
@component
1✔
15
class AzureOpenAITextEmbedder:
1✔
16
    """
17
    Embeds strings using OpenAI models deployed on Azure.
18

19
    ### Usage example
20

21
    ```python
22
    from haystack.components.embedders import AzureOpenAITextEmbedder
23

24
    text_to_embed = "I love pizza!"
25

26
    text_embedder = AzureOpenAITextEmbedder()
27

28
    print(text_embedder.run(text_to_embed))
29

30
    # {'embedding': [0.017020374536514282, -0.023255806416273117, ...],
31
    # 'meta': {'model': 'text-embedding-ada-002-v2',
32
    #          'usage': {'prompt_tokens': 4, 'total_tokens': 4}}}
33
    ```
34
    """
35

36
    def __init__(  # pylint: disable=too-many-positional-arguments
1✔
37
        self,
38
        azure_endpoint: Optional[str] = None,
39
        api_version: Optional[str] = "2023-05-15",
40
        azure_deployment: str = "text-embedding-ada-002",
41
        dimensions: Optional[int] = None,
42
        api_key: Optional[Secret] = Secret.from_env_var("AZURE_OPENAI_API_KEY", strict=False),
43
        azure_ad_token: Optional[Secret] = Secret.from_env_var("AZURE_OPENAI_AD_TOKEN", strict=False),
44
        organization: Optional[str] = None,
45
        timeout: Optional[float] = None,
46
        max_retries: Optional[int] = None,
47
        prefix: str = "",
48
        suffix: str = "",
49
    ):
50
        """
51
        Creates an AzureOpenAITextEmbedder component.
52

53
        :param azure_endpoint:
54
            The endpoint of the model deployed on Azure.
55
        :param api_version:
56
            The version of the API to use.
57
        :param azure_deployment:
58
            The name of the model deployed on Azure. The default model is text-embedding-ada-002.
59
        :param dimensions:
60
            The number of dimensions the resulting output embeddings should have. Only supported in text-embedding-3
61
            and later models.
62
        :param api_key:
63
            The Azure OpenAI API key.
64
            You can set it with an environment variable `AZURE_OPENAI_API_KEY`, or pass with this
65
            parameter during initialization.
66
        :param azure_ad_token:
67
            Microsoft Entra ID token, see Microsoft's
68
            [Entra ID](https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id)
69
            documentation for more information. You can set it with an environment variable
70
            `AZURE_OPENAI_AD_TOKEN`, or pass with this parameter during initialization.
71
            Previously called Azure Active Directory.
72
        :param organization:
73
            Your organization ID. See OpenAI's
74
            [Setting Up Your Organization](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization)
75
            for more information.
76
        :param timeout: The timeout for `AzureOpenAI` client calls, in seconds.
77
            If not set, defaults to either the
78
            `OPENAI_TIMEOUT` environment variable, or 30 seconds.
79
        :param max_retries: Maximum number of retries to contact AzureOpenAI after an internal error.
80
            If not set, defaults to either the `OPENAI_MAX_RETRIES` environment variable, or to 5 retries.
81
        :param prefix:
82
            A string to add at the beginning of each text.
83
        :param suffix:
84
            A string to add at the end of each text.
85
        """
86
        # Why is this here?
87
        # AzureOpenAI init is forcing us to use an init method that takes either base_url or azure_endpoint as not
88
        # None init parameters. This way we accommodate the use case where env var AZURE_OPENAI_ENDPOINT is set instead
89
        # of passing it as a parameter.
90
        azure_endpoint = azure_endpoint or os.environ.get("AZURE_OPENAI_ENDPOINT")
1✔
91
        if not azure_endpoint:
1✔
92
            raise ValueError("Please provide an Azure endpoint or set the environment variable AZURE_OPENAI_ENDPOINT.")
×
93

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

97
        self.api_key = api_key
1✔
98
        self.azure_ad_token = azure_ad_token
1✔
99
        self.api_version = api_version
1✔
100
        self.azure_endpoint = azure_endpoint
1✔
101
        self.azure_deployment = azure_deployment
1✔
102
        self.dimensions = dimensions
1✔
103
        self.organization = organization
1✔
104
        self.timeout = timeout or float(os.environ.get("OPENAI_TIMEOUT", 30.0))
1✔
105
        self.max_retries = max_retries or int(os.environ.get("OPENAI_MAX_RETRIES", 5))
1✔
106
        self.prefix = prefix
1✔
107
        self.suffix = suffix
1✔
108

109
        self._client = AzureOpenAI(
1✔
110
            api_version=api_version,
111
            azure_endpoint=azure_endpoint,
112
            azure_deployment=azure_deployment,
113
            api_key=api_key.resolve_value() if api_key is not None else None,
114
            azure_ad_token=azure_ad_token.resolve_value() if azure_ad_token is not None else None,
115
            organization=organization,
116
            timeout=self.timeout,
117
            max_retries=self.max_retries,
118
        )
119

120
    def _get_telemetry_data(self) -> Dict[str, Any]:
1✔
121
        """
122
        Data that is sent to Posthog for usage analytics.
123
        """
124
        return {"model": self.azure_deployment}
×
125

126
    def to_dict(self) -> Dict[str, Any]:
1✔
127
        """
128
        Serializes the component to a dictionary.
129

130
        :returns:
131
            Dictionary with serialized data.
132
        """
133
        return default_to_dict(
1✔
134
            self,
135
            azure_endpoint=self.azure_endpoint,
136
            azure_deployment=self.azure_deployment,
137
            dimensions=self.dimensions,
138
            organization=self.organization,
139
            api_version=self.api_version,
140
            prefix=self.prefix,
141
            suffix=self.suffix,
142
            api_key=self.api_key.to_dict() if self.api_key is not None else None,
143
            azure_ad_token=self.azure_ad_token.to_dict() if self.azure_ad_token is not None else None,
144
            timeout=self.timeout,
145
            max_retries=self.max_retries,
146
        )
147

148
    @classmethod
1✔
149
    def from_dict(cls, data: Dict[str, Any]) -> "AzureOpenAITextEmbedder":
1✔
150
        """
151
        Deserializes the component from a dictionary.
152

153
        :param data:
154
            Dictionary to deserialize from.
155
        :returns:
156
            Deserialized component.
157
        """
158
        deserialize_secrets_inplace(data["init_parameters"], keys=["api_key", "azure_ad_token"])
×
159
        return default_from_dict(cls, data)
×
160

161
    @component.output_types(embedding=List[float], meta=Dict[str, Any])
1✔
162
    def run(self, text: str):
1✔
163
        """
164
        Embeds a single string.
165

166
        :param text:
167
            Text to embed.
168

169
        :returns:
170
            A dictionary with the following keys:
171
            - `embedding`: The embedding of the input text.
172
            - `meta`: Information about the usage of the model.
173
        """
174
        if not isinstance(text, str):
×
175
            # Check if input is a list and all elements are instances of Document
176
            if isinstance(text, list) and all(isinstance(elem, Document) for elem in text):
×
177
                error_message = "Input must be a string. Use AzureOpenAIDocumentEmbedder for a list of Documents."
×
178
            else:
179
                error_message = "Input must be a string."
×
180
            raise TypeError(error_message)
×
181

182
        # Preprocess the text by adding prefixes/suffixes
183
        # finally, replace newlines as recommended by OpenAI docs
184
        processed_text = f"{self.prefix}{text}{self.suffix}".replace("\n", " ")
×
185

186
        if self.dimensions is not None:
×
187
            response = self._client.embeddings.create(
×
188
                model=self.azure_deployment, dimensions=self.dimensions, input=processed_text
189
            )
190
        else:
191
            response = self._client.embeddings.create(model=self.azure_deployment, input=processed_text)
×
192

193
        return {
×
194
            "embedding": response.data[0].embedding,
195
            "meta": {"model": response.model, "usage": dict(response.usage)},
196
        }
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