Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(tracing): add ai-events lookup for a trace (#105722)

Jon McCallumbfc543147d0d
diff --git a/products/tracing/backend/ai_events.py b/products/tracing/backend/ai_events.py
new file mode 100644
index 000000000000..cd3f9f103777
--- /dev/null
+++ b/products/tracing/backend/ai_events.py
@@ -0,0 +1,117 @@
+from datetime import datetime
+from typing import TYPE_CHECKING
+from uuid import UUID
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.dataclasses import frozen
+
+if TYPE_CHECKING:
+ from posthog.models import Team, User
+
+# A run rarely makes more than a few hundred model calls, and past this many rows the waterfall
+# stops being readable, so the lookup does not page.
+MAX_AI_EVENTS_PER_TRACE = 500
+
+# The LLM analytics event kinds that carry a latency, so each one can be placed on the timeline.
+AI_EVENT_KINDS = ["$ai_generation", "$ai_span", "$ai_embedding"]
+
+
+# OTel ingestion stamps an event with the span's start, while the PostHog AI SDKs and the LLM
+# gateway stamp it when the call finished. The source marker tells the two apart.
+OTEL_INGESTION_SOURCE = "otel"
+
+# `$ai_latency` is sender-controlled. Past this a value is junk rather than a slow call.
+MAX_LATENCY_SECONDS = 7 * 24 * 60 * 60
+
+
+@frozen
+class TraceAiEvent:
+ uuid: str
+ event: str
+ started_at: datetime
+ ai_trace_id: str
+ ai_span_id: str | None
+ ai_parent_id: str | None
+ span_name: str | None
+ latency_seconds: float | None
+ model: str | None
+ provider: str | None
+ input_tokens: int | None
+ output_tokens: int | None
+ total_cost_usd: float | None
+ is_error: bool
+
+
+def fetch_trace_ai_events(*, team: "Team", user: "User | None", trace_id: str) -> list[TraceAiEvent]:
+ """LLM analytics events whose `$ai_trace_id` is the OpenTelemetry trace id, earliest start
+ first. Matches the 32-hex form OTel ingestion writes and the hyphenated UUID form the LLM
+ gateway writes for a `traceparent` header.
+
+ Reads `ai_events`, whose sort key starts with `(team_id, trace_id)`, so a trace with no AI
+ events costs a primary-key miss rather than a scan. That is why the lookup does not fall back
+ to the shared events table: most APM traces have no AI events, and a fallback would scan the
+ team's events on every one of them. There is no time window: the trace id already bounds the
+ read, and the table partitions by retention date rather than event time, so a window prunes
+ nothing. Rows older than the ai_events retention are not found.
+
+ The requesting user is passed through so property access rules mask restricted AI columns for
+ that user rather than falling back to the team default.
+ """
+ # `$ai_latency` is sender-controlled, so the same guard that keeps a junk value out of the
+ # response keeps it out of the start-time arithmetic. The start is computed in the query
+ # because the order and the row cap have to follow it, not the stamped time.
+ query = parse_select(
+ """
+ SELECT
+ uuid,
+ any(event) AS event_name,
+ any(trace_id) AS ai_trace_id,
+ any(span_id) AS ai_span_id,
+ any(parent_id) AS ai_parent_id,
+ any(span_name) AS span_name,
+ any(if(isFinite(latency) AND latency >= 0 AND latency <= {max_latency}, latency, NULL)) AS latency_seconds,
+ any(model) AS model,
+ any(provider) AS provider,
+ any(input_tokens) AS input_tokens,
+ any(output_tokens) AS output_tokens,
+ any(total_cost_usd) AS total_cost_usd,
+ any(is_error) AS is_error,
+ any(if(
+ properties.$ai_ingestion_source = {otel_source} OR isNull(latency) OR NOT isFinite(latency) OR latency < 0 OR latency > {max_latency},
+ timestamp,
+ fromUnixTimestamp64Milli(toUnixTimestamp64Milli(timestamp) - toInt(latency * 1000))
+ )) AS started_at
+ FROM posthog.ai_events
+ WHERE trace_id IN {trace_ids}
+ AND event IN {events}
+ GROUP BY uuid
+ ORDER BY started_at ASC
+ LIMIT {limit}
+ """,
+ placeholders={
+ "events": ast.Constant(value=AI_EVENT_KINDS),
+ # Spans read their ids back as uppercase hex, while OTel ingestion writes them
+ # lowercase. Both forms are constants, so the lookup stays on the sort key.
+ "trace_ids": ast.Constant(value=_stored_trace_id_forms(trace_id)),
+ "otel_source": ast.Constant(value=OTEL_INGESTION_SOURCE),
+ "max_latency": ast.Constant(value=MAX_LATENCY_SECONDS),
+ # Explicit, because HogQL caps a select without a LIMIT at 100 rows.
+ "limit": ast.Constant(value=MAX_AI_EVENTS_PER_TRACE),
+ },
+ )
+ response = execute_hogql_query(query=query, team=team, user=user, query_type="TracingTraceAiEventsQuery")
+ # The event alias differs from the column it aggregates, because an alias equal to a column
+ # name shadows it in WHERE and ClickHouse then rejects the aggregate there.
+ columns = [{"event_name": "event"}.get(c, c) for c in response.columns or []]
+ return [TraceAiEvent(**dict(zip(columns, row))) for row in response.results or []]
+
+
+def _stored_trace_id_forms(trace_id: str) -> list[str]:
+ hex_form = trace_id.lower()
+ try:
+ return [hex_form, str(UUID(hex=hex_form))]
+ except ValueError:
+ return [hex_form]
diff --git a/products/tracing/backend/facade/api.py b/products/tracing/backend/facade/api.py
index af2fb6b4c915..f074dd17c821 100644
--- a/products/tracing/backend/facade/api.py
+++ b/products/tracing/backend/facade/api.py
@@ -34,6 +34,10 @@ from posthog.schema import (
TraceSpansSymbolStatsQueryResponse,
)
+from products.tracing.backend.ai_events import (
+ TraceAiEvent,
+ fetch_trace_ai_events as _fetch_trace_ai_events,
+)
from products.tracing.backend.attribute_breakdown_query_runner import (
FACET_COLUMNS as _FACET_COLUMNS,
run_attribute_breakdown_query as _run_attribute_breakdown_query,
@@ -56,7 +60,7 @@ from products.tracing.backend.self_time import annotate_self_time as _annotate_s
from products.tracing.backend.symbol_stats_query_runner import run_symbol_stats_query as _run_symbol_stats_query
if TYPE_CHECKING:
- from posthog.models import Team
+ from posthog.models import Team, User
# Allowlisted top-level span columns for the "span" breakdown type. Re-exported so the
@@ -240,3 +244,12 @@ def count_session_exceptions(
A session with no such exceptions is absent from the result rather than present with a zero.
"""
return _count_session_exceptions(team=team, session_ids=session_ids, date_from=date_from, date_to=date_to)
+
+
+def fetch_trace_ai_events(*, team: "Team", user: "User | None", trace_id: str) -> list[TraceAiEvent]:
+ """List the LLM analytics events whose `$ai_trace_id` is the trace id, as lowercase hex or as
+ the hyphenated UUID the LLM gateway writes, earliest start first. The events side of the
+ trace-to-AI-events join, which the caller finishes. The user's property access rules apply to
+ the returned columns.
+ """
+ return _fetch_trace_ai_events(team=team, user=user, trace_id=trace_id)
diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.py
index 9b539060a337..0ff70435aab2 100644
--- a/products/tracing/backend/presentation/views.py
+++ b/products/tracing/backend/presentation/views.py
@@ -13,6 +13,7 @@ No business logic here - that belongs in logic.py via the facade.
import json
import base64
from collections.abc import Callable
+from typing import cast
from django.db import models
@@ -45,7 +46,9 @@ from posthog.errors import CHQueryErrorTooManyBytes
from posthog.event_usage import report_user_action
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.query_runner import ExecutionMode
+from posthog.models import User
from posthog.models.property.property import STRING_PREFIX_SUFFIX_OPERATORS
+from posthog.permissions import posthog_feature_flag_enabled
from ..facade.api import (
FACET_COLUMNS,
@@ -54,6 +57,7 @@ from ..facade.api import (
count_session_exceptions,
count_span_exceptions,
count_trace_exceptions,
+ fetch_trace_ai_events,
run_attribute_breakdown_query,
run_count_query,
run_duration_histogram_query,
@@ -75,6 +79,9 @@ from ..logic import (
from ..sparkline_query_runner import TraceSpansSparklineQueryRunner
from .date_window import normalize_tracing_date_range
+# Matches FEATURE_FLAGS.TRACING_AI_EVENTS in the frontend.
+TRACING_AI_EVENTS_FEATURE_FLAG = "tracing-ai-events"
+
def _serialize_compare_rows(compare_rows: list | None) -> list[dict] | None:
"""Serialize comparison-window rows for a response.
@@ -827,6 +834,34 @@ class _TracingTraceResponseSerializer(serializers.Serializer):
)
+class _TracingTraceAiEventSerializer(serializers.Serializer):
+ uuid = serializers.CharField(help_text="Event UUID.")
+ event = serializers.CharField(
+ help_text="The LLM analytics event kind: `$ai_generation`, `$ai_span` or `$ai_embedding`."
+ )
+ started_at = serializers.DateTimeField(
+ help_text="When the call started. Add `latency_seconds` for when it finished. Normalized across OpenTelemetry-sourced events, which are stamped at the start, and SDK-sourced events, which are stamped at the finish."
+ )
+ ai_trace_id = serializers.CharField(help_text="The `$ai_trace_id` of the event, which opens it in LLM analytics.")
+ ai_span_id = serializers.CharField(allow_null=True, help_text="The `$ai_span_id` of the event.")
+ ai_parent_id = serializers.CharField(
+ allow_null=True,
+ help_text="The `$ai_parent_id` of the event. For OpenTelemetry-sourced events this is the parent span's id.",
+ )
+ span_name = serializers.CharField(allow_null=True, help_text="The `$ai_span_name`, set on `$ai_span` events.")
+ latency_seconds = serializers.FloatField(allow_null=True, help_text="How long the call took, in seconds.")
+ model = serializers.CharField(allow_null=True, help_text="The model the call used.")
+ provider = serializers.CharField(allow_null=True, help_text="The provider the call went to.")
+ input_tokens = serializers.IntegerField(allow_null=True, help_text="Prompt tokens.")
+ output_tokens = serializers.IntegerField(allow_null=True, help_text="Completion tokens.")
+ total_cost_usd = serializers.FloatField(allow_null=True, help_text="Total cost of the call, in USD.")
+ is_error = serializers.BooleanField(help_text="Whether the call failed.")
+
+
+class _TracingTraceAiEventsResponseSerializer(serializers.Serializer):
+ results = _TracingTraceAiEventSerializer(many=True, help_text="AI events in the trace, earliest start first.")
+
+
class _TracingSparklineRowSerializer(serializers.Serializer):
time = serializers.DateTimeField(help_text="Start of the time bucket.")
service = serializers.CharField(help_text="Service the count belongs to.")
@@ -1869,6 +1904,48 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
status=status.HTTP_200_OK,
)
+ @extend_schema(responses={200: _TracingTraceAiEventsResponseSerializer})
+ # Both scopes: the response is LLM analytics data, so a token scoped to tracing alone must
+ # not reach it. Scopes gate the token; the access-control check below gates the user.
+ @action(
+ detail=False,
+ methods=["GET"],
+ url_path="trace/(?P<trace_id>[a-zA-Z0-9]+)/ai_events",
+ required_scopes=["tracing:read", "llm_analytics:read"],
+ )
+ def trace_ai_events(self, request: Request, trace_id: str, *args, **kwargs) -> Response:
+ """List the LLM analytics events whose `$ai_trace_id` is this trace's id, so the waterfall
+ can show each model call inline with the spans.
+
+ The spans and the AI events live on different ClickHouse clusters, so one query cannot join
+ them; this returns the events half and the caller places them by time.
+ """
+ # The same flag gates the waterfall rows in the frontend, so the endpoint stays dark for
+ # everyone the drawer would not show them to.
+ if not posthog_feature_flag_enabled(
+ TRACING_AI_EVENTS_FEATURE_FLAG,
+ str(cast(User, request.user).distinct_id),
+ organization_id=self.team.organization_id,
+ team_id=self.team.pk,
+ ):
+ raise PermissionDenied("AI events in traces are not enabled for this user.")
+
+ if not self.user_access_control.check_access_level_for_resource("llm_analytics", "viewer"):
+ raise PermissionDenied("You do not have access to LLM analytics.")
+
+ tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)
+ try:
+ bytes.fromhex(trace_id)
+ except ValueError:
+ return Response(status=status.HTTP_400_BAD_REQUEST)
+
+ events = fetch_trace_ai_events(team=self.team, user=cast(User, request.user), trace_id=trace_id)
+
+ self._report_usage(request, "tracing trace ai events fetched", {"ai_events_count": len(events)})
+
+ response = _TracingTraceAiEventsResponseSerializer(instance={"results": events})
+ return Response(response.data, status=status.HTTP_200_OK)
+
@extend_schema(
parameters=[_TracingAttributesQuerySerializer],
responses={200: _TracingAttributesResponseSerializer},
diff --git a/products/tracing/backend/tests/test_trace_ai_events.py b/products/tracing/backend/tests/test_trace_ai_events.py
new file mode 100644
index 000000000000..7a67e54e20bc
--- /dev/null
+++ b/products/tracing/backend/tests/test_trace_ai_events.py
@@ -0,0 +1,184 @@
+import json
+from typing import Any
+from uuid import uuid4
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+from unittest.mock import patch
+
+from django.http import HttpResponse
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.constants import AvailableFeature
+from posthog.models import OrganizationMembership, User
+from posthog.models.ai_events.test_util import bulk_create_ai_events
+
+from products.access_control.backend.models.access_control import AccessControl
+
+# The form OTel ingestion writes: lowercase hex, 32 characters for a trace and 16 for a span.
+TRACE_A = "4bf92f3577b34da6a3ce929d0e0e4736"
+TRACE_B = "8a3c60f7d188f8fa79d48a391a778fa6"
+# The form the LLM gateway writes for the same trace from a `traceparent` header.
+TRACE_A_UUID = "4bf92f35-77b3-4da6-a3ce-929d0e0e4736"
+PARENT_SPAN = "00f067aa0ba902b7"
+
+
+class TestTraceAiEvents(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ flag_patcher = patch("posthoganalytics.feature_enabled", return_value=True)
+ flag_patcher.start()
+ self.addCleanup(flag_patcher.stop)
+
+ def _get(self, trace_id: str) -> HttpResponse:
+ return self.client.get(f"/api/projects/{self.team.id}/tracing/spans/trace/{trace_id}/ai_events/")
+
+ def _create_ai_event(
+ self,
+ trace_id: str,
+ *,
+ event: str = "$ai_generation",
+ timestamp: str = "2026-06-02T08:00:00Z",
+ properties: dict[str, Any] | None = None,
+ ) -> str:
+ event_uuid = str(uuid4())
+ _create_event(
+ event_uuid=event_uuid,
+ distinct_id="user-1",
+ event=event,
+ team=self.team,
+ properties={"$ai_trace_id": trace_id, **(properties or {})},
+ timestamp=timestamp,
+ )
+ return event_uuid
+
+ def test_lists_the_traces_ai_events_earliest_start_first(self) -> None:
+ generation = self._create_ai_event(
+ TRACE_A,
+ timestamp="2026-06-02T08:00:05Z",
+ properties={
+ "$ai_span_id": "b9c7c989f97918e1",
+ "$ai_parent_id": PARENT_SPAN,
+ "$ai_latency": 4.5,
+ "$ai_model": "model-x",
+ "$ai_provider": "provider-y",
+ "$ai_input_tokens": 120,
+ "$ai_output_tokens": 30,
+ "$ai_total_cost_usd": 0.0071,
+ "$ai_is_error": True,
+ },
+ )
+ span = self._create_ai_event(TRACE_A, event="$ai_span", timestamp="2026-06-02T08:00:01Z")
+ self._create_ai_event(TRACE_B)
+ self._create_ai_event(TRACE_A, event="$ai_feedback")
+ flush_persons_and_events()
+
+ response = self._get(TRACE_A.upper())
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ results = json.loads(response.content)["results"]
+ # The generation is stamped after the span but started before it, so it sorts first.
+ assert [row["uuid"] for row in results] == [generation, span]
+ assert results[0] == {
+ "uuid": generation,
+ "event": "$ai_generation",
+ "started_at": "2026-06-02T08:00:00.500000Z",
+ "ai_trace_id": TRACE_A,
+ "ai_span_id": "b9c7c989f97918e1",
+ "ai_parent_id": PARENT_SPAN,
+ "span_name": None,
+ "latency_seconds": 4.5,
+ "model": "model-x",
+ "provider": "provider-y",
+ "input_tokens": 120,
+ "output_tokens": 30,
+ "total_cost_usd": 0.0071,
+ "is_error": True,
+ }
+ assert results[1]["is_error"] is False
+
+ @parameterized.expand(
+ [
+ ("an SDK event stamped at the finish", {"$ai_latency": 4}, "2026-06-02T08:00:00Z", 4),
+ ("an SDK event with no latency", {}, "2026-06-02T08:00:04Z", None),
+ (
+ "an OTel event stamped at the start",
+ {"$ai_latency": 4, "$ai_ingestion_source": "otel"},
+ "2026-06-02T08:00:04Z",
+ 4,
+ ),
+ # A sender-controlled latency past any real call is dropped rather than overflowing.
+ ("a junk latency", {"$ai_latency": 1e20}, "2026-06-02T08:00:04Z", None),
+ ("a negative latency", {"$ai_latency": -3}, "2026-06-02T08:00:04Z", None),
+ ]
+ )
+ def test_normalizes_the_start_time_by_ingestion_source(
+ self, _name: str, properties: dict[str, Any], expected_start: str, expected_latency: float | None
+ ) -> None:
+ self._create_ai_event(TRACE_A, timestamp="2026-06-02T08:00:04Z", properties=properties)
+ flush_persons_and_events()
+
+ response = self._get(TRACE_A)
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ rows = json.loads(response.content)["results"]
+ assert [(row["started_at"], row["latency_seconds"]) for row in rows] == [(expected_start, expected_latency)]
+
+ def test_finds_the_gateway_uuid_form_of_the_trace_id(self) -> None:
+ by_uuid = self._create_ai_event(TRACE_A_UUID)
+ flush_persons_and_events()
+
+ response = self._get(TRACE_A)
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert [row["uuid"] for row in json.loads(response.content)["results"]] == [by_uuid]
+
+ def test_collapses_duplicate_rows_of_one_event(self) -> None:
+ # ai_events is a plain MergeTree fed by at-least-once ingestion, so one event can land twice.
+ row = {
+ "event_uuid": str(uuid4()),
+ "event": "$ai_generation",
+ "distinct_id": "user-1",
+ "team": self.team,
+ "properties": {"$ai_trace_id": TRACE_A, "$ai_model": "model-x"},
+ "timestamp": "2026-06-02T08:00:00Z",
+ }
+ bulk_create_ai_events([row, row])
+
+ response = self._get(TRACE_A)
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert [r["uuid"] for r in json.loads(response.content)["results"]] == [row["event_uuid"]]
+
+ def test_rejects_a_non_hex_trace_id(self) -> None:
+ response = self._get("zz92f3577b34da6a3ce929d0e0e4736")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+
+ @patch("posthoganalytics.feature_enabled", return_value=False)
+ def test_requires_the_feature_flag(self, _flag: Any) -> None:
+ response = self._get(TRACE_A)
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content
+
+ @parameterized.expand([("viewer", status.HTTP_200_OK), ("none", status.HTTP_403_FORBIDDEN)])
+ def test_requires_llm_analytics_viewer_access(self, access_level: str, expected_status: int) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ membership = OrganizationMembership.objects.get(user=user, organization=self.organization)
+ AccessControl.objects.create(
+ team=self.team,
+ resource="llm_analytics",
+ resource_id=None,
+ access_level=access_level,
+ organization_member=membership,
+ )
+ self.client.force_login(user)
+
+ response = self._get(TRACE_A)
+
+ assert response.status_code == expected_status, response.content
diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.ts
index 1903a838bafb..b39a9e7806c7 100644
--- a/products/tracing/frontend/generated/api.schemas.ts
+++ b/products/tracing/frontend/generated/api.schemas.ts
@@ -969,6 +969,69 @@ export interface _TracingTraceResponseApi {
nextOffset: number | null
}
+export interface _TracingTraceAiEventApi {
+ /** Event UUID. */
+ uuid: string
+ /** The LLM analytics event kind: `$ai_generation`, `$ai_span` or `$ai_embedding`. */
+ event: string
+ /** When the call started. Add `latency_seconds` for when it finished. Normalized across OpenTelemetry-sourced events, which are stamped at the start, and SDK-sourced events, which are stamped at the finish. */
+ started_at: string
+ /** The `$ai_trace_id` of the event, which opens it in LLM analytics. */
+ ai_trace_id: string
+ /**
+ * The `$ai_span_id` of the event.
+ * @nullable
+ */
+ ai_span_id: string | null
+ /**
+ * The `$ai_parent_id` of the event. For OpenTelemetry-sourced events this is the parent span's id.
+ * @nullable
+ */
+ ai_parent_id: string | null
+ /**
+ * The `$ai_span_name`, set on `$ai_span` events.
+ * @nullable
+ */
+ span_name: string | null
+ /**
+ * How long the call took, in seconds.
+ * @nullable
+ */
+ latency_seconds: number | null
+ /**
+ * The model the call used.
+ * @nullable
+ */
+ model: string | null
+ /**
+ * The provider the call went to.
+ * @nullable
+ */
+ provider: string | null
+ /**
+ * Prompt tokens.
+ * @nullable
+ */
+ input_tokens: number | null
+ /**
+ * Completion tokens.
+ * @nullable
+ */
+ output_tokens: number | null
+ /**
+ * Total cost of the call, in USD.
+ * @nullable
+ */
+ total_cost_usd: number | null
+ /** Whether the call failed. */
+ is_error: boolean
+}
+
+export interface _TracingTraceAiEventsResponseApi {
+ /** AI events in the trace, earliest start first. */
+ results: _TracingTraceAiEventApi[]
+}
+
export interface _TracingTreeQueryBodyApi {
/** Span name to scope the matched trace set. Required because the (trace_id, parent_span_id) self-join is unsafe without bounding the matched traces. */
spanName: string
diff --git a/products/tracing/frontend/generated/api.ts b/products/tracing/frontend/generated/api.ts
index 3a2c3fea5387..bb3b3372e4b6 100644
--- a/products/tracing/frontend/generated/api.ts
+++ b/products/tracing/frontend/generated/api.ts
@@ -49,6 +49,7 @@ import type {
_TracingServiceNamesResponseApi,
_TracingSparklineRequestApi,
_TracingSparklineResponseApi,
+ _TracingTraceAiEventsResponseApi,
_TracingTraceRequestApi,
_TracingTraceResponseApi,
_TracingTreeRequestApi,
@@ -590,6 +591,28 @@ export const tracingSpansTraceCreate = async (
})
}
+export const getTracingSpansTraceAiEventsRetrieveUrl = (projectId: string, traceId: string) => {
+ return `/api/projects/${projectId}/tracing/spans/trace/${traceId}/ai_events/`
+}
+
+/**
+ * List the LLM analytics events whose `$ai_trace_id` is this trace's id, so the waterfall
+ * can show each model call inline with the spans.
+ *
+ * The spans and the AI events live on different ClickHouse clusters, so one query cannot join
+ * them; this returns the events half and the caller places them by time.
+ */
+export const tracingSpansTraceAiEventsRetrieve = async (
+ projectId: string,
+ traceId: string,
+ options?: RequestInit
+): Promise<_TracingTraceAiEventsResponseApi> => {
+ return apiMutator<_TracingTraceAiEventsResponseApi>(getTracingSpansTraceAiEventsRetrieveUrl(projectId, traceId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getTracingSpansTreeCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/tracing/spans/tree/`
}
diff --git a/products/tracing/mcp/tools.yaml b/products/tracing/mcp/tools.yaml
index 818ba575ff62..0df1fcad2bec 100644
--- a/products/tracing/mcp/tools.yaml
+++ b/products/tracing/mcp/tools.yaml
@@ -263,6 +263,9 @@ tools:
tracing-spans-symbol-stats-create:
operation: tracing_spans_symbol_stats_create
enabled: false
+ tracing-spans-trace-ai-events-retrieve:
+ operation: tracing_spans_trace_ai_events_retrieve
+ enabled: false
tracing-views-create:
operation: tracing_views_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 18e4371ca127..79c75595c7c8 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -103768,6 +103768,69 @@ export namespace Schemas {
results: _TracingSparklineRow[];
}
+ export interface _TracingTraceAiEvent {
+ /** Event UUID. */
+ uuid: string;
+ /** The LLM analytics event kind: `$ai_generation`, `$ai_span` or `$ai_embedding`. */
+ event: string;
+ /** When the call started. Add `latency_seconds` for when it finished. Normalized across OpenTelemetry-sourced events, which are stamped at the start, and SDK-sourced events, which are stamped at the finish. */
+ started_at: string;
+ /** The `$ai_trace_id` of the event, which opens it in LLM analytics. */
+ ai_trace_id: string;
+ /**
+ * The `$ai_span_id` of the event.
+ * @nullable
+ */
+ ai_span_id: string | null;
+ /**
+ * The `$ai_parent_id` of the event. For OpenTelemetry-sourced events this is the parent span's id.
+ * @nullable
+ */
+ ai_parent_id: string | null;
+ /**
+ * The `$ai_span_name`, set on `$ai_span` events.
+ * @nullable
+ */
+ span_name: string | null;
+ /**
+ * How long the call took, in seconds.
+ * @nullable
+ */
+ latency_seconds: number | null;
+ /**
+ * The model the call used.
+ * @nullable
+ */
+ model: string | null;
+ /**
+ * The provider the call went to.
+ * @nullable
+ */
+ provider: string | null;
+ /**
+ * Prompt tokens.
+ * @nullable
+ */
+ input_tokens: number | null;
+ /**
+ * Completion tokens.
+ * @nullable
+ */
+ output_tokens: number | null;
+ /**
+ * Total cost of the call, in USD.
+ * @nullable
+ */
+ total_cost_usd: number | null;
+ /** Whether the call failed. */
+ is_error: boolean;
+ }
+
+ export interface _TracingTraceAiEventsResponse {
+ /** AI events in the trace, earliest start first. */
+ results: _TracingTraceAiEvent[];
+ }
+
export interface _TracingTraceRequest {
/** Date range for the query. Defaults to last 24 hours. */
dateRange?: _TracingDateRange;