Skip to content
15 changes: 7 additions & 8 deletions sentry_sdk/integrations/openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,15 +132,12 @@ def count_tokens(self: "OpenAIIntegration", s: str) -> int:
return 0


def _capture_exception(exc: "Any", manual_span_cleanup: bool = True) -> None:
def _capture_exception(exc: "Any") -> None:
# Close an eventually open span
# We need to do this by hand because we are not using the start_span context manager
current_span = sentry_sdk.get_current_span()
set_span_errored(current_span)

if manual_span_cleanup and current_span is not None:
current_span.__exit__(None, None, None)

event, hint = event_from_exception(
exc,
client_options=sentry_sdk.get_client().options,
Expand Down Expand Up @@ -709,7 +706,7 @@ def _new_sync_chat_completion(f: "Any", *args: "Any", **kwargs: "Any") -> "Any":
except Exception as exc:
exc_info = sys.exc_info()
with capture_internal_exceptions():
_capture_exception(exc, manual_span_cleanup=False)
_capture_exception(exc)
span.__exit__(None, None, None)
reraise(*exc_info)

Expand Down Expand Up @@ -777,7 +774,7 @@ async def _new_async_chat_completion(f: "Any", *args: "Any", **kwargs: "Any") ->
except Exception as exc:
exc_info = sys.exc_info()
with capture_internal_exceptions():
_capture_exception(exc, manual_span_cleanup=False)
_capture_exception(exc)
span.__exit__(None, None, None)
reraise(*exc_info)

Expand Down Expand Up @@ -1164,7 +1161,7 @@ def _new_sync_embeddings_create(f: "Any", *args: "Any", **kwargs: "Any") -> "Any
except Exception as exc:
exc_info = sys.exc_info()
with capture_internal_exceptions():
_capture_exception(exc, manual_span_cleanup=False)
_capture_exception(exc)
reraise(*exc_info)

_set_embeddings_output_data(
Expand Down Expand Up @@ -1196,7 +1193,7 @@ async def _new_async_embeddings_create(
except Exception as exc:
exc_info = sys.exc_info()
with capture_internal_exceptions():
_capture_exception(exc, manual_span_cleanup=False)
_capture_exception(exc)
reraise(*exc_info)

_set_embeddings_output_data(
Expand Down Expand Up @@ -1260,6 +1257,7 @@ def _new_sync_responses_create(f: "Any", *args: "Any", **kwargs: "Any") -> "Any"
exc_info = sys.exc_info()
with capture_internal_exceptions():
_capture_exception(exc)
span.__exit__(None, None, None)
reraise(*exc_info)

# Attribute check to fail gracefully if the attribute is not present in future `openai` versions.
Expand Down Expand Up @@ -1317,6 +1315,7 @@ async def _new_async_responses_create(f: "Any", *args: "Any", **kwargs: "Any") -
exc_info = sys.exc_info()
with capture_internal_exceptions():
_capture_exception(exc)
span.__exit__(None, None, None)
reraise(*exc_info)

# Attribute check to fail gracefully if the attribute is not present in future `openai` versions.
Expand Down
Loading