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

deepset-ai / haystack / 14794014302

02 May 2025 11:06AM UTC coverage: 90.448% (-0.07%) from 90.513%
14794014302

Pull #9290

github

web-flow
Merge de5d77f03 into e3f9da13d
Pull Request #9290: feat: enable streaming ToolCall/Result from Agent

10899 of 12050 relevant lines covered (90.45%)

0.9 hits per line

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

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

5
import json
1✔
6
import os
1✔
7
from datetime import datetime
1✔
8
from typing import Any, Dict, List, Optional, Union
1✔
9

10
from openai import AsyncOpenAI, AsyncStream, OpenAI, Stream
1✔
11
from openai.types.chat import ChatCompletion, ChatCompletionChunk, ChatCompletionMessage
1✔
12
from openai.types.chat.chat_completion import Choice
1✔
13
from openai.types.chat.chat_completion_chunk import Choice as ChunkChoice
1✔
14

15
from haystack import component, default_from_dict, default_to_dict, logging
1✔
16
from haystack.dataclasses import (
1✔
17
    AsyncStreamingCallbackT,
18
    ChatMessage,
19
    StreamingCallbackT,
20
    StreamingChunk,
21
    SyncStreamingCallbackT,
22
    ToolCall,
23
    select_streaming_callback,
24
)
25
from haystack.tools import (
1✔
26
    Tool,
27
    Toolset,
28
    _check_duplicate_tool_names,
29
    deserialize_tools_or_toolset_inplace,
30
    serialize_tools_or_toolset,
31
)
32
from haystack.utils import Secret, deserialize_callable, deserialize_secrets_inplace, serialize_callable
1✔
33
from haystack.utils.http_client import init_http_client
1✔
34

35
logger = logging.getLogger(__name__)
1✔
36

37

38
@component
1✔
39
class OpenAIChatGenerator:
1✔
40
    """
41
    Completes chats using OpenAI's large language models (LLMs).
42

43
    It works with the gpt-4 and o-series models and supports streaming responses
44
    from OpenAI API. It uses [ChatMessage](https://docs.haystack.deepset.ai/docs/chatmessage)
45
    format in input and output.
46

47
    You can customize how the text is generated by passing parameters to the
48
    OpenAI API. Use the `**generation_kwargs` argument when you initialize
49
    the component or when you run it. Any parameter that works with
50
    `openai.ChatCompletion.create` will work here too.
51

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

55
    ### Usage example
56

57
    ```python
58
    from haystack.components.generators.chat import OpenAIChatGenerator
59
    from haystack.dataclasses import ChatMessage
60

61
    messages = [ChatMessage.from_user("What's Natural Language Processing?")]
62

63
    client = OpenAIChatGenerator()
64
    response = client.run(messages)
65
    print(response)
66
    ```
67
    Output:
68
    ```
69
    {'replies':
70
        [ChatMessage(content='Natural Language Processing (NLP) is a branch of artificial intelligence
71
            that focuses on enabling computers to understand, interpret, and generate human language in
72
            a way that is meaningful and useful.',
73
         role=<ChatRole.ASSISTANT: 'assistant'>, name=None,
74
         meta={'model': 'gpt-4o-mini', 'index': 0, 'finish_reason': 'stop',
75
         'usage': {'prompt_tokens': 15, 'completion_tokens': 36, 'total_tokens': 51}})
76
        ]
77
    }
78
    ```
79
    """
80

81
    def __init__(  # pylint: disable=too-many-positional-arguments
1✔
82
        self,
83
        api_key: Secret = Secret.from_env_var("OPENAI_API_KEY"),
84
        model: str = "gpt-4o-mini",
85
        streaming_callback: Optional[StreamingCallbackT] = None,
86
        api_base_url: Optional[str] = None,
87
        organization: Optional[str] = None,
88
        generation_kwargs: Optional[Dict[str, Any]] = None,
89
        timeout: Optional[float] = None,
90
        max_retries: Optional[int] = None,
91
        tools: Optional[Union[List[Tool], Toolset]] = None,
92
        tools_strict: bool = False,
93
        http_client_kwargs: Optional[Dict[str, Any]] = None,
94
    ):
95
        """
96
        Creates an instance of OpenAIChatGenerator. Unless specified otherwise in `model`, uses OpenAI's gpt-4o-mini
97

98
        Before initializing the component, you can set the 'OPENAI_TIMEOUT' and 'OPENAI_MAX_RETRIES'
99
        environment variables to override the `timeout` and `max_retries` parameters respectively
100
        in the OpenAI client.
101

102
        :param api_key: The OpenAI API key.
103
            You can set it with an environment variable `OPENAI_API_KEY`, or pass with this parameter
104
            during initialization.
105
        :param model: The name of the model to use.
106
        :param streaming_callback: A callback function that is called when a new token is received from the stream.
107
            The callback function accepts [StreamingChunk](https://docs.haystack.deepset.ai/docs/data-classes#streamingchunk)
108
            as an argument.
109
        :param api_base_url: An optional base URL.
110
        :param organization: Your organization ID, defaults to `None`. See
111
        [production best practices](https://platform.openai.com/docs/guides/production-best-practices/setting-up-your-organization).
112
        :param generation_kwargs: Other parameters to use for the model. These parameters are sent directly to
113
            the OpenAI endpoint. See OpenAI [documentation](https://platform.openai.com/docs/api-reference/chat) for
114
            more details.
115
            Some of the supported parameters:
116
            - `max_tokens`: The maximum number of tokens the output text can have.
117
            - `temperature`: What sampling temperature to use. Higher values mean the model will take more risks.
118
                Try 0.9 for more creative applications and 0 (argmax sampling) for ones with a well-defined answer.
119
            - `top_p`: An alternative to sampling with temperature, called nucleus sampling, where the model
120
                considers the results of the tokens with top_p probability mass. For example, 0.1 means only the tokens
121
                comprising the top 10% probability mass are considered.
122
            - `n`: How many completions to generate for each prompt. For example, if the LLM gets 3 prompts and n is 2,
123
                it will generate two completions for each of the three prompts, ending up with 6 completions in total.
124
            - `stop`: One or more sequences after which the LLM should stop generating tokens.
125
            - `presence_penalty`: What penalty to apply if a token is already present at all. Bigger values mean
126
                the model will be less likely to repeat the same token in the text.
127
            - `frequency_penalty`: What penalty to apply if a token has already been generated in the text.
128
                Bigger values mean the model will be less likely to repeat the same token in the text.
129
            - `logit_bias`: Add a logit bias to specific tokens. The keys of the dictionary are tokens, and the
130
                values are the bias to add to that token.
131
        :param timeout:
132
            Timeout for OpenAI client calls. If not set, it defaults to either the
133
            `OPENAI_TIMEOUT` environment variable, or 30 seconds.
134
        :param max_retries:
135
            Maximum number of retries to contact OpenAI after an internal error.
136
            If not set, it defaults to either the `OPENAI_MAX_RETRIES` environment variable, or set to 5.
137
        :param tools:
138
            A list of tools or a Toolset for which the model can prepare calls. This parameter can accept either a
139
            list of `Tool` objects or a `Toolset` instance.
140
        :param tools_strict:
141
            Whether to enable strict schema adherence for tool calls. If set to `True`, the model will follow exactly
142
            the schema provided in the `parameters` field of the tool definition, but this may increase latency.
143
        :param http_client_kwargs:
144
            A dictionary of keyword arguments to configure a custom `httpx.Client`or `httpx.AsyncClient`.
145
            For more information, see the [HTTPX documentation](https://www.python-httpx.org/api/#client).
146
        """
147
        self.api_key = api_key
1✔
148
        self.model = model
1✔
149
        self.generation_kwargs = generation_kwargs or {}
1✔
150
        self.streaming_callback = streaming_callback
1✔
151
        self.api_base_url = api_base_url
1✔
152
        self.organization = organization
1✔
153
        self.timeout = timeout
1✔
154
        self.max_retries = max_retries
1✔
155
        self.tools = tools  # Store tools as-is, whether it's a list or a Toolset
1✔
156
        self.tools_strict = tools_strict
1✔
157
        self.http_client_kwargs = http_client_kwargs
1✔
158
        # Check for duplicate tool names
159
        _check_duplicate_tool_names(list(self.tools or []))
1✔
160

161
        if timeout is None:
1✔
162
            timeout = float(os.environ.get("OPENAI_TIMEOUT", "30.0"))
1✔
163
        if max_retries is None:
1✔
164
            max_retries = int(os.environ.get("OPENAI_MAX_RETRIES", "5"))
1✔
165

166
        client_kwargs: Dict[str, Any] = {
1✔
167
            "api_key": api_key.resolve_value(),
168
            "organization": organization,
169
            "base_url": api_base_url,
170
            "timeout": timeout,
171
            "max_retries": max_retries,
172
        }
173

174
        self.client = OpenAI(http_client=init_http_client(self.http_client_kwargs, async_client=False), **client_kwargs)
1✔
175
        self.async_client = AsyncOpenAI(
1✔
176
            http_client=init_http_client(self.http_client_kwargs, async_client=True), **client_kwargs
177
        )
178

179
    def _get_telemetry_data(self) -> Dict[str, Any]:
1✔
180
        """
181
        Data that is sent to Posthog for usage analytics.
182
        """
183
        return {"model": self.model}
×
184

185
    def to_dict(self) -> Dict[str, Any]:
1✔
186
        """
187
        Serialize this component to a dictionary.
188

189
        :returns:
190
            The serialized component as a dictionary.
191
        """
192
        callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None
1✔
193
        return default_to_dict(
1✔
194
            self,
195
            model=self.model,
196
            streaming_callback=callback_name,
197
            api_base_url=self.api_base_url,
198
            organization=self.organization,
199
            generation_kwargs=self.generation_kwargs,
200
            api_key=self.api_key.to_dict(),
201
            timeout=self.timeout,
202
            max_retries=self.max_retries,
203
            tools=serialize_tools_or_toolset(self.tools),
204
            tools_strict=self.tools_strict,
205
            http_client_kwargs=self.http_client_kwargs,
206
        )
207

208
    @classmethod
1✔
209
    def from_dict(cls, data: Dict[str, Any]) -> "OpenAIChatGenerator":
1✔
210
        """
211
        Deserialize this component from a dictionary.
212

213
        :param data: The dictionary representation of this component.
214
        :returns:
215
            The deserialized component instance.
216
        """
217
        deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"])
1✔
218
        deserialize_tools_or_toolset_inplace(data["init_parameters"], key="tools")
1✔
219
        init_params = data.get("init_parameters", {})
1✔
220
        serialized_callback_handler = init_params.get("streaming_callback")
1✔
221
        if serialized_callback_handler:
1✔
222
            data["init_parameters"]["streaming_callback"] = deserialize_callable(serialized_callback_handler)
1✔
223
        return default_from_dict(cls, data)
1✔
224

225
    @component.output_types(replies=List[ChatMessage])
1✔
226
    def run(
1✔
227
        self,
228
        messages: List[ChatMessage],
229
        streaming_callback: Optional[StreamingCallbackT] = None,
230
        generation_kwargs: Optional[Dict[str, Any]] = None,
231
        *,
232
        tools: Optional[Union[List[Tool], Toolset]] = None,
233
        tools_strict: Optional[bool] = None,
234
    ):
235
        """
236
        Invokes chat completion based on the provided messages and generation parameters.
237

238
        :param messages:
239
            A list of ChatMessage instances representing the input messages.
240
        :param streaming_callback:
241
            A callback function that is called when a new token is received from the stream.
242
        :param generation_kwargs:
243
            Additional keyword arguments for text generation. These parameters will
244
            override the parameters passed during component initialization.
245
            For details on OpenAI API parameters, see [OpenAI documentation](https://platform.openai.com/docs/api-reference/chat/create).
246
        :param tools:
247
            A list of tools or a Toolset for which the model can prepare calls. If set, it will override the
248
            `tools` parameter set during component initialization. This parameter can accept either a list of
249
            `Tool` objects or a `Toolset` instance.
250
        :param tools_strict:
251
            Whether to enable strict schema adherence for tool calls. If set to `True`, the model will follow exactly
252
            the schema provided in the `parameters` field of the tool definition, but this may increase latency.
253
            If set, it will override the `tools_strict` parameter set during component initialization.
254

255
        :returns:
256
            A dictionary with the following key:
257
            - `replies`: A list containing the generated responses as ChatMessage instances.
258
        """
259
        if len(messages) == 0:
1✔
260
            return {"replies": []}
×
261

262
        streaming_callback = select_streaming_callback(
1✔
263
            init_callback=self.streaming_callback, runtime_callback=streaming_callback, requires_async=False
264
        )
265

266
        api_args = self._prepare_api_call(
1✔
267
            messages=messages,
268
            streaming_callback=streaming_callback,
269
            generation_kwargs=generation_kwargs,
270
            tools=tools,
271
            tools_strict=tools_strict,
272
        )
273
        chat_completion: Union[Stream[ChatCompletionChunk], ChatCompletion] = self.client.chat.completions.create(
1✔
274
            **api_args
275
        )
276

277
        if streaming_callback is not None:
1✔
278
            completions = self._handle_stream_response(
1✔
279
                chat_completion,  # type: ignore
280
                streaming_callback,  # type: ignore
281
            )
282

283
        else:
284
            assert isinstance(chat_completion, ChatCompletion), "Unexpected response type for non-streaming request."
1✔
285
            completions = [
1✔
286
                self._convert_chat_completion_to_chat_message(chat_completion, choice)
287
                for choice in chat_completion.choices
288
            ]
289

290
        # before returning, do post-processing of the completions
291
        for message in completions:
1✔
292
            self._check_finish_reason(message.meta)
1✔
293

294
        return {"replies": completions}
1✔
295

296
    @component.output_types(replies=List[ChatMessage])
1✔
297
    async def run_async(
1✔
298
        self,
299
        messages: List[ChatMessage],
300
        streaming_callback: Optional[StreamingCallbackT] = None,
301
        generation_kwargs: Optional[Dict[str, Any]] = None,
302
        *,
303
        tools: Optional[Union[List[Tool], Toolset]] = None,
304
        tools_strict: Optional[bool] = None,
305
    ):
306
        """
307
        Asynchronously invokes chat completion based on the provided messages and generation parameters.
308

309
        This is the asynchronous version of the `run` method. It has the same parameters and return values
310
        but can be used with `await` in async code.
311

312
        :param messages:
313
            A list of ChatMessage instances representing the input messages.
314
        :param streaming_callback:
315
            A callback function that is called when a new token is received from the stream.
316
            Must be a coroutine.
317
        :param generation_kwargs:
318
            Additional keyword arguments for text generation. These parameters will
319
            override the parameters passed during component initialization.
320
            For details on OpenAI API parameters, see [OpenAI documentation](https://platform.openai.com/docs/api-reference/chat/create).
321
        :param tools:
322
            A list of tools or a Toolset for which the model can prepare calls. If set, it will override the
323
            `tools` parameter set during component initialization. This parameter can accept either a list of
324
            `Tool` objects or a `Toolset` instance.
325
        :param tools_strict:
326
            Whether to enable strict schema adherence for tool calls. If set to `True`, the model will follow exactly
327
            the schema provided in the `parameters` field of the tool definition, but this may increase latency.
328
            If set, it will override the `tools_strict` parameter set during component initialization.
329

330
        :returns:
331
            A dictionary with the following key:
332
            - `replies`: A list containing the generated responses as ChatMessage instances.
333
        """
334
        # validate and select the streaming callback
335
        streaming_callback = select_streaming_callback(
1✔
336
            init_callback=self.streaming_callback, runtime_callback=streaming_callback, requires_async=True
337
        )
338

339
        if len(messages) == 0:
1✔
340
            return {"replies": []}
×
341

342
        api_args = self._prepare_api_call(
1✔
343
            messages=messages,
344
            streaming_callback=streaming_callback,
345
            generation_kwargs=generation_kwargs,
346
            tools=tools,
347
            tools_strict=tools_strict,
348
        )
349

350
        chat_completion: Union[
1✔
351
            AsyncStream[ChatCompletionChunk], ChatCompletion
352
        ] = await self.async_client.chat.completions.create(**api_args)
353

354
        if streaming_callback is not None:
1✔
355
            completions = await self._handle_async_stream_response(
1✔
356
                chat_completion,  # type: ignore
357
                streaming_callback,  # type: ignore
358
            )
359

360
        else:
361
            assert isinstance(chat_completion, ChatCompletion), "Unexpected response type for non-streaming request."
1✔
362
            completions = [
1✔
363
                self._convert_chat_completion_to_chat_message(chat_completion, choice)
364
                for choice in chat_completion.choices
365
            ]
366

367
        # before returning, do post-processing of the completions
368
        for message in completions:
1✔
369
            self._check_finish_reason(message.meta)
1✔
370

371
        return {"replies": completions}
1✔
372

373
    def _prepare_api_call(  # noqa: PLR0913
1✔
374
        self,
375
        *,
376
        messages: List[ChatMessage],
377
        streaming_callback: Optional[StreamingCallbackT] = None,
378
        generation_kwargs: Optional[Dict[str, Any]] = None,
379
        tools: Optional[Union[List[Tool], Toolset]] = None,
380
        tools_strict: Optional[bool] = None,
381
    ) -> Dict[str, Any]:
382
        # update generation kwargs by merging with the generation kwargs passed to the run method
383
        generation_kwargs = {**self.generation_kwargs, **(generation_kwargs or {})}
1✔
384

385
        # adapt ChatMessage(s) to the format expected by the OpenAI API
386
        openai_formatted_messages = [message.to_openai_dict_format() for message in messages]
1✔
387

388
        tools = tools or self.tools
1✔
389
        if isinstance(tools, Toolset):
1✔
390
            tools = list(tools)
×
391
        tools_strict = tools_strict if tools_strict is not None else self.tools_strict
1✔
392
        _check_duplicate_tool_names(tools)
1✔
393

394
        openai_tools = {}
1✔
395
        if tools:
1✔
396
            tool_definitions = []
1✔
397
            for t in tools:
1✔
398
                function_spec = {**t.tool_spec}
1✔
399
                if tools_strict:
1✔
400
                    function_spec["strict"] = True
1✔
401
                    function_spec["parameters"]["additionalProperties"] = False
1✔
402
                tool_definitions.append({"type": "function", "function": function_spec})
1✔
403
            openai_tools = {"tools": tool_definitions}
1✔
404

405
        is_streaming = streaming_callback is not None
1✔
406
        num_responses = generation_kwargs.pop("n", 1)
1✔
407
        if is_streaming and num_responses > 1:
1✔
408
            raise ValueError("Cannot stream multiple responses, please set n=1.")
×
409

410
        return {
1✔
411
            "model": self.model,
412
            "messages": openai_formatted_messages,  # type: ignore[arg-type] # openai expects list of specific message types
413
            "stream": streaming_callback is not None,
414
            "n": num_responses,
415
            **openai_tools,
416
            **generation_kwargs,
417
        }
418

419
    def _handle_stream_response(self, chat_completion: Stream, callback: SyncStreamingCallbackT) -> List[ChatMessage]:
1✔
420
        chunks: List[StreamingChunk] = []
1✔
421
        chunk = None
1✔
422
        chunk_delta: StreamingChunk
423

424
        for chunk in chat_completion:  # pylint: disable=not-an-iterable
1✔
425
            assert len(chunk.choices) <= 1, "Streaming responses should have at most one choice."
1✔
426
            chunk_delta = self._convert_chat_completion_chunk_to_streaming_chunk(chunk)
1✔
427
            chunks.append(chunk_delta)
1✔
428
            callback(chunk_delta)
1✔
429
        return [self._convert_streaming_chunks_to_chat_message(chunk, chunks)]
1✔
430

431
    async def _handle_async_stream_response(
1✔
432
        self, chat_completion: AsyncStream, callback: AsyncStreamingCallbackT
433
    ) -> List[ChatMessage]:
434
        chunks: List[StreamingChunk] = []
1✔
435
        chunk = None
1✔
436
        chunk_delta: StreamingChunk
437

438
        async for chunk in chat_completion:  # pylint: disable=not-an-iterable
1✔
439
            assert len(chunk.choices) <= 1, "Streaming responses should have at most one choice."
1✔
440
            chunk_delta = self._convert_chat_completion_chunk_to_streaming_chunk(chunk)
1✔
441
            chunks.append(chunk_delta)
1✔
442
            await callback(chunk_delta)
1✔
443
        return [self._convert_streaming_chunks_to_chat_message(chunk, chunks)]
1✔
444

445
    def _check_finish_reason(self, meta: Dict[str, Any]) -> None:
1✔
446
        if meta["finish_reason"] == "length":
1✔
447
            logger.warning(
1✔
448
                "The completion for index {index} has been truncated before reaching a natural stopping point. "
449
                "Increase the max_tokens parameter to allow for longer completions.",
450
                index=meta["index"],
451
                finish_reason=meta["finish_reason"],
452
            )
453
        if meta["finish_reason"] == "content_filter":
1✔
454
            logger.warning(
1✔
455
                "The completion for index {index} has been truncated due to the content filter.",
456
                index=meta["index"],
457
                finish_reason=meta["finish_reason"],
458
            )
459

460
    def _convert_streaming_chunks_to_chat_message(
1✔
461
        self, last_chunk: ChatCompletionChunk, chunks: List[StreamingChunk]
462
    ) -> ChatMessage:
463
        """
464
        Connects the streaming chunks into a single ChatMessage.
465

466
        :param last_chunk: The last chunk returned by the OpenAI API.
467
        :param chunks: The list of all `StreamingChunk` objects.
468

469
        :returns: The ChatMessage.
470
        """
471
        text = "".join([chunk.content for chunk in chunks])
1✔
472
        tool_calls = []
1✔
473

474
        # Process tool calls if present in any chunk
475
        tool_call_data: Dict[str, Dict[str, str]] = {}  # Track tool calls by index
1✔
476
        for chunk_payload in chunks:
1✔
477
            tool_calls_meta = chunk_payload.meta.get("tool_calls")
1✔
478
            if tool_calls_meta is not None:
1✔
479
                for delta in tool_calls_meta:
1✔
480
                    # We use the index of the tool call to track it across chunks since the ID is not always provided
481
                    if delta.index not in tool_call_data:
1✔
482
                        tool_call_data[delta.index] = {"id": "", "name": "", "arguments": ""}
1✔
483

484
                    # Save the ID if present
485
                    if delta.id is not None:
1✔
486
                        tool_call_data[delta.index]["id"] = delta.id
1✔
487

488
                    if delta.function is not None:
1✔
489
                        if delta.function.name is not None:
1✔
490
                            tool_call_data[delta.index]["name"] += delta.function.name
1✔
491
                        if delta.function.arguments is not None:
1✔
492
                            tool_call_data[delta.index]["arguments"] += delta.function.arguments
1✔
493

494
        # Convert accumulated tool call data into ToolCall objects
495
        for call_data in tool_call_data.values():
1✔
496
            try:
1✔
497
                arguments = json.loads(call_data["arguments"])
1✔
498
                tool_calls.append(ToolCall(id=call_data["id"], tool_name=call_data["name"], arguments=arguments))
1✔
499
            except json.JSONDecodeError:
×
500
                logger.warning(
×
501
                    "OpenAI returned a malformed JSON string for tool call arguments. This tool call "
502
                    "will be skipped. To always generate a valid JSON, set `tools_strict` to `True`. "
503
                    "Tool call ID: {_id}, Tool name: {_name}, Arguments: {_arguments}",
504
                    _id=call_data["id"],
505
                    _name=call_data["name"],
506
                    _arguments=call_data["arguments"],
507
                )
508

509
        # finish_reason can appear in different places so we look for the last one
510
        finish_reasons = [
1✔
511
            chunk.meta.get("finish_reason") for chunk in chunks if chunk.meta.get("finish_reason") is not None
512
        ]
513
        finish_reason = finish_reasons[-1] if finish_reasons else None
1✔
514

515
        meta = {
1✔
516
            "model": last_chunk.model,
517
            "index": 0,
518
            "finish_reason": finish_reason,
519
            "completion_start_time": chunks[0].meta.get("received_at"),  # first chunk received
520
            "usage": self._serialize_usage(last_chunk.usage),  # last chunk has the final usage data if available
521
        }
522

523
        return ChatMessage.from_assistant(text=text or None, tool_calls=tool_calls, meta=meta)
1✔
524

525
    def _convert_chat_completion_to_chat_message(self, completion: ChatCompletion, choice: Choice) -> ChatMessage:
1✔
526
        """
527
        Converts the non-streaming response from the OpenAI API to a ChatMessage.
528

529
        :param completion: The completion returned by the OpenAI API.
530
        :param choice: The choice returned by the OpenAI API.
531
        :return: The ChatMessage.
532
        """
533
        message: ChatCompletionMessage = choice.message
1✔
534
        text = message.content
1✔
535
        tool_calls = []
1✔
536
        if openai_tool_calls := message.tool_calls:
1✔
537
            for openai_tc in openai_tool_calls:
1✔
538
                arguments_str = openai_tc.function.arguments
1✔
539
                try:
1✔
540
                    arguments = json.loads(arguments_str)
1✔
541
                    tool_calls.append(ToolCall(id=openai_tc.id, tool_name=openai_tc.function.name, arguments=arguments))
1✔
542
                except json.JSONDecodeError:
1✔
543
                    logger.warning(
1✔
544
                        "OpenAI returned a malformed JSON string for tool call arguments. This tool call "
545
                        "will be skipped. To always generate a valid JSON, set `tools_strict` to `True`. "
546
                        "Tool call ID: {_id}, Tool name: {_name}, Arguments: {_arguments}",
547
                        _id=openai_tc.id,
548
                        _name=openai_tc.function.name,
549
                        _arguments=arguments_str,
550
                    )
551

552
        chat_message = ChatMessage.from_assistant(text=text, tool_calls=tool_calls)
1✔
553
        chat_message._meta.update(
1✔
554
            {
555
                "model": completion.model,
556
                "index": choice.index,
557
                "finish_reason": choice.finish_reason,
558
                "usage": self._serialize_usage(completion.usage),
559
            }
560
        )
561
        return chat_message
1✔
562

563
    def _convert_chat_completion_chunk_to_streaming_chunk(self, chunk: ChatCompletionChunk) -> StreamingChunk:
1✔
564
        """
565
        Converts the streaming response chunk from the OpenAI API to a StreamingChunk.
566

567
        :param chunk: The chunk returned by the OpenAI API.
568

569
        :returns:
570
            The StreamingChunk.
571
        """
572
        # if there are no choices, return an empty chunk
573
        if len(chunk.choices) == 0:
1✔
574
            return StreamingChunk(content="", meta={"model": chunk.model, "received_at": datetime.now().isoformat()})
1✔
575

576
        # we stream the content of the chunk if it's not a tool or function call
577
        choice: ChunkChoice = chunk.choices[0]
1✔
578
        content = choice.delta.content or ""
1✔
579
        chunk_message = StreamingChunk(content)
1✔
580
        # but save the tool calls and function call in the meta if they are present
581
        # and then connect the chunks in the _convert_streaming_chunks_to_chat_message method
582
        chunk_message.meta.update(
1✔
583
            {
584
                "model": chunk.model,
585
                "index": choice.index,
586
                "tool_calls": choice.delta.tool_calls,
587
                "finish_reason": choice.finish_reason,
588
                "received_at": datetime.now().isoformat(),
589
            }
590
        )
591
        return chunk_message
1✔
592

593
    def _serialize_usage(self, usage):
1✔
594
        """Convert OpenAI usage object to serializable dict recursively"""
595
        if hasattr(usage, "model_dump"):
1✔
596
            return usage.model_dump()
1✔
597
        elif hasattr(usage, "__dict__"):
1✔
598
            return {k: self._serialize_usage(v) for k, v in usage.__dict__.items() if not k.startswith("_")}
×
599
        elif isinstance(usage, dict):
1✔
600
            return {k: self._serialize_usage(v) for k, v in usage.items()}
×
601
        elif isinstance(usage, list):
1✔
602
            return [self._serialize_usage(item) for item in usage]
×
603
        else:
604
            return usage
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc