Skip to content

Commit b1a8b63

Browse files
fix(openai): Avoid double exit causing an unraisable exception (#4736)
Add parameter to the method capturing exceptions in the OpenAI integration, to determine if the span context is closed with __exit__() or not. The option is used to prevent double exit scenarios when a span context is managed automatically. Related to: #4723
1 parent 65755f9 commit b1a8b63

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

sentry_sdk/integrations/openai.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -78,12 +78,12 @@ def count_tokens(self, s):
7878
return 0
7979

8080

81-
def _capture_exception(exc):
82-
# type: (Any) -> None
81+
def _capture_exception(exc, manual_span_cleanup=True):
82+
# type: (Any, bool) -> None
8383
# Close an eventually open span
8484
# We need to do this by hand because we are not using the start_span context manager
8585
current_span = sentry_sdk.get_current_span()
86-
if current_span is not None:
86+
if manual_span_cleanup and current_span is not None:
8787
current_span.__exit__(None, None, None)
8888

8989
event, hint = event_from_exception(
@@ -516,7 +516,7 @@ def _execute_sync(f, *args, **kwargs):
516516
try:
517517
result = f(*args, **kwargs)
518518
except Exception as e:
519-
_capture_exception(e)
519+
_capture_exception(e, manual_span_cleanup=False)
520520
raise e from None
521521

522522
return gen.send(result)
@@ -550,7 +550,7 @@ async def _execute_async(f, *args, **kwargs):
550550
try:
551551
result = await f(*args, **kwargs)
552552
except Exception as e:
553-
_capture_exception(e)
553+
_capture_exception(e, manual_span_cleanup=False)
554554
raise e from None
555555

556556
return gen.send(result)

0 commit comments

Comments
 (0)