aboutsummaryrefslogtreecommitdiff
path: root/.venv/lib/python3.12/site-packages/azure/ai/inference/tracing.py
blob: f7937a99074ac8f0a6bfcc4122897e96b720969f (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import copy
from enum import Enum
import functools
import json
import importlib
import logging
import os
from time import time_ns
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union
from urllib.parse import urlparse

# pylint: disable = no-name-in-module
from azure.core import CaseInsensitiveEnumMeta  # type: ignore
from azure.core.settings import settings
from . import models as _models

try:
    # pylint: disable = no-name-in-module
    from azure.core.tracing import AbstractSpan, SpanKind  # type: ignore
    from opentelemetry.trace import StatusCode, Span

    _tracing_library_available = True
except ModuleNotFoundError:

    _tracing_library_available = False


__all__ = [
    "AIInferenceInstrumentor",
]


_inference_traces_enabled: bool = False
_trace_inference_content: bool = False
_INFERENCE_GEN_AI_SYSTEM_NAME = "az.ai.inference"


class TraceType(str, Enum, metaclass=CaseInsensitiveEnumMeta):  # pylint: disable=C4747
    """An enumeration class to represent different types of traces."""

    INFERENCE = "Inference"


class AIInferenceInstrumentor:
    """
    A class for managing the trace instrumentation of AI Inference.

    This class allows enabling or disabling tracing for AI Inference.
    and provides functionality to check whether instrumentation is active.

    """

    def __init__(self):
        if not _tracing_library_available:
            raise ModuleNotFoundError(
                "Azure Core Tracing Opentelemetry is not installed. "
                "Please install it using 'pip install azure-core-tracing-opentelemetry'"
            )
        # In the future we could support different versions from the same library
        # and have a parameter that specifies the version to use.
        self._impl = _AIInferenceInstrumentorPreview()

    def instrument(self, enable_content_recording: Optional[bool] = None) -> None:
        """
        Enable trace instrumentation for AI Inference.

        :param enable_content_recording: Whether content recording is enabled as part
            of the traces or not. Content in this context refers to chat message content
            and function call tool related function names, function parameter names and
            values. True will enable content recording, False will disable it. If no value
            s provided, then the value read from environment variable
            AZURE_TRACING_GEN_AI_CONTENT_RECORDING_ENABLED is used. If the environment variable
            is not found, then the value will default to False. Please note that successive calls
            to instrument will always apply the content recording value provided with the most
            recent call to instrument (including applying the environment variable if no value is
            provided and defaulting to false if the environment variable is not found), even if
            instrument was already previously called without uninstrument being called in between
            the instrument calls.

        :type enable_content_recording: bool, optional
        """
        self._impl.instrument(enable_content_recording=enable_content_recording)

    def uninstrument(self) -> None:
        """
        Disable trace instrumentation for AI Inference.

        Raises:
            RuntimeError: If instrumentation is not currently enabled.

        This method removes any active instrumentation, stopping the tracing
        of AI Inference.
        """
        self._impl.uninstrument()

    def is_instrumented(self) -> bool:
        """
        Check if trace instrumentation for AI Inference is currently enabled.

        :return: True if instrumentation is active, False otherwise.
        :rtype: bool
        """
        return self._impl.is_instrumented()

    def is_content_recording_enabled(self) -> bool:
        """
        This function gets the content recording value.

        :return: A bool value indicating whether content recording is enabled.
        :rtype: bool
        """
        return self._impl.is_content_recording_enabled()


class _AIInferenceInstrumentorPreview:
    """
    A class for managing the trace instrumentation of AI Inference.

    This class allows enabling or disabling tracing for AI Inference.
    and provides functionality to check whether instrumentation is active.
    """

    def _str_to_bool(self, s):
        if s is None:
            return False
        return str(s).lower() == "true"

    def instrument(self, enable_content_recording: Optional[bool] = None):
        """
        Enable trace instrumentation for AI Inference.

        :param enable_content_recording: Whether content recording is enabled as part
        of the traces or not. Content in this context refers to chat message content
        and function call tool related function names, function parameter names and
        values. True will enable content recording, False will disable it. If no value
        is provided, then the value read from environment variable
        AZURE_TRACING_GEN_AI_CONTENT_RECORDING_ENABLED is used. If the environment variable
        is not found, then the value will default to False.

        :type enable_content_recording: bool, optional
        """
        if enable_content_recording is None:
            var_value = os.environ.get("AZURE_TRACING_GEN_AI_CONTENT_RECORDING_ENABLED")
            enable_content_recording = self._str_to_bool(var_value)
        if not self.is_instrumented():
            self._instrument_inference(enable_content_recording)
        else:
            self._set_content_recording_enabled(enable_content_recording=enable_content_recording)

    def uninstrument(self):
        """
        Disable trace instrumentation for AI Inference.

        This method removes any active instrumentation, stopping the tracing
        of AI Inference.
        """
        if self.is_instrumented():
            self._uninstrument_inference()

    def is_instrumented(self):
        """
        Check if trace instrumentation for AI Inference is currently enabled.

        :return: True if instrumentation is active, False otherwise.
        :rtype: bool
        """
        return self._is_instrumented()

    def set_content_recording_enabled(self, enable_content_recording: bool = False) -> None:
        """This function sets the content recording value.

        :param enable_content_recording: Indicates whether tracing of message content should be enabled.
                                    This also controls whether function call tool function names,
                                    parameter names and parameter values are traced.
        :type enable_content_recording: bool
        """
        self._set_content_recording_enabled(enable_content_recording=enable_content_recording)

    def is_content_recording_enabled(self) -> bool:
        """This function gets the content recording value.

        :return: A bool value indicating whether content tracing is enabled.
        :rtype bool
        """
        return self._is_content_recording_enabled()

    def _set_attributes(self, span: "AbstractSpan", *attrs: Tuple[str, Any]) -> None:
        for attr in attrs:
            key, value = attr
            if value is not None:
                span.add_attribute(key, value)

    def _add_request_chat_message_events(self, span: "AbstractSpan", **kwargs: Any) -> int:
        timestamp = 0
        for message in kwargs.get("messages", []):
            try:
                message = message.as_dict()
            except AttributeError:
                pass

            if message.get("role"):
                timestamp = self._record_event(
                    span,
                    f"gen_ai.{message.get('role')}.message",
                    {
                        "gen_ai.system": _INFERENCE_GEN_AI_SYSTEM_NAME,
                        "gen_ai.event.content": json.dumps(message),
                    },
                    timestamp,
                )

        return timestamp

    def _parse_url(self, url):
        parsed = urlparse(url)
        server_address = parsed.hostname
        port = parsed.port
        return server_address, port

    def _add_request_chat_attributes(self, span: "AbstractSpan", *args: Any, **kwargs: Any) -> None:
        client = args[0]
        endpoint = client._config.endpoint  # pylint: disable=protected-access
        server_address, port = self._parse_url(endpoint)
        model = "chat"
        if kwargs.get("model") is not None:
            model_value = kwargs.get("model")
            if model_value is not None:
                model = model_value

        self._set_attributes(
            span,
            ("gen_ai.operation.name", "chat"),
            ("gen_ai.system", _INFERENCE_GEN_AI_SYSTEM_NAME),
            ("gen_ai.request.model", model),
            ("gen_ai.request.max_tokens", kwargs.get("max_tokens")),
            ("gen_ai.request.temperature", kwargs.get("temperature")),
            ("gen_ai.request.top_p", kwargs.get("top_p")),
            ("server.address", server_address),
        )
        if port is not None and port != 443:
            span.add_attribute("server.port", port)

    def _remove_function_call_names_and_arguments(self, tool_calls: list) -> list:
        tool_calls_copy = copy.deepcopy(tool_calls)
        for tool_call in tool_calls_copy:
            if "function" in tool_call:
                if "name" in tool_call["function"]:
                    del tool_call["function"]["name"]
                if "arguments" in tool_call["function"]:
                    del tool_call["function"]["arguments"]
                if not tool_call["function"]:
                    del tool_call["function"]
        return tool_calls_copy

    def _get_finish_reasons(self, result) -> Optional[List[str]]:
        if hasattr(result, "choices") and result.choices:
            finish_reasons: List[str] = []
            for choice in result.choices:
                finish_reason = getattr(choice, "finish_reason", None)

                if finish_reason is None:
                    # If finish_reason is None, default to "none"
                    finish_reasons.append("none")
                elif hasattr(finish_reason, "value"):
                    # If finish_reason has a 'value' attribute (i.e., it's an enum), use it
                    finish_reasons.append(finish_reason.value)
                elif isinstance(finish_reason, str):
                    # If finish_reason is a string, use it directly
                    finish_reasons.append(finish_reason)
                else:
                    # Default to "none"
                    finish_reasons.append("none")

            return finish_reasons
        return None

    def _get_finish_reason_for_choice(self, choice):
        finish_reason = getattr(choice, "finish_reason", None)
        if finish_reason is not None:
            return finish_reason.value

        return "none"

    def _add_response_chat_message_events(
        self, span: "AbstractSpan", result: _models.ChatCompletions, last_event_timestamp_ns: int
    ) -> None:
        for choice in result.choices:
            attributes = {}
            if _trace_inference_content:
                full_response: Dict[str, Any] = {
                    "message": {"content": choice.message.content},
                    "finish_reason": self._get_finish_reason_for_choice(choice),
                    "index": choice.index,
                }
                if choice.message.tool_calls:
                    full_response["message"]["tool_calls"] = [tool.as_dict() for tool in choice.message.tool_calls]
                attributes = {
                    "gen_ai.system": _INFERENCE_GEN_AI_SYSTEM_NAME,
                    "gen_ai.event.content": json.dumps(full_response),
                }
            else:
                response: Dict[str, Any] = {
                    "finish_reason": self._get_finish_reason_for_choice(choice),
                    "index": choice.index,
                }
                if choice.message.tool_calls:
                    response["message"] = {}
                    tool_calls_function_names_and_arguments_removed = self._remove_function_call_names_and_arguments(
                        choice.message.tool_calls
                    )
                    response["message"]["tool_calls"] = [
                        tool.as_dict() for tool in tool_calls_function_names_and_arguments_removed
                    ]

                attributes = {
                    "gen_ai.system": _INFERENCE_GEN_AI_SYSTEM_NAME,
                    "gen_ai.event.content": json.dumps(response),
                }
            last_event_timestamp_ns = self._record_event(span, "gen_ai.choice", attributes, last_event_timestamp_ns)

    def _add_response_chat_attributes(
        self,
        span: "AbstractSpan",
        result: Union[_models.ChatCompletions, _models.StreamingChatCompletionsUpdate],
    ) -> None:
        self._set_attributes(
            span,
            ("gen_ai.response.id", result.id),
            ("gen_ai.response.model", result.model),
            (
                "gen_ai.usage.input_tokens",
                (result.usage.prompt_tokens if hasattr(result, "usage") and result.usage else None),
            ),
            (
                "gen_ai.usage.output_tokens",
                (result.usage.completion_tokens if hasattr(result, "usage") and result.usage else None),
            ),
        )
        finish_reasons = self._get_finish_reasons(result)
        if not finish_reasons is None:
            span.add_attribute("gen_ai.response.finish_reasons", finish_reasons)  # type: ignore

    def _add_request_details(self, span: "AbstractSpan", args: Any, kwargs: Any) -> int:
        self._add_request_chat_attributes(span, *args, **kwargs)
        if _trace_inference_content:
            return self._add_request_chat_message_events(span, **kwargs)
        return 0

    def _add_response_details(self, span: "AbstractSpan", result: object, last_event_timestamp_ns: int) -> None:
        if isinstance(result, _models.ChatCompletions):
            self._add_response_chat_attributes(span, result)
            self._add_response_chat_message_events(span, result, last_event_timestamp_ns)
        # TODO add more models here

    def _accumulate_response(self, item, accumulate: Dict[str, Any]) -> None:
        if item.finish_reason:
            accumulate["finish_reason"] = item.finish_reason
        if item.index:
            accumulate["index"] = item.index
        if item.delta.content:
            accumulate.setdefault("message", {})
            accumulate["message"].setdefault("content", "")
            accumulate["message"]["content"] += item.delta.content
        if item.delta.tool_calls:
            accumulate.setdefault("message", {})
            accumulate["message"].setdefault("tool_calls", [])
            if item.delta.tool_calls is not None:
                for tool_call in item.delta.tool_calls:
                    if tool_call.id:
                        accumulate["message"]["tool_calls"].append(
                            {
                                "id": tool_call.id,
                                "type": "",
                                "function": {"name": "", "arguments": ""},
                            }
                        )
                    if tool_call.function:
                        accumulate["message"]["tool_calls"][-1]["type"] = "function"
                    if tool_call.function and tool_call.function.name:
                        accumulate["message"]["tool_calls"][-1]["function"]["name"] = tool_call.function.name
                    if tool_call.function and tool_call.function.arguments:
                        accumulate["message"]["tool_calls"][-1]["function"]["arguments"] += tool_call.function.arguments

    def _accumulate_async_streaming_response(self, item, accumulate: Dict[str, Any]) -> None:
        if not "choices" in item:
            return
        if "finish_reason" in item["choices"][0] and item["choices"][0]["finish_reason"]:
            accumulate["finish_reason"] = item["choices"][0]["finish_reason"]
        if "index" in item["choices"][0] and item["choices"][0]["index"]:
            accumulate["index"] = item["choices"][0]["index"]
        if not "delta" in item["choices"][0]:
            return
        if "content" in item["choices"][0]["delta"] and item["choices"][0]["delta"]["content"]:
            accumulate.setdefault("message", {})
            accumulate["message"].setdefault("content", "")
            accumulate["message"]["content"] += item["choices"][0]["delta"]["content"]
        if "tool_calls" in item["choices"][0]["delta"] and item["choices"][0]["delta"]["tool_calls"]:
            accumulate.setdefault("message", {})
            accumulate["message"].setdefault("tool_calls", [])
            if item["choices"][0]["delta"]["tool_calls"] is not None:
                for tool_call in item["choices"][0]["delta"]["tool_calls"]:
                    if tool_call.id:
                        accumulate["message"]["tool_calls"].append(
                            {
                                "id": tool_call.id,
                                "type": "",
                                "function": {"name": "", "arguments": ""},
                            }
                        )
                    if tool_call.function:
                        accumulate["message"]["tool_calls"][-1]["type"] = "function"
                    if tool_call.function and tool_call.function.name:
                        accumulate["message"]["tool_calls"][-1]["function"]["name"] = tool_call.function.name
                    if tool_call.function and tool_call.function.arguments:
                        accumulate["message"]["tool_calls"][-1]["function"]["arguments"] += tool_call.function.arguments

    def _wrapped_stream(
        self, stream_obj: _models.StreamingChatCompletions, span: "AbstractSpan", previous_event_timestamp: int
    ) -> _models.StreamingChatCompletions:
        class StreamWrapper(_models.StreamingChatCompletions):
            def __init__(self, stream_obj, instrumentor):
                super().__init__(stream_obj._response)
                self._instrumentor = instrumentor

            def __iter__(  # pyright: ignore [reportIncompatibleMethodOverride]
                self,
            ) -> Iterator[_models.StreamingChatCompletionsUpdate]:
                accumulate: Dict[str, Any] = {}
                try:
                    chunk = None
                    for chunk in stream_obj:
                        for item in chunk.choices:
                            self._instrumentor._accumulate_response(item, accumulate)
                        yield chunk

                    if chunk is not None:
                        self._instrumentor._add_response_chat_attributes(span, chunk)

                except Exception as exc:
                    # Set the span status to error
                    if isinstance(span.span_instance, Span):  # pyright: ignore [reportPossiblyUnboundVariable]
                        span.span_instance.set_status(
                            StatusCode.ERROR,  # pyright: ignore [reportPossiblyUnboundVariable]
                            description=str(exc),
                        )
                    module = exc.__module__ if hasattr(exc, "__module__") and exc.__module__ != "builtins" else ""
                    error_type = f"{module}.{type(exc).__name__}" if module else type(exc).__name__
                    self._instrumentor._set_attributes(span, ("error.type", error_type))
                    raise

                finally:
                    if stream_obj._done is False:
                        if accumulate.get("finish_reason") is None:
                            accumulate["finish_reason"] = "error"
                    else:
                        # Only one choice expected with streaming
                        accumulate["index"] = 0
                        # Delete message if content tracing is not enabled
                        if not _trace_inference_content:
                            if "message" in accumulate:
                                if "content" in accumulate["message"]:
                                    del accumulate["message"]["content"]
                                if not accumulate["message"]:
                                    del accumulate["message"]
                            if "message" in accumulate:
                                if "tool_calls" in accumulate["message"]:
                                    tool_calls_function_names_and_arguments_removed = (
                                        self._instrumentor._remove_function_call_names_and_arguments(
                                            accumulate["message"]["tool_calls"]
                                        )
                                    )
                                    accumulate["message"]["tool_calls"] = list(
                                        tool_calls_function_names_and_arguments_removed
                                    )
                    attributes = {
                        "gen_ai.system": _INFERENCE_GEN_AI_SYSTEM_NAME,
                        "gen_ai.event.content": json.dumps(accumulate),
                    }
                    self._instrumentor._record_event(span, "gen_ai.choice", attributes, previous_event_timestamp)
                    span.finish()

        return StreamWrapper(stream_obj, self)

    def _async_wrapped_stream(
        self, stream_obj: _models.AsyncStreamingChatCompletions, span: "AbstractSpan", last_event_timestamp_ns: int
    ) -> _models.AsyncStreamingChatCompletions:
        class AsyncStreamWrapper(_models.AsyncStreamingChatCompletions):
            def __init__(self, stream_obj, instrumentor, span, last_event_timestamp_ns):
                super().__init__(stream_obj._response)
                self._instrumentor = instrumentor
                self._accumulate: Dict[str, Any] = {}
                self._stream_obj = stream_obj
                self.span = span
                self._last_result = None
                self._last_event_timestamp_ns = last_event_timestamp_ns

            async def __anext__(self) -> "_models.StreamingChatCompletionsUpdate":
                try:
                    result = await super().__anext__()
                    self._instrumentor._accumulate_async_streaming_response(  # pylint: disable=protected-access, line-too-long # pyright: ignore [reportFunctionMemberAccess]
                        result, self._accumulate
                    )
                    self._last_result = result
                except StopAsyncIteration as exc:
                    self._trace_stream_content()
                    raise exc
                return result

            def _trace_stream_content(self) -> None:
                if self._last_result:
                    self._instrumentor._add_response_chat_attributes(  # pylint: disable=protected-access, line-too-long # pyright: ignore [reportFunctionMemberAccess]
                        span, self._last_result
                    )
                # Only one choice expected with streaming
                self._accumulate["index"] = 0
                # Delete message if content tracing is not enabled
                if not _trace_inference_content:
                    if "message" in self._accumulate:
                        if "content" in self._accumulate["message"]:
                            del self._accumulate["message"]["content"]
                            if not self._accumulate["message"]:
                                del self._accumulate["message"]
                        if "message" in self._accumulate:
                            if "tool_calls" in self._accumulate["message"]:
                                tools_no_recording = self._instrumentor._remove_function_call_names_and_arguments(  # pylint: disable=protected-access, line-too-long # pyright: ignore [reportFunctionMemberAccess]
                                    self._accumulate["message"]["tool_calls"]
                                )
                                self._accumulate["message"]["tool_calls"] = list(tools_no_recording)
                attributes = {
                    "gen_ai.system": _INFERENCE_GEN_AI_SYSTEM_NAME,
                    "gen_ai.event.content": json.dumps(self._accumulate),
                }
                self._last_event_timestamp_ns = self._instrumentor._record_event(  # pylint: disable=protected-access, line-too-long # pyright: ignore [reportFunctionMemberAccess]
                    span, "gen_ai.choice", attributes, self._last_event_timestamp_ns
                )
                span.finish()

        async_stream_wrapper = AsyncStreamWrapper(stream_obj, self, span, last_event_timestamp_ns)
        return async_stream_wrapper

    def _record_event(
        self, span: "AbstractSpan", name: str, attributes: Dict[str, Any], last_event_timestamp_ns: int
    ) -> int:
        timestamp = time_ns()

        # we're recording multiple events, some of them are emitted within (hundreds of) nanoseconds of each other.
        # time.time_ns resolution is not high enough on windows to guarantee unique timestamps for each message.
        # Also Azure Monitor truncates resolution to microseconds and some other backends truncate to milliseconds.
        #
        # But we need to give users a way to restore event order, so we're incrementing the timestamp
        # by 1 microsecond for each message.
        #
        # This is a workaround, we'll find a generic and better solution - see
        # https://github.com/open-telemetry/semantic-conventions/issues/1701
        if last_event_timestamp_ns > 0 and timestamp <= (last_event_timestamp_ns + 1000):
            timestamp = last_event_timestamp_ns + 1000

        span.span_instance.add_event(name=name, attributes=attributes, timestamp=timestamp)

        return timestamp

    def _trace_sync_function(
        self,
        function: Callable,
        *,
        _args_to_ignore: Optional[List[str]] = None,
        _trace_type=TraceType.INFERENCE,
        _name: Optional[str] = None,
    ) -> Callable:
        """
        Decorator that adds tracing to a synchronous function.

        :param function: The function to be traced.
        :type function: Callable
        :param args_to_ignore: A list of argument names to be ignored in the trace.
                            Defaults to None.
        :type: args_to_ignore: [List[str]], optional
        :param trace_type: The type of the trace. Defaults to TraceType.INFERENCE.
        :type trace_type: TraceType, optional
        :param name: The name of the trace, will set to func name if not provided.
        :type name: str, optional
        :return: The traced function.
        :rtype: Callable
        """

        @functools.wraps(function)
        def inner(*args, **kwargs):

            span_impl_type = settings.tracing_implementation()
            if span_impl_type is None:
                return function(*args, **kwargs)

            class_function_name = function.__qualname__

            if class_function_name.startswith("ChatCompletionsClient.complete"):
                if kwargs.get("model") is None:
                    span_name = "chat"
                else:
                    model = kwargs.get("model")
                    span_name = f"chat {model}"

                span = span_impl_type(
                    name=span_name,
                    kind=SpanKind.CLIENT,  # pyright: ignore [reportPossiblyUnboundVariable]
                )

                try:
                    # tracing events not supported in azure-core-tracing-opentelemetry
                    # so need to access the span instance directly
                    with span_impl_type.change_context(span.span_instance):
                        last_event_timestamp_ns = self._add_request_details(span, args, kwargs)
                        result = function(*args, **kwargs)
                        if kwargs.get("stream") is True:
                            return self._wrapped_stream(result, span, last_event_timestamp_ns)
                        self._add_response_details(span, result, last_event_timestamp_ns)
                except Exception as exc:
                    # Set the span status to error
                    if isinstance(span.span_instance, Span):  # pyright: ignore [reportPossiblyUnboundVariable]
                        span.span_instance.set_status(
                            StatusCode.ERROR,  # pyright: ignore [reportPossiblyUnboundVariable]
                            description=str(exc),
                        )
                    module = getattr(exc, "__module__", "")
                    module = module if module != "builtins" else ""
                    error_type = f"{module}.{type(exc).__name__}" if module else type(exc).__name__
                    self._set_attributes(span, ("error.type", error_type))
                    span.finish()
                    raise

                span.finish()
                return result

            # Handle the default case (if the function name does not match)
            return None  # Ensure all paths return

        return inner

    def _trace_async_function(
        self,
        function: Callable,
        *,
        _args_to_ignore: Optional[List[str]] = None,
        _trace_type=TraceType.INFERENCE,
        _name: Optional[str] = None,
    ) -> Callable:
        """
        Decorator that adds tracing to an asynchronous function.

        :param function: The function to be traced.
        :type function: Callable
        :param args_to_ignore: A list of argument names to be ignored in the trace.
                            Defaults to None.
        :type: args_to_ignore: [List[str]], optional
        :param trace_type: The type of the trace. Defaults to TraceType.INFERENCE.
        :type trace_type: TraceType, optional
        :param name: The name of the trace, will set to func name if not provided.
        :type name: str, optional
        :return: The traced function.
        :rtype: Callable
        """

        @functools.wraps(function)
        async def inner(*args, **kwargs):
            span_impl_type = settings.tracing_implementation()
            if span_impl_type is None:
                return await function(*args, **kwargs)

            class_function_name = function.__qualname__

            if class_function_name.startswith("ChatCompletionsClient.complete"):
                if kwargs.get("model") is None:
                    span_name = "chat"
                else:
                    model = kwargs.get("model")
                    span_name = f"chat {model}"

                span = span_impl_type(
                    name=span_name,
                    kind=SpanKind.CLIENT,  # pyright: ignore [reportPossiblyUnboundVariable]
                )
                try:
                    # tracing events not supported in azure-core-tracing-opentelemetry
                    # so need to access the span instance directly
                    with span_impl_type.change_context(span.span_instance):
                        last_event_timestamp_ns = self._add_request_details(span, args, kwargs)
                        result = await function(*args, **kwargs)
                        if kwargs.get("stream") is True:
                            return self._async_wrapped_stream(result, span, last_event_timestamp_ns)
                        self._add_response_details(span, result, last_event_timestamp_ns)

                except Exception as exc:
                    # Set the span status to error
                    if isinstance(span.span_instance, Span):  # pyright: ignore [reportPossiblyUnboundVariable]
                        span.span_instance.set_status(
                            StatusCode.ERROR,  # pyright: ignore [reportPossiblyUnboundVariable]
                            description=str(exc),
                        )
                    module = getattr(exc, "__module__", "")
                    module = module if module != "builtins" else ""
                    error_type = f"{module}.{type(exc).__name__}" if module else type(exc).__name__
                    self._set_attributes(span, ("error.type", error_type))
                    span.finish()
                    raise

                span.finish()
                return result

            # Handle the default case (if the function name does not match)
            return None  # Ensure all paths return

        return inner

    def _inject_async(self, f, _trace_type, _name):
        wrapper_fun = self._trace_async_function(f)
        wrapper_fun._original = f  # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess]
        return wrapper_fun

    def _inject_sync(self, f, _trace_type, _name):
        wrapper_fun = self._trace_sync_function(f)
        wrapper_fun._original = f  # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess]
        return wrapper_fun

    def _inference_apis(self):
        sync_apis = (
            (
                "azure.ai.inference",
                "ChatCompletionsClient",
                "complete",
                TraceType.INFERENCE,
                "inference_chat_completions_complete",
            ),
        )
        async_apis = (
            (
                "azure.ai.inference.aio",
                "ChatCompletionsClient",
                "complete",
                TraceType.INFERENCE,
                "inference_chat_completions_complete",
            ),
        )
        return sync_apis, async_apis

    def _inference_api_list(self):
        sync_apis, async_apis = self._inference_apis()
        yield sync_apis, self._inject_sync
        yield async_apis, self._inject_async

    def _generate_api_and_injector(self, apis):
        for api, injector in apis:
            for module_name, class_name, method_name, trace_type, name in api:
                try:
                    module = importlib.import_module(module_name)
                    api = getattr(module, class_name)
                    if hasattr(api, method_name):
                        yield api, method_name, trace_type, injector, name
                except AttributeError as e:
                    # Log the attribute exception with the missing class information
                    logging.warning(
                        "AttributeError: The module '%s' does not have the class '%s'. %s",
                        module_name,
                        class_name,
                        str(e),
                    )
                except Exception as e:  # pylint: disable=broad-except
                    # Log other exceptions as a warning, as we're not sure what they might be
                    logging.warning("An unexpected error occurred: '%s'", str(e))

    def _available_inference_apis_and_injectors(self):
        """
        Generates a sequence of tuples containing Inference API classes, method names, and
        corresponding injector functions.

        :return: A generator yielding tuples.
        :rtype: tuple
        """
        yield from self._generate_api_and_injector(self._inference_api_list())

    def _instrument_inference(self, enable_content_tracing: bool = False):
        """This function modifies the methods of the Inference API classes to
        inject logic before calling the original methods.
        The original methods are stored as _original attributes of the methods.

        :param enable_content_tracing: Indicates whether tracing of message content should be enabled.
                                    This also controls whether function call tool function names,
                                    parameter names and parameter values are traced.
        :type enable_content_tracing: bool
        """
        # pylint: disable=W0603
        global _inference_traces_enabled
        global _trace_inference_content
        if _inference_traces_enabled:
            raise RuntimeError("Traces already started for azure.ai.inference")
        _inference_traces_enabled = True
        _trace_inference_content = enable_content_tracing
        for (
            api,
            method,
            trace_type,
            injector,
            name,
        ) in self._available_inference_apis_and_injectors():
            # Check if the method of the api class has already been modified
            if not hasattr(getattr(api, method), "_original"):
                setattr(api, method, injector(getattr(api, method), trace_type, name))

    def _uninstrument_inference(self):
        """This function restores the original methods of the Inference API classes
        by assigning them back from the _original attributes of the modified methods.
        """
        # pylint: disable=W0603
        global _inference_traces_enabled
        global _trace_inference_content
        _trace_inference_content = False
        for api, method, _, _, _ in self._available_inference_apis_and_injectors():
            if hasattr(getattr(api, method), "_original"):
                setattr(api, method, getattr(getattr(api, method), "_original"))
        _inference_traces_enabled = False

    def _is_instrumented(self):
        """This function returns True if Inference libary has already been instrumented
        for tracing and False if it has not been instrumented.

        :return: A value indicating whether the Inference library is currently instrumented or not.
        :rtype: bool
        """
        return _inference_traces_enabled

    def _set_content_recording_enabled(self, enable_content_recording: bool = False) -> None:
        """This function sets the content recording value.

        :param enable_content_recording: Indicates whether tracing of message content should be enabled.
                                    This also controls whether function call tool function names,
                                    parameter names and parameter values are traced.
        :type enable_content_recording: bool
        """
        global _trace_inference_content  # pylint: disable=W0603
        _trace_inference_content = enable_content_recording

    def _is_content_recording_enabled(self) -> bool:
        """This function gets the content recording value.

        :return: A bool value indicating whether content tracing is enabled.
        :rtype bool
        """
        return _trace_inference_content