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,536 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import asyncio
6
+ from dataclasses import replace
7
+ from typing import Any
8
+
9
+ from haystack import component, default_to_dict
10
+ from haystack.components.generators.chat import OpenAIChatGenerator
11
+ from haystack.components.generators.chat.openai import (
12
+ _check_finish_reason,
13
+ _convert_chat_completion_chunk_to_streaming_chunk,
14
+ _convert_chat_completion_to_chat_message,
15
+ )
16
+ from haystack.components.generators.utils import _convert_streaming_chunks_to_chat_message, _normalize_messages
17
+ from haystack.dataclasses import (
18
+ ChatMessage,
19
+ ChatRole,
20
+ ComponentInfo,
21
+ ReasoningContent,
22
+ StreamingCallbackT,
23
+ StreamingChunk,
24
+ SyncStreamingCallbackT,
25
+ select_streaming_callback,
26
+ )
27
+ from haystack.dataclasses.streaming_chunk import _invoke_streaming_callback
28
+ from haystack.tools import ToolsType, serialize_tools_or_toolset
29
+ from haystack.utils import serialize_callable
30
+ from haystack.utils.auth import Secret
31
+ from openai import AsyncStream, Stream
32
+ from openai.lib._pydantic import to_strict_json_schema
33
+ from openai.types.chat import ChatCompletion, ChatCompletionChunk, ParsedChatCompletion
34
+ from openai.types.chat.chat_completion import Choice
35
+ from pydantic import BaseModel
36
+
37
+ from haystack_integrations.common.otari.utils import _warn_if_eu_key_on_default_url
38
+
39
+
40
+ def _reasoning_content(message_or_delta: Any) -> ReasoningContent | None:
41
+ """
42
+ Read the reasoning that Otari adds to a response message or a streamed delta.
43
+
44
+ Otari sends the reasoning as `reasoning`, a plain string, and provider data that has to be sent back on the next
45
+ request, such as Anthropic's thinking signature, as `extra_content`.
46
+ """
47
+ reasoning = getattr(message_or_delta, "reasoning", None)
48
+ if isinstance(reasoning, dict):
49
+ reasoning = reasoning.get("content")
50
+ reasoning_text = reasoning if isinstance(reasoning, str) else ""
51
+ extra_content = getattr(message_or_delta, "extra_content", None)
52
+ if not isinstance(extra_content, dict):
53
+ extra_content = {}
54
+ if not reasoning_text and not extra_content:
55
+ return None
56
+ return ReasoningContent(
57
+ reasoning_text=reasoning_text, extra={"extra_content": extra_content} if extra_content else {}
58
+ )
59
+
60
+
61
+ def _merge_extra_content(total: dict[str, Any], extra_content: dict[str, Any]) -> None:
62
+ """Merge the `extra_content` of one streamed delta into the total, per provider namespace."""
63
+ for namespace, values in extra_content.items():
64
+ if isinstance(values, dict) and isinstance(total.get(namespace), dict):
65
+ total[namespace] = {**total[namespace], **values}
66
+ else:
67
+ total[namespace] = values
68
+
69
+
70
+ @component
71
+ class OtariChatGenerator(OpenAIChatGenerator):
72
+ """
73
+ Completes chats using models served through an [Otari](https://github.com/mozilla-ai/otari) gateway.
74
+
75
+ Otari is an OpenAI-compatible LLM gateway that routes requests to many providers and applies API keys, budgets,
76
+ and usage tracking. By default, this component calls the otari.ai gateway. For an account in otari.ai's EU
77
+ region, whose API keys start with `otk_v1_eu_`, set `api_base_url` to `"https://eu.api.otari.ai/api/v1"`.
78
+ To call a gateway you run yourself, set `api_base_url`, for example to `"http://localhost:8000/api/v1"`.
79
+
80
+ Name models with a selector the gateway accepts, such as `provider:model` (`"openai:gpt-5-mini"`,
81
+ `"anthropic:claude-sonnet-4-6"`), a model alias, or a routing policy name. For details, see the
82
+ [Otari model docs](https://github.com/mozilla-ai/otari/blob/main/docs/models.md).
83
+
84
+ You can pass any parameter of the Otari chat completions endpoint through `generation_kwargs`, at initialization
85
+ or in the `run` method. Request headers, such as Otari's `Idempotency-Key`, go into
86
+ `generation_kwargs["extra_headers"]`.
87
+
88
+ When the gateway prices a request, `meta["usage"]` of the reply contains its cost in US dollars as `cost_usd`,
89
+ and `pricing_source`. When streaming, pass `generation_kwargs={"stream_options": {"include_usage": True}}` to
90
+ receive usage.
91
+
92
+ When the model reasons, for example with `generation_kwargs={"reasoning_effort": "low"}`, the reasoning is in the
93
+ `reasoning` of the reply and, when streaming, of the streamed chunks. If the gateway adds provider data that the
94
+ next request needs, such as Anthropic's thinking signature, the component sends the reasoning back with the reply
95
+ in later requests. Anthropic models need this to keep reasoning across tool calls.
96
+
97
+ ### Usage example
98
+
99
+ ```python
100
+ from haystack.dataclasses import ChatMessage
101
+ from haystack_integrations.components.generators.otari import OtariChatGenerator
102
+
103
+ # Reads the API key from the OTARI_API_KEY environment variable
104
+ generator = OtariChatGenerator()
105
+ response = generator.run([ChatMessage.from_user("What's Natural Language Processing? Be brief.")])
106
+ print(response["replies"][0].text)
107
+ # >> Natural Language Processing (NLP) is a field of artificial intelligence that enables computers to ...
108
+ print(response["replies"][0].meta["usage"]["cost_usd"])
109
+ # >> 0.000279
110
+ ```
111
+ """
112
+
113
+ def __init__(
114
+ self,
115
+ *,
116
+ api_key: Secret = Secret.from_env_var("OTARI_API_KEY"),
117
+ model: str = "openai:gpt-5-mini",
118
+ streaming_callback: StreamingCallbackT | None = None,
119
+ api_base_url: str = "https://api.otari.ai/api/v1",
120
+ generation_kwargs: dict[str, Any] | None = None,
121
+ tools: ToolsType | None = None,
122
+ tools_strict: bool = False,
123
+ timeout: float | None = None,
124
+ max_retries: int | None = None,
125
+ http_client_kwargs: dict[str, Any] | None = None,
126
+ ) -> None:
127
+ """
128
+ Creates an instance of OtariChatGenerator.
129
+
130
+ :param api_key:
131
+ The Otari API key: a key issued by your gateway, or an otari.ai API key.
132
+ Defaults to the `OTARI_API_KEY` environment variable.
133
+ :param model:
134
+ The model selector, for example `"openai:gpt-5-mini"`. The gateway must have the provider configured.
135
+ :param streaming_callback:
136
+ A callback function that is called when a new token is received from the stream.
137
+ The callback function accepts StreamingChunk as an argument.
138
+ :param api_base_url:
139
+ The OpenAI-compatible API root of the Otari gateway, including the `/api/v1` path.
140
+ Defaults to the otari.ai gateway. For an account in otari.ai's EU region, use
141
+ `"https://eu.api.otari.ai/api/v1"`.
142
+ :param generation_kwargs:
143
+ Other parameters to use for the model. These parameters are sent directly to the Otari endpoint.
144
+ Some of the supported parameters:
145
+ - `max_tokens`: The maximum number of tokens the output text can have.
146
+ - `temperature`: What sampling temperature to use. Higher values mean the model will take more risks.
147
+ Try 0.9 for more creative applications and 0 (argmax sampling) for ones with a well-defined answer.
148
+ - `top_p`: An alternative to sampling with temperature, called nucleus sampling, where the model
149
+ considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens
150
+ comprising the top 10% probability mass are considered.
151
+ - `stream_options`: Pass `{"include_usage": True}` to receive usage, including cost, when streaming.
152
+ - `extra_headers`: Headers to send with the request, for example Otari's `Idempotency-Key`.
153
+ - `response_format`: A JSON schema or a Pydantic model that enforces the structure of the model's response.
154
+ If provided, the output will always be validated against this
155
+ format (unless the model returns a tool call).
156
+ For details, see the [OpenAI Structured Outputs documentation](https://platform.openai.com/docs/guides/structured-outputs).
157
+ Notes:
158
+ - For structured outputs with streaming,
159
+ the `response_format` must be a JSON schema and not a Pydantic model.
160
+ :param tools:
161
+ A list of Tool and/or Toolset objects, or a single Toolset for which the model can prepare calls.
162
+ Each tool should have a unique name.
163
+ :param tools_strict:
164
+ Whether to enable strict schema adherence for tool calls. If set to `True`, the model will follow exactly
165
+ the schema provided in the `parameters` field of the tool definition, but this may increase latency.
166
+ :param timeout:
167
+ The timeout for the Otari API call.
168
+ :param max_retries:
169
+ Maximum number of retries to contact Otari after an internal error.
170
+ If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable, or set to 5.
171
+ :param http_client_kwargs:
172
+ A dictionary of keyword arguments to configure a custom `httpx.Client`or `httpx.AsyncClient`.
173
+ For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client).
174
+ """
175
+ # the @component decorator recreates the class, so the zero-argument form of super() cannot be used
176
+ super(OtariChatGenerator, self).__init__( # noqa: UP008
177
+ api_key=api_key,
178
+ model=model,
179
+ streaming_callback=streaming_callback,
180
+ api_base_url=api_base_url,
181
+ generation_kwargs=generation_kwargs,
182
+ tools=tools,
183
+ tools_strict=tools_strict,
184
+ timeout=timeout,
185
+ max_retries=max_retries,
186
+ http_client_kwargs=http_client_kwargs,
187
+ )
188
+
189
+ def warm_up(self) -> None:
190
+ """
191
+ Warm up the tools and initialize the synchronous OpenAI client.
192
+
193
+ Logs a warning if the API key belongs to otari.ai's EU region but `api_base_url` is left at its default.
194
+ """
195
+ creates_client = self.client is None
196
+ super(OtariChatGenerator, self).warm_up() # noqa: UP008
197
+ if creates_client:
198
+ _warn_if_eu_key_on_default_url(self.api_key, self.api_base_url)
199
+
200
+ async def warm_up_async(self) -> None:
201
+ """
202
+ Warm up the tools and initialize the asynchronous OpenAI client.
203
+
204
+ Logs a warning if the API key belongs to otari.ai's EU region but `api_base_url` is left at its default.
205
+ """
206
+ creates_client = self.async_client is None
207
+ await super(OtariChatGenerator, self).warm_up_async() # noqa: UP008
208
+ if creates_client:
209
+ _warn_if_eu_key_on_default_url(self.api_key, self.api_base_url)
210
+
211
+ def to_dict(self) -> dict[str, Any]:
212
+ """
213
+ Serialize this component to a dictionary.
214
+
215
+ :returns:
216
+ The serialized component as a dictionary.
217
+ """
218
+ callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None
219
+ generation_kwargs = self.generation_kwargs.copy()
220
+ response_format = generation_kwargs.get("response_format")
221
+ # If the response format is a Pydantic model, it's converted to openai's json schema format
222
+ # If it's already a json schema, it's left as is
223
+ if response_format and isinstance(response_format, type) and issubclass(response_format, BaseModel):
224
+ json_schema = {
225
+ "type": "json_schema",
226
+ "json_schema": {
227
+ "name": response_format.__name__,
228
+ "strict": True,
229
+ "schema": to_strict_json_schema(response_format),
230
+ },
231
+ }
232
+
233
+ generation_kwargs["response_format"] = json_schema
234
+
235
+ # if we didn't implement the to_dict method here then the to_dict method of the superclass would be used
236
+ # which would serialize some fields that we don't want to serialize (e.g. the ones we don't have in
237
+ # the __init__)
238
+ # it would be hard to maintain the compatibility as superclass changes
239
+ return default_to_dict(
240
+ self,
241
+ model=self.model,
242
+ streaming_callback=callback_name,
243
+ api_base_url=self.api_base_url,
244
+ generation_kwargs=generation_kwargs,
245
+ api_key=self.api_key.to_dict(),
246
+ tools=serialize_tools_or_toolset(self.tools),
247
+ tools_strict=self.tools_strict,
248
+ timeout=self.timeout,
249
+ max_retries=self.max_retries,
250
+ http_client_kwargs=self.http_client_kwargs,
251
+ )
252
+
253
+ def _convert_chat_completion_to_chat_message(
254
+ self, completion: ChatCompletion | ParsedChatCompletion, choice: Choice
255
+ ) -> ChatMessage:
256
+ """Convert a choice of a chat completion into a ChatMessage, including Otari's reasoning."""
257
+ message = _convert_chat_completion_to_chat_message(completion=completion, choice=choice)
258
+ reasoning = _reasoning_content(choice.message)
259
+ if reasoning is None:
260
+ return message
261
+ return ChatMessage.from_assistant(
262
+ text=message.text, meta=message.meta, name=message.name, tool_calls=message.tool_calls, reasoning=reasoning
263
+ )
264
+
265
+ def _convert_chat_completion_chunk_to_streaming_chunk(
266
+ self,
267
+ chunk: ChatCompletionChunk,
268
+ previous_chunks: list[StreamingChunk],
269
+ component_info: ComponentInfo | None = None,
270
+ ) -> StreamingChunk:
271
+ """Convert a streamed chunk into a StreamingChunk, including Otari's reasoning."""
272
+ streaming_chunk = _convert_chat_completion_chunk_to_streaming_chunk(
273
+ chunk=chunk, previous_chunks=previous_chunks, component_info=component_info
274
+ )
275
+ reasoning = _reasoning_content(chunk.choices[0].delta) if chunk.choices else None
276
+ # a StreamingChunk holds one kind of content, and Otari streams reasoning and text in separate deltas
277
+ if reasoning is not None and not streaming_chunk.content and not streaming_chunk.tool_calls:
278
+ # print_streaming_chunk prints its reasoning header on the first reasoning chunk
279
+ start = not any(previous.reasoning for previous in previous_chunks)
280
+ return replace(streaming_chunk, reasoning=reasoning, index=0, start=start)
281
+ if streaming_chunk.content and any(previous.reasoning for previous in previous_chunks):
282
+ # after reasoning, the parent no longer marks the first text chunk as the start of the text
283
+ return replace(streaming_chunk, start=not any(previous.content for previous in previous_chunks))
284
+ return streaming_chunk
285
+
286
+ def _convert_streaming_chunks_to_chat_message(self, chunks: list[StreamingChunk]) -> ChatMessage:
287
+ """Combine streamed chunks into a ChatMessage, keeping the `extra_content` that goes with the reasoning."""
288
+ message = _convert_streaming_chunks_to_chat_message(chunks=chunks)
289
+ extra_content: dict[str, Any] = {}
290
+ for chunk in chunks:
291
+ if chunk.reasoning and (chunk_extra_content := chunk.reasoning.extra.get("extra_content")):
292
+ _merge_extra_content(extra_content, chunk_extra_content)
293
+ if not extra_content:
294
+ return message
295
+ reasoning = ReasoningContent(
296
+ reasoning_text=message.reasoning.reasoning_text if message.reasoning else "",
297
+ extra={"extra_content": extra_content},
298
+ )
299
+ return ChatMessage.from_assistant(
300
+ text=message.text, meta=message.meta, name=message.name, tool_calls=message.tool_calls, reasoning=reasoning
301
+ )
302
+
303
+ def _convert_message_to_api_format(self, message: ChatMessage) -> dict[str, Any]:
304
+ """Convert a ChatMessage into the request format, including an assistant reply's reasoning to replay."""
305
+ formatted = message.to_openai_dict_format()
306
+ reasoning = message.reasoning
307
+ # Only reasoning that comes with provider data to replay, such as Anthropic's thinking signature, goes back.
308
+ # Some providers reject reasoning in a request: Cohere answers it with a 400.
309
+ if reasoning is not None and message.is_from(ChatRole.ASSISTANT):
310
+ if extra_content := reasoning.extra.get("extra_content"):
311
+ formatted["reasoning"] = reasoning.reasoning_text
312
+ formatted["extra_content"] = extra_content
313
+ return formatted
314
+
315
+ # Bridge for haystack-ai < 3.5, whose OpenAIChatGenerator doesn't call the four conversion methods above.
316
+ # The methods below are copied from OpenAIChatGenerator on Haystack main, except that _prepare_api_call reformats
317
+ # the messages. Remove them once the minimum haystack-ai version is 3.5.
318
+
319
+ def _prepare_api_call(
320
+ self,
321
+ *,
322
+ messages: list[ChatMessage],
323
+ streaming_callback: StreamingCallbackT | None = None,
324
+ generation_kwargs: dict[str, Any] | None = None,
325
+ tools: ToolsType | None = None,
326
+ tools_strict: bool | None = None,
327
+ ) -> dict[str, Any]:
328
+ api_args = super(OtariChatGenerator, self)._prepare_api_call( # noqa: UP008
329
+ messages=messages,
330
+ streaming_callback=streaming_callback,
331
+ generation_kwargs=generation_kwargs,
332
+ tools=tools,
333
+ tools_strict=tools_strict,
334
+ )
335
+ api_args["messages"] = [self._convert_message_to_api_format(message) for message in messages]
336
+ return api_args
337
+
338
+ @component.output_types(replies=list[ChatMessage])
339
+ def run(
340
+ self,
341
+ messages: list[ChatMessage] | str,
342
+ streaming_callback: StreamingCallbackT | None = None,
343
+ generation_kwargs: dict[str, Any] | None = None,
344
+ *,
345
+ tools: ToolsType | None = None,
346
+ tools_strict: bool | None = None,
347
+ ) -> dict[str, list[ChatMessage]]:
348
+ """
349
+ Invokes chat completion based on the provided messages and generation parameters.
350
+
351
+ :param messages:
352
+ A list of ChatMessage instances representing the input messages. If a string is provided, it is converted
353
+ to a list containing a ChatMessage with user role.
354
+ :param streaming_callback:
355
+ A callback function that is called when a new token is received from the stream.
356
+ :param generation_kwargs:
357
+ Additional keyword arguments for text generation. These are merged per key with the
358
+ `generation_kwargs` passed at initialization: keys provided here take precedence, keys set
359
+ only at initialization are kept.
360
+ :param tools:
361
+ A list of Tool and/or Toolset objects, or a single Toolset for which the model can prepare calls.
362
+ If set, it will override the `tools` parameter provided during initialization.
363
+ :param tools_strict:
364
+ Whether to enable strict schema adherence for tool calls. If set to `True`, the model will follow exactly
365
+ the schema provided in the `parameters` field of the tool definition, but this may increase latency.
366
+ If set, it will override the `tools_strict` parameter set during component initialization.
367
+
368
+ :returns:
369
+ A dictionary with the following key:
370
+ - `replies`: A list containing the generated responses as ChatMessage instances, including the
371
+ model's reasoning when it returns any.
372
+ """
373
+ self.warm_up()
374
+
375
+ messages = _normalize_messages(messages)
376
+
377
+ if len(messages) == 0:
378
+ return {"replies": []}
379
+
380
+ streaming_callback = select_streaming_callback(
381
+ init_callback=self.streaming_callback, runtime_callback=streaming_callback, requires_async=False
382
+ )
383
+ chat_completion: Stream[ChatCompletionChunk] | ChatCompletion | ParsedChatCompletion
384
+
385
+ api_args = self._prepare_api_call(
386
+ messages=messages,
387
+ streaming_callback=streaming_callback,
388
+ generation_kwargs=generation_kwargs,
389
+ tools=tools,
390
+ tools_strict=tools_strict,
391
+ )
392
+ openai_endpoint = api_args.pop("openai_endpoint")
393
+ assert self.client is not None # noqa: S101 # mypy: client is built by warm_up above
394
+ openai_endpoint_method = getattr(self.client.chat.completions, openai_endpoint)
395
+ chat_completion = openai_endpoint_method(**api_args)
396
+
397
+ if streaming_callback is not None:
398
+ completions = self._handle_stream_response(
399
+ # we cannot check isinstance(chat_completion, Stream) because some observability tools wrap Stream
400
+ # and return a different type. See https://github.com/deepset-ai/haystack/issues/9014.
401
+ chat_completion, # type: ignore[arg-type]
402
+ streaming_callback,
403
+ )
404
+
405
+ else:
406
+ assert isinstance(chat_completion, ChatCompletion), "Unexpected response type for non-streaming request." # noqa: S101
407
+ completions = [
408
+ self._convert_chat_completion_to_chat_message(completion=chat_completion, choice=choice)
409
+ for choice in chat_completion.choices
410
+ ]
411
+
412
+ # before returning, do post-processing of the completions
413
+ for message in completions:
414
+ _check_finish_reason(message.meta)
415
+
416
+ return {"replies": completions}
417
+
418
+ @component.output_types(replies=list[ChatMessage])
419
+ async def run_async(
420
+ self,
421
+ messages: list[ChatMessage] | str,
422
+ streaming_callback: StreamingCallbackT | None = None,
423
+ generation_kwargs: dict[str, Any] | None = None,
424
+ *,
425
+ tools: ToolsType | None = None,
426
+ tools_strict: bool | None = None,
427
+ ) -> dict[str, list[ChatMessage]]:
428
+ """
429
+ Asynchronously invokes chat completion based on the provided messages and generation parameters.
430
+
431
+ This is the asynchronous version of the `run` method. It has the same parameters and return values
432
+ but can be used with `await` in async code.
433
+
434
+ :param messages:
435
+ A list of ChatMessage instances representing the input messages. If a string is provided, it is converted
436
+ to a list containing a ChatMessage with user role.
437
+ :param streaming_callback:
438
+ A callback function that is called when a new token is received from the stream. Async callbacks are
439
+ preferred; a sync callback is accepted but will run synchronously on the event loop and may block it.
440
+ :param generation_kwargs:
441
+ Additional keyword arguments for text generation. These are merged per key with the
442
+ `generation_kwargs` passed at initialization: keys provided here take precedence, keys set
443
+ only at initialization are kept.
444
+ :param tools: A list of Tool and/or Toolset objects, or a single Toolset for which the model can prepare calls.
445
+ If set, it will override the `tools` parameter provided during initialization.
446
+ :param tools_strict:
447
+ Whether to enable strict schema adherence for tool calls. If set to `True`, the model will follow exactly
448
+ the schema provided in the `parameters` field of the tool definition, but this may increase latency.
449
+ If set, it will override the `tools_strict` parameter set during component initialization.
450
+
451
+ :returns:
452
+ A dictionary with the following key:
453
+ - `replies`: A list containing the generated responses as ChatMessage instances, including the
454
+ model's reasoning when it returns any.
455
+ """
456
+ await self.warm_up_async()
457
+
458
+ messages = _normalize_messages(messages)
459
+
460
+ # validate and select the streaming callback
461
+ streaming_callback = select_streaming_callback(
462
+ init_callback=self.streaming_callback, runtime_callback=streaming_callback, requires_async=True
463
+ )
464
+ chat_completion: AsyncStream[ChatCompletionChunk] | ChatCompletion | ParsedChatCompletion
465
+
466
+ if len(messages) == 0:
467
+ return {"replies": []}
468
+
469
+ api_args = self._prepare_api_call(
470
+ messages=messages,
471
+ streaming_callback=streaming_callback,
472
+ generation_kwargs=generation_kwargs,
473
+ tools=tools,
474
+ tools_strict=tools_strict,
475
+ )
476
+
477
+ openai_endpoint = api_args.pop("openai_endpoint")
478
+ assert self.async_client is not None # noqa: S101 # mypy: async_client is built by warm_up_async above
479
+ openai_endpoint_method = getattr(self.async_client.chat.completions, openai_endpoint)
480
+ chat_completion = await openai_endpoint_method(**api_args)
481
+
482
+ if streaming_callback is not None:
483
+ completions = await self._handle_async_stream_response(
484
+ # we cannot check isinstance(chat_completion, AsyncStream) because some observability tools wrap
485
+ # AsyncStream and return a different type. See https://github.com/deepset-ai/haystack/issues/9014.
486
+ chat_completion, # type: ignore[arg-type]
487
+ streaming_callback,
488
+ )
489
+
490
+ else:
491
+ assert isinstance(chat_completion, ChatCompletion), "Unexpected response type for non-streaming request." # noqa: S101
492
+ completions = [
493
+ self._convert_chat_completion_to_chat_message(completion=chat_completion, choice=choice)
494
+ for choice in chat_completion.choices
495
+ ]
496
+
497
+ # before returning, do post-processing of the completions
498
+ for message in completions:
499
+ _check_finish_reason(message.meta)
500
+
501
+ return {"replies": completions}
502
+
503
+ def _handle_stream_response(self, chat_completion: Stream, callback: SyncStreamingCallbackT) -> list[ChatMessage]:
504
+ component_info = ComponentInfo.from_component(self)
505
+ chunks: list[StreamingChunk] = []
506
+ for chunk in chat_completion:
507
+ assert len(chunk.choices) <= 1, "Streaming responses should have at most one choice." # noqa: S101
508
+ chunk_delta = self._convert_chat_completion_chunk_to_streaming_chunk(
509
+ chunk=chunk, previous_chunks=chunks, component_info=component_info
510
+ )
511
+ chunks.append(chunk_delta)
512
+ callback(chunk_delta)
513
+ return [self._convert_streaming_chunks_to_chat_message(chunks=chunks)]
514
+
515
+ async def _handle_async_stream_response(
516
+ self, chat_completion: AsyncStream, callback: StreamingCallbackT
517
+ ) -> list[ChatMessage]:
518
+ component_info = ComponentInfo.from_component(self)
519
+ chunks: list[StreamingChunk] = []
520
+ try:
521
+ async for chunk in chat_completion:
522
+ assert len(chunk.choices) <= 1, "Streaming responses should have at most one choice." # noqa: S101
523
+ chunk_delta = self._convert_chat_completion_chunk_to_streaming_chunk(
524
+ chunk=chunk, previous_chunks=chunks, component_info=component_info
525
+ )
526
+ chunks.append(chunk_delta)
527
+ await _invoke_streaming_callback(callback, chunk_delta)
528
+
529
+ except asyncio.CancelledError:
530
+ await asyncio.shield(chat_completion.close())
531
+ # close the stream when task is cancelled
532
+ # asyncio.shield ensures the close operation completes
533
+ # https://docs.python.org/3/library/asyncio-task.html#shielding-from-cancellation
534
+ raise # Re-raise to propagate cancellation
535
+
536
+ return [self._convert_streaming_chunks_to_chat_message(chunks=chunks)]
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 .ranker import OtariRanker
6
+
7
+ __all__ = ["OtariRanker"]