|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import json |
| 4 | +from collections import OrderedDict |
| 5 | +from collections.abc import Mapping |
| 6 | +from contextvars import ContextVar |
| 7 | +from typing import Any |
| 8 | + |
| 9 | +from opentelemetry.context import Context |
| 10 | +from opentelemetry.sdk.trace import ReadableSpan, SpanProcessor, TracerProvider |
| 11 | +from opentelemetry.semconv._incubating.attributes.gen_ai_attributes import ( # No public import for these constants yet |
| 12 | + GEN_AI_INPUT_MESSAGES, |
| 13 | + GEN_AI_OPERATION_NAME, |
| 14 | + GEN_AI_OUTPUT_MESSAGES, |
| 15 | + GEN_AI_REQUEST_MAX_TOKENS, |
| 16 | + GEN_AI_REQUEST_MODEL, |
| 17 | + GEN_AI_REQUEST_TEMPERATURE, |
| 18 | + GEN_AI_RESPONSE_MODEL, |
| 19 | + GEN_AI_SYSTEM, |
| 20 | + GEN_AI_TOOL_DEFINITIONS, |
| 21 | + GEN_AI_USAGE_INPUT_TOKENS, |
| 22 | + GEN_AI_USAGE_OUTPUT_TOKENS, |
| 23 | + GenAiOperationNameValues, |
| 24 | +) |
| 25 | +from opentelemetry.semconv.attributes.server_attributes import SERVER_ADDRESS, SERVER_PORT |
| 26 | +from opentelemetry.trace import Span |
| 27 | +from posthog.client import Client as PostHogClient |
| 28 | + |
| 29 | +from stirling.config import AppSettings |
| 30 | + |
| 31 | +# Per-request user ID, set by middleware from the X-User-Id header. |
| 32 | +# When not set, PostHog generates a random ID and marks the event as personless. |
| 33 | +current_user_id: ContextVar[str | None] = ContextVar("current_user_id", default=None) |
| 34 | + |
| 35 | + |
| 36 | +class LRUSet: |
| 37 | + """Least Recently Used Set: a set with a maximum size that evicts the oldest entries first.""" |
| 38 | + |
| 39 | + def __init__(self, max_size: int) -> None: |
| 40 | + self._max_size = max_size |
| 41 | + self._data: OrderedDict[str, None] = OrderedDict() |
| 42 | + |
| 43 | + def __contains__(self, key: str) -> bool: |
| 44 | + return key in self._data |
| 45 | + |
| 46 | + def add(self, key: str) -> None: |
| 47 | + self._data[key] = None |
| 48 | + if len(self._data) > self._max_size: |
| 49 | + self._data.popitem(last=False) |
| 50 | + |
| 51 | + |
| 52 | +def _parse_json_attr(attrs: Mapping[str, Any], key: str) -> Any | None: |
| 53 | + """Parse a JSON string span attribute, returning None on failure.""" |
| 54 | + raw = attrs.get(key) |
| 55 | + if raw is None: |
| 56 | + return None |
| 57 | + try: |
| 58 | + return json.loads(str(raw)) |
| 59 | + except (json.JSONDecodeError, TypeError): |
| 60 | + return None |
| 61 | + |
| 62 | + |
| 63 | +def _transform_output_choices(choices: list[Any]) -> list[Any]: |
| 64 | + """Transform Pydantic AI's parts-based output format to PostHog-compatible format. |
| 65 | +
|
| 66 | + Pydantic AI emits: ``[{"role": "assistant", "parts": [{"type": "tool_call", "name": "..."}]}]`` |
| 67 | + PostHog expects: ``[{"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "..."}}]}]`` |
| 68 | + """ |
| 69 | + for choice in choices: |
| 70 | + if not isinstance(choice, dict) or "parts" not in choice: |
| 71 | + continue |
| 72 | + tool_calls = [] |
| 73 | + for part in choice.get("parts", []): |
| 74 | + if isinstance(part, dict) and part.get("type") == "tool_call": |
| 75 | + tool_calls.append( |
| 76 | + { |
| 77 | + "type": "function", |
| 78 | + "id": part.get("id", ""), |
| 79 | + "function": {"name": part.get("name", "")}, |
| 80 | + } |
| 81 | + ) |
| 82 | + if tool_calls: |
| 83 | + choice["tool_calls"] = tool_calls |
| 84 | + choice["content"] = choice.pop("parts") |
| 85 | + return choices |
| 86 | + |
| 87 | + |
| 88 | +def _extract_user_message(attrs: Mapping[str, Any]) -> str: |
| 89 | + """Extract the last user message text from the input messages span attribute.""" |
| 90 | + messages = _parse_json_attr(attrs, GEN_AI_INPUT_MESSAGES) |
| 91 | + if not isinstance(messages, list): |
| 92 | + return "" |
| 93 | + for msg in reversed(messages): |
| 94 | + if not isinstance(msg, dict): |
| 95 | + continue |
| 96 | + if msg.get("role") == "user": |
| 97 | + for part in msg.get("parts", []): |
| 98 | + if isinstance(part, dict) and part.get("type") == "text": |
| 99 | + return str(part.get("content", "")) |
| 100 | + return "" |
| 101 | + |
| 102 | + |
| 103 | +# TODO: Replace with an official PostHog integration if one ever exists |
| 104 | +class PostHogSpanProcessor(SpanProcessor): |
| 105 | + """Translates Pydantic AI OpenTelemetry spans into PostHog $ai_generation events.""" |
| 106 | + |
| 107 | + def __init__(self, client: PostHogClient) -> None: |
| 108 | + self._client = client |
| 109 | + self._seen_traces = LRUSet(max_size=10_000) |
| 110 | + |
| 111 | + def on_start(self, span: Span, parent_context: Context | None = None) -> None: |
| 112 | + pass |
| 113 | + |
| 114 | + def on_end(self, span: ReadableSpan) -> None: |
| 115 | + attrs = dict(span.attributes or {}) |
| 116 | + if attrs.get(GEN_AI_OPERATION_NAME) != GenAiOperationNameValues.CHAT.value: |
| 117 | + return |
| 118 | + |
| 119 | + properties = self._build_generation_properties(span, attrs) |
| 120 | + self._maybe_emit_trace_event(span, attrs, properties) |
| 121 | + self._client.capture( |
| 122 | + distinct_id=current_user_id.get(), |
| 123 | + event="$ai_generation", |
| 124 | + properties=properties, |
| 125 | + ) |
| 126 | + |
| 127 | + def _build_generation_properties(self, span: ReadableSpan, attrs: Mapping[str, Any]) -> dict[str, object]: |
| 128 | + """Build the $ai_generation event properties from span data.""" |
| 129 | + properties: dict[str, object] = { |
| 130 | + "$ai_provider": attrs.get(GEN_AI_SYSTEM, ""), |
| 131 | + "$ai_model": attrs.get(GEN_AI_RESPONSE_MODEL) or attrs.get(GEN_AI_REQUEST_MODEL, ""), |
| 132 | + "$ai_input_tokens": attrs.get(GEN_AI_USAGE_INPUT_TOKENS, 0), |
| 133 | + "$ai_output_tokens": attrs.get(GEN_AI_USAGE_OUTPUT_TOKENS, 0), |
| 134 | + } |
| 135 | + |
| 136 | + if span.context: |
| 137 | + properties["$ai_trace_id"] = format(span.context.trace_id, "032x") |
| 138 | + properties["$ai_span_id"] = format(span.context.span_id, "016x") |
| 139 | + if span.parent and span.parent.span_id: |
| 140 | + properties["$ai_parent_id"] = format(span.parent.span_id, "016x") |
| 141 | + if span.start_time and span.end_time: |
| 142 | + properties["$ai_latency"] = (span.end_time - span.start_time) / 1e9 |
| 143 | + |
| 144 | + self._add_message_properties(properties, attrs) |
| 145 | + self._add_model_parameters(properties, attrs) |
| 146 | + self._add_tool_definitions(properties, attrs) |
| 147 | + self._add_base_url(properties, attrs) |
| 148 | + |
| 149 | + return properties |
| 150 | + |
| 151 | + def _maybe_emit_trace_event( |
| 152 | + self, span: ReadableSpan, attrs: Mapping[str, Any], properties: dict[str, object] |
| 153 | + ) -> None: |
| 154 | + """Emit an $ai_trace event for the first span seen per trace ID.""" |
| 155 | + trace_id = str(properties.get("$ai_trace_id", "")) |
| 156 | + if not trace_id or trace_id in self._seen_traces: |
| 157 | + return |
| 158 | + |
| 159 | + self._seen_traces.add(trace_id) |
| 160 | + trace_properties: dict[str, object] = { |
| 161 | + "$ai_trace_id": trace_id, |
| 162 | + "$ai_trace_name": _extract_user_message(attrs), |
| 163 | + "$ai_provider": attrs.get(GEN_AI_SYSTEM, ""), |
| 164 | + } |
| 165 | + if span.start_time and span.end_time: |
| 166 | + trace_properties["$ai_latency"] = (span.end_time - span.start_time) / 1e9 |
| 167 | + self._client.capture( |
| 168 | + distinct_id=current_user_id.get(), |
| 169 | + event="$ai_trace", |
| 170 | + properties=trace_properties, |
| 171 | + ) |
| 172 | + |
| 173 | + @staticmethod |
| 174 | + def _add_message_properties(properties: dict[str, object], attrs: Mapping[str, Any]) -> None: |
| 175 | + input_messages = _parse_json_attr(attrs, GEN_AI_INPUT_MESSAGES) |
| 176 | + if input_messages is not None: |
| 177 | + properties["$ai_input"] = input_messages |
| 178 | + |
| 179 | + output_messages = _parse_json_attr(attrs, GEN_AI_OUTPUT_MESSAGES) |
| 180 | + if isinstance(output_messages, list): |
| 181 | + properties["$ai_output_choices"] = _transform_output_choices(output_messages) |
| 182 | + elif output_messages is not None: |
| 183 | + properties["$ai_output_choices"] = output_messages |
| 184 | + |
| 185 | + @staticmethod |
| 186 | + def _add_model_parameters(properties: dict[str, object], attrs: Mapping[str, Any]) -> None: |
| 187 | + model_parameters: dict[str, object] = {} |
| 188 | + if GEN_AI_REQUEST_TEMPERATURE in attrs: |
| 189 | + model_parameters["temperature"] = attrs[GEN_AI_REQUEST_TEMPERATURE] |
| 190 | + if GEN_AI_REQUEST_MAX_TOKENS in attrs: |
| 191 | + model_parameters["max_tokens"] = attrs[GEN_AI_REQUEST_MAX_TOKENS] |
| 192 | + if model_parameters: |
| 193 | + properties["$ai_model_parameters"] = model_parameters |
| 194 | + |
| 195 | + @staticmethod |
| 196 | + def _add_tool_definitions(properties: dict[str, object], attrs: Mapping[str, Any]) -> None: |
| 197 | + tools = _parse_json_attr(attrs, GEN_AI_TOOL_DEFINITIONS) |
| 198 | + if tools is not None: |
| 199 | + properties["$ai_tools"] = tools |
| 200 | + |
| 201 | + @staticmethod |
| 202 | + def _add_base_url(properties: dict[str, object], attrs: Mapping[str, Any]) -> None: |
| 203 | + parts: list[str] = [] |
| 204 | + if host := attrs.get(SERVER_ADDRESS): |
| 205 | + parts.append(str(host)) |
| 206 | + if port := attrs.get(SERVER_PORT): |
| 207 | + parts.append(str(port)) |
| 208 | + if parts: |
| 209 | + properties["$ai_base_url"] = ":".join(parts) |
| 210 | + |
| 211 | + def shutdown(self) -> None: |
| 212 | + self._client.shutdown() |
| 213 | + |
| 214 | + def force_flush(self, timeout_millis: int = 30000) -> bool: |
| 215 | + self._client.flush() |
| 216 | + return True |
| 217 | + |
| 218 | + |
| 219 | +def setup_posthog_tracking(settings: AppSettings) -> TracerProvider | None: |
| 220 | + """Configure OpenTelemetry with a PostHog span processor for LLM analytics. |
| 221 | +
|
| 222 | + Returns the TracerProvider so it can be shut down on app exit, |
| 223 | + or None when tracking is disabled. |
| 224 | + """ |
| 225 | + if not settings.posthog_enabled or not settings.posthog_api_key: |
| 226 | + return None |
| 227 | + |
| 228 | + client = PostHogClient(project_api_key=settings.posthog_api_key, host=settings.posthog_host) |
| 229 | + processor = PostHogSpanProcessor(client) |
| 230 | + |
| 231 | + provider = TracerProvider() |
| 232 | + provider.add_span_processor(processor) |
| 233 | + return provider |
0 commit comments