typesafe-haystack 0.1.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.
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 .document_classifier import TypeSafeDocumentClassifier
6
+
7
+ __all__ = ["TypeSafeDocumentClassifier"]
@@ -0,0 +1,375 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import asyncio
6
+ from concurrent.futures import ThreadPoolExecutor
7
+ from dataclasses import replace
8
+ from typing import Any
9
+
10
+ from haystack import Document, component, default_to_dict, logging
11
+ from haystack.utils import Secret
12
+ from typesafe_sdk import (
13
+ AsyncTypeSafeClient,
14
+ Choice,
15
+ Noul,
16
+ Question,
17
+ RetryPolicy,
18
+ Score,
19
+ SystemOneResponse,
20
+ TypeSafeClient,
21
+ TypeSafeError,
22
+ )
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ _QUESTION_TYPES = ("choice", "score", "noul")
27
+ _ERROR_FIELD = "classification_error"
28
+
29
+
30
+ @component
31
+ class TypeSafeDocumentClassifier:
32
+ """
33
+ Answers typed questions about each document with a TypeSafe System One model and stores the answers in its metadata.
34
+
35
+ System One models such as Jev don't generate text: they answer every question in one request and return
36
+ calibrated probabilities. Each question has one of three types:
37
+ - `choice`: picks one label from `criteria`, a dict of label to description (or `None`).
38
+ - `score`: rates the text on the ordered levels in `criteria`, a list of level descriptions.
39
+ - `noul`: returns the probability that the yes/no question in `instructions` is true.
40
+
41
+ Answers are stored under `meta[metadata_field]`, keyed by question ID. Questions can be dicts or the SDK's
42
+ `Choice`, `Score` and `Noul` objects. See the [TypeSafe documentation](https://docs.typesafe.ai/primitives) for the
43
+ full question and answer format.
44
+
45
+ Documents without text to classify are returned in `failed_documents` with the reason in
46
+ `meta["classification_error"]`. So are documents whose request failed, unless `raise_on_failure` is `True`.
47
+
48
+ The component also works with servers that implement the TypeSafe API, such as [Ollaya](https://ollaya.dev),
49
+ which runs open decision models locally. Set `api_base_url` to the server and `model` to one of its models.
50
+
51
+ ### Usage example
52
+
53
+ ```python
54
+ from haystack import Document
55
+
56
+ from haystack_integrations.components.classifiers.typesafe import TypeSafeDocumentClassifier
57
+
58
+ classifier = TypeSafeDocumentClassifier(
59
+ questions={
60
+ "department": {
61
+ "type": "choice",
62
+ "instructions": "Which department should handle this ticket?",
63
+ "criteria": {"billing": None, "technical": None, "sales": None},
64
+ },
65
+ "urgency": {
66
+ "type": "score",
67
+ "instructions": "How urgent is this ticket?",
68
+ "criteria": ["can wait", "this week", "today"],
69
+ },
70
+ "refund": {"type": "noul", "instructions": "Is the customer asking for a refund?"},
71
+ }
72
+ )
73
+
74
+ result = classifier.run(documents=[Document(content="I was charged twice, please refund me today.")])
75
+ print(result["documents"][0].meta["typesafe"])
76
+ # {'department': {'type': 'choice', 'choice': 'billing', 'confidence': 0.9516,
77
+ # 'probabilities': {'billing': 0.9677, 'technical': 0.0221, 'sales': 0.0102}},
78
+ # 'urgency': {'type': 'score', 'score': 1.948, 'confidence': 0.9389,
79
+ # 'legend': {'0': 'can wait', '1': 'this week', '2': 'today'},
80
+ # 'probabilities': {'0': 0.0113, '1': 0.0295, '2': 0.9593}},
81
+ # 'refund': {'type': 'noul', 'noul': 0.9498}}
82
+ print(result["failed_documents"])
83
+ # []
84
+ ```
85
+ """
86
+
87
+ def __init__(
88
+ self,
89
+ questions: dict[str, Question],
90
+ *,
91
+ model: str = "jev-latest",
92
+ api_key: Secret = Secret.from_env_var("TYPESAFE_API_KEY"),
93
+ api_base_url: str | None = None,
94
+ classification_field: str | None = None,
95
+ metadata_field: str = "typesafe",
96
+ timeout: float | None = None,
97
+ max_retries: int | None = None,
98
+ max_workers: int = 3,
99
+ raise_on_failure: bool = False,
100
+ ) -> None:
101
+ """
102
+ Creates a TypeSafeDocumentClassifier.
103
+
104
+ :param questions:
105
+ Questions to answer for every document, keyed by question ID. Each value is a dict or an SDK `Choice`,
106
+ `Score` or `Noul` object with a `type` (`choice`, `score` or `noul`), `instructions`, and for `choice` and
107
+ `score` questions, `criteria`.
108
+ :param model:
109
+ Name of the System One model to use.
110
+ :param api_key:
111
+ The TypeSafe API key. Servers such as Ollaya accept any non-empty value unless they are configured
112
+ with a key.
113
+ :param api_base_url:
114
+ Base URL of the API. If `None`, the `TYPESAFE_BASE_URL` environment variable is used, or
115
+ `https://api.typesafe.ai` if it is unset.
116
+ :param classification_field:
117
+ Name of the document's metadata field to classify. If `None`, `Document.content` is classified.
118
+ :param metadata_field:
119
+ Name of the metadata field the answers are written to.
120
+ :param timeout:
121
+ Timeout in seconds for each request attempt. If `None`, the SDK default of 10 seconds is used.
122
+ :param max_retries:
123
+ Maximum number of retries after a failed request attempt. If `None`, the SDK default of 2 is used.
124
+ :param max_workers:
125
+ Maximum number of worker threads in `run` and of concurrent requests in `run_async`. Must be at least 1.
126
+ :param raise_on_failure:
127
+ If `True`, the first failed request raises its error. If `False`, documents whose request failed are
128
+ returned in `failed_documents`.
129
+ :raises ValueError:
130
+ If `questions` is empty, a question has an unknown `type`, a `choice` or `score` question has no
131
+ `criteria`, or `max_workers` is smaller than 1.
132
+ """
133
+ if not questions:
134
+ msg = "`questions` must contain at least one question."
135
+ raise ValueError(msg)
136
+ for question_id, question in questions.items():
137
+ # SDK question objects are validated by the SDK when they are created
138
+ if isinstance(question, (Choice, Score, Noul)):
139
+ continue
140
+ if question.get("type") not in _QUESTION_TYPES:
141
+ msg = f"Question '{question_id}' has type {question.get('type')!r}; use one of {_QUESTION_TYPES}."
142
+ raise ValueError(msg)
143
+ if question["type"] != "noul" and not question.get("criteria"):
144
+ msg = f"Question '{question_id}' of type '{question['type']}' needs `criteria`."
145
+ raise ValueError(msg)
146
+ if max_workers < 1:
147
+ msg = f"`max_workers` must be at least 1, got {max_workers}."
148
+ raise ValueError(msg)
149
+
150
+ self.questions = questions
151
+ self.model = model
152
+ self.api_key = api_key
153
+ self.api_base_url = api_base_url
154
+ self.classification_field = classification_field
155
+ self.metadata_field = metadata_field
156
+ self.timeout = timeout
157
+ self.max_retries = max_retries
158
+ self.max_workers = max_workers
159
+ self.raise_on_failure = raise_on_failure
160
+ self._client: TypeSafeClient | None = None
161
+ self._async_client: AsyncTypeSafeClient | None = None
162
+
163
+ def _client_kwargs(self) -> dict[str, Any]:
164
+ # The SDK's retry budget defaults to 30 seconds in total, which would skip retries after a long attempt.
165
+ # `timeout` already bounds each attempt, so the budget is disabled.
166
+ retry_kwargs: dict[str, Any] = {"timeout": None}
167
+ if self.max_retries is not None:
168
+ retry_kwargs["max_retries"] = self.max_retries
169
+ return {
170
+ "api_key": self.api_key.resolve_value(),
171
+ "base_url": self.api_base_url,
172
+ "model": self.model,
173
+ "timeout": self.timeout,
174
+ "retry": RetryPolicy(**retry_kwargs),
175
+ }
176
+
177
+ def warm_up(self) -> None:
178
+ """
179
+ Creates the synchronous TypeSafe client.
180
+ """
181
+ if self._client is None:
182
+ self._client = TypeSafeClient(**self._client_kwargs())
183
+
184
+ async def warm_up_async(self) -> None:
185
+ """
186
+ Creates the asynchronous TypeSafe client.
187
+ """
188
+ if self._async_client is None:
189
+ self._async_client = AsyncTypeSafeClient(**self._client_kwargs())
190
+
191
+ def close(self) -> None:
192
+ """
193
+ Releases the synchronous TypeSafe client.
194
+ """
195
+ if self._client is not None:
196
+ self._client.close()
197
+ self._client = None
198
+
199
+ async def close_async(self) -> None:
200
+ """
201
+ Releases the asynchronous TypeSafe client.
202
+ """
203
+ if self._async_client is not None:
204
+ await self._async_client.aclose()
205
+ self._async_client = None
206
+
207
+ def to_dict(self) -> dict[str, Any]:
208
+ """
209
+ Serializes the component to a dictionary.
210
+
211
+ :returns:
212
+ Dictionary with serialized data.
213
+ """
214
+ return default_to_dict(
215
+ self,
216
+ questions={
217
+ question_id: question.model_dump() if isinstance(question, (Choice, Score, Noul)) else question
218
+ for question_id, question in self.questions.items()
219
+ },
220
+ model=self.model,
221
+ api_key=self.api_key,
222
+ api_base_url=self.api_base_url,
223
+ classification_field=self.classification_field,
224
+ metadata_field=self.metadata_field,
225
+ timeout=self.timeout,
226
+ max_retries=self.max_retries,
227
+ max_workers=self.max_workers,
228
+ raise_on_failure=self.raise_on_failure,
229
+ )
230
+
231
+ def _succeed(self, document: Document, response: SystemOneResponse) -> tuple[Document, bool]:
232
+ """
233
+ Adds the answers from a TypeSafe response to a copy of the document.
234
+
235
+ :param document:
236
+ The classified document.
237
+ :param response:
238
+ The TypeSafe response for the document.
239
+ :returns:
240
+ A copy of the document with the answers under `meta[metadata_field]` and no `classification_error`, and
241
+ `True` to mark it as classified.
242
+ """
243
+ # JSON mode turns the integer score levels into string keys, so the metadata stays JSON-serializable
244
+ answers = {question_id: answer.model_dump(mode="json") for question_id, answer in response.answers.items()}
245
+ # Drop the error left by an earlier failed run
246
+ meta = {key: value for key, value in document.meta.items() if key != _ERROR_FIELD}
247
+ return replace(document, meta={**meta, self.metadata_field: answers}), True
248
+
249
+ def _classify(self, client: TypeSafeClient, document: Document) -> tuple[Document, bool]:
250
+ """
251
+ Sends one document to the TypeSafe API and adds the answers to a copy of it.
252
+
253
+ :param client:
254
+ The synchronous TypeSafe client.
255
+ :param document:
256
+ The document to classify.
257
+ :returns:
258
+ A copy of the document with the answers under `meta[metadata_field]` and `True`, or a copy with the reason
259
+ under `meta["classification_error"]` and `False` if the document has no text or its request failed.
260
+ :raises TypeSafeError:
261
+ If the request fails and `raise_on_failure` is `True`.
262
+ """
263
+ text = document.content if self.classification_field is None else document.meta.get(self.classification_field)
264
+ if not text:
265
+ return replace(document, meta={**document.meta, _ERROR_FIELD: "Document has no text to classify."}), False
266
+ try:
267
+ response = client.system_one(state=text, questions=self.questions)
268
+ except TypeSafeError as error:
269
+ if self.raise_on_failure:
270
+ raise
271
+ logger.warning("Classifying document {document_id} failed: {error}", document_id=document.id, error=error)
272
+ return replace(document, meta={**document.meta, _ERROR_FIELD: str(error)}), False
273
+ return self._succeed(document=document, response=response)
274
+
275
+ async def _classify_async(
276
+ self, client: AsyncTypeSafeClient, document: Document, semaphore: asyncio.Semaphore
277
+ ) -> tuple[Document, bool]:
278
+ """
279
+ Asynchronously sends one document to the TypeSafe API and adds the answers to a copy of it.
280
+
281
+ :param client:
282
+ The asynchronous TypeSafe client.
283
+ :param document:
284
+ The document to classify.
285
+ :param semaphore:
286
+ Limits how many requests run at once.
287
+ :returns:
288
+ A copy of the document with the answers under `meta[metadata_field]` and `True`, or a copy with the reason
289
+ under `meta["classification_error"]` and `False` if the document has no text or its request failed.
290
+ :raises TypeSafeError:
291
+ If the request fails and `raise_on_failure` is `True`.
292
+ """
293
+ text = document.content if self.classification_field is None else document.meta.get(self.classification_field)
294
+ if not text:
295
+ return replace(document, meta={**document.meta, _ERROR_FIELD: "Document has no text to classify."}), False
296
+ try:
297
+ async with semaphore:
298
+ response = await client.system_one(state=text, questions=self.questions)
299
+ except TypeSafeError as error:
300
+ if self.raise_on_failure:
301
+ raise
302
+ logger.warning("Classifying document {document_id} failed: {error}", document_id=document.id, error=error)
303
+ return replace(document, meta={**document.meta, _ERROR_FIELD: str(error)}), False
304
+ return self._succeed(document=document, response=response)
305
+
306
+ @component.output_types(documents=list[Document], failed_documents=list[Document])
307
+ def run(self, documents: list[Document]) -> dict[str, list[Document]]:
308
+ """
309
+ Answers the questions for each document and adds the answers to its metadata.
310
+
311
+ Each document is sent as its own request, with up to `max_workers` requests running at once.
312
+
313
+ :param documents:
314
+ Documents to classify.
315
+ :returns:
316
+ A dictionary with the following keys:
317
+ - `documents`: The classified documents. Each has a `metadata_field` entry mapping each question ID to its
318
+ answer.
319
+ - `failed_documents`: The documents that have no text to classify or whose request failed, with the
320
+ reason in `meta["classification_error"]`.
321
+ :raises TypeSafeError:
322
+ If a request fails and `raise_on_failure` is `True`.
323
+ """
324
+ self.warm_up()
325
+ assert self._client is not None # noqa: S101 # mypy: the client is created by warm_up above
326
+
327
+ client = self._client
328
+ with ThreadPoolExecutor(max_workers=self.max_workers) as executor:
329
+ results = list(executor.map(lambda document: self._classify(client=client, document=document), documents))
330
+ return {
331
+ "documents": [document for document, succeeded in results if succeeded],
332
+ "failed_documents": [document for document, succeeded in results if not succeeded],
333
+ }
334
+
335
+ @component.output_types(documents=list[Document], failed_documents=list[Document])
336
+ async def run_async(self, documents: list[Document]) -> dict[str, list[Document]]:
337
+ """
338
+ Asynchronously answers the questions for each document and adds the answers to its metadata.
339
+
340
+ This is the asynchronous version of the `run` method with the same parameters and return values. Up to
341
+ `max_workers` requests run concurrently.
342
+
343
+ :param documents:
344
+ Documents to classify.
345
+ :returns:
346
+ A dictionary with the following keys:
347
+ - `documents`: The classified documents. Each has a `metadata_field` entry mapping each question ID to its
348
+ answer.
349
+ - `failed_documents`: The documents that have no text to classify or whose request failed, with the
350
+ reason in `meta["classification_error"]`.
351
+ :raises TypeSafeError:
352
+ If a request fails and `raise_on_failure` is `True`.
353
+ """
354
+ await self.warm_up_async()
355
+ assert self._async_client is not None # noqa: S101 # mypy: the client is created by warm_up_async above
356
+
357
+ # Bound concurrency to max_workers, mirroring the ThreadPoolExecutor in the sync `run`
358
+ semaphore = asyncio.Semaphore(self.max_workers)
359
+ tasks = [
360
+ asyncio.create_task(self._classify_async(client=self._async_client, document=document, semaphore=semaphore))
361
+ for document in documents
362
+ ]
363
+ try:
364
+ results = await asyncio.gather(*tasks)
365
+ except Exception:
366
+ # We only expect to get here when `raise_on_failure` is `True`, since `_classify_async` otherwise records a
367
+ # failed request in `failed_documents` instead of raising. Cancel the remaining requests before re-raising.
368
+ for task in tasks:
369
+ task.cancel()
370
+ await asyncio.gather(*tasks, return_exceptions=True)
371
+ raise
372
+ return {
373
+ "documents": [document for document, succeeded in results if succeeded],
374
+ "failed_documents": [document for document, succeeded in results if not succeeded],
375
+ }
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 .text_router import TypeSafeTextRouter
6
+
7
+ __all__ = ["TypeSafeTextRouter"]
@@ -0,0 +1,236 @@
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.utils import Secret
9
+ from typesafe_sdk import AsyncTypeSafeClient, Choice, RetryPolicy, SystemOneResponse, TypeSafeClient
10
+
11
+ _LOW_CONFIDENCE = "low_confidence"
12
+
13
+
14
+ @component
15
+ class TypeSafeTextRouter:
16
+ """
17
+ Routes a text to the connection of the label a TypeSafe System One model picks for it.
18
+
19
+ The model answers a single `choice` question over `labels` and returns calibrated probabilities. The component
20
+ has one output per label. When `min_confidence` is set, it also has a `low_confidence` output that receives the
21
+ text whenever the answer's `confidence` is below the threshold, so uncertain texts can go to a fallback such as
22
+ an LLM or a human. See [confidence-gated routing](https://docs.typesafe.ai/patterns/confidence-routing).
23
+
24
+ The component also works with servers that implement the TypeSafe API, such as [Ollaya](https://ollaya.dev),
25
+ which runs open decision models locally. Set `api_base_url` to the server and `model` to one of its models.
26
+
27
+ ### Usage example
28
+
29
+ ```python
30
+ from haystack_integrations.components.routers.typesafe import TypeSafeTextRouter
31
+
32
+ router = TypeSafeTextRouter(
33
+ labels={
34
+ "billing": "Payments, invoices, refunds and charges",
35
+ "technical": "Bugs, crashes and errors in the product",
36
+ },
37
+ instructions="Which team should handle this support request?",
38
+ min_confidence=0.6,
39
+ )
40
+
41
+ print(router.run(text="I was charged twice for my subscription."))
42
+ # {'billing': 'I was charged twice for my subscription.'}
43
+ ```
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ labels: list[str] | dict[str, str | None],
49
+ *,
50
+ instructions: str = "Which category does this text belong to?",
51
+ model: str = "jev-latest",
52
+ api_key: Secret = Secret.from_env_var("TYPESAFE_API_KEY"),
53
+ api_base_url: str | None = None,
54
+ min_confidence: float | None = None,
55
+ timeout: float | None = None,
56
+ max_retries: int | None = None,
57
+ ) -> None:
58
+ """
59
+ Creates a TypeSafeTextRouter.
60
+
61
+ :param labels:
62
+ The labels to route between, each becoming an output connection. Pass a dict of label to description to
63
+ tell the model what each label means.
64
+ :param instructions:
65
+ The question the model answers by picking one of the labels.
66
+ :param model:
67
+ Name of the System One model to use.
68
+ :param api_key:
69
+ The TypeSafe API key. Servers such as Ollaya accept any non-empty value unless they are configured
70
+ with a key.
71
+ :param api_base_url:
72
+ Base URL of the API. If `None`, the `TYPESAFE_BASE_URL` environment variable is used, or
73
+ `https://api.typesafe.ai` if it is unset.
74
+ :param min_confidence:
75
+ Threshold between 0 and 1 for the answer's `confidence`. Texts below it are sent to the `low_confidence`
76
+ output. If `None`, every text goes to a label output.
77
+ :param timeout:
78
+ Timeout in seconds for each request attempt. If `None`, the SDK default of 10 seconds is used.
79
+ :param max_retries:
80
+ Maximum number of retries after a failed request attempt. If `None`, the SDK default of 2 is used.
81
+ :raises ValueError:
82
+ If `labels` is empty or contains `low_confidence`, or if `min_confidence` is outside 0 to 1.
83
+ """
84
+ if not labels:
85
+ msg = "`labels` must contain at least one label."
86
+ raise ValueError(msg)
87
+ if _LOW_CONFIDENCE in labels:
88
+ msg = f"`{_LOW_CONFIDENCE}` is reserved for the low confidence output and can't be used as a label."
89
+ raise ValueError(msg)
90
+ if min_confidence is not None and not 0 <= min_confidence <= 1:
91
+ msg = f"`min_confidence` must be between 0 and 1, got {min_confidence}."
92
+ raise ValueError(msg)
93
+
94
+ self.labels = labels
95
+ self.instructions = instructions
96
+ self.model = model
97
+ self.api_key = api_key
98
+ self.api_base_url = api_base_url
99
+ self.min_confidence = min_confidence
100
+ self.timeout = timeout
101
+ self.max_retries = max_retries
102
+ self._client: TypeSafeClient | None = None
103
+ self._async_client: AsyncTypeSafeClient | None = None
104
+
105
+ # TypeSafe takes choice criteria as a dict of label to description
106
+ criteria = labels if isinstance(labels, dict) else dict.fromkeys(labels)
107
+ self._question = Choice(instructions=instructions, criteria=criteria)
108
+
109
+ outputs = list(labels)
110
+ if min_confidence is not None:
111
+ outputs.append(_LOW_CONFIDENCE)
112
+ component.set_output_types(self, **dict.fromkeys(outputs, str))
113
+
114
+ def _client_kwargs(self) -> dict[str, Any]:
115
+ # The SDK's retry budget defaults to 30 seconds in total, which would skip retries after a long attempt.
116
+ # `timeout` already bounds each attempt, so the budget is disabled.
117
+ retry_kwargs: dict[str, Any] = {"timeout": None}
118
+ if self.max_retries is not None:
119
+ retry_kwargs["max_retries"] = self.max_retries
120
+ return {
121
+ "api_key": self.api_key.resolve_value(),
122
+ "base_url": self.api_base_url,
123
+ "model": self.model,
124
+ "timeout": self.timeout,
125
+ "retry": RetryPolicy(**retry_kwargs),
126
+ }
127
+
128
+ def warm_up(self) -> None:
129
+ """
130
+ Creates the synchronous TypeSafe client.
131
+ """
132
+ if self._client is None:
133
+ self._client = TypeSafeClient(**self._client_kwargs())
134
+
135
+ async def warm_up_async(self) -> None:
136
+ """
137
+ Creates the asynchronous TypeSafe client.
138
+ """
139
+ if self._async_client is None:
140
+ self._async_client = AsyncTypeSafeClient(**self._client_kwargs())
141
+
142
+ def close(self) -> None:
143
+ """
144
+ Releases the synchronous TypeSafe client.
145
+ """
146
+ if self._client is not None:
147
+ self._client.close()
148
+ self._client = None
149
+
150
+ async def close_async(self) -> None:
151
+ """
152
+ Releases the asynchronous TypeSafe client.
153
+ """
154
+ if self._async_client is not None:
155
+ await self._async_client.aclose()
156
+ self._async_client = None
157
+
158
+ def to_dict(self) -> dict[str, Any]:
159
+ """
160
+ Serializes the component to a dictionary.
161
+
162
+ :returns:
163
+ Dictionary with serialized data.
164
+ """
165
+ return default_to_dict(
166
+ self,
167
+ labels=self.labels,
168
+ instructions=self.instructions,
169
+ model=self.model,
170
+ api_key=self.api_key,
171
+ api_base_url=self.api_base_url,
172
+ min_confidence=self.min_confidence,
173
+ timeout=self.timeout,
174
+ max_retries=self.max_retries,
175
+ )
176
+
177
+ def _route(self, text: str, response: SystemOneResponse) -> dict[str, str]:
178
+ """
179
+ Picks the output for the text from the TypeSafe response.
180
+
181
+ :param text:
182
+ The routed text.
183
+ :param response:
184
+ The TypeSafe response for the text.
185
+ :returns:
186
+ A dictionary mapping `low_confidence` to the text if `min_confidence` is set and the answer's `confidence`
187
+ is below it, otherwise mapping the picked label to the text.
188
+ """
189
+ answer = response.choices["route"]
190
+ if self.min_confidence is not None and answer.confidence < self.min_confidence:
191
+ return {_LOW_CONFIDENCE: text}
192
+ return {answer.choice: text}
193
+
194
+ def run(self, text: str) -> dict[str, str]:
195
+ """
196
+ Routes the text to the output of the label the model picks.
197
+
198
+ :param text:
199
+ The text to route.
200
+ :returns:
201
+ A dictionary with a single key, the picked label or `low_confidence`, mapped to the input text.
202
+ :raises TypeError:
203
+ If `text` is not a string.
204
+ """
205
+ if not isinstance(text, str):
206
+ msg = "TypeSafeTextRouter expects a str as input."
207
+ raise TypeError(msg)
208
+
209
+ self.warm_up()
210
+ assert self._client is not None # noqa: S101 # mypy: the client is created by warm_up above
211
+
212
+ response = self._client.system_one(state=text, questions={"route": self._question})
213
+ return self._route(text=text, response=response)
214
+
215
+ async def run_async(self, text: str) -> dict[str, str]:
216
+ """
217
+ Asynchronously routes the text to the output of the label the model picks.
218
+
219
+ This is the asynchronous version of the `run` method with the same parameters and return values.
220
+
221
+ :param text:
222
+ The text to route.
223
+ :returns:
224
+ A dictionary with a single key, the picked label or `low_confidence`, mapped to the input text.
225
+ :raises TypeError:
226
+ If `text` is not a string.
227
+ """
228
+ if not isinstance(text, str):
229
+ msg = "TypeSafeTextRouter expects a str as input."
230
+ raise TypeError(msg)
231
+
232
+ await self.warm_up_async()
233
+ assert self._async_client is not None # noqa: S101 # mypy: the client is created by warm_up_async above
234
+
235
+ response = await self._async_client.system_one(state=text, questions={"route": self._question})
236
+ return self._route(text=text, response=response)
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.5
2
+ Name: typesafe-haystack
3
+ Version: 0.1.0
4
+ Summary: Haystack integration for TypeSafe System One decision models
5
+ Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/typesafe#readme
6
+ Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
7
+ Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/typesafe
8
+ Author-email: deepset GmbH <info@deepset.ai>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE.txt
11
+ Keywords: Haystack,Jev,Ollaya,TypeSafe,classification,decision model,routing
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Programming Language :: Python :: Implementation :: CPython
21
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: haystack-ai>=3.0.0
24
+ Requires-Dist: typesafe-sdk>=0.7.1
25
+ Description-Content-Type: text/markdown
26
+
27
+ # typesafe-haystack
28
+
29
+ [![PyPI - Version](https://img.shields.io/pypi/v/typesafe-haystack.svg)](https://pypi.org/project/typesafe-haystack)
30
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/typesafe-haystack.svg)](https://pypi.org/project/typesafe-haystack)
31
+
32
+ - [Integration page](https://haystack.deepset.ai/integrations/typesafe)
33
+ - [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/typesafe/CHANGELOG.md)
34
+
35
+ ---
36
+
37
+ ## Contributing
38
+
39
+ Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
40
+
41
+ ### Integration tests
42
+
43
+ Integration tests run against a local [Ollaya](https://ollaya.dev) server, which serves open decision models through the TypeSafe API:
44
+
45
+ ```bash
46
+ docker run -d --name ollaya -p 11435:11435 -v ollaya:/home/ollaya/.ollaya ghcr.io/ollaya-dev/ollaya
47
+ docker exec ollaya ollaya pull laya:en
48
+ TYPESAFE_BASE_URL=http://localhost:11435 TYPESAFE_API_KEY=local hatch run test:integration
49
+ ```
@@ -0,0 +1,10 @@
1
+ haystack_integrations/components/classifiers/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ haystack_integrations/components/classifiers/typesafe/__init__.py,sha256=dyEiH_rwcBcFnOdLYeSW6BFEPrJ0XAB7jP-reCRIUvs,213
3
+ haystack_integrations/components/classifiers/typesafe/document_classifier.py,sha256=dg_IOSnKTfjEltu3kcD7ftGKiYcHYWwzo1cC-W_XTHY,17177
4
+ haystack_integrations/components/routers/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ haystack_integrations/components/routers/typesafe/__init__.py,sha256=KslDcbP8MhhhA_Q498zb8zQiZ3augD128AVm3Y34G9U,189
6
+ haystack_integrations/components/routers/typesafe/text_router.py,sha256=dle4cCIwI2iFWuCoidgqZEbrX6GY5YPJ5Ln-OpuGkcc,9450
7
+ typesafe_haystack-0.1.0.dist-info/METADATA,sha256=D61mFWclxldAOkB7loQcKsTuLFB4uDHwwb1V1AH2zFA,2326
8
+ typesafe_haystack-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
9
+ typesafe_haystack-0.1.0.dist-info/licenses/LICENSE.txt,sha256=OrAtTu4aPmrTjKDSTzkSPgo_ji6NOMWO2N9JOTFyAzM,11350
10
+ typesafe_haystack-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023-present deepset GmbH
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.