Coverage for app / inference / tracer.py: 64%

28 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1""" 

2InferenceTracer — OTEL span management for inference engines. 

3 

4Provides a thin wrapper around the OpenTelemetry tracer so engines don't 

5import opentelemetry directly and the span lifecycle is uniform across all 

6execution types. 

7""" 

8 

9from __future__ import annotations 

10 

11from contextlib import contextmanager 

12from typing import Any, Generator 

13 

14from opentelemetry import trace as _otel_trace 

15 

16_tracer = _otel_trace.get_tracer("svc-ai.inference") 

17 

18 

19class InferenceTracer: 

20 """ 

21 Manages OTEL spans for one inference execution. 

22 

23 Usage:: 

24 

25 tracer = InferenceTracer() 

26 with tracer.root_span("agent", user_id="u1", session_id="s1") as span: 

27 tracer.set_input(span, request.input) 

28 result = await engine._do_infer(ctx) 

29 tracer.set_output(span, result.output) 

30 """ 

31 

32 @contextmanager 

33 def root_span( 

34 self, 

35 execution_type: str, 

36 **attributes: Any, 

37 ) -> Generator[Any, None, None]: 

38 """Open a root ``inference.<type>`` span, yield it, then close it.""" 

39 span_attrs: dict[str, str] = { 

40 "inference.type": execution_type, 

41 **{k: str(v) for k, v in attributes.items() if v is not None}, 

42 } 

43 with _tracer.start_as_current_span( 

44 f"inference.{execution_type}", attributes=span_attrs 

45 ) as span: 

46 yield span 

47 

48 # ── Attribute helpers ───────────────────────────────────────────────────── 

49 

50 def set_input(self, span: Any, text: str) -> None: 

51 if span and span.is_recording(): 

52 span.set_attribute("llm.input", text[:2000]) 

53 

54 def set_output(self, span: Any, text: str) -> None: 

55 if span and span.is_recording(): 

56 span.set_attribute("llm.output", text[:2000]) 

57 

58 def set_error(self, span: Any, exc: Exception) -> None: 

59 if span and span.is_recording(): 

60 span.record_exception(exc) 

61 span.set_status(_otel_trace.StatusCode.ERROR, str(exc)) 

62 

63 def set_usage(self, span: Any, usage: dict[str, Any]) -> None: 

64 if span and span.is_recording(): 

65 span.set_attribute("llm.prompt_tokens", usage.get("prompt_tokens", 0)) 

66 span.set_attribute( 

67 "llm.completion_tokens", usage.get("completion_tokens", 0) 

68 ) 

69 cost = usage.get("estimated_cost_usd") 

70 if cost is not None: 

71 span.set_attribute("llm.cost_usd", float(cost))