Coverage for app / util / observability.py: 81%

84 statements  

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

1""" 

2Lightweight observability utilities for svc-ai. 

3 

4Provides: 

5 setup_tracing() — configure OTLP trace exporter and LiteLLM OTEL callback. 

6 LLMSpan — structured dataclass for a single LLM invocation; call .log() to emit. 

7""" 

8 

9from __future__ import annotations 

10 

11import logging 

12import os 

13from dataclasses import dataclass, field 

14from typing import Any 

15 

16 

17from langchain_core.callbacks.base import BaseCallbackHandler as _LCBaseCallbackHandler 

18 

19 

20class LangChainOtelHandler(_LCBaseCallbackHandler): 

21 """LangChain callback handler that creates OTEL child spans for tool executions. 

22 

23 Instantiate once per agent invocation and pass via RunnableConfig(callbacks=[...]). 

24 Tool spans are automatically parented to whichever OTEL span is current at the time 

25 the tool starts (typically a `graph.node.*` span set by _span_node in graph.py). 

26 The handler never raises — errors are silently ignored so agent execution is unaffected. 

27 """ 

28 

29 raise_error = False 

30 

31 def __init__(self) -> None: 

32 super().__init__() 

33 from opentelemetry import trace 

34 

35 self._tracer = trace.get_tracer("svc-ai.tools") 

36 self._spans: dict[str, Any] = {} 

37 

38 def on_tool_start( 

39 self, 

40 serialized: dict[str, Any], 

41 input_str: str, 

42 *, 

43 run_id: Any, 

44 **kwargs: Any, 

45 ) -> None: 

46 try: 

47 from opentelemetry import context as otel_ctx 

48 

49 tool_name = serialized.get("name", "tool") 

50 span = self._tracer.start_span( 

51 f"tool.{tool_name}", 

52 context=otel_ctx.get_current(), 

53 ) 

54 if span.is_recording(): 

55 span.set_attribute("tool.name", tool_name) 

56 span.set_attribute("tool.input", str(input_str)[:500]) 

57 self._spans[str(run_id)] = span 

58 except Exception: 

59 pass 

60 

61 def on_tool_end(self, output: str, *, run_id: Any, **kwargs: Any) -> None: 

62 try: 

63 span = self._spans.pop(str(run_id), None) 

64 if span and span.is_recording(): 

65 span.set_attribute("tool.output", str(output)[:500]) 

66 span.end() 

67 except Exception: 

68 pass 

69 

70 def on_tool_error(self, error: Any, *, run_id: Any, **kwargs: Any) -> None: 

71 try: 

72 from opentelemetry import trace as otel_trace 

73 

74 span = self._spans.pop(str(run_id), None) 

75 if span and span.is_recording(): 

76 exc = error if isinstance(error, Exception) else Exception(str(error)) 

77 span.record_exception(exc) 

78 span.set_status(otel_trace.StatusCode.ERROR, str(error)) 

79 span.end() 

80 except Exception: 

81 pass 

82 

83 

84def setup_tracing(service_name: str = "svc-ai") -> bool: 

85 """Configure OpenTelemetry with OTLP export and enable LiteLLM's OTEL callback. 

86 

87 Reads OTEL_EXPORTER_OTLP_ENDPOINT from the environment. Returns True when 

88 tracing is successfully initialised, False when the endpoint is absent or 

89 the SDK is unavailable (so callers can log a warning but not hard-fail). 

90 """ 

91 endpoint = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT") 

92 if not endpoint: 

93 return False 

94 

95 try: 

96 from opentelemetry import trace 

97 from opentelemetry.sdk.resources import Resource, SERVICE_NAME 

98 from opentelemetry.sdk.trace import TracerProvider 

99 from opentelemetry.sdk.trace.export import BatchSpanProcessor 

100 from opentelemetry.exporter.otlp.proto.http.trace_exporter import ( 

101 OTLPSpanExporter, 

102 ) 

103 

104 resource = Resource.create({SERVICE_NAME: service_name}) 

105 provider = TracerProvider(resource=resource) 

106 exporter = OTLPSpanExporter(endpoint=f"{endpoint.rstrip('/')}/v1/traces") 

107 provider.add_span_processor(BatchSpanProcessor(exporter)) 

108 trace.set_tracer_provider(provider) 

109 

110 import litellm 

111 

112 litellm.success_callback = list( 

113 set(getattr(litellm, "success_callback", []) or []) | {"otel"} 

114 ) 

115 litellm.failure_callback = list( 

116 set(getattr(litellm, "failure_callback", []) or []) | {"otel"} 

117 ) 

118 

119 return True 

120 except Exception: 

121 return False 

122 

123 

124@dataclass 

125class LLMSpan: 

126 """Structured record for one LLM invocation inside an agent.""" 

127 

128 agent: str 

129 model: str = "" 

130 iteration: int = 0 

131 prompt_tokens: int = 0 

132 completion_tokens: int = 0 

133 latency_ms: int = 0 

134 tool_calls: list[str] = field(default_factory=list) 

135 error: str | None = None 

136 cost_usd: float | None = None 

137 

138 def log(self, logger: logging.Logger | logging.LoggerAdapter) -> None: 

139 from opentelemetry import trace as _otel 

140 

141 ctx = _otel.get_current_span().get_span_context() 

142 trace_id = format(ctx.trace_id, "032x") if ctx.is_valid else "none" 

143 status = "error" if self.error else "ok" 

144 cost_part = ( 

145 f" cost_usd={self.cost_usd:.8f}" if self.cost_usd is not None else "" 

146 ) 

147 logger.info( 

148 "llm_span agent=%s model=%s iter=%d status=%s " 

149 "prompt_tokens=%d completion_tokens=%d latency_ms=%d tools=%s trace_id=%s%s", 

150 self.agent, 

151 self.model or "?", 

152 self.iteration, 

153 status, 

154 self.prompt_tokens, 

155 self.completion_tokens, 

156 self.latency_ms, 

157 ",".join(self.tool_calls) if self.tool_calls else "none", 

158 trace_id, 

159 cost_part, 

160 ) 

161 if self.error: 

162 logger.warning( 

163 "llm_span_error agent=%s trace_id=%s error=%s", 

164 self.agent, 

165 trace_id, 

166 self.error, 

167 )