Skip to content

Commit a5e5000

Browse files
committed
openai: Guard span ending based on the flag rather than the context manager
1 parent 47e8356 commit a5e5000

File tree

1 file changed

+7
-9
lines changed
  • instrumentation/elastic-opentelemetry-instrumentation-openai/src/opentelemetry/instrumentation/openai

1 file changed

+7
-9
lines changed

instrumentation/elastic-opentelemetry-instrumentation-openai/src/opentelemetry/instrumentation/openai/wrappers.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -67,9 +67,13 @@ def __init__(
6767
self.choices = []
6868
self.usage = None
6969
self.service_tier = None
70-
self.in_context_manager = False
70+
self.ended = False
7171

7272
def end(self, exc=None):
73+
if self.ended:
74+
return
75+
76+
self.ended = True
7377
if exc is not None:
7478
self.span.set_status(StatusCode.ERROR, str(exc))
7579
self.span.set_attribute(ERROR_TYPE, exc.__class__.__qualname__)
@@ -113,8 +117,6 @@ def process_chunk(self, chunk):
113117
self.service_tier = chunk.service_tier
114118

115119
def __enter__(self):
116-
# flag we are inside a context manager and want to follow its lifetime
117-
self.in_context_manager = True
118120
return self
119121

120122
def __exit__(self, exc_type, exc_value, traceback):
@@ -131,9 +133,7 @@ def __iter__(self):
131133
except Exception as exc:
132134
self.end(exc)
133135
raise
134-
# if we are inside a context manager we'll end when exiting it
135-
if not self.in_context_manager:
136-
self.end()
136+
self.end()
137137

138138
async def __aenter__(self):
139139
# No difference in behavior between sync and async context manager
@@ -153,6 +153,4 @@ async def __aiter__(self):
153153
except Exception as exc:
154154
self.end(exc)
155155
raise
156-
# if we are inside a context manager we'll end when exiting it
157-
if not self.in_context_manager:
158-
self.end()
156+
self.end()

0 commit comments

Comments
 (0)