Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import functools
import inspect
import logging
import weakref
from enum import Enum
from types import SimpleNamespace
from typing import (
Expand Down Expand Up @@ -1036,17 +1037,41 @@ def _remove_redundant_reasoning_entries(
del output_messages[index]


class _ReadState:
__slots__ = ("started",)

def __init__(self) -> None:
self.started = False


def _end_span_if_unread(span: trace_api.Span, read_state: _ReadState) -> None:
# A finalizer generator that never started never runs its ``finally``.
if not read_state.started and span.is_recording():
span.end()


def _end_span_with_error(span: trace_api.Span, error: BaseException) -> None:
span.record_exception(error)
span.set_status(trace_api.Status(trace_api.StatusCode.ERROR, description=str(error)))
span.end()


class _TracedSyncStream(wrapt.ObjectProxy): # type: ignore[misc,name-defined,type-arg,unused-ignore]
"""Proxy the original stream while collecting tracing data."""

def __init__(self, wrapped: Any, finalized_iterator: Any) -> None:
def __init__(self, wrapped: Any, finalized_iterator: Any, span: trace_api.Span) -> None:
super().__init__(wrapped)
self._self_finalized_iterator = finalized_iterator
self._self_span = span
self._self_read_state = _ReadState()
# Ends the span if the stream is discarded without being read.
weakref.finalize(self, _end_span_if_unread, span, self._self_read_state)

def __iter__(self) -> Any:
return self

def __next__(self) -> Any:
self._self_read_state.started = True
return next(self._self_finalized_iterator)

def close(self) -> Any:
Expand All @@ -1055,6 +1080,7 @@ def close(self) -> Any:
try:
return self._self_finalized_iterator.close()
finally:
_end_span_if_unread(self._self_span, self._self_read_state)
wrapped_close = getattr(self.__wrapped__, "close", None)
if wrapped_close is not None:
wrapped_close()
Expand All @@ -1063,14 +1089,18 @@ def close(self) -> Any:
class _TracedAsyncStream(wrapt.ObjectProxy): # type: ignore[misc,name-defined,type-arg,unused-ignore]
"""Async counterpart of ``_TracedSyncStream``."""

def __init__(self, wrapped: Any, finalized_iterator: Any) -> None:
def __init__(self, wrapped: Any, finalized_iterator: Any, span: trace_api.Span) -> None:
super().__init__(wrapped)
self._self_finalized_iterator = finalized_iterator
self._self_span = span
self._self_read_state = _ReadState()
weakref.finalize(self, _end_span_if_unread, span, self._self_read_state)

def __aiter__(self) -> Any:
return self

async def __anext__(self) -> Any:
self._self_read_state.started = True
return await self._self_finalized_iterator.__anext__()

async def aclose(self) -> None:
Expand All @@ -1079,6 +1109,7 @@ async def aclose(self) -> None:
try:
await self._self_finalized_iterator.aclose()
finally:
_end_span_if_unread(self._self_span, self._self_read_state)
wrapped_aclose = getattr(self.__wrapped__, "aclose", None)
if wrapped_aclose is not None:
await wrapped_aclose()
Expand Down Expand Up @@ -1222,24 +1253,52 @@ async def _finalize_aresponses_streaming_span(span: trace_api.Span, stream: Any)
from litellm.responses.streaming_iterator import ResponsesAPIStreamingIterator
from litellm.types.llms.openai import ResponsesAPIStreamEvents

terminal_events = (
ResponsesAPIStreamEvents.RESPONSE_COMPLETED,
ResponsesAPIStreamEvents.RESPONSE_INCOMPLETE,
ResponsesAPIStreamEvents.RESPONSE_FAILED,
)
if isinstance(stream, ResponsesAPIStreamingIterator):
async for token in stream:
if token.type == ResponsesAPIStreamEvents.RESPONSE_COMPLETED:
_finalize_span(span, token.response)
try:
async for token in stream:
if token.type in terminal_events and span.is_recording():
_finalize_span(span, token.response)
span.end()
yield token
except Exception as e:
if span.is_recording():
span.record_exception(e)
span.set_status(trace_api.Status(trace_api.StatusCode.ERROR, description=str(e)))
raise
finally:
if span.is_recording():
span.end()
yield token


def _finalize_responses_streaming_span(span: trace_api.Span, stream: Any) -> Any:
from litellm.responses.streaming_iterator import SyncResponsesAPIStreamingIterator
from litellm.types.llms.openai import ResponsesAPIStreamEvents

terminal_events = (
ResponsesAPIStreamEvents.RESPONSE_COMPLETED,
ResponsesAPIStreamEvents.RESPONSE_INCOMPLETE,
ResponsesAPIStreamEvents.RESPONSE_FAILED,
)
if isinstance(stream, SyncResponsesAPIStreamingIterator):
for token in stream:
if token.type == ResponsesAPIStreamEvents.RESPONSE_COMPLETED:
_finalize_span(span, token.response)
try:
for token in stream:
if token.type in terminal_events and span.is_recording():
_finalize_span(span, token.response)
span.end()
yield token
except Exception as e:
if span.is_recording():
span.record_exception(e)
span.set_status(trace_api.Status(trace_api.StatusCode.ERROR, description=str(e)))
raise
finally:
if span.is_recording():
span.end()
yield token


class LiteLLMInstrumentor(BaseInstrumentor): # type: ignore
Expand Down Expand Up @@ -1411,9 +1470,15 @@ def _responses_wrapper(self, *args: Any, **kwargs: Any) -> Any:
)
_instrument_func_type_responses(span, kwargs)

result = self.original_litellm_funcs["responses"](*args, **kwargs)
try:
result = self.original_litellm_funcs["responses"](*args, **kwargs)
except BaseException as e:
_end_span_with_error(span, e)
raise
if isinstance(result, SyncResponsesAPIStreamingIterator):
return _TracedSyncStream(result, _finalize_responses_streaming_span(span, result))
return _TracedSyncStream(
result, _finalize_responses_streaming_span(span, result), span
)
span.end()
return result
else:
Expand All @@ -1434,11 +1499,17 @@ async def _aresponses_wrapper(self, *args: Any, **kwargs: Any) -> Any:
name="aresponses", attributes=dict(get_attributes_from_context())
)
_instrument_func_type_responses(span, kwargs)
result = await self.original_litellm_funcs["aresponses"](*args, **kwargs)
try:
result = await self.original_litellm_funcs["aresponses"](*args, **kwargs)
except BaseException as e:
_end_span_with_error(span, e)
raise
from litellm.responses.streaming_iterator import ResponsesAPIStreamingIterator

if isinstance(result, ResponsesAPIStreamingIterator):
return _TracedAsyncStream(result, _finalize_aresponses_streaming_span(span, result))
return _TracedAsyncStream(
result, _finalize_aresponses_streaming_span(span, result), span
)
span.end()
return result
else:
Expand All @@ -1462,10 +1533,14 @@ def _completion_wrapper(self, *args: Any, **kwargs: Any) -> Any:
)
_instrument_func_type_completion(span, kwargs)

result = self.original_litellm_funcs["completion"](*args, **kwargs)
try:
result = self.original_litellm_funcs["completion"](*args, **kwargs)
except BaseException as e:
_end_span_with_error(span, e)
raise

if isinstance(result, CustomStreamWrapper):
return _TracedSyncStream(result, _finalize_sync_streaming_span(span, result))
return _TracedSyncStream(result, _finalize_sync_streaming_span(span, result), span)

_finalize_span(span, result)
span.end()
Expand All @@ -1489,10 +1564,14 @@ async def _acompletion_wrapper(self, *args: Any, **kwargs: Any) -> Any:
)
_instrument_func_type_completion(span, kwargs)

result = await self.original_litellm_funcs["acompletion"](*args, **kwargs)
try:
result = await self.original_litellm_funcs["acompletion"](*args, **kwargs)
except BaseException as e:
_end_span_with_error(span, e)
raise

if hasattr(result, "__aiter__"):
return _TracedAsyncStream(result, _finalize_streaming_span(span, result))
return _TracedAsyncStream(result, _finalize_streaming_span(span, result), span)

_finalize_span(span, result)
span.end()
Expand Down
Loading
Loading