otari-haystack 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
@@ -0,0 +1,28 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from haystack import logging
6
+ from haystack.utils.auth import Secret
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+ _DEFAULT_API_BASE_URL = "https://api.otari.ai/api/v1"
11
+ _EU_API_BASE_URL = "https://eu.api.otari.ai/api/v1"
12
+ _EU_API_KEY_PREFIX = "otk_v1_eu_"
13
+
14
+
15
+ def _warn_if_eu_key_on_default_url(api_key: Secret, api_base_url: str | None) -> None:
16
+ """
17
+ Log a warning if an API key of otari.ai's EU region is sent to the default otari.ai host.
18
+
19
+ The default host rejects such keys with a bare 401 that doesn't name the right host.
20
+ """
21
+ resolved_api_key = api_key.resolve_value()
22
+ if api_base_url == _DEFAULT_API_BASE_URL and resolved_api_key and resolved_api_key.startswith(_EU_API_KEY_PREFIX):
23
+ logger.warning(
24
+ "The Otari API key belongs to otari.ai's EU region, which {default_url} rejects. "
25
+ "Set api_base_url to {eu_url}.",
26
+ default_url=_DEFAULT_API_BASE_URL,
27
+ eu_url=_EU_API_BASE_URL,
28
+ )
File without changes
@@ -0,0 +1,8 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from .document_embedder import OtariDocumentEmbedder
6
+ from .text_embedder import OtariTextEmbedder
7
+
8
+ __all__ = ["OtariDocumentEmbedder", "OtariTextEmbedder"]
@@ -0,0 +1,265 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from collections.abc import Iterable
6
+ from decimal import Decimal
7
+ from typing import Any
8
+
9
+ from haystack import component, default_to_dict, logging
10
+ from haystack.components.embedders import OpenAIDocumentEmbedder
11
+ from haystack.utils.auth import Secret
12
+ from more_itertools import batched
13
+ from openai import APIError
14
+ from openai.types import CreateEmbeddingResponse
15
+ from tqdm import tqdm
16
+ from tqdm.asyncio import tqdm as async_tqdm
17
+
18
+ from haystack_integrations.common.otari.utils import _warn_if_eu_key_on_default_url
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ def _merge_usage(total: dict[str, Any], batch: dict[str, Any]) -> None:
24
+ """
25
+ Add the usage of one batch to the running total.
26
+
27
+ Token counts are summed. Otari's `cost_usd` is summed only while every batch reports it, so that a partial cost is
28
+ never reported as the total.
29
+ """
30
+ total["prompt_tokens"] += batch["prompt_tokens"]
31
+ total["total_tokens"] += batch["total_tokens"]
32
+ if total.get("cost_usd") is not None and batch.get("cost_usd") is not None:
33
+ total["cost_usd"] = str(Decimal(total["cost_usd"]) + Decimal(batch["cost_usd"]))
34
+ else:
35
+ total.pop("cost_usd", None)
36
+ total.pop("pricing_source", None)
37
+
38
+
39
+ @component
40
+ class OtariDocumentEmbedder(OpenAIDocumentEmbedder):
41
+ """
42
+ Computes Document embeddings using models served through an [Otari](https://github.com/mozilla-ai/otari) gateway.
43
+
44
+ The embedding of each Document is stored in the `embedding` field of the Document.
45
+
46
+ By default, this component calls the otari.ai gateway. For an account in otari.ai's EU region, whose API keys
47
+ start with `otk_v1_eu_`, set `api_base_url` to `"https://eu.api.otari.ai/api/v1"`. To call a gateway you run
48
+ yourself, set `api_base_url`, for example to `"http://localhost:8000/api/v1"`.
49
+
50
+ Name models with a selector the gateway accepts, such as `"openai:text-embedding-3-small"`.
51
+
52
+ When the gateway prices a request, `meta["usage"]` contains its cost in US dollars as `cost_usd`, and
53
+ `pricing_source`. If the Documents are sent in more than one batch, `cost_usd` is the sum over all batches.
54
+
55
+ ### Usage example
56
+
57
+ ```python
58
+ from haystack import Document
59
+ from haystack_integrations.components.embedders.otari import OtariDocumentEmbedder
60
+
61
+ # Reads the API key from the OTARI_API_KEY environment variable
62
+ document_embedder = OtariDocumentEmbedder()
63
+ result = document_embedder.run([Document(content="I love pizza!")])
64
+ print(result["documents"][0].embedding)
65
+ # >> [0.017020374536514282, -0.023255806416273117, ...]
66
+ ```
67
+ """
68
+
69
+ def __init__(
70
+ self,
71
+ *,
72
+ api_key: Secret = Secret.from_env_var("OTARI_API_KEY"),
73
+ model: str = "openai:text-embedding-3-small",
74
+ dimensions: int | None = None,
75
+ api_base_url: str = "https://api.otari.ai/api/v1",
76
+ prefix: str = "",
77
+ suffix: str = "",
78
+ batch_size: int = 32,
79
+ progress_bar: bool = True,
80
+ meta_fields_to_embed: list[str] | None = None,
81
+ embedding_separator: str = "\n",
82
+ timeout: float | None = None,
83
+ max_retries: int | None = None,
84
+ http_client_kwargs: dict[str, Any] | None = None,
85
+ raise_on_failure: bool = False,
86
+ ) -> None:
87
+ """
88
+ Creates an OtariDocumentEmbedder component.
89
+
90
+ :param api_key:
91
+ The Otari API key: a key issued by your gateway, or an otari.ai API key.
92
+ Defaults to the `OTARI_API_KEY` environment variable.
93
+ :param model:
94
+ The embedding model selector, for example `"openai:text-embedding-3-small"`.
95
+ The gateway must have the provider configured.
96
+ :param dimensions:
97
+ The number of dimensions of the resulting embeddings. Only some models support this parameter.
98
+ :param api_base_url:
99
+ The OpenAI-compatible API root of the Otari gateway, including the `/api/v1` path.
100
+ Defaults to the otari.ai gateway. For an account in otari.ai's EU region, use
101
+ `"https://eu.api.otari.ai/api/v1"`.
102
+ :param prefix:
103
+ A string to add to the beginning of each text.
104
+ :param suffix:
105
+ A string to add to the end of each text.
106
+ :param batch_size:
107
+ Number of Documents to encode at once.
108
+ :param progress_bar:
109
+ Whether to show a progress bar or not. Can be helpful to disable in production deployments to keep
110
+ the logs clean.
111
+ :param meta_fields_to_embed:
112
+ List of meta fields that should be embedded along with the Document text.
113
+ :param embedding_separator:
114
+ Separator used to concatenate the meta fields to the Document text.
115
+ :param timeout:
116
+ Timeout for the API call. If not set, it defaults to either the `OPENAI_TIMEOUT` environment
117
+ variable, or 30 seconds.
118
+ :param max_retries:
119
+ Maximum number of retries to contact Otari after an internal error.
120
+ If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable, or set to 5.
121
+ :param http_client_kwargs:
122
+ A dictionary of keyword arguments to configure a custom `httpx.Client`or `httpx.AsyncClient`.
123
+ For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client).
124
+ :param raise_on_failure:
125
+ Whether to raise an exception if the embedding request fails. If `False`, the component logs the error
126
+ and continues processing the remaining documents. If `True`, it raises an exception on failure.
127
+ """
128
+ super(OtariDocumentEmbedder, self).__init__( # noqa: UP008
129
+ api_key=api_key,
130
+ model=model,
131
+ dimensions=dimensions,
132
+ api_base_url=api_base_url,
133
+ prefix=prefix,
134
+ suffix=suffix,
135
+ batch_size=batch_size,
136
+ progress_bar=progress_bar,
137
+ meta_fields_to_embed=meta_fields_to_embed,
138
+ embedding_separator=embedding_separator,
139
+ timeout=timeout,
140
+ max_retries=max_retries,
141
+ http_client_kwargs=http_client_kwargs,
142
+ raise_on_failure=raise_on_failure,
143
+ )
144
+
145
+ def warm_up(self) -> None:
146
+ """
147
+ Initialize the synchronous OpenAI client.
148
+
149
+ Logs a warning if the API key belongs to otari.ai's EU region but `api_base_url` is left at its default.
150
+ """
151
+ creates_client = self.client is None
152
+ super(OtariDocumentEmbedder, self).warm_up() # noqa: UP008
153
+ if creates_client:
154
+ _warn_if_eu_key_on_default_url(self.api_key, self.api_base_url)
155
+
156
+ async def warm_up_async(self) -> None:
157
+ """
158
+ Initialize the asynchronous OpenAI client.
159
+
160
+ Logs a warning if the API key belongs to otari.ai's EU region but `api_base_url` is left at its default.
161
+ """
162
+ creates_client = self.async_client is None
163
+ await super(OtariDocumentEmbedder, self).warm_up_async() # noqa: UP008
164
+ if creates_client:
165
+ _warn_if_eu_key_on_default_url(self.api_key, self.api_base_url)
166
+
167
+ def _embedding_args(self, batch: tuple[tuple[str, str], ...]) -> dict[str, Any]:
168
+ args: dict[str, Any] = {"model": self.model, "input": [b[1] for b in batch], "encoding_format": "float"}
169
+ if self.dimensions is not None:
170
+ args["dimensions"] = self.dimensions
171
+ return args
172
+
173
+ def _handle_failed_batch(self, batch: tuple[tuple[str, str], ...], exc: APIError) -> None:
174
+ ids = ", ".join(b[0] for b in batch)
175
+ logger.exception("Failed embedding of documents {ids} caused by {exc}", ids=ids, exc=exc)
176
+ if self.raise_on_failure:
177
+ raise exc
178
+
179
+ @staticmethod
180
+ def _add_batch_result(
181
+ batch: tuple[tuple[str, str], ...],
182
+ response: CreateEmbeddingResponse,
183
+ doc_ids_to_embeddings: dict[str, list[float]],
184
+ meta: dict[str, Any],
185
+ ) -> None:
186
+ embeddings = [el.embedding for el in response.data]
187
+ doc_ids_to_embeddings.update(dict(zip((b[0] for b in batch), embeddings, strict=True)))
188
+ if "model" not in meta:
189
+ meta["model"] = response.model
190
+ if "usage" not in meta:
191
+ meta["usage"] = dict(response.usage)
192
+ else:
193
+ _merge_usage(meta["usage"], dict(response.usage))
194
+
195
+ def _embed_batch(
196
+ self, texts_to_embed: dict[str, str], batch_size: int
197
+ ) -> tuple[dict[str, list[float]], dict[str, Any]]:
198
+ """
199
+ Embed a list of texts in batches.
200
+
201
+ Overrides the parent's method to sum Otari's cost over all batches, see `_merge_usage`.
202
+ """
203
+ doc_ids_to_embeddings: dict[str, list[float]] = {}
204
+ meta: dict[str, Any] = {}
205
+ for batch in tqdm(
206
+ batched(texts_to_embed.items(), batch_size), disable=not self.progress_bar, desc="Calculating embeddings"
207
+ ):
208
+ try:
209
+ # this method is invoked after warm_up, so client is not None
210
+ assert self.client is not None # noqa: S101
211
+ response = self.client.embeddings.create(**self._embedding_args(batch))
212
+ except APIError as exc:
213
+ self._handle_failed_batch(batch, exc)
214
+ continue
215
+ self._add_batch_result(batch, response, doc_ids_to_embeddings, meta)
216
+ return doc_ids_to_embeddings, meta
217
+
218
+ async def _embed_batch_async(
219
+ self, texts_to_embed: dict[str, str], batch_size: int
220
+ ) -> tuple[dict[str, list[float]], dict[str, Any]]:
221
+ """
222
+ Embed a list of texts in batches asynchronously.
223
+
224
+ Overrides the parent's method to sum Otari's cost over all batches, see `_merge_usage`.
225
+ """
226
+ doc_ids_to_embeddings: dict[str, list[float]] = {}
227
+ meta: dict[str, Any] = {}
228
+ batches: Iterable[tuple[tuple[str, str], ...]] = list(batched(texts_to_embed.items(), batch_size))
229
+ if self.progress_bar:
230
+ batches = async_tqdm(batches, desc="Calculating embeddings")
231
+ for batch in batches:
232
+ try:
233
+ # this method is invoked after warm_up_async, so async_client is not None
234
+ assert self.async_client is not None # noqa: S101
235
+ response = await self.async_client.embeddings.create(**self._embedding_args(batch))
236
+ except APIError as exc:
237
+ self._handle_failed_batch(batch, exc)
238
+ continue
239
+ self._add_batch_result(batch, response, doc_ids_to_embeddings, meta)
240
+ return doc_ids_to_embeddings, meta
241
+
242
+ def to_dict(self) -> dict[str, Any]:
243
+ """
244
+ Serializes the component to a dictionary.
245
+
246
+ :returns:
247
+ Dictionary with serialized data.
248
+ """
249
+ return default_to_dict(
250
+ self,
251
+ api_key=self.api_key.to_dict(),
252
+ model=self.model,
253
+ dimensions=self.dimensions,
254
+ api_base_url=self.api_base_url,
255
+ prefix=self.prefix,
256
+ suffix=self.suffix,
257
+ batch_size=self.batch_size,
258
+ progress_bar=self.progress_bar,
259
+ meta_fields_to_embed=self.meta_fields_to_embed,
260
+ embedding_separator=self.embedding_separator,
261
+ timeout=self.timeout,
262
+ max_retries=self.max_retries,
263
+ http_client_kwargs=self.http_client_kwargs,
264
+ raise_on_failure=self.raise_on_failure,
265
+ )
@@ -0,0 +1,132 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from typing import Any
6
+
7
+ from haystack import component, default_to_dict
8
+ from haystack.components.embedders import OpenAITextEmbedder
9
+ from haystack.utils.auth import Secret
10
+
11
+ from haystack_integrations.common.otari.utils import _warn_if_eu_key_on_default_url
12
+
13
+
14
+ @component
15
+ class OtariTextEmbedder(OpenAITextEmbedder):
16
+ """
17
+ Embeds strings using embedding models served through an [Otari](https://github.com/mozilla-ai/otari) gateway.
18
+
19
+ By default, this component calls the otari.ai gateway. For an account in otari.ai's EU region, whose API keys
20
+ start with `otk_v1_eu_`, set `api_base_url` to `"https://eu.api.otari.ai/api/v1"`. To call a gateway you run
21
+ yourself, set `api_base_url`, for example to `"http://localhost:8000/api/v1"`.
22
+
23
+ Name models with a selector the gateway accepts, such as `"openai:text-embedding-3-small"`.
24
+
25
+ ### Usage example
26
+
27
+ ```python
28
+ from haystack_integrations.components.embedders.otari import OtariTextEmbedder
29
+
30
+ # Reads the API key from the OTARI_API_KEY environment variable
31
+ text_embedder = OtariTextEmbedder()
32
+ print(text_embedder.run("I love pizza!"))
33
+ # >> {'embedding': [0.017020374536514282, -0.023255806416273117, ...],
34
+ # >> 'meta': {'model': 'text-embedding-3-small', 'usage': {'prompt_tokens': 4, 'total_tokens': 4}}}
35
+ ```
36
+ """
37
+
38
+ def __init__(
39
+ self,
40
+ *,
41
+ api_key: Secret = Secret.from_env_var("OTARI_API_KEY"),
42
+ model: str = "openai:text-embedding-3-small",
43
+ dimensions: int | None = None,
44
+ api_base_url: str = "https://api.otari.ai/api/v1",
45
+ prefix: str = "",
46
+ suffix: str = "",
47
+ timeout: float | None = None,
48
+ max_retries: int | None = None,
49
+ http_client_kwargs: dict[str, Any] | None = None,
50
+ ) -> None:
51
+ """
52
+ Creates an OtariTextEmbedder component.
53
+
54
+ :param api_key:
55
+ The Otari API key: a key issued by your gateway, or an otari.ai API key.
56
+ Defaults to the `OTARI_API_KEY` environment variable.
57
+ :param model:
58
+ The embedding model selector, for example `"openai:text-embedding-3-small"`.
59
+ The gateway must have the provider configured.
60
+ :param dimensions:
61
+ The number of dimensions of the resulting embeddings. Only some models support this parameter.
62
+ :param api_base_url:
63
+ The OpenAI-compatible API root of the Otari gateway, including the `/api/v1` path.
64
+ Defaults to the otari.ai gateway. For an account in otari.ai's EU region, use
65
+ `"https://eu.api.otari.ai/api/v1"`.
66
+ :param prefix:
67
+ A string to add to the beginning of each text.
68
+ :param suffix:
69
+ A string to add to the end of each text.
70
+ :param timeout:
71
+ Timeout for the API call. If not set, it defaults to either the `OPENAI_TIMEOUT` environment
72
+ variable, or 30 seconds.
73
+ :param max_retries:
74
+ Maximum number of retries to contact Otari after an internal error.
75
+ If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable, or set to 5.
76
+ :param http_client_kwargs:
77
+ A dictionary of keyword arguments to configure a custom `httpx.Client`or `httpx.AsyncClient`.
78
+ For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client).
79
+ """
80
+ super(OtariTextEmbedder, self).__init__( # noqa: UP008
81
+ api_key=api_key,
82
+ model=model,
83
+ dimensions=dimensions,
84
+ api_base_url=api_base_url,
85
+ prefix=prefix,
86
+ suffix=suffix,
87
+ timeout=timeout,
88
+ max_retries=max_retries,
89
+ http_client_kwargs=http_client_kwargs,
90
+ )
91
+
92
+ def warm_up(self) -> None:
93
+ """
94
+ Initialize the synchronous OpenAI client.
95
+
96
+ Logs a warning if the API key belongs to otari.ai's EU region but `api_base_url` is left at its default.
97
+ """
98
+ creates_client = self.client is None
99
+ super(OtariTextEmbedder, self).warm_up() # noqa: UP008
100
+ if creates_client:
101
+ _warn_if_eu_key_on_default_url(self.api_key, self.api_base_url)
102
+
103
+ async def warm_up_async(self) -> None:
104
+ """
105
+ Initialize the asynchronous OpenAI client.
106
+
107
+ Logs a warning if the API key belongs to otari.ai's EU region but `api_base_url` is left at its default.
108
+ """
109
+ creates_client = self.async_client is None
110
+ await super(OtariTextEmbedder, self).warm_up_async() # noqa: UP008
111
+ if creates_client:
112
+ _warn_if_eu_key_on_default_url(self.api_key, self.api_base_url)
113
+
114
+ def to_dict(self) -> dict[str, Any]:
115
+ """
116
+ Serializes the component to a dictionary.
117
+
118
+ :returns:
119
+ Dictionary with serialized data.
120
+ """
121
+ return default_to_dict(
122
+ self,
123
+ api_key=self.api_key.to_dict(),
124
+ model=self.model,
125
+ dimensions=self.dimensions,
126
+ api_base_url=self.api_base_url,
127
+ prefix=self.prefix,
128
+ suffix=self.suffix,
129
+ timeout=self.timeout,
130
+ max_retries=self.max_retries,
131
+ http_client_kwargs=self.http_client_kwargs,
132
+ )
File without changes
@@ -0,0 +1,7 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from .chat.chat_generator import OtariChatGenerator
6
+
7
+ __all__ = ["OtariChatGenerator"]
@@ -0,0 +1,7 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from .chat_generator import OtariChatGenerator
6
+
7
+ __all__ = ["OtariChatGenerator"]