Skip to content

Commit 82e4bff

Browse files
committed
cleanup some duplicated code
1 parent 0d4f204 commit 82e4bff

File tree

1 file changed

+19
-18
lines changed
  • util/opentelemetry-util-genai/src/opentelemetry/util/genai

1 file changed

+19
-18
lines changed

util/opentelemetry-util-genai/src/opentelemetry/util/genai/generators.py

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,21 @@ def _maybe_set_span_messages(
163163
)
164164

165165

166+
def _apply_finish_attributes(span: Span, invocation: LLMInvocation) -> None:
167+
"""Apply attributes/messages common to finish() paths."""
168+
_apply_common_span_attributes(span, invocation)
169+
_maybe_set_span_messages(
170+
span, invocation.messages, invocation.chat_generations
171+
)
172+
173+
174+
def _apply_error_attributes(span: Span, error: Error) -> None:
175+
"""Apply status and error attributes common to error() paths."""
176+
span.set_status(Status(StatusCode.ERROR, error.message))
177+
if span.is_recording():
178+
span.set_attribute(ErrorAttributes.ERROR_TYPE, error.type.__qualname__)
179+
180+
166181
class BaseTelemetryGenerator:
167182
"""
168183
Abstract base for emitters mapping GenAI types -> OpenTelemetry.
@@ -266,36 +281,22 @@ def finish(self, invocation: LLMInvocation):
266281
state = self.spans.get(invocation.run_id)
267282
if state is None:
268283
with self._start_span_for_invocation(invocation) as span:
269-
_apply_common_span_attributes(span, invocation)
270-
_maybe_set_span_messages(
271-
span, invocation.messages, invocation.chat_generations
272-
)
284+
_apply_finish_attributes(span, invocation)
273285
self._finalize_invocation(invocation)
274286
return
275287

276288
span = state.span
277-
_apply_common_span_attributes(span, invocation)
278-
_maybe_set_span_messages(
279-
span, invocation.messages, invocation.chat_generations
280-
)
289+
_apply_finish_attributes(span, invocation)
281290
self._finalize_invocation(invocation)
282291

283292
def error(self, error: Error, invocation: LLMInvocation):
284293
state = self.spans.get(invocation.run_id)
285294
if state is None:
286295
with self._start_span_for_invocation(invocation) as span:
287-
span.set_status(Status(StatusCode.ERROR, error.message))
288-
if span.is_recording():
289-
span.set_attribute(
290-
ErrorAttributes.ERROR_TYPE, error.type.__qualname__
291-
)
296+
_apply_error_attributes(span, error)
292297
self._finalize_invocation(invocation)
293298
return
294299

295300
span = state.span
296-
span.set_status(Status(StatusCode.ERROR, error.message))
297-
if span.is_recording():
298-
span.set_attribute(
299-
ErrorAttributes.ERROR_TYPE, error.type.__qualname__
300-
)
301+
_apply_error_attributes(span, error)
301302
self._finalize_invocation(invocation)

0 commit comments

Comments
 (0)