: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(llma): read sentiment from evaluations (#65591)
Radu Raicea0f31021132f4
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 88dedd9061d1..2b863fb5148d 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -25198,6 +25198,53 @@"required": ["type"],"type": "object"},+ "LLMSentimentMessage": {+ "additionalProperties": false,+ "properties": {+ "label": {+ "type": "string"+ },+ "score": {+ "type": "number"+ },+ "scores": {+ "additionalProperties": {+ "type": "number"+ },+ "type": "object"+ }+ },+ "required": ["label", "score"],+ "type": "object"+ },+ "LLMSentimentResult": {+ "additionalProperties": false,+ "properties": {+ "label": {+ "type": "string"+ },+ "message_count": {+ "type": "number"+ },+ "messages": {+ "additionalProperties": {+ "$ref": "#/definitions/LLMSentimentMessage"+ },+ "type": "object"+ },+ "score": {+ "type": "number"+ },+ "scores": {+ "additionalProperties": {+ "type": "number"+ },+ "type": "object"+ }+ },+ "required": ["label", "score"],+ "type": "object"+ },"LLMTrace": {"additionalProperties": false,"properties": {@@ -25245,6 +25292,9 @@"requestCost": {"type": "number"},+ "sentiment": {+ "$ref": "#/definitions/LLMSentimentResult"+ },"tools": {"items": {"type": "string"@@ -25288,6 +25338,9 @@},"properties": {"type": "object"+ },+ "sentiment": {+ "$ref": "#/definitions/LLMSentimentResult"}},"required": ["id", "event", "properties", "createdAt"],@@ -43206,6 +43259,10 @@"dateRange": {"$ref": "#/definitions/DateRange"},+ "includeSentiment": {+ "description": "Include stored sentiment evaluation results for the trace and its generations.",+ "type": "boolean"+ },"kind": {"const": "TraceQuery","type": "string"@@ -43881,6 +43938,10 @@"groupTypeIndex": {"$ref": "#/definitions/integer"},+ "includeSentiment": {+ "description": "Include stored sentiment evaluation results for returned traces and direct generation events.",+ "type": "boolean"+ },"kind": {"const": "TracesQuery","type": "string"diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex e3e6ed5bbad8..2e21cbaf0519 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -5307,6 +5307,21 @@ export interface LLMTraceEvent {event: AIEventType | string // Allow both specific AI events and other event typesproperties: Record<string, any>createdAt: string+ sentiment?: LLMSentimentResult+}++export interface LLMSentimentMessage {+ label: string+ score: number+ scores?: Record<string, number>+}++export interface LLMSentimentResult {+ label: string+ score: number+ scores?: Record<string, number>+ messages?: Record<string, LLMSentimentMessage>+ message_count?: number}// Snake-case here for the DataTable component.@@ -5338,6 +5353,7 @@ export interface LLMTrace {events: LLMTraceEvent[]isSupportTrace?: booleantools?: string[]+ sentiment?: LLMSentimentResult}export interface TracesQueryResponse extends AnalyticsQueryResponseBase {@@ -5362,6 +5378,8 @@ export interface TracesQuery extends DataNode<TracesQueryResponse> {personId?: stringgroupKey?: stringgroupTypeIndex?: integer+ /** Include stored sentiment evaluation results for returned traces and direct generation events. */+ includeSentiment?: boolean/** Use random ordering instead of timestamp DESC. Useful for representative sampling to avoid recency bias. */randomOrder?: boolean}@@ -5378,6 +5396,8 @@ export interface TraceQuery extends DataNode<TraceQueryResponse> {kind: NodeKind.TraceQuerytraceId: stringdateRange?: DateRange+ /** Include stored sentiment evaluation results for the trace and its generations. */+ includeSentiment?: boolean/** Properties configurable in the interface */properties?: AnyPropertyFilter[]}diff --git a/posthog/hogql_queries/ai/sentiment_evaluations.py b/posthog/hogql_queries/ai/sentiment_evaluations.pynew file mode 100644index 000000000000..9c639479c43f--- /dev/null+++ b/posthog/hogql_queries/ai/sentiment_evaluations.py@@ -0,0 +1,415 @@+from __future__ import annotations++from collections.abc import Mapping, Sequence+from dataclasses import dataclass+from typing import TYPE_CHECKING, Any++import orjson++from posthog.hogql import ast+from posthog.hogql.parser import parse_select++from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events++if TYPE_CHECKING:+ from posthog.hogql.constants import LimitContext+ from posthog.hogql.modifiers import HogQLQueryModifiers+ from posthog.hogql.timings import HogQLTimings++ from posthog.models import Team+++SentimentMessage = dict[str, Any]+SentimentResult = dict[str, Any]++AI_EVENTS_GENERATION_SENTIMENT_GENERATION_ID_SELECT = "ifNull(nullIf(nullIf(toString(generation_id), ''), 'null'), '')"+MAX_GENERATION_SENTIMENT_EVALUATIONS_PER_TRACE = 1000+SENTIMENT_LABELS = ("positive", "neutral", "negative")+++@dataclass(frozen=True)+class SentimentEvaluationLookup:+ by_trace_id: dict[str, SentimentResult]+ by_generation_id: dict[str, SentimentResult]+++EMPTY_SENTIMENT_EVALUATION_LOOKUP = SentimentEvaluationLookup(by_trace_id={}, by_generation_id={})+++def get_generation_sentiment_lookup_ids(+ event_id: str,+ event_name: str,+ properties: Mapping[str, object] | None,+) -> list[str]:+ ids = [event_id] if event_id else []+ if event_name != "$ai_generation" or properties is None:+ return ids++ generation_id = _normalize_lookup_id(properties.get("$ai_generation_id"))+ if generation_id:+ ids.append(generation_id)++ return dedupe_non_empty(ids)+++def get_sentiment_for_generation(+ lookup: SentimentEvaluationLookup,+ generation_ids: Sequence[str],+) -> SentimentResult | None:+ for generation_id in generation_ids:+ sentiment = lookup.by_generation_id.get(generation_id)+ if sentiment is not None:+ return sentiment+ return None+++_SENTIMENT_EVALUATIONS_SQL = """+SELECT+ trace_id,+ toString(properties.$ai_target_event_id) AS generation_id,+ argMax(toString(properties.$ai_sentiment_label), timestamp) AS label,+ argMax(toString(properties.$ai_sentiment_score), timestamp) AS score,+ argMax(properties.$ai_sentiment_scores, timestamp) AS scores,+ argMax(properties.$ai_sentiment_messages, timestamp) AS messages,+ argMax(toString(properties.$ai_sentiment_message_count), timestamp) AS message_count+FROM posthog.ai_events AS ai_events+WHERE event = '$ai_evaluation'+ AND properties.$ai_evaluation_runtime = 'sentiment'+ AND trace_id IN {trace_ids}+ AND length(toString(properties.$ai_target_event_id)) > 0+ AND {generation_filter}+GROUP BY trace_id, toString(properties.$ai_target_event_id)+LIMIT {limit}+"""++_TRACE_SENTIMENT_EVALUATIONS_SQL = """+SELECT+ trace_id,+ groupArray(tuple(generation_id, label, score, scores, messages, message_count)) AS generation_results+FROM (+ SELECT+ trace_id,+ toString(properties.$ai_target_event_id) AS generation_id,+ argMax(toString(properties.$ai_sentiment_label), timestamp) AS label,+ argMax(toString(properties.$ai_sentiment_score), timestamp) AS score,+ argMax(properties.$ai_sentiment_scores, timestamp) AS scores,+ argMax(properties.$ai_sentiment_messages, timestamp) AS messages,+ argMax(toString(properties.$ai_sentiment_message_count), timestamp) AS message_count+ FROM posthog.ai_events AS ai_events+ WHERE event = '$ai_evaluation'+ AND properties.$ai_evaluation_runtime = 'sentiment'+ AND trace_id IN {trace_ids}+ AND length(toString(properties.$ai_target_event_id)) > 0+ GROUP BY trace_id, toString(properties.$ai_target_event_id)+)+GROUP BY trace_id+LIMIT {limit}+"""+++def load_generation_sentiment_evaluations_for_traces(+ *,+ team: Team,+ trace_ids: Sequence[str],+ generation_ids: Sequence[str] | None = None,+ timings: HogQLTimings | None = None,+ modifiers: HogQLQueryModifiers | None = None,+ limit_context: LimitContext | None = None,+ query_type: str = "LLMGenerationSentimentEvaluations",+) -> SentimentEvaluationLookup:+ unique_trace_ids = dedupe_non_empty(trace_ids)+ if not unique_trace_ids:+ return EMPTY_SENTIMENT_EVALUATION_LOOKUP++ unique_generation_ids = dedupe_non_empty(generation_ids or [])+ generation_filter: ast.Expr = ast.Constant(value=True)+ if unique_generation_ids:+ generation_filter = ast.CompareOperation(+ op=ast.CompareOperationOp.In,+ left=ast.Field(chain=["properties", "$ai_target_event_id"]),+ right=ast.Tuple(exprs=[ast.Constant(value=generation_id) for generation_id in unique_generation_ids]),+ )++ query = parse_select(_SENTIMENT_EVALUATIONS_SQL)+ result = query_ai_events(+ query=query,+ placeholders={+ "trace_ids": ast.Tuple(exprs=[ast.Constant(value=trace_id) for trace_id in unique_trace_ids]),+ "generation_filter": generation_filter,+ "limit": ast.Constant(+ value=max(+ len(unique_trace_ids) * MAX_GENERATION_SENTIMENT_EVALUATIONS_PER_TRACE,+ len(unique_generation_ids),+ 1,+ )+ ),+ },+ team=team,+ query_type=query_type,+ fall_back_to_events=True,+ timings=timings,+ modifiers=modifiers,+ limit_context=limit_context,+ )++ by_trace_generation: dict[str, list[tuple[str, SentimentResult]]] = {}+ by_generation_id: dict[str, SentimentResult] = {}++ for row in result.results or []:+ trace_id, generation_id, label, score, scores, messages, message_count = row+ normalized = normalize_sentiment_result(label, score, scores, messages, message_count)++ trace_id = str(trace_id)+ generation_id = str(generation_id)+ by_generation_id[generation_id] = normalized+ by_trace_generation.setdefault(trace_id, []).append((generation_id, normalized))++ return SentimentEvaluationLookup(+ by_trace_id={+ trace_id: _aggregate_trace_sentiment(generation_results)+ for trace_id, generation_results in by_trace_generation.items()+ },+ by_generation_id=by_generation_id,+ )+++def load_trace_sentiment_evaluations(+ *,+ team: Team,+ trace_ids: Sequence[str],+ timings: HogQLTimings | None = None,+ modifiers: HogQLQueryModifiers | None = None,+ limit_context: LimitContext | None = None,+ query_type: str = "LLMTraceSentimentEvaluations",+) -> dict[str, SentimentResult]:+ unique_trace_ids = dedupe_non_empty(trace_ids)+ if not unique_trace_ids:+ return {}++ query = parse_select(_TRACE_SENTIMENT_EVALUATIONS_SQL)+ result = query_ai_events(+ query=query,+ placeholders={+ "trace_ids": ast.Tuple(exprs=[ast.Constant(value=trace_id) for trace_id in unique_trace_ids]),+ "limit": ast.Constant(value=len(unique_trace_ids)),+ },+ team=team,+ query_type=query_type,+ fall_back_to_events=True,+ timings=timings,+ modifiers=modifiers,+ limit_context=limit_context,+ )++ by_trace_id: dict[str, SentimentResult] = {}+ for row in result.results or []:+ trace_id, generation_results = row+ normalized_generation_results: list[tuple[str, SentimentResult]] = []+ for generation_result in generation_results or []:+ if not isinstance(generation_result, list | tuple) or len(generation_result) < 6:+ continue+ generation_id, label, score, scores, messages, message_count = generation_result[:6]+ normalized_generation_results.append(+ (+ str(generation_id),+ normalize_sentiment_result(label, score, scores, messages, message_count),+ )+ )++ if normalized_generation_results:+ by_trace_id[str(trace_id)] = _aggregate_trace_sentiment(normalized_generation_results)++ return by_trace_id+++def dedupe_non_empty(values: Sequence[str]) -> list[str]:+ seen: set[str] = set()+ result: list[str] = []+ for value in values:+ if not value or value in seen:+ continue+ seen.add(value)+ result.append(value)+ return result+++def _normalize_lookup_id(value: object) -> str | None:+ if value is None:+ return None++ value_string = value if isinstance(value, str) else str(value)+ if not value_string or value_string == "null":+ return None+ return value_string+++def normalize_sentiment_result(+ label: object,+ score: object,+ scores: object,+ messages: object,+ message_count: object,+) -> SentimentResult:+ label_value = _normalize_label(label)+ scores_value = _normalize_scores(scores)+ messages_value = _normalize_messages(messages)+ score_value = _normalize_float(score)++ if score_value is None:+ score_value = scores_value.get(label_value, 0.0)++ return {+ "label": label_value,+ "score": score_value,+ "scores": scores_value,+ "messages": messages_value,+ "message_count": _normalize_int(message_count) or len(messages_value),+ }+++def _aggregate_trace_sentiment(generation_results: list[tuple[str, SentimentResult]]) -> SentimentResult:+ flat_messages: dict[str, SentimentMessage] = {}+ score_dicts: list[dict[str, float]] = []++ for generation_id, result in generation_results:+ messages = result.get("messages")+ if isinstance(messages, dict) and messages:+ message_score_dicts: list[dict[str, float]] = []+ for message_index, message in messages.items():+ if not isinstance(message, dict):+ continue+ flat_messages[f"{generation_id}:{message_index}"] = message+ message_scores = _score_dict_from_sentiment(message)+ if message_scores is not None:+ message_score_dicts.append(message_scores)+ if message_score_dicts:+ score_dicts.extend(message_score_dicts)+ continue++ result_scores = _score_dict_from_sentiment(result)+ if result_scores is not None:+ score_dicts.append(result_scores)++ scores = _average_score_dicts(score_dicts)+ label = (+ max(SENTIMENT_LABELS, key=lambda sentiment_label: scores.get(sentiment_label, 0.0))+ if _has_score_signal(scores)+ else "neutral"+ )+ return {+ "label": label,+ "score": scores[label],+ "scores": scores,+ "messages": flat_messages,+ "message_count": len(flat_messages),+ }+++def _decode_jsonish(value: object) -> object:+ if isinstance(value, dict | list):+ return value+ if isinstance(value, bytes):+ try:+ return orjson.loads(value)+ except orjson.JSONDecodeError:+ return value.decode("utf-8", errors="ignore")+ if isinstance(value, str):+ if not value:+ return None+ try:+ return orjson.loads(value)+ except orjson.JSONDecodeError:+ return value+ return value+++def _normalize_label(value: object) -> str:+ if isinstance(value, str) and value in SENTIMENT_LABELS:+ return value+ return "neutral"+++def _normalize_float(value: object) -> float | None:+ if isinstance(value, bool) or value is None:+ return None+ if isinstance(value, int | float):+ return float(value)+ if isinstance(value, str):+ try:+ return float(value)+ except ValueError:+ return None+ return None+++def _normalize_int(value: object) -> int | None:+ if isinstance(value, bool) or value is None:+ return None+ if isinstance(value, int):+ return value+ if isinstance(value, float):+ return int(value)+ if isinstance(value, str):+ try:+ return int(value)+ except ValueError:+ return None+ return None+++def _normalize_scores(value: object) -> dict[str, float]:+ decoded = _decode_jsonish(value)+ if not isinstance(decoded, dict):+ return {"positive": 0.0, "neutral": 0.0, "negative": 0.0}++ return {+ "positive": _normalize_float(decoded.get("positive")) or 0.0,+ "neutral": _normalize_float(decoded.get("neutral")) or 0.0,+ "negative": _normalize_float(decoded.get("negative")) or 0.0,+ }+++def _normalize_messages(value: object) -> dict[str, SentimentMessage]:+ decoded = _decode_jsonish(value)+ if not isinstance(decoded, dict):+ return {}++ messages: dict[str, SentimentMessage] = {}+ for key, raw_message in decoded.items():+ if not isinstance(raw_message, dict):+ continue++ messages[str(key)] = {+ "label": _normalize_label(raw_message.get("label")),+ "score": _normalize_float(raw_message.get("score")) or 0.0,+ "scores": _normalize_scores(raw_message.get("scores")),+ }++ return messages+++def _score_dict_from_sentiment(value: Mapping[str, object]) -> dict[str, float] | None:+ scores = _normalize_scores(value.get("scores"))+ if _has_score_signal(scores):+ return scores++ score = _normalize_float(value.get("score"))+ if score is None or score == 0.0:+ return None++ label = _normalize_label(value.get("label"))+ return {sentiment_label: score if sentiment_label == label else 0.0 for sentiment_label in SENTIMENT_LABELS}+++def _has_score_signal(scores: Mapping[str, float]) -> bool:+ return any(score != 0.0 for score in scores.values())+++def _average_score_dicts(score_dicts: list[dict[str, float]]) -> dict[str, float]:+ if not score_dicts:+ return {"positive": 0.0, "neutral": 0.0, "negative": 0.0}++ return {+ label: round(sum(scores.get(label, 0.0) for scores in score_dicts) / len(score_dicts), 4)+ for label in SENTIMENT_LABELS+ }diff --git a/posthog/hogql_queries/ai/test/test_sentiment_evaluations.py b/posthog/hogql_queries/ai/test/test_sentiment_evaluations.pynew file mode 100644index 000000000000..a5518fa7ffbd--- /dev/null+++ b/posthog/hogql_queries/ai/test/test_sentiment_evaluations.py@@ -0,0 +1,141 @@+from types import SimpleNamespace+from typing import cast++from unittest.mock import patch++from parameterized import parameterized++from posthog.hogql_queries.ai.sentiment_evaluations import load_trace_sentiment_evaluations, normalize_sentiment_result+from posthog.models import Team++GenerationResultRow = tuple[object, object, object, object, object, object]+++def _load_trace_sentiment_from_generation_results(generation_results: list[GenerationResultRow]) -> dict[str, object]:+ result = SimpleNamespace(results=[["trace-1", generation_results]])++ with patch("posthog.hogql_queries.ai.sentiment_evaluations.query_ai_events", return_value=result):+ sentiment_by_trace_id = load_trace_sentiment_evaluations(+ team=cast(Team, SimpleNamespace(id=1)),+ trace_ids=["trace-1"],+ )++ return cast(dict[str, object], sentiment_by_trace_id["trace-1"])+++def test_load_trace_sentiment_evaluations_aggregates_generation_tuples() -> None:+ sentiment = _load_trace_sentiment_from_generation_results(+ [+ (+ "generation-1",+ "positive",+ 0.9,+ {"positive": 0.9, "neutral": 0.08, "negative": 0.02},+ {+ "0": {+ "label": "positive",+ "score": 0.9,+ "scores": {"positive": 0.9, "neutral": 0.08, "negative": 0.02},+ }+ },+ 1,+ )+ ]+ )++ assert sentiment["label"] == "positive"+ assert sentiment["score"] == 0.9+ assert sentiment["message_count"] == 1+ assert cast(dict[str, object], sentiment["messages"])["generation-1:0"] == {+ "label": "positive",+ "score": 0.9,+ "scores": {"positive": 0.9, "neutral": 0.08, "negative": 0.02},+ }+++ [+ (+ "falls_back_to_generation_scores_when_message_scores_are_empty",+ [+ (+ "generation-1",+ "negative",+ 0.82,+ {"positive": 0.02, "neutral": 0.16, "negative": 0.82},+ {"0": {"label": "neutral"}},+ 1,+ )+ ],+ "negative",+ 0.82,+ ),+ (+ "uses_message_scores_when_present",+ [+ (+ "generation-1",+ "negative",+ 0.82,+ {"positive": 0.02, "neutral": 0.16, "negative": 0.82},+ {+ "0": {+ "label": "positive",+ "score": 0.91,+ "scores": {"positive": 0.91, "neutral": 0.08, "negative": 0.01},+ }+ },+ 1,+ )+ ],+ "positive",+ 0.91,+ ),+ (+ "uses_neutral_when_no_score_signal_exists",+ [+ (+ "generation-1",+ "positive",+ None,+ {},+ {"0": {"label": "positive"}},+ 1,+ )+ ],+ "neutral",+ 0.0,+ ),+ ]+)+def test_load_trace_sentiment_evaluations_handles_sparse_scores(+ _name: str,+ generation_results: list[GenerationResultRow],+ expected_label: str,+ expected_score: float,+) -> None:+ sentiment = _load_trace_sentiment_from_generation_results(generation_results)++ assert sentiment["label"] == expected_label+ assert sentiment["score"] == expected_score+++ [+ ("string_values", "positive", "0.75", '{"positive":0.75,"neutral":0.2,"negative":0.05}', "2", 0.75, 2),+ ("invalid_label", "mixed", None, {}, None, 0.0, 0),+ ]+)+def test_normalize_sentiment_result_coerces_values(+ _name: str,+ label: object,+ score: object,+ scores: object,+ message_count: object,+ expected_score: float,+ expected_message_count: int,+) -> None:+ sentiment = normalize_sentiment_result(label, score, scores, {}, message_count)++ assert sentiment["score"] == expected_score+ assert sentiment["message_count"] == expected_message_countdiff --git a/posthog/hogql_queries/ai/test/test_trace_query_runner.py b/posthog/hogql_queries/ai/test/test_trace_query_runner.pyindex 6e44f71d55be..7e33d140810e 100644--- a/posthog/hogql_queries/ai/test/test_trace_query_runner.py+++ b/posthog/hogql_queries/ai/test/test_trace_query_runner.py@@ -6,6 +6,7 @@ from uuid import UUIDimport pytestfrom freezegun import freeze_timefrom posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, _create_person, snapshot_clickhouse_queries+from unittest.mock import patchfrom posthog.schema import (DateRange,@@ -195,6 +196,38 @@ def _create_ai_embedding_event()+def _create_ai_sentiment_evaluation_event(+ *,+ trace_id: str,+ generation_id: str,+ team: Team | None = None,+ distinct_id: str | None = None,+ timestamp: datetime | None = None,+) -> None:+ _create_event(+ event="$ai_evaluation",+ distinct_id=distinct_id,+ team=team,+ timestamp=timestamp,+ properties={+ "$ai_trace_id": trace_id,+ "$ai_evaluation_runtime": "sentiment",+ "$ai_target_event_id": generation_id,+ "$ai_sentiment_label": "negative",+ "$ai_sentiment_score": 0.8,+ "$ai_sentiment_scores": {"positive": 0.1, "neutral": 0.1, "negative": 0.8},+ "$ai_sentiment_messages": {+ "0": {+ "label": "negative",+ "score": 0.8,+ "scores": {"positive": 0.1, "neutral": 0.1, "negative": 0.8},+ }+ },+ "$ai_sentiment_message_count": 1,+ },+ )++class TestTraceQueryRunner(ClickhouseTestMixin, BaseTest):def setUp(self):super().setUp()@@ -309,6 +342,74 @@ class TestTraceQueryRunner(ClickhouseTestMixin, BaseTest):},)+ def test_stored_sentiment_evaluations_are_mapped_to_trace_and_generation(self):+ event_uuid = uuid.uuid4()+ generation_id = "generation-id-1"+ _create_person(distinct_ids=["person1"], team=self.team)+ _create_ai_generation_event(+ distinct_id="person1",+ trace_id="trace1",+ input="Foo",+ output="Bar",+ team=self.team,+ timestamp=datetime(2025, 1, 15, 0),+ event_uuid=event_uuid,+ properties={"$ai_generation_id": generation_id},+ )+ _create_ai_sentiment_evaluation_event(+ distinct_id="person1",+ trace_id="trace1",+ generation_id=generation_id,+ team=self.team,+ timestamp=datetime(2025, 1, 15, 0, 1),+ )++ response = TraceQueryRunner(+ team=self.team,+ query=TraceQuery(+ traceId="trace1",+ includeSentiment=True,+ dateRange=DateRange(date_from="2025-01-15T00:00:00Z", date_to="2025-01-15T02:00:00Z"),+ ),+ ).calculate()++ assert len(response.results) == 1+ trace = response.results[0]+ assert trace.sentiment is not None+ assert trace.sentiment.label == "negative"+ assert trace.sentiment.score == 0.8+ assert trace.sentiment.messages is not None+ assert trace.sentiment.messages[f"{generation_id}:0"].label == "negative"+ assert len(trace.events) == 1+ assert trace.events[0].sentiment is not None+ assert trace.events[0].sentiment.label == "negative"+ assert trace.events[0].sentiment.messages is not None+ assert trace.events[0].sentiment.messages["0"].score == 0.8++ @patch("posthog.hogql_queries.ai.trace_query_runner.load_generation_sentiment_evaluations_for_traces")+ def test_stored_sentiment_evaluation_lookup_is_opt_in(self, mock_load_sentiment):+ _create_person(distinct_ids=["person1"], team=self.team)+ _create_ai_generation_event(+ distinct_id="person1",+ trace_id="trace1",+ input="Foo",+ output="Bar",+ team=self.team,+ timestamp=datetime(2025, 1, 15, 0),+ )++ response = TraceQueryRunner(+ team=self.team,+ query=TraceQuery(+ traceId="trace1",+ dateRange=DateRange(date_from="2025-01-15T00:00:00Z", date_to="2025-01-15T02:00:00Z"),+ ),+ ).calculate()++ assert len(response.results) == 1+ assert response.results[0].sentiment is None+ mock_load_sentiment.assert_not_called()+def test_maps_all_fields(self):"""Test that all fields are mapped correctly."""_create_person(distinct_ids=["person1"], team=self.team)@@ -1530,9 +1631,9 @@ class TestTraceQueryRunner(ClickhouseTestMixin, BaseTest):assert trace.traceName == "fallback-trace"# Numeric fields must be actual numbers, not strings (validates toFloat wrapping)- assert isinstance(trace.totalLatency, (int, float))- assert isinstance(trace.inputTokens, (int, float))- assert isinstance(trace.outputTokens, (int, float))+ assert isinstance(trace.totalLatency, int | float)+ assert isinstance(trace.inputTokens, int | float)+ assert isinstance(trace.outputTokens, int | float)# Heavy columns should be present in event properties (from events JSON blob)assert len(trace.events) >= 1diff --git a/posthog/hogql_queries/ai/test/test_traces_query_runner.py b/posthog/hogql_queries/ai/test/test_traces_query_runner.pyindex 887557e82fb6..e08fbe2229ce 100644--- a/posthog/hogql_queries/ai/test/test_traces_query_runner.py+++ b/posthog/hogql_queries/ai/test/test_traces_query_runner.py@@ -6,6 +6,7 @@ from uuid import UUIDimport pytestfrom freezegun import freeze_timefrom posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, _create_person, snapshot_clickhouse_queries+from unittest.mock import patchfrom posthog.schema import (DateRange,@@ -197,6 +198,38 @@ def _create_ai_embedding_event()+def _create_ai_sentiment_evaluation_event(+ *,+ trace_id: str,+ generation_id: str,+ team: Team | None = None,+ distinct_id: str | None = None,+ timestamp: datetime | None = None,+) -> None:+ _create_event(+ event="$ai_evaluation",+ distinct_id=distinct_id,+ team=team,+ timestamp=timestamp,+ properties={+ "$ai_trace_id": trace_id,+ "$ai_evaluation_runtime": "sentiment",+ "$ai_target_event_id": generation_id,+ "$ai_sentiment_label": "negative",+ "$ai_sentiment_score": 0.8,+ "$ai_sentiment_scores": {"positive": 0.1, "neutral": 0.1, "negative": 0.8},+ "$ai_sentiment_messages": {+ "0": {+ "label": "negative",+ "score": 0.8,+ "scores": {"positive": 0.1, "neutral": 0.1, "negative": 0.8},+ }+ },+ "$ai_sentiment_message_count": 1,+ },+ )++class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):def setUp(self):super().setUp()@@ -308,6 +341,72 @@ class TestTracesQueryRunner(ClickhouseTestMixin, BaseTest):# test_trace_id_filter removed - TracesQuery no longer supports traceId parameter+ @freeze_time("2025-01-16T00:00:00Z")+ def test_stored_sentiment_evaluations_are_mapped_to_trace_and_generation(self):+ event_uuid = uuid.uuid4()+ generation_id = "generation-id-1"+ _create_person(distinct_ids=["person1"], team=self.team)+ _create_ai_generation_event(+ distinct_id="person1",+ trace_id="trace1",+ input="Foo",+ output="Bar",+ team=self.team,+ timestamp=datetime(2025, 1, 15, 0),+ event_uuid=event_uuid,+ properties={"$ai_parent_id": "trace1", "$ai_generation_id": generation_id},+ )+ _create_ai_sentiment_evaluation_event(+ distinct_id="person1",+ trace_id="trace1",+ generation_id=generation_id,+ team=self.team,+ timestamp=datetime(2025, 1, 15, 0, 1),+ )++ response = TracesQueryRunner(+ team=self.team,+ query=TracesQuery(+ includeSentiment=True,+ dateRange=DateRange(date_from="2025-01-15T00:00:00Z", date_to="2025-01-15T02:00:00Z"),+ ),+ ).calculate()++ assert len(response.results) == 1+ trace = response.results[0]+ assert trace.sentiment is not None+ assert trace.sentiment.label == "negative"+ assert trace.sentiment.score == 0.8+ assert trace.sentiment.messages is not None+ assert trace.sentiment.messages[f"{generation_id}:0"].label == "negative"+ assert len(trace.events) == 1+ assert trace.events[0].sentiment is None++ @freeze_time("2025-01-16T00:00:00Z")+ @patch("posthog.hogql_queries.ai.traces_query_runner.load_trace_sentiment_evaluations")+ def test_stored_sentiment_evaluation_lookup_is_opt_in(self, mock_load_sentiment):+ _create_person(distinct_ids=["person1"], team=self.team)+ _create_ai_generation_event(+ distinct_id="person1",+ trace_id="trace1",+ input="Foo",+ output="Bar",+ team=self.team,+ timestamp=datetime(2025, 1, 15, 0),+ properties={"$ai_parent_id": "trace1"},+ )++ response = TracesQueryRunner(+ team=self.team,+ query=TracesQuery(+ dateRange=DateRange(date_from="2025-01-15T00:00:00Z", date_to="2025-01-15T02:00:00Z"),+ ),+ ).calculate()++ assert len(response.results) == 1+ assert response.results[0].sentiment is None+ mock_load_sentiment.assert_not_called()+@freeze_time("2025-01-16T00:00:00Z")@snapshot_clickhouse_queriesdef test_pagination(self):diff --git a/posthog/hogql_queries/ai/trace_query_runner.py b/posthog/hogql_queries/ai/trace_query_runner.pyindex 484fb3224c77..96a07de7f7e9 100644--- a/posthog/hogql_queries/ai/trace_query_runner.py+++ b/posthog/hogql_queries/ai/trace_query_runner.py@@ -19,6 +19,13 @@ from posthog.hogql.parser import parse_selectfrom posthog.hogql.property import property_to_exprfrom posthog.hogql_queries.ai.ai_table_resolver import query_ai_events+from posthog.hogql_queries.ai.sentiment_evaluations import (+ EMPTY_SENTIMENT_EVALUATION_LOOKUP,+ SentimentEvaluationLookup,+ get_generation_sentiment_lookup_ids,+ get_sentiment_for_generation,+ load_generation_sentiment_evaluations_for_traces,+)from posthog.hogql_queries.ai.utils import merge_heavy_propertiesfrom posthog.hogql_queries.query_runner import AnalyticsQueryRunnerfrom posthog.hogql_queries.utils.query_date_range import QueryDateRange@@ -38,6 +45,7 @@ TRACE_FIELDS_MAPPING: dict[str, str] = {"total_cost": "totalCost","events": "events","trace_name": "traceName",+ "sentiment": "sentiment",}@@ -82,7 +90,18 @@ class TraceQueryRunner(AnalyticsQueryRunner[TraceQueryResponse]):)columns: list[str] = query_result.columns or []- results = self._map_results(columns, query_result.results)+ sentiment_lookup = EMPTY_SENTIMENT_EVALUATION_LOOKUP+ if self.query.includeSentiment and query_result.results:+ sentiment_lookup = load_generation_sentiment_evaluations_for_traces(+ team=self.team,+ trace_ids=[self.query.traceId],+ timings=self.timings,+ modifiers=self.modifiers,+ limit_context=self.limit_context,+ query_type="TraceQuerySentimentEvaluations",+ )++ results = self._map_results(columns, query_result.results, sentiment_lookup)return TraceQueryResponse(columns=columns,@@ -185,7 +204,7 @@ class TraceQueryRunner(AnalyticsQueryRunner[TraceQueryResponse]):return {**super().get_cache_payload(),# When the response schema changes, increment this version to invalidate the cache.- "schema_version": 5,+ "schema_version": 9,}@cached_property@@ -228,27 +247,38 @@ class TraceQueryRunner(AnalyticsQueryRunner[TraceQueryResponse]):return ast.And(exprs=where_exprs)- def _map_event(self, event_tuple: tuple) -> LLMTraceEvent:+ def _map_event(self, event_tuple: tuple, sentiment_lookup: SentimentEvaluationLookup) -> LLMTraceEvent:event_uuid, event_name, event_timestamp, event_properties, *heavy = event_tupleheavy_columns = dict(zip(("input", "output", "output_choices", "input_state", "output_state", "tools"), heavy))+ event_id = str(event_uuid)+ properties = merge_heavy_properties(event_properties, heavy_columns)generation: dict[str, Any] = {- "id": str(event_uuid),+ "id": event_id,"event": event_name,"createdAt": event_timestamp.isoformat(),- "properties": merge_heavy_properties(event_properties, heavy_columns),+ "properties": properties,}+ sentiment_lookup_ids = get_generation_sentiment_lookup_ids(event_id, event_name, properties)+ sentiment = get_sentiment_for_generation(sentiment_lookup, sentiment_lookup_ids)+ if sentiment is not None:+ generation["sentiment"] = sentimentreturn LLMTraceEvent.model_validate(generation)- def _map_trace(self, result: dict[str, Any], created_at: datetime) -> LLMTrace:+ def _map_trace(+ self, result: dict[str, Any], created_at: datetime, sentiment_lookup: SentimentEvaluationLookup+ ) -> LLMTrace:generations = []for event_tuple in result["events"]:- generations.append(self._map_event(event_tuple))+ generations.append(self._map_event(event_tuple, sentiment_lookup))trace_dict = {**result,"created_at": created_at.isoformat(),"events": generations,}+ sentiment = sentiment_lookup.by_trace_id.get(str(result["id"]))+ if sentiment is not None:+ trace_dict["sentiment"] = sentimentfor raw_key, parsed_key in [("input_state", "input_state_parsed"), ("output_state", "output_state_parsed")]:raw = trace_dict.get(raw_key) or Nonetrace_dict[raw_key] = raw@@ -262,7 +292,9 @@ class TraceQueryRunner(AnalyticsQueryRunner[TraceQueryResponse]):)return trace- def _map_results(self, columns: list[str], query_results: list) -> list[LLMTrace]:+ def _map_results(+ self, columns: list[str], query_results: list, sentiment_lookup: SentimentEvaluationLookup+ ) -> list[LLMTrace]:mapped_results = [dict(zip(columns, value)) for value in query_results]traces = []@@ -277,6 +309,6 @@ class TraceQueryRunner(AnalyticsQueryRunner[TraceQueryResponse]):if first_timestamp > date_to or last_timestamp < date_from:continue- traces.append(self._map_trace(result, first_timestamp))+ traces.append(self._map_trace(result, first_timestamp, sentiment_lookup))return tracesdiff --git a/posthog/hogql_queries/ai/traces_query_runner.py b/posthog/hogql_queries/ai/traces_query_runner.pyindex 1848c8854a68..5f970e1e87c7 100644--- a/posthog/hogql_queries/ai/traces_query_runner.py+++ b/posthog/hogql_queries/ai/traces_query_runner.py@@ -24,6 +24,13 @@ from posthog.hogql.property import property_to_exprfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Product, tags_context+from posthog.hogql_queries.ai.sentiment_evaluations import (+ EMPTY_SENTIMENT_EVALUATION_LOOKUP,+ SentimentEvaluationLookup,+ get_generation_sentiment_lookup_ids,+ get_sentiment_for_generation,+ load_trace_sentiment_evaluations,+)from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginatorfrom posthog.hogql_queries.query_runner import AnalyticsQueryRunnerfrom posthog.hogql_queries.utils.query_date_range import QueryDateRange@@ -192,7 +199,23 @@ class TracesQueryRunner(AnalyticsQueryRunner[TracesQueryResponse]):)columns: list[str] = query_result.columns or []- results = self._map_results(columns, query_result.results)+ sentiment_lookup = EMPTY_SENTIMENT_EVALUATION_LOOKUP+ if self.query.includeSentiment and query_result.results and columns:+ id_index = columns.index("id") if "id" in columns else -1+ result_trace_ids = [str(row[id_index]) for row in query_result.results if id_index >= 0 and row[id_index]]+ sentiment_lookup = SentimentEvaluationLookup(+ by_trace_id=load_trace_sentiment_evaluations(+ team=self.team,+ trace_ids=result_trace_ids,+ timings=self.timings,+ modifiers=self.modifiers,+ limit_context=self.limit_context,+ query_type="TracesQuerySentimentEvaluations",+ ),+ by_generation_id={},+ )++ results = self._map_results(columns, query_result.results, sentiment_lookup)return TracesQueryResponse(columns=columns,@@ -350,7 +373,7 @@ class TracesQueryRunner(AnalyticsQueryRunner[TracesQueryResponse]):return {**super().get_cache_payload(),# When the response schema changes, increment this version to invalidate the cache.- "schema_version": 6,+ "schema_version": 10,}@cached_property@@ -377,7 +400,9 @@ class TracesQueryRunner(AnalyticsQueryRunner[TracesQueryResponse]):return narrowed_range- def _map_results(self, columns: list[str], query_results: list):+ def _map_results(+ self, columns: list[str], query_results: list, sentiment_lookup: SentimentEvaluationLookup+ ) -> list[LLMTrace]:mapped_results = [dict(zip(columns, value)) for value in query_results]traces = []@@ -392,11 +417,13 @@ class TracesQueryRunner(AnalyticsQueryRunner[TracesQueryResponse]):if first_timestamp > date_to or last_timestamp < date_from:continue- traces.append(self._map_trace(result, first_timestamp))+ traces.append(self._map_trace(result, first_timestamp, sentiment_lookup))return traces- def _map_trace(self, result: dict[str, Any], created_at: datetime) -> LLMTrace:+ def _map_trace(+ self, result: dict[str, Any], created_at: datetime, sentiment_lookup: SentimentEvaluationLookup+ ) -> LLMTrace:TRACE_FIELDS_MAPPING = {"id": "id","ai_session_id": "aiSessionId",@@ -417,17 +444,21 @@ class TracesQueryRunner(AnalyticsQueryRunner[TracesQueryResponse]):"error_count": "errorCount","is_support_trace": "isSupportTrace","tools": "tools",+ "sentiment": "sentiment",}generations = []for uuid, event_name, timestamp, properties in result["events"]:- generations.append(self._map_event(uuid, event_name, timestamp, properties))+ generations.append(self._map_event(uuid, event_name, timestamp, properties, sentiment_lookup))trace_dict = {**result,"created_at": created_at.isoformat(),"events": generations,}+ sentiment = sentiment_lookup.by_trace_id.get(str(result["id"]))+ if sentiment is not None:+ trace_dict["sentiment"] = sentimentfor raw_key, parsed_key in [("input_state", "input_state_parsed"), ("output_state", "output_state_parsed")]:raw = trace_dict.get(raw_key)if raw is not None:@@ -442,14 +473,25 @@ class TracesQueryRunner(AnalyticsQueryRunner[TracesQueryResponse]):return tracedef _map_event(- self, event_uuid: UUID, event_name: str, event_timestamp: datetime, event_properties: str+ self,+ event_uuid: UUID,+ event_name: str,+ event_timestamp: datetime,+ event_properties: str,+ sentiment_lookup: SentimentEvaluationLookup,) -> LLMTraceEvent:+ event_id = str(event_uuid)+ properties = orjson.loads(event_properties)generation: dict[str, Any] = {- "id": str(event_uuid),+ "id": event_id,"event": event_name,"createdAt": event_timestamp.isoformat(),- "properties": orjson.loads(event_properties),+ "properties": properties,}+ sentiment_lookup_ids = get_generation_sentiment_lookup_ids(event_id, event_name, properties)+ sentiment = get_sentiment_for_generation(sentiment_lookup, sentiment_lookup_ids)+ if sentiment is not None:+ generation["sentiment"] = sentimentreturn LLMTraceEvent.model_validate(generation)def _get_subquery_filter(self) -> ast.Expr:diff --git a/posthog/schema.py b/posthog/schema.pyindex f1cdd1ed7b8d..3c0cf0476507 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -1549,6 +1549,26 @@ class IntegrationFilter(BaseModel):)+class LLMSentimentMessage(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ label: str+ score: float+ scores: dict[str, float] | None = None+++class LLMSentimentResult(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ label: str+ message_count: float | None = None+ messages: dict[str, LLMSentimentMessage] | None = None+ score: float+ scores: dict[str, float] | None = None++class LLMTraceEvent(BaseModel):model_config = ConfigDict(extra="forbid",@@ -1557,6 +1577,7 @@ class LLMTraceEvent(BaseModel):event: AIEventType | strid: strproperties: dict[str, Any]+ sentiment: LLMSentimentResult | None = Noneclass LLMTracePerson(BaseModel):@@ -5541,6 +5562,7 @@ class LLMTrace(BaseModel):outputTokens: float | None = Noneperson: LLMTracePerson | None = NonerequestCost: float | None = None+ sentiment: LLMSentimentResult | None = Nonetools: list[str] | None = NonetotalCost: float | None = NonetotalLatency: float | None = None@@ -20685,6 +20707,10 @@ class TraceQuery(BaseModel):extra="forbid",)dateRange: DateRange | None = None+ includeSentiment: bool | None = Field(+ default=None,+ description=("Include stored sentiment evaluation results for the trace and its generations."),+ )kind: Literal["TraceQuery"] = "TraceQuery"modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")properties: (@@ -20758,6 +20784,10 @@ class TracesQuery(BaseModel):filterTestAccounts: bool | None = NonegroupKey: str | None = NonegroupTypeIndex: int | None = None+ includeSentiment: bool | None = Field(+ default=None,+ description=("Include stored sentiment evaluation results for returned traces and direct generation events."),+ )kind: Literal["TracesQuery"] = "TracesQuery"limit: int | None = Nonemodifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")diff --git a/posthog/temporal/ai_observability/sentiment/README.md b/posthog/temporal/ai_observability/sentiment/README.mdindex d5bde16f26cf..568c87e99d89 100644--- a/posthog/temporal/ai_observability/sentiment/README.md+++ b/posthog/temporal/ai_observability/sentiment/README.md@@ -1,16 +1,17 @@# Sentiment classification-On-demand sentiment analysis for AI observability traces.-Classifies user messages from `$ai_generation` events using an ONNX model-(`cardiffnlp/twitter-roberta-base-sentiment-latest`).+Sentiment classification for AI observability workflows.+The classifier analyzes user messages from `$ai_generation` events using an ONNX model+(`cardiffnlp/twitter-roberta-base-sentiment-latest`), and callers persist the result as `$ai_evaluation` events when sentiment is configured as an AI evaluation.## How it works-1. Frontend calls the sentiment API with one or more trace IDs-2. Django starts a Temporal workflow (`llma-sentiment-classify`)-3. The activity fetches `$ai_generation` events via HogQL,- extracts user messages, and classifies them in a single batch-4. Results are cached (24h TTL) and returned to the frontend+There are two call paths:++1. Sentiment AI evaluations run through the evaluation workflow, classify the target generation's user messages, and emit stored `$ai_evaluation` events with `$ai_sentiment_*` properties.+2. Trace clustering can still call the `llma-sentiment-classify` Temporal workflow for best-effort aggregate sentiment.++The AI observability UI reads stored sentiment evaluation events. It does not trigger on-read sentiment classification.## Package structure@@ -81,7 +82,7 @@ pytest posthog/temporal/ai_observability/sentiment/ -x -qTests mock the model and HogQL layer so the sentiment dependency groupis not required to run them.-## API endpoints+## UI data flow-- `POST /api/environments/:team_id/llm_analytics/sentiment/` -- single trace-- `POST /api/environments/:team_id/llm_analytics/sentiment/batch/` -- up to 25 traces+The Sentiment tab and trace/generation sentiment displays read `$ai_evaluation` events where `$ai_evaluation_runtime = 'sentiment'`.+If a project has no sentiment evaluation configured, the Sentiment tab shows onboarding instead of running classification on read.diff --git a/products/ai_observability/backend/api/__init__.py b/products/ai_observability/backend/api/__init__.pyindex 4a0253a7f245..e6fc1b9bcacc 100644--- a/products/ai_observability/backend/api/__init__.py+++ b/products/ai_observability/backend/api/__init__.py@@ -15,7 +15,6 @@ from .provider_keys import LLMProviderKeyValidationViewSet, LLMProviderKeyViewSefrom .proxy import SUPPORTED_MODELS_WITH_THINKING, LLMProxyViewSetfrom .review_queues import ReviewQueueItemViewSet, ReviewQueueViewSetfrom .score_definitions import ScoreDefinitionViewSet-from .sentiment import AIObservabilitySentimentViewSetfrom .summarization import AIObservabilitySummarizationViewSetfrom .taggers import TaggerViewSetfrom .text_repr import AIObservabilityTextReprViewSet@@ -44,7 +43,6 @@ __all__ = ["ReviewQueueViewSet","ReviewQueueItemViewSet","ScoreDefinitionViewSet",- "AIObservabilitySentimentViewSet","AIObservabilityOfflineEvaluationsViewSet","PersonalSpendViewSet","TaggerViewSet",diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.pyindex 75ed392d7f96..33cb5e7acf7c 100644--- a/products/ai_observability/backend/api/evaluations.py+++ b/products/ai_observability/backend/api/evaluations.py@@ -430,6 +430,10 @@ class EvaluationSerializer(serializers.ModelSerializer):class EvaluationFilter(django_filters.FilterSet):search = django_filters.CharFilter(method="filter_search", help_text="Search in name or description")enabled = django_filters.BooleanFilter(help_text="Filter by enabled status")+ evaluation_type = django_filters.ChoiceFilter(+ choices=EvaluationType.choices,+ help_text="Filter by evaluation type",+ )order_by = django_filters.OrderingFilter(fields=(("created_at", "created_at"),@@ -448,6 +452,7 @@ class EvaluationFilter(django_filters.FilterSet):fields = {"id": ["in"],"enabled": ["exact"],+ "evaluation_type": ["exact"],}def filter_search(self, queryset, name, value):diff --git a/products/ai_observability/backend/api/sentiment.py b/products/ai_observability/backend/api/sentiment.pydeleted file mode 100644index 2dfdd3774301..000000000000--- a/products/ai_observability/backend/api/sentiment.py+++ /dev/null@@ -1,424 +0,0 @@-"""On-demand sentiment analysis for LLM traces and generations.--Triggers a Temporal workflow to classify sentiment on $ai_generation user messages-and returns the result synchronously (blocks until Temporal completes).-"""--import time-import uuid-import asyncio-from collections import namedtuple-from datetime import timedelta--from django.conf import settings-from django.core.cache import cache--import structlog-from drf_spectacular.types import OpenApiTypes-from drf_spectacular.utils import extend_schema-from pydantic import ValidationError as PydanticValidationError-from rest_framework import serializers, status, viewsets-from rest_framework.decorators import action-from rest_framework.request import Request-from rest_framework.response import Response-from temporalio.common import RetryPolicy, WorkflowIDReusePolicy--from posthog.schema import HogQLFilters--from posthog.hogql import ast-from posthog.hogql.constants import LimitContext-from posthog.hogql.filters import replace_filters-from posthog.hogql.parser import parse_select-from posthog.hogql.query import execute_hogql_query--from posthog.api.monitoring import monitor-from posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.clickhouse.query_tagging import Feature, Product, tags_context-from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events-from posthog.permissions import AccessControlPermission-from posthog.rate_limit import AIObservabilitySentimentBurstThrottle, AIObservabilitySentimentSustainedThrottle-from posthog.temporal.ai_observability.sentiment.constants import (- BATCH_MAX_GENERATION_IDS,- BATCH_MAX_TRACE_IDS,- CACHE_KEY_PREFIX,- MAX_RETRY_ATTEMPTS,- WORKFLOW_NAME,- WORKFLOW_TIMEOUT_BATCH_SECONDS,-)-from posthog.temporal.ai_observability.sentiment.schema import ClassifySentimentInput-from posthog.temporal.common.client import sync_connect--from products.ai_observability.backend.api.metrics import llma_track_latency--# Maximum rows returned from sentiment_generations.sql per call. Matches the-# frontend's GENERATIONS_PAGE_SIZE so a single page request gets the full slice-# in one round-trip. Baked into `_SENTIMENT_GENERATIONS_SQL` at import time-# below so this is the single source of truth.-GENERATIONS_QUERY_LIMIT = 200--logger = structlog.get_logger(__name__)--ANALYSIS_LEVEL_CHOICES = ["trace", "generation"]-BATCH_MAX_BY_LEVEL = {- "trace": BATCH_MAX_TRACE_IDS,- "generation": BATCH_MAX_GENERATION_IDS,-}---class SentimentRequestSerializer(serializers.Serializer):- ids = serializers.ListField(- child=serializers.CharField(),- min_length=1,- max_length=BATCH_MAX_GENERATION_IDS,- required=True,- help_text="Trace IDs (analysis_level=trace) or generation event UUIDs (analysis_level=generation).",- )- analysis_level = serializers.ChoiceField(- choices=ANALYSIS_LEVEL_CHOICES,- default="trace",- required=False,- help_text="Whether the IDs are 'trace' IDs or 'generation' IDs.",- )- force_refresh = serializers.BooleanField(- default=False,- required=False,- help_text="If true, bypass cache and reclassify.",- )- date_from = serializers.CharField(- required=False,- default=None,- allow_null=True,- help_text="Start of date range for the lookup (e.g. '-7d' or '2026-01-01'). Defaults to -30d.",- )- date_to = serializers.CharField(- required=False,- default=None,- allow_null=True,- help_text="End of date range for the lookup. Defaults to now.",- )---class MessageSentimentSerializer(serializers.Serializer):- label = serializers.CharField() # type: ignore[assignment]- score = serializers.FloatField()- scores = serializers.DictField(child=serializers.FloatField())---class SentimentResultSerializer(serializers.Serializer):- label = serializers.CharField() # type: ignore[assignment]- score = serializers.FloatField()- scores = serializers.DictField(child=serializers.FloatField())- messages = serializers.DictField(child=MessageSentimentSerializer())- message_count = serializers.IntegerField()---class SentimentBatchResponseSerializer(serializers.Serializer):- results = serializers.DictField(child=SentimentResultSerializer())---# Preflight runs against `events` (not `posthog.ai_events`): the events sort-# key starts `(team_id, toDate(timestamp), event)` so date filtering prunes-# granules cheaply, while ai_events is `(team_id, trace_id, timestamp)` —-# unusable for date pruning until trace_id is bounded.-#-# The `max(timestamp)` / `min(timestamp)` aggregates intentionally use distinct-# aliases (`ts_max` / `ts_min`) rather than reusing `timestamp` / `created_at`.-# `replace_filters` injects a timestamp range as `toTimeZone(timestamp, '<tz>') > ...`-# for teams whose timezone is non-UTC, and HogQL would bind that inner `timestamp`-# to a same-named SELECT alias, producing `max(toTimeZone(timestamp, ...))` inside-# WHERE — an illegal aggregate in WHERE that surfaces as a 500 to the Sentiment tab.-_SENTIMENT_GENERATIONS_PREFLIGHT_SQL = f"""-SELECT- argMax(uuid, timestamp) as uuid,- properties.$ai_trace_id as trace_id,- argMax(properties.$ai_model, timestamp) as model,- argMax(distinct_id, timestamp) as distinct_id,- max(timestamp) as ts_max,- min(timestamp) as ts_min-FROM events-WHERE event = '$ai_generation'- AND length(coalesce(properties.$ai_trace_id, '')) > 0- AND {{filters}}-GROUP BY trace_id-ORDER BY ts_max DESC, trace_id DESC-LIMIT {GENERATIONS_QUERY_LIMIT}-"""--# The explicit `LIMIT` matches the preflight's `GENERATIONS_QUERY_LIMIT` —-# without it, `execute_hogql_query` (via `LimitContext.QUERY`) injects its-# default of 100 rows, silently truncating the heavy `GROUP BY trace_id`-# to the first 100 trace_ids whenever the preflight returns more. That-# manifests in the UI as blank sentiment cards for the truncated half,-# even though the underlying input is present in ClickHouse.-_SENTIMENT_GENERATIONS_HEAVY_SQL = f"""-SELECT- trace_id,- argMax(input, timestamp) as ai_input-FROM posthog.ai_events AS ai_events-WHERE event = '$ai_generation'- AND trace_id IN {{trace_ids}}- AND uuid IN {{uuids}}- AND timestamp >= {{ts_start}}- AND timestamp <= {{ts_end}}-GROUP BY trace_id-LIMIT {GENERATIONS_QUERY_LIMIT}-"""--_PreflightRow = namedtuple("_PreflightRow", ["uuid", "trace_id", "model", "distinct_id", "ts_max", "ts_min"])---class SentimentGenerationsRequestSerializer(serializers.Serializer):- """Filter shape mirrors the previous frontend `api.query({filters: ...})` payload.-- `filters` accepts the same `HogQLFilters` schema that the legacy frontend HogQL- path used (dateRange, filterTestAccounts, properties), so the migration is- behaviour-preserving for callers that pass a request unchanged.- """-- filters = serializers.JSONField(required=False, default=dict)---class SentimentGenerationsRowSerializer(serializers.Serializer):- uuid = serializers.CharField(allow_null=True)- trace_id = serializers.CharField(allow_null=True)- ai_input = serializers.JSONField(allow_null=True)- model = serializers.CharField(allow_null=True)- distinct_id = serializers.CharField(allow_null=True)- timestamp = serializers.CharField(allow_null=True)- created_at = serializers.CharField(allow_null=True)---class SentimentGenerationsResponseSerializer(serializers.Serializer):- # Shape kept tuple-style to match the existing frontend transformer (see- # `aiObservabilitySentimentLogic.ts::fetchGenerations`); positions:- # [uuid, trace_id, ai_input, model, distinct_id, timestamp, created_at].- results = serializers.ListField(child=serializers.ListField())---class AIObservabilitySentimentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):- scope_object = "llm_analytics"- permission_classes = [AccessControlPermission]- throttle_classes = [- AIObservabilitySentimentBurstThrottle,- AIObservabilitySentimentSustainedThrottle,- ]-- def _cache_key(self, level: str, id_: str) -> str:- return f"{CACHE_KEY_PREFIX}:{level}:{self.team_id}:{id_}"-- def _execute_workflow(- self,- client,- ids: list[str],- analysis_level: str = "trace",- date_from: str | None = None,- date_to: str | None = None,- ) -> dict[str, dict]:- workflow_input = ClassifySentimentInput(- team_id=self.team_id,- ids=ids,- analysis_level=analysis_level,- date_from=date_from,- date_to=date_to,- )- workflow_id = f"llma-sentiment-{self.team_id}-{int(time.time() * 1000)}-{uuid.uuid4().hex[:8]}"-- return asyncio.run(- client.execute_workflow(- WORKFLOW_NAME,- workflow_input,- id=workflow_id,- task_queue=settings.LLMA_SENTIMENT_TASK_QUEUE,- id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,- retry_policy=RetryPolicy(maximum_attempts=MAX_RETRY_ATTEMPTS),- task_timeout=timedelta(seconds=WORKFLOW_TIMEOUT_BATCH_SECONDS),- )- )-- @extend_schema(- request=SentimentRequestSerializer,- responses={- 200: SentimentBatchResponseSerializer,- 400: OpenApiTypes.OBJECT,- 500: OpenApiTypes.OBJECT,- },- tags=["AI observability"],- )- @llma_track_latency("llma_sentiment_create")- @monitor(feature=None, endpoint="llma_sentiment_create", method="POST")- def create(self, request: Request, **kwargs) -> Response:- serializer = SentimentRequestSerializer(data=request.data)- if not serializer.is_valid():- return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)-- ids: list[str] = serializer.validated_data["ids"]- analysis_level: str = serializer.validated_data["analysis_level"]- force_refresh: bool = serializer.validated_data["force_refresh"]- date_from: str | None = serializer.validated_data.get("date_from")- date_to: str | None = serializer.validated_data.get("date_to")-- max_size = BATCH_MAX_BY_LEVEL[analysis_level]- if len(ids) > max_size:- return Response(- {"ids": [f"Ensure this field has no more than {max_size} elements."]},- status=status.HTTP_400_BAD_REQUEST,- )-- results: dict[str, dict] = {}- misses: list[str] = []-- if not force_refresh:- cache_keys = {id_: self._cache_key(analysis_level, id_) for id_ in ids}- cached_values = cache.get_many(list(cache_keys.values()))-- for id_ in ids:- cached = cached_values.get(cache_keys[id_])- if cached is not None:- results[id_] = cached- else:- misses.append(id_)- else:- misses = list(ids)-- if misses:- try:- client = sync_connect()- batch_results = self._execute_workflow(- client,- misses,- analysis_level=analysis_level,- date_from=date_from,- date_to=date_to,- )-- for id_ in misses:- result = batch_results.get(id_)- if result:- results[id_] = result- else:- results[id_] = {"error": "Failed to compute sentiment"}-- except Exception as e:- logger.exception(- "Failed to compute sentiment",- team_id=self.team_id,- analysis_level=analysis_level,- ids=misses,- error=str(e),- )- return Response(- {"error": "Failed to compute sentiment"},- status=status.HTTP_500_INTERNAL_SERVER_ERROR,- )-- return Response({"results": results}, status=status.HTTP_200_OK)-- @extend_schema(- request=SentimentGenerationsRequestSerializer,- responses={- 200: SentimentGenerationsResponseSerializer,- 400: OpenApiTypes.OBJECT,- 500: OpenApiTypes.OBJECT,- },- tags=["AI observability"],- )- @action(detail=False, methods=["post"], url_path="generations")- @llma_track_latency("llma_sentiment_generations")- @monitor(feature=None, endpoint="llma_sentiment_generations", method="POST")- def generations(self, request: Request, **kwargs) -> Response:- serializer = SentimentGenerationsRequestSerializer(data=request.data)- if not serializer.is_valid():- return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)-- filters_payload = serializer.validated_data.get("filters") or {}- # Narrow to pydantic's ValidationError so unrelated 500s (e.g. a future- # import shift making `HogQLFilters` resolve to None) surface as 500- # rather than getting masked as a 400. Heavy property filters (`$ai_input`- # etc.) would read as NULL on the dedicated path — assumed not exposed- # in the sentiment-tab UI's property picker, which only surfaces- # non-heavy props.- try:- filters = HogQLFilters.model_validate(filters_payload)- except PydanticValidationError as e:- # `e.errors()` is a structured list of pydantic error dicts — safe to- # serialize and free of stack-trace context. `str(e)` would surface- # the full exception representation (CodeQL flagged it as info exposure).- return Response({"filters": e.errors()}, status=status.HTTP_400_BAD_REQUEST)-- preflight_query = replace_filters(parse_select(_SENTIMENT_GENERATIONS_PREFLIGHT_SQL), filters, self.team)-- with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=self.team_id):- try:- preflight_result = execute_hogql_query(- query=preflight_query,- placeholders={},- team=self.team,- query_type="LLMSentimentGenerationsTraceIdResolve",- limit_context=LimitContext.QUERY,- )- except Exception as e:- logger.exception(- "Failed to resolve sentiment generations trace_ids",- team_id=self.team_id,- error=str(e),- )- return Response(- {"error": "Failed to fetch sentiment generations"},- status=status.HTTP_500_INTERNAL_SERVER_ERROR,- )-- preflight_rows = [_PreflightRow(*row) for row in (preflight_result.results or [])]- if not preflight_rows:- return Response({"results": []}, status=status.HTTP_200_OK)-- trace_ids = [str(row.trace_id) for row in preflight_rows]- uuids = [str(row.uuid) for row in preflight_rows]- ts_start = min(row.ts_min for row in preflight_rows)- ts_end = max(row.ts_max for row in preflight_rows)-- heavy_query = parse_select(_SENTIMENT_GENERATIONS_HEAVY_SQL)- heavy_placeholders = {- "trace_ids": ast.Tuple(exprs=[ast.Constant(value=tid) for tid in trace_ids]),- "uuids": ast.Tuple(exprs=[ast.Constant(value=u) for u in uuids]),- "ts_start": ast.Constant(value=ts_start),- "ts_end": ast.Constant(value=ts_end),- }- try:- heavy_result = query_ai_events(- query=heavy_query,- placeholders=heavy_placeholders,- team=self.team,- query_type="LLMSentimentGenerations",- fall_back_to_events=True,- limit_context=LimitContext.QUERY,- )- except Exception as e:- logger.exception(- "Failed to fetch sentiment generations",- team_id=self.team_id,- error=str(e),- )- return Response(- {"error": "Failed to fetch sentiment generations"},- status=status.HTTP_500_INTERNAL_SERVER_ERROR,- )-- ai_input_by_trace = {str(trace_id): ai_input for trace_id, ai_input in (heavy_result.results or [])}- # Positional response shape (unchanged, frontend depends on it): row[0..6] =- # [uuid, trace_id, ai_input, model, distinct_id, ts_max, ts_min]. The internal- # `ts_max` / `ts_min` aliases (see `_SENTIMENT_GENERATIONS_PREFLIGHT_SQL`) are- # the same values the frontend consumes as `timestamp` and `createdAt` at- # `aiObservabilitySentimentLogic.ts::fetchGenerations`.- results = [- [- row.uuid,- row.trace_id,- ai_input_by_trace.get(str(row.trace_id)),- row.model,- row.distinct_id,- row.ts_max,- row.ts_min,- ]- for row in preflight_rows- ]- return Response({"results": results}, status=status.HTTP_200_OK)diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.pyindex 701d7f072193..631f3abb3f21 100644--- a/products/ai_observability/backend/api/test/test_evaluations.py+++ b/products/ai_observability/backend/api/test/test_evaluations.py@@ -298,6 +298,31 @@ class TestEvaluationConfigsApi(APIBaseTest):self.assertIn("model_configuration", first)self.assertEqual(first["evaluation_config"], {"prompt": "Prompt 1"})+ def test_can_filter_evaluations_by_evaluation_type(self):+ Evaluation.objects.create(+ name="Judge evaluation",+ evaluation_type="llm_judge",+ evaluation_config={"prompt": "Prompt"},+ output_type="boolean",+ output_config={},+ team=self.team,+ created_by=self.user,+ )+ Evaluation.objects.create(+ name="Sentiment evaluation",+ evaluation_type="sentiment",+ evaluation_config={"source": "user_messages"},+ output_type="sentiment",+ output_config={},+ team=self.team,+ created_by=self.user,+ )++ response = self.client.get(f"/api/environments/{self.team.id}/evaluations/?evaluation_type=sentiment")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual([evaluation["name"] for evaluation in response.data["results"]], ["Sentiment evaluation"])+def test_mcp_list_returns_slim_payload(self):Evaluation.objects.create(name="Evaluation 1",diff --git a/products/ai_observability/backend/api/test/test_sentiment_generations.py b/products/ai_observability/backend/api/test/test_sentiment_generations.pydeleted file mode 100644index b7562324854d..000000000000--- a/products/ai_observability/backend/api/test/test_sentiment_generations.py+++ /dev/null@@ -1,317 +0,0 @@-from datetime import UTC, datetime-from typing import Any, cast--from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person-from unittest.mock import MagicMock, patch--from parameterized import parameterized-from rest_framework import status---class TestSentimentGenerationsEndpoint(APIBaseTest):- URL: str = ""-- def setUp(self) -> None:- super().setUp()- self.URL = f"/api/environments/{self.team.id}/llm_analytics/sentiment/generations/"-- def _make_response(self, rows: list[list[Any]]) -> MagicMock:- response = MagicMock()- response.results = rows- return response-- def _preflight_row(- self,- uuid: str = "uuid-1",- trace_id: str = "trace-1",- model: str = "gpt-4",- distinct_id: str = "person-1",- ts_max: Any = "2026-04-27T07:00:00+00:00",- ts_min: Any = "2026-04-27T06:50:00+00:00",- ) -> list[Any]:- return [uuid, trace_id, model, distinct_id, ts_max, ts_min]-- @patch("products.ai_observability.backend.api.sentiment.query_ai_events")- @patch("products.ai_observability.backend.api.sentiment.execute_hogql_query")- def test_returns_rows_in_tuple_order(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:- mock_preflight.return_value = self._make_response(- [- self._preflight_row(- uuid="uuid-1",- trace_id="trace-1",- model="gpt-4",- distinct_id="person-1",- ts_max="2026-04-27T07:00:00+00:00",- ts_min="2026-04-27T06:50:00+00:00",- ),- ]- )- mock_heavy.return_value = self._make_response([["trace-1", '[{"role":"user","content":"hi"}]']])-- response = self.client.post(- self.URL,- {"filters": {"dateRange": {"date_from": "-7d", "date_to": None}, "properties": []}},- content_type="application/json",- )-- assert response.status_code == status.HTTP_200_OK- body = response.json()- assert body == {- "results": [- [- "uuid-1",- "trace-1",- '[{"role":"user","content":"hi"}]',- "gpt-4",- "person-1",- "2026-04-27T07:00:00+00:00",- "2026-04-27T06:50:00+00:00",- ]- ]- }- assert mock_preflight.call_args.kwargs["query_type"] == "LLMSentimentGenerationsTraceIdResolve"- assert mock_heavy.call_args.kwargs["query_type"] == "LLMSentimentGenerations"-- @patch("products.ai_observability.backend.api.sentiment.query_ai_events")- @patch("products.ai_observability.backend.api.sentiment.execute_hogql_query")- def test_invalid_filters_returns_400(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:- response = self.client.post(- self.URL,- {"filters": {"filterTestAccounts": "this should be a bool"}},- content_type="application/json",- )- assert response.status_code == status.HTTP_400_BAD_REQUEST- assert mock_preflight.call_count == 0- assert mock_heavy.call_count == 0-- @parameterized.expand(- [- ("missing_filters_key", {}),- ("empty_filters_dict", {"filters": {}}),- ]- )- @patch("products.ai_observability.backend.api.sentiment.query_ai_events")- @patch("products.ai_observability.backend.api.sentiment.execute_hogql_query")- def test_empty_preflight_skips_heavy_query(- self,- _name: str,- payload: dict[str, Any],- mock_preflight: MagicMock,- mock_heavy: MagicMock,- ) -> None:- mock_preflight.return_value = self._make_response([])-- response = self.client.post(self.URL, payload, content_type="application/json")- assert response.status_code == status.HTTP_200_OK- assert response.json() == {"results": []}- assert mock_heavy.call_count == 0-- @parameterized.expand(- [- ("preflight", "preflight"),- ("heavy", "heavy"),- ]- )- @patch("products.ai_observability.backend.api.sentiment.query_ai_events")- @patch("products.ai_observability.backend.api.sentiment.execute_hogql_query")- def test_clickhouse_failure_returns_500(- self,- _name: str,- failing_stage: str,- mock_preflight: MagicMock,- mock_heavy: MagicMock,- ) -> None:- if failing_stage == "preflight":- mock_preflight.side_effect = RuntimeError("clickhouse boom")- else:- mock_preflight.return_value = self._make_response([self._preflight_row()])- mock_heavy.side_effect = RuntimeError("clickhouse boom")-- response = self.client.post(self.URL, {"filters": {}}, content_type="application/json")- assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR- if failing_stage == "preflight":- assert mock_heavy.call_count == 0-- @patch("products.ai_observability.backend.api.sentiment.query_ai_events")- @patch("products.ai_observability.backend.api.sentiment.execute_hogql_query")- def test_preflight_targets_events_and_heavy_targets_ai_events(- self, mock_preflight: MagicMock, mock_heavy: MagicMock- ) -> None:- from posthog.hogql import ast-- mock_preflight.return_value = self._make_response(- [- self._preflight_row(- uuid="uuid-1",- trace_id="trace-1",- ts_max=datetime(2026, 4, 27, 7, 0, tzinfo=UTC),- ts_min=datetime(2026, 4, 27, 6, 50, tzinfo=UTC),- ),- self._preflight_row(- uuid="uuid-2",- trace_id="trace-2",- ts_max=datetime(2026, 4, 27, 6, 30, tzinfo=UTC),- ts_min=datetime(2026, 4, 27, 6, 0, tzinfo=UTC),- ),- ]- )- mock_heavy.return_value = self._make_response(- [- ["trace-1", '[{"role":"user","content":"hi"}]'],- ["trace-2", '[{"role":"user","content":"hello"}]'],- ]- )-- response = self.client.post(self.URL, {"filters": {}}, content_type="application/json")- assert response.status_code == status.HTTP_200_OK-- preflight_query = mock_preflight.call_args.kwargs["query"]- preflight_select = cast(ast.SelectQuery, preflight_query)- # nosemgrep: hogql-no-string-table-chain- assert preflight_select.select_from.table.chain == ["events"] # type: ignore[union-attr]-- heavy_query = mock_heavy.call_args.kwargs["query"]- heavy_select = cast(ast.SelectQuery, heavy_query)- # nosemgrep: hogql-no-string-table-chain- assert heavy_select.select_from.table.chain == ["posthog", "ai_events"] # type: ignore[union-attr]-- heavy_placeholders = mock_heavy.call_args.kwargs["placeholders"]- trace_id_values = [c.value for c in heavy_placeholders["trace_ids"].exprs]- uuid_values = [c.value for c in heavy_placeholders["uuids"].exprs]- assert trace_id_values == ["trace-1", "trace-2"]- assert uuid_values == ["uuid-1", "uuid-2"]- assert heavy_placeholders["ts_start"].value == datetime(2026, 4, 27, 6, 0, tzinfo=UTC)- assert heavy_placeholders["ts_end"].value == datetime(2026, 4, 27, 7, 0, tzinfo=UTC)-- # The heavy SQL must carry an explicit `LIMIT` matching the preflight's- # `GENERATIONS_QUERY_LIMIT`. Without it, `execute_hogql_query` (via- # `LimitContext.QUERY`) injects a default of 100 rows and the `GROUP BY- # trace_id` is silently truncated when the preflight returns more, so- # the truncated half renders as blank cards on the Sentiment tab.- @patch("products.ai_observability.backend.api.sentiment.query_ai_events")- @patch("products.ai_observability.backend.api.sentiment.execute_hogql_query")- def test_heavy_query_has_explicit_limit(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:- from posthog.hogql import ast as hogql_ast-- from products.ai_observability.backend.api.sentiment import GENERATIONS_QUERY_LIMIT-- mock_preflight.return_value = self._make_response([self._preflight_row()])- mock_heavy.return_value = self._make_response([["trace-1", '[{"role":"user","content":"hi"}]']])-- response = self.client.post(self.URL, {"filters": {}}, content_type="application/json")- assert response.status_code == status.HTTP_200_OK-- heavy_query = mock_heavy.call_args.kwargs["query"]- heavy_select = cast(hogql_ast.SelectQuery, heavy_query)- assert heavy_select.limit is not None, "heavy query must have an explicit LIMIT"- assert isinstance(heavy_select.limit, hogql_ast.Constant)- assert heavy_select.limit.value == GENERATIONS_QUERY_LIMIT-- # When the heavy table returns fewer rows than the preflight (e.g. a- # trace had no input column, or partial ai_events coverage in some- # future state), the un-matched traces fall back to null ai_input and- # the response still includes them positionally. This keeps the- # frontend dedup grouping (and the per-card "View trace" links)- # working for the remaining rows.- @patch("products.ai_observability.backend.api.sentiment.query_ai_events")- @patch("products.ai_observability.backend.api.sentiment.execute_hogql_query")- def test_traces_without_heavy_match_get_null_ai_input(- self, mock_preflight: MagicMock, mock_heavy: MagicMock- ) -> None:- mock_preflight.return_value = self._make_response(- [- self._preflight_row(uuid="uuid-1", trace_id="trace-1"),- self._preflight_row(uuid="uuid-2", trace_id="trace-2"),- ]- )- mock_heavy.return_value = self._make_response([["trace-1", '[{"role":"user","content":"hi"}]']])-- response = self.client.post(self.URL, {"filters": {}}, content_type="application/json")- assert response.status_code == status.HTTP_200_OK- body = response.json()- assert len(body["results"]) == 2- assert body["results"][0][2] == '[{"role":"user","content":"hi"}]'- assert body["results"][1][2] is None---class TestSentimentGenerationsRealClickhouse(ClickhouseTestMixin, APIBaseTest):- """Regression coverage that exercises the real `replace_filters` + ClickHouse- pipeline for the Sentiments-tab preflight, not the mocked path.-- Previously the preflight aliased `max(timestamp) AS timestamp`, which shadowed- the `timestamp` column. `replace_filters` injects `toTimeZone(timestamp, '<tz>')`- comparisons for any team whose `timezone` is not UTC, and HogQL bound that- inner `timestamp` to the aggregate alias — surfacing as an "illegal aggregate- in WHERE" 500 from ClickHouse. The frontend swallowed the 500 into an empty- `results` array, rendering the "No generations with user input found" copy on- the Sentiments tab even when valid `$ai_generation` events existed for the- team. The mocked tests above never tripped this because they short-circuit- `execute_hogql_query`.- """-- URL: str = ""-- def setUp(self) -> None:- super().setUp()- self.URL = f"/api/environments/{self.team.id}/llm_analytics/sentiment/generations/"- # Reproduce the customer config that triggered the bug — any non-UTC tz- # is sufficient; `replace_filters` only wraps `timestamp` in `toTimeZone`- # when the team timezone differs from UTC.- self.team.timezone = "US/Eastern"- self.team.save()-- @parameterized.expand(- [- ("no_events", False),- ("with_event", True),- ]- )- @patch("products.ai_observability.backend.api.sentiment.query_ai_events")- def test_preflight_against_real_clickhouse_for_non_utc_team(- self,- _name: str,- seed_event: bool,- mock_heavy: MagicMock,- ) -> None:- """Without the alias-shadow fix, the preflight 500s here regardless of data- — the regression is in the SQL/`replace_filters` interaction, not in row- retrieval. The `with_event` case additionally confirms end-to-end shape on- a non-UTC team so a future refactor of the preflight can't silently drop- rows for the affected timezone class."""- if seed_event:- _create_person(team_id=self.team.pk, distinct_ids=["person-1"])- _create_event(- event="$ai_generation",- team=self.team,- distinct_id="person-1",- properties={- "$ai_trace_id": "trace-non-utc-1",- "$ai_model": "gpt-4",- "$ai_input": [{"role": "user", "content": "hi"}],- },- )- mock_heavy.return_value = MagicMock(- results=[("trace-non-utc-1", '[{"role":"user","content":"hi"}]')],- )- else:- mock_heavy.return_value = MagicMock(results=[])-- response = self.client.post(- self.URL,- {"filters": {"dateRange": {"date_from": "-1d", "date_to": None}}},- content_type="application/json",- )-- assert response.status_code == status.HTTP_200_OK, response.content- body = response.json()- if seed_event:- assert len(body["results"]) == 1- # Response tuple positions: [uuid, trace_id, ai_input, model, distinct_id, ts_max, ts_min]- assert body["results"][0][1] == "trace-non-utc-1"- assert body["results"][0][3] == "gpt-4"- assert body["results"][0][4] == "person-1"- else:- assert body == {"results": []}- # Heavy query is skipped when preflight is empty — confirms the preflight- # ran to completion (rather than crashing) and returned no rows.- assert mock_heavy.call_count == 0diff --git a/products/ai_observability/backend/routes.py b/products/ai_observability/backend/routes.pyindex 1ca60f2681fe..b3526b39a54c 100644--- a/products/ai_observability/backend/routes.py+++ b/products/ai_observability/backend/routes.py@@ -4,7 +4,6 @@ from posthog.settings import CLOUD_DEPLOYMENT, DEBUG, TESTfrom products.ai_observability.backend.api import (AIObservabilityClusteringRunViewSet,AIObservabilityOfflineEvaluationsViewSet,- AIObservabilitySentimentViewSet,AIObservabilitySummarizationViewSet,AIObservabilityTextReprViewSet,AIObservabilityTranslateViewSet,@@ -97,9 +96,6 @@ def register_routes(routers: RouterRegistry) -> None:routers.register_legacy_dual_route(r"llm_analytics/clustering_jobs", ClusteringJobViewSet, "project_llm_analytics_clustering_jobs", ["team_id"])- routers.register_legacy_dual_route(- r"llm_analytics/sentiment", AIObservabilitySentimentViewSet, "project_llm_analytics_sentiment", ["team_id"]- )routers.register_legacy_dual_route(r"llm_analytics/offline_evaluations",AIObservabilityOfflineEvaluationsViewSet,diff --git a/products/ai_observability/frontend/AIObservabilityScene.tsx b/products/ai_observability/frontend/AIObservabilityScene.tsxindex a5c019d340a7..a2c347a2e3ab 100644--- a/products/ai_observability/frontend/AIObservabilityScene.tsx+++ b/products/ai_observability/frontend/AIObservabilityScene.tsx@@ -46,6 +46,7 @@ import { AIObservabilityTraces } from './AIObservabilityTracesScene'import { AIObservabilityUsers } from './AIObservabilityUsers'import { useSortableColumns } from './hooks/useSortableColumns'import { llmPersonsLazyLoaderLogic } from './llmPersonsLazyLoaderLogic'+import { GENERATION_SENTIMENT_SELECT } from './sentimentResults'import { aiObservabilityDashboardLogic } from './tabs/aiObservabilityDashboardLogic'import { aiObservabilityErrorsLogic } from './tabs/aiObservabilityErrorsLogic'import { getDefaultGenerationsColumns, aiObservabilityGenerationsLogic } from './tabs/aiObservabilityGenerationsLogic'@@ -300,7 +301,7 @@ function AIObservabilityGenerations(): JSX.Element {),},person: aiObservabilityColumnRenderers.person,- "'' -- Sentiment": aiObservabilityColumnRenderers["'' -- Sentiment"],+ [GENERATION_SENTIMENT_SELECT]: aiObservabilityColumnRenderers[GENERATION_SENTIMENT_SELECT],'properties.$ai_tools_called': aiObservabilityColumnRenderers['properties.$ai_tools_called'],"f'{properties.$ai_model}' -- Model": {renderTitle: () => renderSortableColumnTitle('properties.$ai_model', 'Model'),diff --git a/products/ai_observability/frontend/AIObservabilitySessionScene.tsx b/products/ai_observability/frontend/AIObservabilitySessionScene.tsxindex 51c2775846e9..ded7bd268165 100644--- a/products/ai_observability/frontend/AIObservabilitySessionScene.tsx+++ b/products/ai_observability/frontend/AIObservabilitySessionScene.tsx@@ -8,7 +8,6 @@ import { LemonButton, LemonTag, Spinner, SpinnerOverlay, Tooltip } from '@posthoimport { AccessControlAction } from 'lib/components/AccessControlAction'import { TZLabel } from 'lib/components/TZLabel'import { FEATURE_FLAGS } from 'lib/constants'-import { dayjs } from 'lib/dayjs'import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'import { Link } from 'lib/lemon-ui/Link'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'@@ -29,9 +28,7 @@ import { AIObservabilityTraceEvents } from './components/AIObservabilityTraceEveimport { SentimentBar } from './components/SentimentTag'import { TranscriptBubbleStream } from './ConversationDisplay/TranscriptBubbleStream'import { SessionTurn } from './extractSessionTurns'-import { llmSentimentLazyLoaderLogic } from './llmSentimentLazyLoaderLogic'import { llmSessionTitleLazyLoaderLogic } from './llmSessionTitleLazyLoaderLogic'-import { SENTIMENT_DATE_WINDOW_DAYS } from './sentimentUtils'import { formatLLMCost, getTraceTimestamp, sanitizeTraceUrlSearchParams } from './utils'const LLMASessionFeedbackDisplay = lazy(() =>@@ -59,33 +56,13 @@ export function AIObservabilitySessionScene(): JSX.Element {)}-function SessionTraceSentimentBar({ traceId, createdAt }: { traceId: string; createdAt?: string }): JSX.Element | null {- const { sentimentByTraceId, isTraceLoading } = useValues(llmSentimentLazyLoaderLogic)- const { ensureSentimentLoaded } = useActions(llmSentimentLazyLoaderLogic)-- const cached = sentimentByTraceId[traceId]- const loading = isTraceLoading(traceId)-- if (cached === undefined && !loading) {- ensureSentimentLoaded(- traceId,- createdAt- ? { dateFrom: createdAt, dateTo: dayjs(createdAt).add(SENTIMENT_DATE_WINDOW_DAYS, 'day').toISOString() }- : undefined- )- }-- if (cached === null) {+function SessionTraceSentimentBar({ sentiment }: { sentiment?: LLMTrace['sentiment'] }): JSX.Element | null {+ if (!sentiment) {return null}return (- <SentimentBar- label={cached?.label ?? 'neutral'}- score={cached?.score ?? 0}- loading={loading || cached === undefined}- messages={cached?.messages}- />+ <SentimentBar label={sentiment.label ?? 'neutral'} score={sentiment.score ?? 0} messages={sentiment.messages} />)}@@ -321,7 +298,6 @@ function SessionTurnView({{showStepsPanel && (<StepsPanel- traceId={trace.id}fullTrace={fullTrace}expandedEventIds={expandedGenerationIds}onToggleEventExpand={toggleGenerationExpanded}@@ -330,7 +306,7 @@ function SessionTurnView({</div><div className="w-40 shrink-0 flex flex-col gap-1 text-xs text-muted">- <SessionTraceSentimentBar traceId={trace.id} createdAt={trace.createdAt} />+ <SessionTraceSentimentBar sentiment={trace.sentiment} /><div className="flex flex-col gap-1 items-start">{hasTranscript && (<LemonButton size="xsmall" type="tertiary" onClick={() => toggleSteps(trace.id)}>@@ -405,12 +381,10 @@ function TurnBody({}function StepsPanel({- traceId,fullTrace,expandedEventIds,onToggleEventExpand,}: {- traceId: stringfullTrace: LLMTrace | undefinedexpandedEventIds: Set<string>onToggleEventExpand: (eventId: string) => void@@ -422,7 +396,6 @@ function StepsPanel({isLoading={false}expandedEventIds={expandedEventIds}onToggleEventExpand={onToggleEventExpand}- traceId={traceId}/></div>)diff --git a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx b/products/ai_observability/frontend/AIObservabilityTraceScene.tsxindex b03cc566f2c7..07b38c712684 100644--- a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx+++ b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx@@ -44,7 +44,6 @@ import { JSONViewer } from 'lib/components/JSONViewer'import { NotFound } from 'lib/components/NotFound'import ViewRecordingButton, { RecordingPlayerType } from 'lib/components/ViewRecordingButton/ViewRecordingButton'import { FEATURE_FLAGS } from 'lib/constants'-import { dayjs } from 'lib/dayjs'import { useKeyboardHotkeys } from 'lib/hooks/useKeyboardHotkeys'import { IconWithCount } from 'lib/lemon-ui/icons/icons'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'@@ -85,16 +84,14 @@ import { SaveToDatasetButton } from './datasets/SaveToDatasetButton'import { FeedbackViewDisplay } from './feedback-view/FeedbackViewDisplay'import { generationEvaluationRunsLogic } from './generationEvaluationRunsLogic'import { useAIData } from './hooks/useAIData'-import { llmGenerationSentimentLazyLoaderLogic } from './llmGenerationSentimentLazyLoaderLogic'import { LLMInputOutput } from './LLMInputOutput'import { llmPersonsLazyLoaderLogic } from './llmPersonsLazyLoaderLogic'-import { llmSentimentLazyLoaderLogic } from './llmSentimentLazyLoaderLogic'import { normalizeMessages } from './messageNormalization'import { openInPlayground } from './playground/llmPlaygroundPromptsLogic'import { ReviewQueuePickerModal } from './reviewQueues/ReviewQueuePickerModal'import { reviewQueuesApi } from './reviewQueues/reviewQueuesApi'import { SearchHighlight } from './SearchHighlight'-import { SENTIMENT_DATE_WINDOW_DAYS } from './sentimentUtils'+import { sentimentEvaluationAvailabilityLogic } from './sentimentEvaluationAvailabilityLogic'import { SummaryViewDisplay } from './summary-view/SummaryViewDisplay'import { TextViewDisplay } from './text-view/TextViewDisplay'import { exportTraceToClipboard, exportTraceToFile } from './traceExportUtils'@@ -610,9 +607,18 @@ function CreateSentimentEvaluationButton({ traceId }: { traceId: string }): JSX.const { generationEvaluationRuns, generationEvaluationRunsLoading } = useValues(generationEvaluationRunsLogic({ lookupBy: 'trace', traceId }))+ const { hasLoadedSentimentEvaluations, hasSentimentEvaluations, sentimentEvaluationsLoading } = useValues(+ sentimentEvaluationAvailabilityLogic+ )const hasSentimentEvaluationRun = generationEvaluationRuns.some(isSentimentRun)- if (generationEvaluationRunsLoading || hasSentimentEvaluationRun) {+ if (+ generationEvaluationRunsLoading ||+ sentimentEvaluationsLoading ||+ !hasLoadedSentimentEvaluations ||+ hasSentimentEvaluations ||+ hasSentimentEvaluationRun+ ) {return null}@@ -1001,17 +1007,7 @@ function TraceMetadata({showBillingInfo?: boolean}): JSX.Element {const { personsCache } = useValues(llmPersonsLazyLoaderLogic)- const { getTraceSentiment, isTraceLoading } = useValues(llmSentimentLazyLoaderLogic)- const { ensureSentimentLoaded } = useActions(llmSentimentLazyLoaderLogic)-- const sentimentResult = getTraceSentiment(trace.id)- const sentimentLoading = isTraceLoading(trace.id)- if (sentimentResult === undefined && !sentimentLoading) {- ensureSentimentLoaded(trace.id, {- dateFrom: trace.createdAt,- dateTo: dayjs(trace.createdAt).add(SENTIMENT_DATE_WINDOW_DAYS, 'day').toISOString(),- })- }+ const sentimentResult = trace.sentimentconst traceCostContext = costContextFromTrace(trace)@@ -1053,7 +1049,7 @@ function TraceMetadata({{feedbackEvents.map((feedback) => (<FeedbackTag key={feedback.id} properties={feedback.properties} />))}- {sentimentResult && !sentimentLoading && (+ {sentimentResult && (<Chip title="Sentiment"><SentimentBarlabel={sentimentResult.label ?? 'neutral'}@@ -1208,8 +1204,6 @@ const TreeNode = React.memo(function TraceNode({const traceLogic = useMountedLogic(aiObservabilityTraceLogic)const { eventTypeExpanded } = useValues(traceLogic)const { searchParams } = useValues(router)- const { getGenerationSentiment, isGenerationLoading } = useValues(llmGenerationSentimentLazyLoaderLogic)- const { ensureGenerationSentimentLoaded } = useActions(llmGenerationSentimentLazyLoaderLogic)const eventType = getEventType(item)const isCollapsedDueToFilter = !eventTypeExpanded(eventType)const isBillable =@@ -1219,13 +1213,7 @@ const TreeNode = React.memo(function TraceNode({!!(item as LLMTraceEvent).properties?.$ai_billableconst isGeneration = isLLMEvent(item) && (item as LLMTraceEvent).event === '$ai_generation'- const genSentiment = isGeneration ? getGenerationSentiment(item.id) : undefined- if (isGeneration && genSentiment === undefined && !isGenerationLoading(item.id)) {- ensureGenerationSentimentLoaded(item.id, {- dateFrom: topLevelTrace.createdAt,- dateTo: dayjs(topLevelTrace.createdAt).add(SENTIMENT_DATE_WINDOW_DAYS, 'day').toISOString(),- })- }+ const genSentiment = isGeneration ? (item as LLMTraceEvent).sentiment : undefinedconst children = [isLLMEvent(item) && item.properties.$ai_is_error && (@@ -1694,6 +1682,7 @@ const EventContent = React.memo(eventId={event.id}generationEventId={event.id}traceId={trace.id}+ timestamp={event.createdAt}rawInput={event.properties.$ai_input}rawOutput={event.properties.$ai_output_choices ??@@ -1706,11 +1695,13 @@ const EventContent = React.memo(searchQuery={searchQuery}displayOption={displayOption}highlightMessageIndex={highlightMessageIndex}+ generationSentiment={event.sentiment}/>) : event.event === '$ai_embedding' ? (<EventContentConversationeventId={event.id}traceId={trace.id}+ timestamp={event.createdAt}rawInput={event.properties.$ai_input}rawOutput="Embedding vector generated"searchQuery={searchQuery}@@ -1720,6 +1711,7 @@ const EventContent = React.memo(<EventContentConversationeventId={event.id}traceId={trace.id}+ timestamp={event.createdAt}rawInput={event.properties.$ai_input_state}rawOutput={event.properties.$ai_output_state}errorData={event.properties.$ai_error}diff --git a/products/ai_observability/frontend/AIObservabilityTracesScene.tsx b/products/ai_observability/frontend/AIObservabilityTracesScene.tsxindex 3cd77e7ab7cf..688a6b211e42 100644--- a/products/ai_observability/frontend/AIObservabilityTracesScene.tsx+++ b/products/ai_observability/frontend/AIObservabilityTracesScene.tsx@@ -114,7 +114,7 @@ function TracesOptionsMenu(): JSX.Element | null {onChange={setShowSentimentColumn}label="Show sentiment"fullWidth- tooltip="Show the sentiment column. Turn off to skip computing sentiment for traces in the table."+ tooltip="Show the sentiment column from stored sentiment evaluation results."data-attr="llm-traces-show-sentiment-toggle"/></div>diff --git a/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.tsx b/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.tsxindex 3179ff4080b3..6fc32835bf1d 100644--- a/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.tsx+++ b/products/ai_observability/frontend/ConversationDisplay/ConversationMessagesDisplay.tsx@@ -1,5 +1,4 @@import clsx from 'clsx'-import { useValues } from 'kea'import React from 'react'import { IconCode, IconEye, IconMarkdown, IconMarkdownFilled, IconWrench } from '@posthog/icons'@@ -13,10 +12,10 @@ import { isObject } from 'lib/utils/guards'import { getJsonContainerForDisplay, JSONValueDisplay } from '../components/JSONValueDisplay'import { MessageSentimentBar } from '../components/SentimentTag'-import { llmGenerationSentimentLazyLoaderLogic } from '../llmGenerationSentimentLazyLoaderLogic'import { LLMInputOutput } from '../LLMInputOutput'import { SearchHighlight } from '../SearchHighlight'import { containsSearchQuery } from '../searchUtils'+import type { GenerationSentiment } from '../sentimentResults'import { CompatMessage, MultiModalContentItem, VercelSDKImageMessage } from '../types'import {getGeminiInlineData,@@ -78,7 +77,7 @@ export function ConversationMessagesDisplay({searchQuery,displayOption,traceId,- generationEventId,+ generationSentiment,highlightMessageIndex,}: {inputNormalized: CompatMessage[]@@ -93,6 +92,7 @@ export function ConversationMessagesDisplay({displayOption?: ConversationDisplayOptiontraceId?: string | nullgenerationEventId?: string+ generationSentiment?: GenerationSentiment | null/** Original $ai_input index to auto-expand and highlight (e.g. from sentiment tab deep link) */highlightMessageIndex?: number | null}): JSX.Element {@@ -106,9 +106,6 @@ export function ConversationMessagesDisplay({const outputRolesSignature = outputNormalized.map((message) => message.role).join('|')const inputMessageShowStates = messageShowStates.inputconst outputMessageShowStates = messageShowStates.output- const { getGenerationSentiment } = useValues(llmGenerationSentimentLazyLoaderLogic)-- const generationSentiment = generationEventId ? getGenerationSentiment(generationEventId) : undefined// Sentiment is only available for user messages that have a known original// index in $ai_input (sourceIndex). System/assistant messages and messagesdiff --git a/products/ai_observability/frontend/aiObservabilityAIDataLogic.test.ts b/products/ai_observability/frontend/aiObservabilityAIDataLogic.test.tsindex 6ddab0faf7e8..7943f806d1ee 100644--- a/products/ai_observability/frontend/aiObservabilityAIDataLogic.test.ts+++ b/products/ai_observability/frontend/aiObservabilityAIDataLogic.test.ts@@ -15,7 +15,7 @@ describe('aiObservabilityAIDataLogic', () => {initKeaTests()})- it('passes through when both input and output are already present — no TraceQuery fetch', async () => {+ it('passes through when both input and output are already present — no heavy-prop lookup', async () => {const logic = aiObservabilityAIDataLogic()logic.mount()@@ -41,32 +41,20 @@ describe('aiObservabilityAIDataLogic', () => {})expect(mockApi.query).not.toHaveBeenCalled()+ expect(mockApi.queryHogQL).not.toHaveBeenCalled()})- it('fetches via TraceQuery and populates heavy props when input is missing', async () => {- jest.spyOn(mockApi, 'query').mockResolvedValue({+ it('fetches from ai_events and populates heavy props when input is missing', async () => {+ jest.spyOn(mockApi, 'queryHogQL').mockResolvedValue({results: [- {- id: 'trace-1',- events: [- {- id: 'event-1',- event: '$ai_generation',- createdAt: '2026-04-30T10:00:00Z',- properties: {- $ai_input: [{ role: 'user', content: 'hi' }],- $ai_output_choices: [{ role: 'assistant', content: 'hello' }],- $ai_tools: [{ function: { name: 'search' } }],- },- },- {- id: 'event-2',- event: '$ai_span',- createdAt: '2026-04-30T10:00:01Z',- properties: {},- },- ],- },+ [+ JSON.stringify([{ role: 'user', content: 'post-strip hi' }]),+ null,+ JSON.stringify([{ role: 'assistant', content: 'post-strip hello' }]),+ null,+ null,+ JSON.stringify([{ function: { name: 'search' } }]),+ ],],} as any)@@ -87,18 +75,65 @@ describe('aiObservabilityAIDataLogic', () => {.toMatchValues({aiDataCache: {'event-1': {- input: [{ role: 'user', content: 'hi' }],- output: [{ role: 'assistant', content: 'hello' }],+ input: [{ role: 'user', content: 'post-strip hi' }],+ output: [{ role: 'assistant', content: 'post-strip hello' }],tools: [{ function: { name: 'search' } }],},},})- expect(mockApi.query).toHaveBeenCalledTimes(1)+ expect(mockApi.queryHogQL).toHaveBeenCalledTimes(1)+ expect(mockApi.queryHogQL.mock.calls[0][0]).toContain('FROM posthog.ai_events AS ai_events')+ expect(mockApi.query).not.toHaveBeenCalled()+ })++ it('falls back to events when ai_events has no heavy props row', async () => {+ jest.spyOn(mockApi, 'queryHogQL')+ .mockResolvedValueOnce({ results: [] } as any)+ .mockResolvedValueOnce({+ results: [+ [+ [{ role: 'user', content: 'events hi' }],+ null,+ [{ role: 'assistant', content: 'events hello' }],+ null,+ null,+ [{ function: { name: 'events-search' } }],+ ],+ ],+ } as any)++ const logic = aiObservabilityAIDataLogic()+ logic.mount()++ await expectLogic(logic, () => {+ logic.actions.loadAIDataForEvent({+ eventId: 'event-1',+ input: undefined,+ output: undefined,+ tools: undefined,+ traceId: 'trace-1',+ timestamp: '2026-04-30T10:00:00Z',+ })+ })+ .toFinishAllListeners()+ .toMatchValues({+ aiDataCache: {+ 'event-1': {+ input: [{ role: 'user', content: 'events hi' }],+ output: [{ role: 'assistant', content: 'events hello' }],+ tools: [{ function: { name: 'events-search' } }],+ },+ },+ })++ expect(mockApi.queryHogQL).toHaveBeenCalledTimes(2)+ expect(mockApi.queryHogQL.mock.calls[0][0]).toContain('FROM posthog.ai_events AS ai_events')+ expect(mockApi.queryHogQL.mock.calls[1][0]).toContain('FROM events')})- it('degrades gracefully to the passed-in values when TraceQuery throws', async () => {- jest.spyOn(mockApi, 'query').mockRejectedValue(new Error('network down'))+ it('degrades gracefully to the passed-in values when the lookup throws', async () => {+ jest.spyOn(mockApi, 'queryHogQL').mockRejectedValue(new Error('network down'))const logic = aiObservabilityAIDataLogic()logic.mount()@@ -130,7 +165,7 @@ describe('aiObservabilityAIDataLogic', () => {['timestamp missing', { traceId: 'trace-1', timestamp: undefined }],['both missing', { traceId: undefined, timestamp: undefined }],])('skips the fetch when trace coordinates are incomplete (%s)', async (_label, coords) => {- const querySpy = jest.spyOn(mockApi, 'query')+ const querySpy = jest.spyOn(mockApi, 'queryHogQL')const logic = aiObservabilityAIDataLogic()logic.mount()diff --git a/products/ai_observability/frontend/aiObservabilityAIDataLogic.ts b/products/ai_observability/frontend/aiObservabilityAIDataLogic.tsindex 33bedc150e07..3e9a0bddab4d 100644--- a/products/ai_observability/frontend/aiObservabilityAIDataLogic.ts+++ b/products/ai_observability/frontend/aiObservabilityAIDataLogic.ts@@ -2,11 +2,55 @@ import { actions, kea, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import api from 'lib/api'+import { dayjs } from 'lib/dayjs'-import { NodeKind, TraceQuery } from '~/queries/schema/schema-general'+import { ProductKey } from '~/queries/schema/schema-general'+import { hogql } from '~/queries/utils'import type { aiObservabilityAIDataLogicType } from './aiObservabilityAIDataLogicType'-import { readAiInput, readAiOutput } from './utils'+import { parseJSONPreview } from './utils'++const AI_DATA_QUERY_TAGS = {+ productKey: ProductKey.AI_OBSERVABILITY,+ scene: 'ai_observability_trace',+}++const EVENT_TIMESTAMP_WINDOW_MINUTES = 10++type AIDataQueryRow = [unknown, unknown, unknown, unknown, unknown, unknown]++interface AIDataQuerySource {+ from: string+ traceIdExpression: string+ inputExpression: string+ outputExpression: string+ outputChoicesExpression: string+ inputStateExpression: string+ outputStateExpression: string+ toolsExpression: string+}++const AI_EVENTS_SOURCE: AIDataQuerySource = {+ from: 'posthog.ai_events AS ai_events',+ traceIdExpression: 'trace_id',+ inputExpression: 'input',+ outputExpression: 'output',+ outputChoicesExpression: 'output_choices',+ inputStateExpression: 'input_state',+ outputStateExpression: 'output_state',+ toolsExpression: 'tools',+}++const EVENTS_SOURCE: AIDataQuerySource = {+ from: 'events',+ traceIdExpression: 'properties.$ai_trace_id',+ inputExpression: 'properties.$ai_input',+ outputExpression: 'properties.$ai_output',+ outputChoicesExpression: 'properties.$ai_output_choices',+ inputStateExpression: 'properties.$ai_input_state',+ outputStateExpression: 'properties.$ai_output_state',+ toolsExpression: 'properties.$ai_tools',+}export interface AIData {input: unknown@@ -23,8 +67,114 @@ export interface LoadAIDataParams {timestamp?: string}+function isUsableValue(value: unknown): boolean {+ return value !== null && value !== undefined && value !== '' && value !== 'null'+}++function parseHeavyValue(value: unknown): unknown {+ if (!isUsableValue(value)) {+ return undefined+ }+ try {+ return parseJSONPreview(value)+ } catch {+ return value+ }+}++function firstUsableValue(...values: unknown[]): unknown {+ for (const value of values) {+ const parsed = parseHeavyValue(value)+ if (isUsableValue(parsed)) {+ return parsed+ }+ }+ return undefined+}++function mapAIDataQueryRow(row: AIDataQueryRow): AIData {+ const [input, output, outputChoices, inputState, outputState, tools] = row+ return {+ input: firstUsableValue(input, inputState),+ output: firstUsableValue(outputChoices, outputState, output),+ tools: parseHeavyValue(tools),+ }+}++function hasLoadedAIData(data: AIData): boolean {+ return isUsableValue(data.input) || isUsableValue(data.output) || isUsableValue(data.tools)+}++function hasInputAndOutput(data: AIData): boolean {+ return data.input != null && data.output != null+}++function mergeAIData(base: AIData, loaded: AIData | null): AIData {+ if (!loaded) {+ return base+ }+ return {+ input: loaded.input ?? base.input,+ output: loaded.output ?? base.output,+ tools: loaded.tools ?? base.tools,+ }+}++async function queryAIDataForEvent(params: LoadAIDataParams, source: AIDataQuerySource): Promise<AIData | null> {+ if (!params.traceId || !params.timestamp) {+ return null+ }++ const eventTimestamp = dayjs(params.timestamp)+ if (!eventTimestamp.isValid()) {+ return null+ }++ const dateFrom = eventTimestamp.subtract(EVENT_TIMESTAMP_WINDOW_MINUTES, 'minute').toISOString()+ const dateTo = eventTimestamp.add(EVENT_TIMESTAMP_WINDOW_MINUTES, 'minute').toISOString()+ const response = await api.queryHogQL<AIDataQueryRow[]>(+ hogql`+ SELECT+ argMax(ai_input, timestamp) AS ai_input,+ argMax(ai_output, timestamp) AS ai_output,+ argMax(ai_output_choices, timestamp) AS ai_output_choices,+ argMax(ai_input_state, timestamp) AS ai_input_state,+ argMax(ai_output_state, timestamp) AS ai_output_state,+ argMax(ai_tools, timestamp) AS ai_tools+ FROM (+ SELECT+ toString(uuid) AS uuid,+ timestamp,+ ${hogql.raw(source.inputExpression)} AS ai_input,+ ${hogql.raw(source.outputExpression)} AS ai_output,+ ${hogql.raw(source.outputChoicesExpression)} AS ai_output_choices,+ ${hogql.raw(source.inputStateExpression)} AS ai_input_state,+ ${hogql.raw(source.outputStateExpression)} AS ai_output_state,+ ${hogql.raw(source.toolsExpression)} AS ai_tools+ FROM ${hogql.raw(source.from)}+ WHERE ${hogql.raw(source.traceIdExpression)} = ${params.traceId}+ AND toString(uuid) = ${params.eventId}+ AND timestamp >= toDateTime(${dateFrom})+ AND timestamp <= toDateTime(${dateTo})+ )+ GROUP BY uuid+ LIMIT 1+ `,+ { ...AI_DATA_QUERY_TAGS, name: 'ai_observability_event_heavy_props_lookup' }+ )++ const row = response.results?.[0]+ if (!row) {+ return null+ }++ const data = mapAIDataQueryRow(row)+ return hasLoadedAIData(data) ? data : null+}+async function loadAIDataAsync(params: LoadAIDataParams): Promise<AIData> {- const { eventId, input, output, tools, traceId, timestamp } = params+ const { input, output, tools, traceId, timestamp } = params+ let loadedData: AIData = { input, output, tools }// Passthrough: caller already has both sides of the conversation (e.g. the trace page// hydrates rows from the TraceQuery that has heavy props merged back). No fetch needed.@@ -38,30 +188,24 @@ async function loadAIDataAsync(params: LoadAIDataParams): Promise<AIData> {return { input, output, tools }}- // Heavy props live only on `ai_events`. Reuse the existing TraceQuery pipeline- // (ai_events first, shared `events` on zero rows) to fetch the event's heavy columns- // by (trace_id, event uuid). TraceQueryDateRange auto-widens the window by ±10 minutes,- // so a single timestamp is sufficient.+ // Query the dedicated table directly first. TraceQuery still has a rollout gate, so+ // using it here can repeat the original `events` read and miss stripped heavy props.try {- const traceQuery: TraceQuery = {- kind: NodeKind.TraceQuery,- traceId,- dateRange: { date_from: timestamp, date_to: timestamp },- }- const response = await api.query(traceQuery)- const event = response.results?.[0]?.events?.find((e) => e.id === eventId)- if (!event) {- return { input, output, tools }- }- const props = event.properties ?? {}- return {- input: readAiInput(props) ?? input,- output: readAiOutput(props) ?? output,- tools: props.$ai_tools ?? tools,+ const aiEventsData = await queryAIDataForEvent(params, AI_EVENTS_SOURCE)+ loadedData = mergeAIData(loadedData, aiEventsData)+ if (hasInputAndOutput(loadedData)) {+ return loadedData}} catch (error) {- console.warn('[aiObservabilityAIDataLogic] failed to load heavy AI props via TraceQuery', error)- return { input, output, tools }+ console.warn('[aiObservabilityAIDataLogic] failed to load heavy AI props from ai_events', error)+ }++ try {+ const eventsData = await queryAIDataForEvent(params, EVENTS_SOURCE)+ return mergeAIData(loadedData, eventsData)+ } catch (error) {+ console.warn('[aiObservabilityAIDataLogic] failed to load heavy AI props from events', error)+ return loadedData}}diff --git a/products/ai_observability/frontend/aiObservabilityColumnRenderers.tsx b/products/ai_observability/frontend/aiObservabilityColumnRenderers.tsxindex 48ed88eb26f2..4e9b2e1ba163 100644--- a/products/ai_observability/frontend/aiObservabilityColumnRenderers.tsx+++ b/products/ai_observability/frontend/aiObservabilityColumnRenderers.tsx@@ -22,8 +22,9 @@ import { LLMMessageDisplay } from './ConversationDisplay/ConversationMessagesDisimport { EventData, useAIData } from './hooks/useAIData'import { llmGenerationSentimentLazyLoaderLogic } from './llmGenerationSentimentLazyLoaderLogic'import { llmPersonsLazyLoaderLogic } from './llmPersonsLazyLoaderLogic'-import { llmSentimentLazyLoaderLogic } from './llmSentimentLazyLoaderLogic'import { normalizeMessages } from './messageNormalization'+import type { GenerationSentimentLookup } from './sentimentQueries'+import { GENERATION_SENTIMENT_SELECT } from './sentimentResults'import { traceReviewsLazyLoaderLogic } from './traceReviews/traceReviewsLazyLoaderLogic'import { TraceReviewValue } from './traceReviews/TraceReviewValue'import { CompatMessage } from './types'@@ -191,47 +192,58 @@ export function LazyPersonColumnCell({ distinctId }: { distinctId: string }): JSreturn <PersonColumnCell person={personData} />}-function LazySentimentColumnCell({ traceId }: { traceId: string }): JSX.Element {- const { sentimentByTraceId, isTraceLoading } = useValues(llmSentimentLazyLoaderLogic)- const { ensureSentimentLoaded } = useActions(llmSentimentLazyLoaderLogic)- const { dateFilter } = useValues(aiObservabilitySharedLogic)-- const cached = sentimentByTraceId[traceId]- const loading = isTraceLoading(traceId)+function getStringColumnValue(record: unknown[], columns: string[], column: string): string | null {+ const index = columns.findIndex((col) => col === column)+ if (index < 0) {+ return null+ }- // Deferred via effect so trace-messages/persons effects (which also run- // after commit) get a chance to dispatch before sentiment's batched- // fan-out claims the browser's connection pool.- useEffect(() => {- if (cached === undefined && !loading) {- ensureSentimentLoaded(traceId, dateFilter)- }- }, [traceId, cached, loading, dateFilter, ensureSentimentLoaded])+ const value = record[index]+ return typeof value === 'string' && value ? value : null+}- if (loading || cached === undefined) {- return <AIDataLoading variant="inline" />+function getGenerationSentimentLookup(record: unknown, query: DataTableNode): GenerationSentimentLookup | null {+ if (!Array.isArray(record) || !isEventsQuery(query.source)) {+ return null}- if (cached === null) {- return <>–</>+ const columns = query.source.select ?? []+ const eventId = getStringColumnValue(record, columns, 'uuid')+ const traceId = getStringColumnValue(record, columns, 'properties.$ai_trace_id')++ if (!eventId || !traceId) {+ return null}- return <SentimentBar label={cached.label} score={cached.score} size="full" messages={cached.messages} />+ const generationId = getStringColumnValue(record, columns, 'properties.$ai_generation_id')+ const generationIds = generationId && generationId !== eventId ? [eventId, generationId] : [eventId]++ return {+ key: eventId,+ traceId,+ generationIds,+ }}-function LazyGenerationSentimentCell({ generationEventId }: { generationEventId: string }): JSX.Element {- const { sentimentByGenerationId, isGenerationLoading } = useValues(llmGenerationSentimentLazyLoaderLogic)+function LazyGenerationSentimentCell({ lookup }: { lookup: GenerationSentimentLookup }): JSX.Element {+ const { getGenerationSentiment, isGenerationLoading } = useValues(llmGenerationSentimentLazyLoaderLogic)const { ensureGenerationSentimentLoaded } = useActions(llmGenerationSentimentLazyLoaderLogic)- const { dateFilter } = useValues(aiObservabilitySharedLogic)- const cached = sentimentByGenerationId[generationEventId]- const loading = isGenerationLoading(generationEventId)+ const lookupKey = lookup.key+ const lookupTraceId = lookup.traceId+ const lookupGenerationIdsKey = lookup.generationIds.join('\0')+ const cached = getGenerationSentiment(lookupKey)+ const loading = isGenerationLoading(lookupKey)useEffect(() => {if (cached === undefined && !loading) {- ensureGenerationSentimentLoaded(generationEventId, dateFilter)+ ensureGenerationSentimentLoaded({+ key: lookupKey,+ traceId: lookupTraceId,+ generationIds: lookupGenerationIdsKey ? lookupGenerationIdsKey.split('\0') : [],+ })}- }, [generationEventId, cached, loading, dateFilter, ensureGenerationSentimentLoaded])+ }, [cached, ensureGenerationSentimentLoaded, loading, lookupGenerationIdsKey, lookupKey, lookupTraceId])if (loading || cached === undefined) {return <AIDataLoading variant="inline" />@@ -491,33 +503,28 @@ export const aiObservabilityColumnRenderers: Record<string, QueryContextColumn>return <>–</>}const traceRecord = record as LLMTrace- if (!traceRecord.id) {+ if (!traceRecord.sentiment) {return <>–</>}- return <LazySentimentColumnCell traceId={traceRecord.id} />+ return (+ <SentimentBar+ label={traceRecord.sentiment.label}+ score={traceRecord.sentiment.score}+ size="full"+ messages={traceRecord.sentiment.messages}+ />+ )},},- "'' -- Sentiment": {+ [GENERATION_SENTIMENT_SELECT]: {title: 'Sentiment',render: ({ record, query }) => {- if (!Array.isArray(record) || !isDataTableNode(query) || !isEventsQuery(query.source)) {- return <>–</>- }-- const select = query.source.select ?? []- const uuidIdx = select.findIndex((c) => c === 'uuid')-- if (uuidIdx < 0) {- return <>–</>- }-- const uuid = record[uuidIdx]-- if (typeof uuid !== 'string') {+ if (!isDataTableNode(query)) {return <>–</>}- return <LazyGenerationSentimentCell generationEventId={uuid} />+ const lookup = getGenerationSentimentLookup(record, query)+ return lookup ? <LazyGenerationSentimentCell lookup={lookup} /> : <>–</>},},'properties.$ai_tools_called': {diff --git a/products/ai_observability/frontend/aiObservabilitySessionDataLogic.ts b/products/ai_observability/frontend/aiObservabilitySessionDataLogic.tsindex c00a32e5c839..7411920ee357 100644--- a/products/ai_observability/frontend/aiObservabilitySessionDataLogic.ts+++ b/products/ai_observability/frontend/aiObservabilitySessionDataLogic.ts@@ -204,7 +204,7 @@ export const aiObservabilitySessionDataLogic = kea<aiObservabilitySessionDataLoglisteners(({ actions, values }) => {// Closure-scoped in-flight lock for `loadFullTrace`. Mirrors the pattern used// by sibling lazy loaders in this product (llmPersonsLazyLoaderLogic,- // llmSentimentLazyLoaderLogic, traceReviewsLazyLoaderLogic, etc.). We can't+ // traceReviewsLazyLoaderLogic, etc.). We can't// rely on `values.loadingFullTraces` for this guard because kea reducers run// synchronously *before* listeners — so the reducer has already added this// traceId by the time the listener checks. The closure-scoped Set lets the@@ -248,6 +248,7 @@ export const aiObservabilitySessionDataLogic = kea<aiObservabilitySessionDataLogconst traceQuery: TraceQuery = {kind: NodeKind.TraceQuery,traceId,+ includeSentiment: true,}try {const response = await api.query(traceQuery)diff --git a/products/ai_observability/frontend/aiObservabilitySessionLogic.ts b/products/ai_observability/frontend/aiObservabilitySessionLogic.tsindex d319f7bee351..26774c16f01d 100644--- a/products/ai_observability/frontend/aiObservabilitySessionLogic.ts+++ b/products/ai_observability/frontend/aiObservabilitySessionLogic.ts@@ -73,6 +73,7 @@ export const aiObservabilitySessionLogic = kea<aiObservabilitySessionLogicType>(): DataTableNode => {const tracesQuery: TracesQuery = {kind: NodeKind.TracesQuery,+ includeSentiment: true,dateRange: dateRange?.dateFrom? {date_from: dateRange.dateFrom,diff --git a/products/ai_observability/frontend/aiObservabilityTraceDataLogic.ts b/products/ai_observability/frontend/aiObservabilityTraceDataLogic.tsindex ca28b2b61046..f7b634c5cbeb 100644--- a/products/ai_observability/frontend/aiObservabilityTraceDataLogic.ts+++ b/products/ai_observability/frontend/aiObservabilityTraceDataLogic.ts@@ -21,7 +21,6 @@ import { InsightLogicProps } from '~/types'import type { aiObservabilityTraceDataLogicType } from './aiObservabilityTraceDataLogicType'import { aiObservabilityTraceLogic } from './aiObservabilityTraceLogic'import { llmPersonsLazyLoaderLogic } from './llmPersonsLazyLoaderLogic'-import { llmSentimentLazyLoaderLogic } from './llmSentimentLazyLoaderLogic'import { captureNormalizationFailure, normalizeMessages } from './messageNormalization'import {SearchOccurrence,@@ -30,7 +29,6 @@ import {findSidebarOccurrences,findTraceOccurrences,} from './searchUtils'-import { SENTIMENT_DATE_WINDOW_DAYS } from './sentimentUtils'import { formatLLMUsage, getEventType, getSessionID, isLLMEvent } from './utils'export interface TraceDataLogicProps {@@ -44,6 +42,7 @@ function getDataNodeLogicProps({ traceId, query, cachedResults }: TraceDataLogicconst fallbackTraceQuery: TraceQuery = {kind: NodeKind.TraceQuery,traceId,+ includeSentiment: true,// Match trace logic defaults so we still fetch data if query is briefly undefined.dateRange: {date_from: dayjs.utc().subtract(1, 'year').startOf('day').toISOString(),@@ -504,13 +503,6 @@ export const aiObservabilityTraceDataLogic = kea<aiObservabilityTraceDataLogicTyllmPersonsLazyLoaderLogic.actions.ensurePersonLoaded(trace.distinctId)}- if (trace?.id) {- llmSentimentLazyLoaderLogic.actions.ensureSentimentLoaded(trace.id, {- dateFrom: trace.createdAt,- dateTo: dayjs(trace.createdAt).add(SENTIMENT_DATE_WINDOW_DAYS, 'day').toISOString(),- })- }-actions.reportSingleTraceLoadIfReady()},})),diff --git a/products/ai_observability/frontend/aiObservabilityTraceLogic.ts b/products/ai_observability/frontend/aiObservabilityTraceLogic.tsindex 2bdd2904bb0b..2f2c4fcc6a44 100644--- a/products/ai_observability/frontend/aiObservabilityTraceLogic.ts+++ b/products/ai_observability/frontend/aiObservabilityTraceLogic.ts@@ -186,8 +186,8 @@ export const aiObservabilityTraceLogic = kea<aiObservabilityTraceLogicType>([{initializeMessageStates: (_, { inputCount, outputCount }) => {// Will be initialized based on display option in listener- const inputStates = new Array(inputCount).fill(false)- const outputStates = new Array(outputCount).fill(true)+ const inputStates = Array.from({ length: inputCount }, () => false)+ const outputStates = Array.from({ length: outputCount }, () => true)return { input: inputStates, output: outputStates }},toggleMessage: (state, { type, index }) => {@@ -324,6 +324,7 @@ export const aiObservabilityTraceLogic = kea<aiObservabilityTraceLogicType>([const traceQuery: TraceQuery = {kind: NodeKind.TraceQuery,traceId,+ includeSentiment: true,dateRange: dateRange?.dateFrom? // dateFrom is a minimum timestamp of an event for a trace.{@@ -396,14 +397,14 @@ export const aiObservabilityTraceLogic = kea<aiObservabilityTraceLogicType>([initializeMessageStates: ({ inputCount, outputCount }) => {// Apply display option when initializingconst displayOption = values.displayOption- const inputStates = new Array(inputCount).fill(false).map((_, i) => {+ const inputStates = Array.from({ length: inputCount }, (_, i) => {if (displayOption === DisplayOption.ExpandAll) {return true}// For collapse except output and last input, only show last inputreturn i === inputCount - 1})- const outputStates = new Array(outputCount).fill(true)+ const outputStates = Array.from({ length: outputCount }, () => true)// Update the states directlyactions.applySearchResults(inputStates, outputStates)diff --git a/products/ai_observability/frontend/components/AIObservabilityEventCard.tsx b/products/ai_observability/frontend/components/AIObservabilityEventCard.tsxindex b6acbf2c8fac..4e1fec534c1f 100644--- a/products/ai_observability/frontend/components/AIObservabilityEventCard.tsx+++ b/products/ai_observability/frontend/components/AIObservabilityEventCard.tsx@@ -1,12 +1,10 @@-import { useValues } from 'kea'-import { IconChevronDown, IconChevronRight } from '@posthog/icons'import { LemonTag, Tooltip } from '@posthog/lemon-ui'+import type { LLMSentimentResult } from '~/queries/schema/schema-general'import { EventDetails } from '~/scenes/activity/explore/EventDetails'import { EventType } from '~/types'-import { llmGenerationSentimentLazyLoaderLogic } from '../llmGenerationSentimentLazyLoaderLogic'import { asString, costContextFromProperties, formatLLMCost, hasCostBreakdown } from '../utils'import { CostBreakdownTooltip } from './CostBreakdownTooltip'import { SentimentBar } from './SentimentTag'@@ -17,20 +15,17 @@ interface AIObservabilityEventCardProps {event: stringcreatedAt: stringproperties: Record<string, any>+ sentiment?: LLMSentimentResult}isExpanded: booleanonToggleExpand: () => void- traceId?: string}export function AIObservabilityEventCard({event,isExpanded,onToggleExpand,- traceId,}: AIObservabilityEventCardProps): JSX.Element {- const { getGenerationSentiment } = useValues(llmGenerationSentimentLazyLoaderLogic)-const isGeneration = event.event === '$ai_generation'const isEmbedding = event.event === '$ai_embedding'const eventForDetails: EventType = {@@ -105,18 +100,13 @@ export function AIObservabilityEventCard({</LemonTag></Tooltip>)}- {isGeneration &&- traceId &&- (() => {- const genSentiment = getGenerationSentiment(event.id)- return genSentiment ? (- <SentimentBar- label={genSentiment.label}- score={genSentiment.score}- messages={genSentiment.messages}- />- ) : null- })()}+ {isGeneration && event.sentiment && (+ <SentimentBar+ label={event.sentiment.label}+ score={event.sentiment.score}+ messages={event.sentiment.messages}+ />+ )}</div></div>{isExpanded && (diff --git a/products/ai_observability/frontend/components/AIObservabilityTraceEvents.tsx b/products/ai_observability/frontend/components/AIObservabilityTraceEvents.tsxindex 0b761b5ad274..b0f0ad6c61b3 100644--- a/products/ai_observability/frontend/components/AIObservabilityTraceEvents.tsx+++ b/products/ai_observability/frontend/components/AIObservabilityTraceEvents.tsx@@ -9,7 +9,6 @@ interface AIObservabilityTraceEventsProps {isLoading: booleanexpandedEventIds: Set<string>onToggleEventExpand: (eventId: string) => void- traceId?: string}export function AIObservabilityTraceEvents({@@ -17,7 +16,6 @@ export function AIObservabilityTraceEvents({isLoading,expandedEventIds,onToggleEventExpand,- traceId,}: AIObservabilityTraceEventsProps): JSX.Element {if (isLoading) {return <Spinner />@@ -49,7 +47,6 @@ export function AIObservabilityTraceEvents({event={event}isExpanded={expandedEventIds.has(event.id)}onToggleExpand={() => onToggleEventExpand(event.id)}- traceId={traceId}/>))}</>diff --git a/products/ai_observability/frontend/components/EventContentWithAsyncData.test.tsx b/products/ai_observability/frontend/components/EventContentWithAsyncData.test.tsxnew file mode 100644index 000000000000..597567a09fc5--- /dev/null+++ b/products/ai_observability/frontend/components/EventContentWithAsyncData.test.tsx@@ -0,0 +1,64 @@+import '@testing-library/jest-dom'++import { cleanup, render } from '@testing-library/react'+import { Provider } from 'kea'++import { initKeaTests } from '~/test/init'++import { useAIData } from '../hooks/useAIData'+import { EventContentConversation } from './EventContentWithAsyncData'++jest.mock('../customParser/useCustomParserMaxTool', () => ({+ useCustomParserMaxTool: jest.fn(() => null),+}))++jest.mock('../hooks/useAIData', () => ({+ useAIData: jest.fn(),+}))++const mockUseAIData = useAIData as jest.MockedFunction<typeof useAIData>++describe('EventContentConversation', () => {+ beforeEach(() => {+ initKeaTests()+ mockUseAIData.mockImplementation((eventData) => ({+ input: eventData?.input,+ output: eventData?.output,+ tools: eventData?.tools,+ isLoading: false,+ }))+ })++ afterEach(() => {+ cleanup()+ jest.resetAllMocks()+ })++ it('passes trace coordinates to the AI data loader', () => {+ const rawInput = [{ role: 'user', content: 'hi' }]+ const rawOutput = [{ role: 'assistant', content: 'hello' }]+ const tools = [{ function: { name: 'search' } }]++ render(+ <Provider>+ <EventContentConversation+ eventId="event-1"+ traceId="trace-1"+ timestamp="2026-06-23T10:00:00Z"+ rawInput={rawInput}+ rawOutput={rawOutput}+ tools={tools}+ />+ </Provider>+ )++ expect(mockUseAIData).toHaveBeenCalledWith({+ uuid: 'event-1',+ input: rawInput,+ output: rawOutput,+ tools,+ traceId: 'trace-1',+ timestamp: '2026-06-23T10:00:00Z',+ })+ })+})diff --git a/products/ai_observability/frontend/components/EventContentWithAsyncData.tsx b/products/ai_observability/frontend/components/EventContentWithAsyncData.tsxindex 49ca002598bf..7eea5a096600 100644--- a/products/ai_observability/frontend/components/EventContentWithAsyncData.tsx+++ b/products/ai_observability/frontend/components/EventContentWithAsyncData.tsx@@ -11,6 +11,7 @@ import {import { useCustomParserMaxTool } from '../customParser/useCustomParserMaxTool'import { useAIData } from '../hooks/useAIData'import { normalizeMessage, normalizeMessages } from '../messageNormalization'+import type { GenerationSentiment } from '../sentimentResults'import { parserRecipesLogic } from '../settings/parserRecipesLogic'import { AIDataLoading } from './AIDataLoading'import { JSONValueDisplay } from './JSONValueDisplay'@@ -18,6 +19,7 @@ import { JSONValueDisplay } from './JSONValueDisplay'interface EventContentConversationProps {eventId: stringtraceId?: string | null+ timestamp?: stringrawInput: unknownrawOutput: unknowntools?: unknown@@ -30,6 +32,7 @@ interface EventContentConversationProps {highlightMessageIndex?: number | null/** Generation id for per-message sentiment lookups; only generations have sentiment. */generationEventId?: string+ generationSentiment?: GenerationSentiment | null}// Renders an event's input/output, routing to one of two renderers: the chat UI@@ -38,6 +41,7 @@ interface EventContentConversationProps {export function EventContentConversation({eventId,traceId,+ timestamp,rawInput,rawOutput,tools,@@ -48,11 +52,20 @@ export function EventContentConversation({displayOption,highlightMessageIndex,generationEventId,+ generationSentiment,}: EventContentConversationProps): JSX.Element {- const { input, output, isLoading } = useAIData({+ const {+ input,+ output,+ tools: loadedTools,+ isLoading,+ } = useAIData({uuid: eventId,input: rawInput,output: rawOutput,+ tools,+ traceId: traceId ?? undefined,+ timestamp,})// The normalizer is a module singleton — recipesVersion signals the memos below are staleconst { recipesVersion } = useValues(parserRecipesLogic)@@ -64,7 +77,7 @@ export function EventContentConversation({return undefined}const indices: number[] = []- if (tools) {+ if (loadedTools) {indices.push(-1) // tools message prepended by normalizeMessages}if (Array.isArray(input)) {@@ -77,12 +90,12 @@ export function EventContentConversation({}return indices// oxlint-disable-next-line react-hooks/exhaustive-deps- }, [input, tools, generationEventId, recipesVersion])+ }, [input, loadedTools, generationEventId, recipesVersion])const { recognized: inputRecognized, messages: inputMessages } = React.useMemo(- () => normalizeMessages(input, 'user', tools),+ () => normalizeMessages(input, 'user', loadedTools),// oxlint-disable-next-line react-hooks/exhaustive-deps- [input, tools, recipesVersion]+ [input, loadedTools, recipesVersion])const { recognized: outputRecognized, messages: outputMessages } = React.useMemo(() => normalizeMessages(output, 'assistant'),@@ -94,7 +107,7 @@ export function EventContentConversation({eventId,input,output,- tools,+ tools: loadedTools,inputRecognized,outputRecognized,isLoading,@@ -128,7 +141,7 @@ export function EventContentConversation({searchQuery={searchQuery}displayOption={displayOption}traceId={traceId}- generationEventId={generationEventId}+ generationSentiment={generationSentiment}highlightMessageIndex={highlightMessageIndex}/>)diff --git a/products/ai_observability/frontend/components/SentimentTag.tsx b/products/ai_observability/frontend/components/SentimentTag.tsxindex 2377faa4478d..7d566855033c 100644--- a/products/ai_observability/frontend/components/SentimentTag.tsx+++ b/products/ai_observability/frontend/components/SentimentTag.tsx@@ -4,7 +4,7 @@ import { LemonTag, LemonTagProps, Tooltip } from '@posthog/lemon-ui'import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'-import type { MessageSentiment } from '../llmSentimentLazyLoaderLogic'+import type { MessageSentiment } from '../sentimentResults'import type { SentimentLabel } from '../sentimentUtils'import { buildSentimentBarTooltip, buildTagTooltip, capitalize, computeExtremes, formatScore } from '../sentimentUtils'diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.tsindex 871eee56f97b..614908daddc7 100644--- a/products/ai_observability/frontend/generated/api.schemas.ts+++ b/products/ai_observability/frontend/generated/api.schemas.ts@@ -626,10 +626,9 @@ export interface TestHogResponseApi {* * `generation` - generation* * `evaluation` - evaluation*/-export type ClusteringJobAnalysisLevelEnumApi =- (typeof ClusteringJobAnalysisLevelEnumApi)[keyof typeof ClusteringJobAnalysisLevelEnumApi]+export type AnalysisLevelEnumApi = (typeof AnalysisLevelEnumApi)[keyof typeof AnalysisLevelEnumApi]-export const ClusteringJobAnalysisLevelEnumApi = {+export const AnalysisLevelEnumApi = {Trace: 'trace',Generation: 'generation',Evaluation: 'evaluation',@@ -639,7 +638,7 @@ export interface ClusteringJobApi {readonly id: string/** @maxLength 100 */name: string- analysis_level: ClusteringJobAnalysisLevelEnumApi+ analysis_level: AnalysisLevelEnumApievent_filters?: unknownenabled?: booleanreadonly created_at: string@@ -659,7 +658,7 @@ export interface PatchedClusteringJobApi {readonly id?: string/** @maxLength 100 */name?: string- analysis_level?: ClusteringJobAnalysisLevelEnumApi+ analysis_level?: AnalysisLevelEnumApievent_filters?: unknownenabled?: booleanreadonly created_at?: string@@ -1495,85 +1494,6 @@ export interface ScoreDefinitionNewVersionApi {base_version?: number}-/**- * * `trace` - trace- * * `generation` - generation- */-export type SentimentRequestAnalysisLevelEnumApi =- (typeof SentimentRequestAnalysisLevelEnumApi)[keyof typeof SentimentRequestAnalysisLevelEnumApi]--export const SentimentRequestAnalysisLevelEnumApi = {- Trace: 'trace',- Generation: 'generation',-} as const--export interface SentimentRequestApi {- /**- * Trace IDs (analysis_level=trace) or generation event UUIDs (analysis_level=generation).- * @minItems 1- * @maxItems 5- */- ids: string[]- /** Whether the IDs are 'trace' IDs or 'generation' IDs.- *- * * `trace` - trace- * * `generation` - generation */- analysis_level?: SentimentRequestAnalysisLevelEnumApi- /** If true, bypass cache and reclassify. */- force_refresh?: boolean- /**- * Start of date range for the lookup (e.g. '-7d' or '2026-01-01'). Defaults to -30d.- * @nullable- */- date_from?: string | null- /**- * End of date range for the lookup. Defaults to now.- * @nullable- */- date_to?: string | null-}--export type MessageSentimentApiScores = { [key: string]: number }--export interface MessageSentimentApi {- label: string- score: number- scores: MessageSentimentApiScores-}--export type SentimentResultApiScores = { [key: string]: number }--export type SentimentResultApiMessages = { [key: string]: MessageSentimentApi }--export interface SentimentResultApi {- label: string- score: number- scores: SentimentResultApiScores- messages: SentimentResultApiMessages- message_count: number-}--export type SentimentBatchResponseApiResults = { [key: string]: SentimentResultApi }--export interface SentimentBatchResponseApi {- results: SentimentBatchResponseApiResults-}--/**- * Filter shape mirrors the previous frontend `api.query({filters: ...})` payload.- *- * `filters` accepts the same `HogQLFilters` schema that the legacy frontend HogQL- * path used (dateRange, filterTestAccounts, properties), so the migration is- * behaviour-preserving for callers that pass a request unchanged.- */-export interface SentimentGenerationsRequestApi {- filters?: unknown-}--export interface SentimentGenerationsResponseApi {- results: unknown[][]-}-/*** * `trace` - trace* * `event` - event@@ -2359,6 +2279,14 @@ export type EvaluationsListParams = {* Filter by enabled status*/enabled?: boolean+ /**+ * Filter by evaluation type+ *+ * * `llm_judge` - LLM as a judge+ * * `hog` - Hog+ * * `sentiment` - Sentiment analysis+ */+ evaluation_type?: EvaluationsListEvaluationType/*** Multiple values may be separated by commas.*/@@ -2388,6 +2316,15 @@ export type EvaluationsListParams = {search?: string}+export type EvaluationsListEvaluationType =+ (typeof EvaluationsListEvaluationType)[keyof typeof EvaluationsListEvaluationType]++export const EvaluationsListEvaluationType = {+ Hog: 'hog',+ LlmJudge: 'llm_judge',+ Sentiment: 'sentiment',+} as const+export type LlmAnalyticsClusteringConfigRetrieve200 = { [key: string]: unknown }export type LlmAnalyticsClusteringConfigSetEventFiltersCreate200 = { [key: string]: unknown }@@ -2563,14 +2500,6 @@ export type LlmAnalyticsScoreDefinitionsListParams = {search?: string}-export type LlmAnalyticsSentimentCreate400 = { [key: string]: unknown }--export type LlmAnalyticsSentimentCreate500 = { [key: string]: unknown }--export type LlmAnalyticsSentimentGenerationsCreate400 = { [key: string]: unknown }--export type LlmAnalyticsSentimentGenerationsCreate500 = { [key: string]: unknown }-export type LlmAnalyticsSummarizationCreate400 = { [key: string]: unknown }export type LlmAnalyticsSummarizationCreate403 = { [key: string]: unknown }diff --git a/products/ai_observability/frontend/generated/api.ts b/products/ai_observability/frontend/generated/api.tsindex 5be27c5672cb..c3587624b14d 100644--- a/products/ai_observability/frontend/generated/api.ts+++ b/products/ai_observability/frontend/generated/api.ts@@ -88,10 +88,6 @@ import type {ScoreDefinitionApi,ScoreDefinitionCreateApi,ScoreDefinitionNewVersionApi,- SentimentBatchResponseApi,- SentimentGenerationsRequestApi,- SentimentGenerationsResponseApi,- SentimentRequestApi,SummarizeRequestApi,SummarizeResponseApi,TaggerApi,@@ -1603,40 +1599,6 @@ export const llmAnalyticsScoreDefinitionsNewVersionCreate = async (})}-export const getLlmAnalyticsSentimentCreateUrl = (projectId: string) => {- return `/api/projects/${projectId}/llm_analytics/sentiment/`-}--export const llmAnalyticsSentimentCreate = async (- projectId: string,- sentimentRequestApi: SentimentRequestApi,- options?: RequestInit-): Promise<SentimentBatchResponseApi> => {- return apiMutator<SentimentBatchResponseApi>(getLlmAnalyticsSentimentCreateUrl(projectId), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(sentimentRequestApi),- })-}--export const getLlmAnalyticsSentimentGenerationsCreateUrl = (projectId: string) => {- return `/api/projects/${projectId}/llm_analytics/sentiment/generations/`-}--export const llmAnalyticsSentimentGenerationsCreate = async (- projectId: string,- sentimentGenerationsRequestApi?: SentimentGenerationsRequestApi,- options?: RequestInit-): Promise<SentimentGenerationsResponseApi> => {- return apiMutator<SentimentGenerationsResponseApi>(getLlmAnalyticsSentimentGenerationsCreateUrl(projectId), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(sentimentGenerationsRequestApi),- })-}-export const getLlmAnalyticsSummarizationCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/llm_analytics/summarization/`}diff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.tsindex 07000f51719e..7e43a1b4cb81 100644--- a/products/ai_observability/frontend/generated/api.zod.ts+++ b/products/ai_observability/frontend/generated/api.zod.ts@@ -1352,43 +1352,6 @@ export const LlmAnalyticsScoreDefinitionsNewVersionCreateBody = /* @__PURE__ */),})-export const llmAnalyticsSentimentCreateBodyIdsMax = 5--export const llmAnalyticsSentimentCreateBodyAnalysisLevelDefault = `trace`-export const llmAnalyticsSentimentCreateBodyForceRefreshDefault = false--export const LlmAnalyticsSentimentCreateBody = /* @__PURE__ */ zod.object({- ids: zod- .array(zod.string())- .min(1)- .max(llmAnalyticsSentimentCreateBodyIdsMax)- .describe('Trace IDs (analysis_level=trace) or generation event UUIDs (analysis_level=generation).'),- analysis_level: zod- .enum(['trace', 'generation'])- .describe('\* `trace` - trace\n\* `generation` - generation')- .default(llmAnalyticsSentimentCreateBodyAnalysisLevelDefault)- .describe(- "Whether the IDs are 'trace' IDs or 'generation' IDs.\n\n\* `trace` - trace\n\* `generation` - generation"- ),- force_refresh: zod- .boolean()- .default(llmAnalyticsSentimentCreateBodyForceRefreshDefault)- .describe('If true, bypass cache and reclassify.'),- date_from: zod- .string()- .nullish()- .describe("Start of date range for the lookup (e.g. '-7d' or '2026-01-01'). Defaults to -30d."),- date_to: zod.string().nullish().describe('End of date range for the lookup. Defaults to now.'),-})--export const LlmAnalyticsSentimentGenerationsCreateBody = /* @__PURE__ */ zod- .object({- filters: zod.unknown().optional(),- })- .describe(- 'Filter shape mirrors the previous frontend `api.query({filters: ...})` payload.\n\n`filters` accepts the same `HogQLFilters` schema that the legacy frontend HogQL\npath used (dateRange, filterTestAccounts, properties), so the migration is\nbehaviour-preserving for callers that pass a request unchanged.'- )-/**** Generate an AI-powered summary of an LLM trace or event.diff --git a/products/ai_observability/frontend/hooks/useAIData.ts b/products/ai_observability/frontend/hooks/useAIData.tsindex e9eae3116867..4fa4ad15d36c 100644--- a/products/ai_observability/frontend/hooks/useAIData.ts+++ b/products/ai_observability/frontend/hooks/useAIData.ts@@ -32,12 +32,12 @@ export function useAIData(eventData: EventData | undefined): UseAIDataResult {const cached = eventId ? aiDataCache[eventId] : undefinedconst loading = eventId ? isEventLoading(eventId) : false- // Only fire the loader when a real fetch is possible — we need trace coordinates to- // look the heavy props up via TraceQuery.+ // Only fire the loader when a real fetch is possible and a heavy prop is missing.const canFetch = !!traceId && !!timestamp+ const shouldFetch = canFetch && (input == null || output == null)useEffect(() => {- if (!eventId || cached || loading || !canFetch) {+ if (!eventId || cached || loading || !shouldFetch) {return}@@ -49,7 +49,7 @@ export function useAIData(eventData: EventData | undefined): UseAIDataResult {traceId,timestamp,})- }, [cached, loading, canFetch, loadAIDataForEvent, eventId, input, output, tools, traceId, timestamp])+ }, [cached, loading, canFetch, loadAIDataForEvent, eventId, input, output, tools, traceId, timestamp, shouldFetch])if (!eventId) {return {@@ -65,6 +65,6 @@ export function useAIData(eventData: EventData | undefined): UseAIDataResult {input: cached?.input ?? input,output: cached?.output ?? output,tools: cached?.tools ?? tools,- isLoading: canFetch && (loading || !cached),+ isLoading: shouldFetch && (loading || !cached),}}diff --git a/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogic.test.ts b/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogic.test.tsindex ef8b03bf2000..e645aac9b67e 100644--- a/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogic.test.ts+++ b/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogic.test.ts@@ -3,11 +3,19 @@ import { expectLogic } from 'kea-test-utils'import { initKeaTests } from '~/test/init'import { llmGenerationSentimentLazyLoaderLogic } from './llmGenerationSentimentLazyLoaderLogic'-import type { GenerationSentiment, MessageSentiment } from './llmSentimentLazyLoaderLogic'+import type { GenerationSentiment } from './sentimentResults'describe('llmGenerationSentimentLazyLoaderLogic', () => {let logic: ReturnType<typeof llmGenerationSentimentLazyLoaderLogic.build>+ const sentiment: GenerationSentiment = {+ label: 'positive',+ score: 0.9,+ scores: { positive: 0.9, neutral: 0.08, negative: 0.02 },+ messages: {},+ message_count: 1,+ }+beforeEach(() => {initKeaTests()logic = llmGenerationSentimentLazyLoaderLogic()@@ -18,362 +26,65 @@ describe('llmGenerationSentimentLazyLoaderLogic', () => {logic.unmount()})- describe('initial state', () => {- it('should have empty sentiment cache', () => {- expect(logic.values.sentimentByGenerationId).toEqual({})- })-- it('should have empty loading set', () => {- expect(logic.values.loadingGenerationIds).toEqual(new Set())- })- })-- describe('ensureGenerationSentimentLoaded action', () => {- it('should add generation ID to loading set', async () => {- await expectLogic(logic, () => {- logic.actions.ensureGenerationSentimentLoaded('gen-1')- }).toMatchValues({- loadingGenerationIds: new Set(['gen-1']),- })- })-- it('should handle multiple generation IDs', async () => {- logic.actions.ensureGenerationSentimentLoaded('gen-1')- logic.actions.ensureGenerationSentimentLoaded('gen-2')- logic.actions.ensureGenerationSentimentLoaded('gen-3')-- expect(logic.values.loadingGenerationIds).toEqual(new Set(['gen-1', 'gen-2', 'gen-3']))- })-- it('should not add duplicate generation IDs to loading set', async () => {- logic.actions.ensureGenerationSentimentLoaded('gen-1')- logic.actions.ensureGenerationSentimentLoaded('gen-1')- logic.actions.ensureGenerationSentimentLoaded('gen-1')-- expect(logic.values.loadingGenerationIds).toEqual(new Set(['gen-1']))- })+ it('starts with an empty cache and loading set', () => {+ expect(logic.values.sentimentByGenerationKey).toEqual({})+ expect(logic.values.loadingGenerationKeys).toEqual(new Set())})- describe('loadGenerationSentimentBatchSuccess action', () => {- it('should store sentiment results', async () => {- const mockResult: GenerationSentiment = {- label: 'positive',- score: 0.95,- scores: { positive: 0.95, negative: 0.03, neutral: 0.02 },- messages: {},- }-- await expectLogic(logic, () => {- logic.actions.loadGenerationSentimentBatchSuccess({ 'gen-1': mockResult }, ['gen-1'])- }).toMatchValues({- sentimentByGenerationId: {- 'gen-1': mockResult,- },- })- })-- it('should remove generation IDs from loading set', async () => {- logic.actions.ensureGenerationSentimentLoaded('gen-1')- logic.actions.ensureGenerationSentimentLoaded('gen-2')-- const mockResult: GenerationSentiment = {- label: 'positive',- score: 0.8,- scores: { positive: 0.8, negative: 0.1, neutral: 0.1 },- messages: {},- }-- await expectLogic(logic, () => {- logic.actions.loadGenerationSentimentBatchSuccess({ 'gen-1': mockResult }, ['gen-1'])- }).toMatchValues({- loadingGenerationIds: new Set(['gen-2']),- })- })-- it('should store null for generations without results', async () => {- await expectLogic(logic, () => {- logic.actions.loadGenerationSentimentBatchSuccess({}, ['gen-1', 'gen-2'])- }).toMatchValues({- sentimentByGenerationId: {- 'gen-1': null,- 'gen-2': null,- },- })- })-- it('should handle multiple results in batch', async () => {- const result1: GenerationSentiment = {- label: 'positive',- score: 0.9,- scores: { positive: 0.9, negative: 0.05, neutral: 0.05 },- messages: {},- }-- const result2: GenerationSentiment = {- label: 'negative',- score: 0.85,- scores: { positive: 0.1, negative: 0.85, neutral: 0.05 },- messages: {},- }-- await expectLogic(logic, () => {- logic.actions.loadGenerationSentimentBatchSuccess({ 'gen-1': result1, 'gen-2': result2 }, [- 'gen-1',- 'gen-2',- ])- }).toMatchValues({- sentimentByGenerationId: {- 'gen-1': result1,- 'gen-2': result2,- },- })- })-- it('should preserve existing results when adding new ones', async () => {- const result1: GenerationSentiment = {- label: 'positive',- score: 0.9,- scores: { positive: 0.9, negative: 0.05, neutral: 0.05 },- messages: {},- }-- const result2: GenerationSentiment = {- label: 'negative',- score: 0.8,- scores: { positive: 0.1, negative: 0.8, neutral: 0.1 },- messages: {},- }-- logic.actions.loadGenerationSentimentBatchSuccess({ 'gen-1': result1 }, ['gen-1'])- logic.actions.loadGenerationSentimentBatchSuccess({ 'gen-2': result2 }, ['gen-2'])-- expect(logic.values.sentimentByGenerationId).toEqual({- 'gen-1': result1,- 'gen-2': result2,+ it('marks a generation as loading when queued', async () => {+ await expectLogic(logic, () => {+ logic.actions.ensureGenerationSentimentLoaded({+ key: 'event-uuid-1',+ traceId: 'trace-1',+ generationIds: ['event-uuid-1'],})+ }).toMatchValues({+ loadingGenerationKeys: new Set(['event-uuid-1']),})})- describe('loadGenerationSentimentBatchFailure action', () => {- it('should set null for failed generations', async () => {- await expectLogic(logic, () => {- logic.actions.loadGenerationSentimentBatchFailure(['gen-1', 'gen-2'])- }).toMatchValues({- sentimentByGenerationId: {- 'gen-1': null,- 'gen-2': null,- },- })- })-- it('should remove generation IDs from loading set', async () => {- logic.actions.ensureGenerationSentimentLoaded('gen-1')- logic.actions.ensureGenerationSentimentLoaded('gen-2')- logic.actions.ensureGenerationSentimentLoaded('gen-3')-- await expectLogic(logic, () => {- logic.actions.loadGenerationSentimentBatchFailure(['gen-1', 'gen-2'])- }).toMatchValues({- loadingGenerationIds: new Set(['gen-3']),- })- })-- it('should preserve existing results when failing new ones', async () => {- const existingResult: GenerationSentiment = {- label: 'positive',- score: 0.9,- scores: { positive: 0.9, negative: 0.05, neutral: 0.05 },- messages: {},- }-- logic.actions.loadGenerationSentimentBatchSuccess({ 'gen-1': existingResult }, ['gen-1'])- logic.actions.loadGenerationSentimentBatchFailure(['gen-2', 'gen-3'])-- expect(logic.values.sentimentByGenerationId).toEqual({- 'gen-1': existingResult,- 'gen-2': null,- 'gen-3': null,- })+ it('stores successful sentiment results by lookup key', async () => {+ await expectLogic(logic, () => {+ logic.actions.loadGenerationSentimentBatchSuccess({ 'event-uuid-1': sentiment }, ['event-uuid-1'])+ }).toMatchValues({+ sentimentByGenerationKey: {+ 'event-uuid-1': sentiment,+ },})})- describe('isGenerationLoading selector', () => {- it('should return false when generation is not loading', () => {- expect(logic.values.isGenerationLoading('gen-1')).toBe(false)- })-- it('should return true when generation is loading', () => {- logic.actions.ensureGenerationSentimentLoaded('gen-1')- expect(logic.values.isGenerationLoading('gen-1')).toBe(true)- })-- it('should return false after successful load', () => {- logic.actions.ensureGenerationSentimentLoaded('gen-1')-- const mockResult: GenerationSentiment = {- label: 'positive',- score: 0.9,- scores: { positive: 0.9, negative: 0.05, neutral: 0.05 },- messages: {},- }-- logic.actions.loadGenerationSentimentBatchSuccess({ 'gen-1': mockResult }, ['gen-1'])- expect(logic.values.isGenerationLoading('gen-1')).toBe(false)+ it('stores null for requested generations without results', async () => {+ await expectLogic(logic, () => {+ logic.actions.loadGenerationSentimentBatchSuccess({}, ['event-uuid-1', 'event-uuid-2'])+ }).toMatchValues({+ sentimentByGenerationKey: {+ 'event-uuid-1': null,+ 'event-uuid-2': null,+ },})-- it('should return false after failed load', () => {- logic.actions.ensureGenerationSentimentLoaded('gen-1')- logic.actions.loadGenerationSentimentBatchFailure(['gen-1'])- expect(logic.values.isGenerationLoading('gen-1')).toBe(false)- })-- it.each([- ['gen-1', 'gen-2', false, true],- ['gen-2', 'gen-1', false, true],- ['gen-3', 'gen-4', false, true],- ])(- 'should handle multiple generations independently (%s loading, checking %s)',- (loadingId, checkId, expectedCheck, expectedLoading) => {- logic.actions.ensureGenerationSentimentLoaded(loadingId)- expect(logic.values.isGenerationLoading(checkId)).toBe(expectedCheck)- expect(logic.values.isGenerationLoading(loadingId)).toBe(expectedLoading)- }- )})- describe('getGenerationSentiment selector', () => {- it('should return undefined when sentiment is not cached', () => {- expect(logic.values.getGenerationSentiment('gen-1')).toBeUndefined()- })-- it('should return cached sentiment result', () => {- const mockResult: GenerationSentiment = {- label: 'positive',- score: 0.9,- scores: { positive: 0.9, negative: 0.05, neutral: 0.05 },- messages: {},- }-- logic.actions.loadGenerationSentimentBatchSuccess({ 'gen-1': mockResult }, ['gen-1'])- expect(logic.values.getGenerationSentiment('gen-1')).toEqual(mockResult)- })-- it('should return null for failed generations', () => {- logic.actions.loadGenerationSentimentBatchFailure(['gen-1'])- expect(logic.values.getGenerationSentiment('gen-1')).toBeNull()- })-- it('should return undefined while generation is loading', () => {- logic.actions.ensureGenerationSentimentLoaded('gen-1')- expect(logic.values.getGenerationSentiment('gen-1')).toBeUndefined()+ it('clears loading keys after failures', async () => {+ logic.actions.ensureGenerationSentimentLoaded({+ key: 'event-uuid-1',+ traceId: 'trace-1',+ generationIds: ['event-uuid-1'],})- it.each([- ['positive', 0.95, { positive: 0.95, negative: 0.03, neutral: 0.02 }],- ['negative', 0.88, { positive: 0.05, negative: 0.88, neutral: 0.07 }],- ['neutral', 0.75, { positive: 0.15, negative: 0.1, neutral: 0.75 }],- ])('should handle different sentiment labels (%s)', (label, score, scores) => {- const mockResult: GenerationSentiment = {- label,- score,- scores,- messages: {},- }-- logic.actions.loadGenerationSentimentBatchSuccess({ 'gen-1': mockResult }, ['gen-1'])- const result = logic.values.getGenerationSentiment('gen-1')- expect(result?.label).toBe(label)- expect(result?.score).toBe(score)- expect(result?.scores).toEqual(scores)- })-- it('should handle message-level sentiment within generation', () => {- const message0: MessageSentiment = {- label: 'positive',- score: 0.95,- scores: { positive: 0.95, negative: 0.03, neutral: 0.02 },- }-- const message1: MessageSentiment = {- label: 'neutral',- score: 0.7,- scores: { positive: 0.2, negative: 0.1, neutral: 0.7 },- }-- const generationSentiment: GenerationSentiment = {- label: 'positive',- score: 0.85,- scores: { positive: 0.85, negative: 0.08, neutral: 0.07 },- messages: {- 0: message0,- 1: message1,- },- }-- logic.actions.loadGenerationSentimentBatchSuccess({ 'gen-1': generationSentiment }, ['gen-1'])- const result = logic.values.getGenerationSentiment('gen-1')- expect(result?.messages[0]).toEqual(message0)- expect(result?.messages[1]).toEqual(message1)- expect(result?.messages[2]).toBeUndefined()+ await expectLogic(logic, () => {+ logic.actions.loadGenerationSentimentBatchFailure(['event-uuid-1'])+ }).toMatchValues({+ loadingGenerationKeys: new Set(),+ sentimentByGenerationKey: {+ 'event-uuid-1': null,+ },})})- describe('edge cases', () => {- it('should handle empty batch success', async () => {- await expectLogic(logic, () => {- logic.actions.loadGenerationSentimentBatchSuccess({}, [])- }).toMatchValues({- sentimentByGenerationId: {},- loadingGenerationIds: new Set(),- })- })-- it('should handle empty batch failure', async () => {- await expectLogic(logic, () => {- logic.actions.loadGenerationSentimentBatchFailure([])- }).toMatchValues({- sentimentByGenerationId: {},- loadingGenerationIds: new Set(),- })- })-- it('should overwrite existing sentiment when loading same generation again', () => {- const result1: GenerationSentiment = {- label: 'positive',- score: 0.8,- scores: { positive: 0.8, negative: 0.1, neutral: 0.1 },- messages: {},- }-- const result2: GenerationSentiment = {- label: 'negative',- score: 0.9,- scores: { positive: 0.05, negative: 0.9, neutral: 0.05 },- messages: {},- }-- logic.actions.loadGenerationSentimentBatchSuccess({ 'gen-1': result1 }, ['gen-1'])- expect(logic.values.getGenerationSentiment('gen-1')).toEqual(result1)-- logic.actions.loadGenerationSentimentBatchSuccess({ 'gen-1': result2 }, ['gen-1'])- expect(logic.values.getGenerationSentiment('gen-1')).toEqual(result2)- })-- it('should handle partial batch success with some nulls', () => {- const result1: GenerationSentiment = {- label: 'positive',- score: 0.9,- scores: { positive: 0.9, negative: 0.05, neutral: 0.05 },- messages: {},- }-- logic.actions.loadGenerationSentimentBatchSuccess({ 'gen-1': result1 }, ['gen-1', 'gen-2', 'gen-3'])+ it('returns cached sentiment through the selector', () => {+ logic.actions.loadGenerationSentimentBatchSuccess({ 'event-uuid-1': sentiment }, ['event-uuid-1'])- expect(logic.values.sentimentByGenerationId).toEqual({- 'gen-1': result1,- 'gen-2': null,- 'gen-3': null,- })- })+ expect(logic.values.getGenerationSentiment('event-uuid-1')).toEqual(sentiment)+ expect(logic.values.getGenerationSentiment('event-uuid-2')).toBeUndefined()})})diff --git a/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogic.ts b/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogic.tsindex 0b60db635cbb..4584f41ee2a2 100644--- a/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogic.ts+++ b/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogic.ts@@ -1,31 +1,16 @@import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'-import api from 'lib/api'import { chunk } from 'lib/utils/arrays'import { teamLogic } from 'scenes/teamLogic'import type { llmGenerationSentimentLazyLoaderLogicType } from './llmGenerationSentimentLazyLoaderLogicType'-import type { GenerationSentiment } from './llmSentimentLazyLoaderLogic'+import { fetchStoredGenerationSentiments, type GenerationSentimentLookup } from './sentimentQueries'+import type { GenerationSentiment } from './sentimentResults'import { runWithConcurrency } from './utils'-export interface GenerationSentimentDateRange {- dateFrom?: string | null- dateTo?: string | null-}--interface BatchGenerationSentimentResponse {- results: Record<string, GenerationSentiment | { error: string }>-}--function isValidGenerationSentiment(value: unknown): value is GenerationSentiment {- return !!value && typeof value === 'object' && 'label' in value && !('error' in value)-}--const BATCH_MAX_SIZE = 5-// Mirrors llmSentimentLazyLoaderLogic: capping in-flight requests per flush-// keeps sentiment from starving sibling lazy loaders on list pages with many-// rows, given the browser's per-origin connection limit (~6).+const BATCH_MAX_SIZE = 100const MAX_CONCURRENT_BATCHES = 2+const BATCH_TIMER_DISPOSABLE_KEY = 'generationSentimentBatchTimer'export const llmGenerationSentimentLazyLoaderLogic = kea<llmGenerationSentimentLazyLoaderLogicType>([path(['products', 'ai_observability', 'frontend', 'llmGenerationSentimentLazyLoaderLogic']),@@ -35,83 +20,78 @@ export const llmGenerationSentimentLazyLoaderLogic = kea<llmGenerationSentimentL}),actions({- ensureGenerationSentimentLoaded: (generationId: string, dateRange?: GenerationSentimentDateRange) => ({- generationId,- dateRange,- }),+ ensureGenerationSentimentLoaded: (lookup: GenerationSentimentLookup) => ({ lookup }),loadGenerationSentimentBatchSuccess: (results: Record<string, GenerationSentiment | null>,- requestedGenerationIds: string[]- ) => ({- results,- requestedGenerationIds,- }),- loadGenerationSentimentBatchFailure: (requestedGenerationIds: string[]) => ({ requestedGenerationIds }),- clearLoadingGeneration: (generationId: string) => ({ generationId }),+ requestedKeys: string[]+ ) => ({ results, requestedKeys }),+ loadGenerationSentimentBatchFailure: (requestedKeys: string[]) => ({ requestedKeys }),+ clearLoadingGeneration: (key: string) => ({ key }),}),reducers({- sentimentByGenerationId: [+ sentimentByGenerationKey: [{} as Record<string, GenerationSentiment | null>,{- loadGenerationSentimentBatchSuccess: (state, { results, requestedGenerationIds }) => {- const newState = { ...state }+ loadGenerationSentimentBatchSuccess: (state, { results, requestedKeys }) => {+ const next = { ...state }- for (const generationId of requestedGenerationIds) {- newState[generationId] = results[generationId] ?? null+ for (const key of requestedKeys) {+ next[key] = results[key] ?? null}- return newState+ return next},- loadGenerationSentimentBatchFailure: (state, { requestedGenerationIds }) => {- const newState = { ...state }+ loadGenerationSentimentBatchFailure: (state, { requestedKeys }) => {+ const next = { ...state }- for (const generationId of requestedGenerationIds) {- newState[generationId] = null+ for (const key of requestedKeys) {+ next[key] = null}- return newState+ return next},},],- loadingGenerationIds: [+ loadingGenerationKeys: [new Set<string>(),{- ensureGenerationSentimentLoaded: (state, { generationId }) => {- if (state.has(generationId)) {+ ensureGenerationSentimentLoaded: (state, { lookup }) => {+ if (state.has(lookup.key)) {return state}- const newSet = new Set(state)- newSet.add(generationId)- return newSet+ const next = new Set(state)+ next.add(lookup.key)+ return next},- loadGenerationSentimentBatchSuccess: (state, { requestedGenerationIds }) => {- const newSet = new Set(state)+ loadGenerationSentimentBatchSuccess: (state, { requestedKeys }) => {+ const next = new Set(state)- for (const id of requestedGenerationIds) {- newSet.delete(id)+ for (const key of requestedKeys) {+ next.delete(key)}- return newSet+ return next},- loadGenerationSentimentBatchFailure: (state, { requestedGenerationIds }) => {- const newSet = new Set(state)+ loadGenerationSentimentBatchFailure: (state, { requestedKeys }) => {+ const next = new Set(state)- for (const id of requestedGenerationIds) {- newSet.delete(id)+ for (const key of requestedKeys) {+ next.delete(key)}- return newSet+ return next},- clearLoadingGeneration: (state, { generationId }) => {- if (!state.has(generationId)) {+ clearLoadingGeneration: (state, { key }) => {+ if (!state.has(key)) {return state}- const newSet = new Set(state)- newSet.delete(generationId)- return newSet++ const next = new Set(state)+ next.delete(key)+ return next},},],@@ -119,85 +99,63 @@ export const llmGenerationSentimentLazyLoaderLogic = kea<llmGenerationSentimentLselectors({isGenerationLoading: [- (s) => [s.loadingGenerationIds],- (loadingGenerationIds): ((generationId: string) => boolean) => {- return (generationId: string) => loadingGenerationIds.has(generationId)+ (s) => [s.loadingGenerationKeys],+ (loadingGenerationKeys): ((key: string) => boolean) => {+ return (key: string) => loadingGenerationKeys.has(key)},],getGenerationSentiment: [- (s) => [s.sentimentByGenerationId],- (sentimentByGenerationId): ((generationId: string) => GenerationSentiment | null | undefined) => {- return (generationId: string) => sentimentByGenerationId[generationId]+ (s) => [s.sentimentByGenerationKey],+ (sentimentByGenerationKey): ((key: string) => GenerationSentiment | null | undefined) => {+ return (key: string) => sentimentByGenerationKey[key]},],}),- listeners(({ values, actions }) => {- let pendingGenerationIds = new Set<string>()- let batchTimer: ReturnType<typeof setTimeout> | null = null- let pendingDateRange: GenerationSentimentDateRange | undefined-+ listeners(({ values, actions, cache }) => {return {- ensureGenerationSentimentLoaded: ({ generationId, dateRange }) => {- if (values.sentimentByGenerationId[generationId] !== undefined) {- actions.clearLoadingGeneration(generationId)+ ensureGenerationSentimentLoaded: ({ lookup }) => {+ if (values.sentimentByGenerationKey[lookup.key] !== undefined) {+ actions.clearLoadingGeneration(lookup.key)return}- pendingGenerationIds.add(generationId)- if (dateRange) {- pendingDateRange = dateRange- }-- if (batchTimer) {- return- }-- batchTimer = setTimeout(async () => {- const allIds = Array.from(pendingGenerationIds)- const dateRangeForBatch = pendingDateRange- pendingGenerationIds = new Set()- pendingDateRange = undefined- batchTimer = null-- if (allIds.length === 0) {- return- }+ const pendingLookups = (cache.pendingLookups ??= new Map<string, GenerationSentimentLookup>()) as Map<+ string,+ GenerationSentimentLookup+ >+ pendingLookups.set(lookup.key, lookup)++ cache.disposables.add(() => {+ const batchTimer = setTimeout(() => {+ cache.disposables.dispose(BATCH_TIMER_DISPOSABLE_KEY)+ void (async () => {+ const pendingLookups = cache.pendingLookups as Map<string, GenerationSentimentLookup>+ const allLookups = Array.from(pendingLookups.values())+ cache.pendingLookups = new Map<string, GenerationSentimentLookup>()++ if (!values.currentTeamId || allLookups.length === 0) {+ actions.loadGenerationSentimentBatchFailure(allLookups.map((lookup) => lookup.key))+ return+ }- const teamId = values.currentTeamId+ const chunks = chunk(allLookups, BATCH_MAX_SIZE)- if (!teamId) {- return- }+ await runWithConcurrency(chunks, MAX_CONCURRENT_BATCHES, async (batch) => {+ const requestedKeys = batch.map((lookup) => lookup.key)- const chunks = chunk(allIds, BATCH_MAX_SIZE)-- await runWithConcurrency(chunks, MAX_CONCURRENT_BATCHES, async (batch) => {- try {- // nosemgrep: prefer-codegen-api- const response = await api.create<BatchGenerationSentimentResponse>(- `api/environments/${teamId}/llm_analytics/sentiment/`,- {- ids: batch,- analysis_level: 'generation',- date_from: dateRangeForBatch?.dateFrom || undefined,- date_to: dateRangeForBatch?.dateTo || undefined,+ try {+ const results = await fetchStoredGenerationSentiments(batch)+ actions.loadGenerationSentimentBatchSuccess(results, requestedKeys)+ } catch {+ actions.loadGenerationSentimentBatchFailure(requestedKeys)}- )-- const results: Record<string, GenerationSentiment | null> = {}-- for (const generationId of batch) {- const raw = response.results[generationId]- results[generationId] = isValidGenerationSentiment(raw) ? raw : null- }+ })+ })()+ }, 0)- actions.loadGenerationSentimentBatchSuccess(results, batch)- } catch {- actions.loadGenerationSentimentBatchFailure(batch)- }- })- }, 0)+ return () => clearTimeout(batchTimer)+ }, BATCH_TIMER_DISPOSABLE_KEY)},}}),diff --git a/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogicType.ts b/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogicType.tsnew file mode 100644index 000000000000..df54455563b6--- /dev/null+++ b/products/ai_observability/frontend/llmGenerationSentimentLazyLoaderLogicType.ts@@ -0,0 +1,116 @@+// Generated by kea-typegen on Thu, 25 Jun 2026 14:15:26 GMT. DO NOT EDIT THIS FILE MANUALLY.++import type { Logic } from 'kea'++import type { GenerationSentimentLookup } from './sentimentQueries'+import type { GenerationSentiment } from './sentimentResults'+import type { LLMSentimentResult } from '../../../frontend/src/queries/schema/schema-general'++export interface llmGenerationSentimentLazyLoaderLogicType extends Logic {+ actionCreators: {+ ensureGenerationSentimentLoaded: (lookup: GenerationSentimentLookup) => ({+ type: "ensure generation sentiment loaded (products.ai_observability.frontend.llmGenerationSentimentLazyLoaderLogic)";+ payload: {+ lookup: GenerationSentimentLookup;+ };+ });+ loadGenerationSentimentBatchSuccess: (results: Record<string, GenerationSentiment | null>, requestedKeys: string[]) => ({+ type: "load generation sentiment batch success (products.ai_observability.frontend.llmGenerationSentimentLazyLoaderLogic)";+ payload: {+ requestedKeys: string[];+ results: Record<string, LLMSentimentResult | null>;+ };+ });+ loadGenerationSentimentBatchFailure: (requestedKeys: string[]) => ({+ type: "load generation sentiment batch failure (products.ai_observability.frontend.llmGenerationSentimentLazyLoaderLogic)";+ payload: {+ requestedKeys: string[];+ };+ });+ clearLoadingGeneration: (key: string) => ({+ type: "clear loading generation (products.ai_observability.frontend.llmGenerationSentimentLazyLoaderLogic)";+ payload: {+ key: string;+ };+ });+ };+ actionKeys: {+ "ensure generation sentiment loaded (products.ai_observability.frontend.llmGenerationSentimentLazyLoaderLogic)": "ensureGenerationSentimentLoaded";+ "load generation sentiment batch success (products.ai_observability.frontend.llmGenerationSentimentLazyLoaderLogic)": "loadGenerationSentimentBatchSuccess";+ "load generation sentiment batch failure (products.ai_observability.frontend.llmGenerationSentimentLazyLoaderLogic)": "loadGenerationSentimentBatchFailure";+ "clear loading generation (products.ai_observability.frontend.llmGenerationSentimentLazyLoaderLogic)": "clearLoadingGeneration";+ };+ actionTypes: {+ ensureGenerationSentimentLoaded: "ensure generation sentiment loaded (products.ai_observability.frontend.llmGenerationSentimentLazyLoaderLogic)";+ loadGenerationSentimentBatchSuccess: "load generation sentiment batch success (products.ai_observability.frontend.llmGenerationSentimentLazyLoaderLogic)";+ loadGenerationSentimentBatchFailure: "load generation sentiment batch failure (products.ai_observability.frontend.llmGenerationSentimentLazyLoaderLogic)";+ clearLoadingGeneration: "clear loading generation (products.ai_observability.frontend.llmGenerationSentimentLazyLoaderLogic)";+ };+ actions: {+ ensureGenerationSentimentLoaded: (lookup: GenerationSentimentLookup) => void;+ loadGenerationSentimentBatchSuccess: (results: Record<string, GenerationSentiment | null>, requestedKeys: string[]) => void;+ loadGenerationSentimentBatchFailure: (requestedKeys: string[]) => void;+ clearLoadingGeneration: (key: string) => void;+ };+ asyncActions: {+ ensureGenerationSentimentLoaded: (lookup: GenerationSentimentLookup) => Promise<any>;+ loadGenerationSentimentBatchSuccess: (results: Record<string, GenerationSentiment | null>, requestedKeys: string[]) => Promise<any>;+ loadGenerationSentimentBatchFailure: (requestedKeys: string[]) => Promise<any>;+ clearLoadingGeneration: (key: string) => Promise<any>;+ };+ defaults: {+ sentimentByGenerationKey: Record<string, GenerationSentiment | null>;+ loadingGenerationKeys: Set<string>;+ };+ events: {};+ key: undefined;+ listeners: {+ "ensureGenerationSentimentLoaded": ((action: {+ type: "ensure generation sentiment loaded (products.ai_observability.frontend.llmGenerationSentimentLazyLoaderLogic)";+ payload: {+ lookup: GenerationSentimentLookup;+ };+ }, previousState: any) => void | Promise<void>)[];+ };+ path: [+ "products",+ "ai_observability",+ "frontend",+ "llmGenerationSentimentLazyLoaderLogic"+ ];+ pathString: "products.ai_observability.frontend.llmGenerationSentimentLazyLoaderLogic";+ props: Record<string, unknown>;+ reducer: (state: any, action: any, fullState: any) => {+ sentimentByGenerationKey: Record<string, GenerationSentiment | null>;+ loadingGenerationKeys: Set<string>;+ };+ reducers: {+ sentimentByGenerationKey: (state: Record<string, GenerationSentiment | null>, action: any, fullState: any) => Record<string, GenerationSentiment | null>;+ loadingGenerationKeys: (state: Set<string>, action: any, fullState: any) => Set<string>;+ };+ selector: (state: any) => {+ sentimentByGenerationKey: Record<string, GenerationSentiment | null>;+ loadingGenerationKeys: Set<string>;+ };+ selectors: {+ sentimentByGenerationKey: (state: any, props?: any) => Record<string, GenerationSentiment | null>;+ loadingGenerationKeys: (state: any, props?: any) => Set<string>;+ currentTeamId: (state: any, props?: any) => number | null;+ isGenerationLoading: (state: any, props?: any) => ((key: string) => boolean);+ getGenerationSentiment: (state: any, props?: any) => ((key: string) => GenerationSentiment | null | undefined);+ };+ sharedListeners: {};+ values: {+ sentimentByGenerationKey: Record<string, GenerationSentiment | null>;+ loadingGenerationKeys: Set<string>;+ currentTeamId: number | null;+ isGenerationLoading: ((key: string) => boolean);+ getGenerationSentiment: ((key: string) => GenerationSentiment | null | undefined);+ };+ _isKea: true;+ _isKeaWithKey: false;+ __keaTypeGenInternalSelectorTypes: {+ isGenerationLoading: (loadingGenerationKeys: Set<string>) => ((key: string) => boolean);+ getGenerationSentiment: (sentimentByGenerationKey: Record<string, GenerationSentiment | null>) => ((key: string) => GenerationSentiment | null | undefined);+ };+}\ No newline at end of filediff --git a/products/ai_observability/frontend/llmSentimentLazyLoaderLogic.test.ts b/products/ai_observability/frontend/llmSentimentLazyLoaderLogic.test.tsdeleted file mode 100644index beda41ebeafa..000000000000--- a/products/ai_observability/frontend/llmSentimentLazyLoaderLogic.test.ts+++ /dev/null@@ -1,420 +0,0 @@-import { expectLogic } from 'kea-test-utils'--import api from 'lib/api'--import { initKeaTests } from '~/test/init'--import { SentimentResult, llmSentimentLazyLoaderLogic } from './llmSentimentLazyLoaderLogic'--describe('llmSentimentLazyLoaderLogic', () => {- let logic: ReturnType<typeof llmSentimentLazyLoaderLogic.build>-- beforeEach(() => {- initKeaTests()- logic = llmSentimentLazyLoaderLogic()- logic.mount()- })-- afterEach(() => {- logic.unmount()- })-- describe('initial state', () => {- it('should have empty sentiment cache', () => {- expect(logic.values.sentimentByTraceId).toEqual({})- })-- it('should have empty loading set', () => {- expect(logic.values.loadingTraceIds).toEqual(new Set())- })- })-- describe('ensureSentimentLoaded action', () => {- it('should add trace ID to loading set', async () => {- await expectLogic(logic, () => {- logic.actions.ensureSentimentLoaded('trace-1')- }).toMatchValues({- loadingTraceIds: new Set(['trace-1']),- })- })-- it('should handle multiple trace IDs', async () => {- logic.actions.ensureSentimentLoaded('trace-1')- logic.actions.ensureSentimentLoaded('trace-2')- logic.actions.ensureSentimentLoaded('trace-3')-- expect(logic.values.loadingTraceIds).toEqual(new Set(['trace-1', 'trace-2', 'trace-3']))- })-- it('should not add duplicate trace IDs to loading set', async () => {- logic.actions.ensureSentimentLoaded('trace-1')- logic.actions.ensureSentimentLoaded('trace-1')- logic.actions.ensureSentimentLoaded('trace-1')-- expect(logic.values.loadingTraceIds).toEqual(new Set(['trace-1']))- })- })-- describe('loadSentimentBatchSuccess action', () => {- it('should store sentiment results', async () => {- const mockResult: SentimentResult = {- label: 'positive',- score: 0.95,- scores: { positive: 0.95, negative: 0.03, neutral: 0.02 },- messages: {},- message_count: 2,- }-- await expectLogic(logic, () => {- logic.actions.loadSentimentBatchSuccess({ 'trace-1': mockResult }, ['trace-1'])- }).toMatchValues({- sentimentByTraceId: {- 'trace-1': mockResult,- },- })- })-- it('should remove trace IDs from loading set', async () => {- logic.actions.ensureSentimentLoaded('trace-1')- logic.actions.ensureSentimentLoaded('trace-2')-- const mockResult: SentimentResult = {- label: 'positive',- score: 0.8,- scores: { positive: 0.8, negative: 0.1, neutral: 0.1 },- messages: {},- message_count: 1,- }-- await expectLogic(logic, () => {- logic.actions.loadSentimentBatchSuccess({ 'trace-1': mockResult }, ['trace-1'])- }).toMatchValues({- loadingTraceIds: new Set(['trace-2']),- })- })-- it('should store null for traces without results', async () => {- await expectLogic(logic, () => {- logic.actions.loadSentimentBatchSuccess({}, ['trace-1', 'trace-2'])- }).toMatchValues({- sentimentByTraceId: {- 'trace-1': null,- 'trace-2': null,- },- })- })-- it('should handle multiple results in batch', async () => {- const result1: SentimentResult = {- label: 'positive',- score: 0.9,- scores: { positive: 0.9, negative: 0.05, neutral: 0.05 },- messages: {},- message_count: 1,- }-- const result2: SentimentResult = {- label: 'negative',- score: 0.85,- scores: { positive: 0.1, negative: 0.85, neutral: 0.05 },- messages: {},- message_count: 3,- }-- await expectLogic(logic, () => {- logic.actions.loadSentimentBatchSuccess({ 'trace-1': result1, 'trace-2': result2 }, [- 'trace-1',- 'trace-2',- ])- }).toMatchValues({- sentimentByTraceId: {- 'trace-1': result1,- 'trace-2': result2,- },- })- })-- it('should preserve existing results when adding new ones', async () => {- const result1: SentimentResult = {- label: 'positive',- score: 0.9,- scores: { positive: 0.9, negative: 0.05, neutral: 0.05 },- messages: {},- message_count: 1,- }-- const result2: SentimentResult = {- label: 'negative',- score: 0.8,- scores: { positive: 0.1, negative: 0.8, neutral: 0.1 },- messages: {},- message_count: 1,- }-- logic.actions.loadSentimentBatchSuccess({ 'trace-1': result1 }, ['trace-1'])- logic.actions.loadSentimentBatchSuccess({ 'trace-2': result2 }, ['trace-2'])-- expect(logic.values.sentimentByTraceId).toEqual({- 'trace-1': result1,- 'trace-2': result2,- })- })- })-- describe('loadSentimentBatchFailure action', () => {- it('should set null for failed traces', async () => {- await expectLogic(logic, () => {- logic.actions.loadSentimentBatchFailure(['trace-1', 'trace-2'])- }).toMatchValues({- sentimentByTraceId: {- 'trace-1': null,- 'trace-2': null,- },- })- })-- it('should remove trace IDs from loading set', async () => {- logic.actions.ensureSentimentLoaded('trace-1')- logic.actions.ensureSentimentLoaded('trace-2')- logic.actions.ensureSentimentLoaded('trace-3')-- await expectLogic(logic, () => {- logic.actions.loadSentimentBatchFailure(['trace-1', 'trace-2'])- }).toMatchValues({- loadingTraceIds: new Set(['trace-3']),- })- })-- it('should preserve existing results when failing new ones', async () => {- const existingResult: SentimentResult = {- label: 'positive',- score: 0.9,- scores: { positive: 0.9, negative: 0.05, neutral: 0.05 },- messages: {},- message_count: 1,- }-- logic.actions.loadSentimentBatchSuccess({ 'trace-1': existingResult }, ['trace-1'])- logic.actions.loadSentimentBatchFailure(['trace-2', 'trace-3'])-- expect(logic.values.sentimentByTraceId).toEqual({- 'trace-1': existingResult,- 'trace-2': null,- 'trace-3': null,- })- })- })-- describe('isTraceLoading selector', () => {- it('should return false when trace is not loading', () => {- expect(logic.values.isTraceLoading('trace-1')).toBe(false)- })-- it('should return true when trace is loading', () => {- logic.actions.ensureSentimentLoaded('trace-1')- expect(logic.values.isTraceLoading('trace-1')).toBe(true)- })-- it('should return false after successful load', () => {- logic.actions.ensureSentimentLoaded('trace-1')-- const mockResult: SentimentResult = {- label: 'positive',- score: 0.9,- scores: { positive: 0.9, negative: 0.05, neutral: 0.05 },- messages: {},- message_count: 1,- }-- logic.actions.loadSentimentBatchSuccess({ 'trace-1': mockResult }, ['trace-1'])- expect(logic.values.isTraceLoading('trace-1')).toBe(false)- })-- it('should return false after failed load', () => {- logic.actions.ensureSentimentLoaded('trace-1')- logic.actions.loadSentimentBatchFailure(['trace-1'])- expect(logic.values.isTraceLoading('trace-1')).toBe(false)- })-- it.each([- ['trace-1', 'trace-2', false, true],- ['trace-2', 'trace-1', false, true],- ['trace-3', 'trace-4', false, true],- ])(- 'should handle multiple traces independently (%s loading, checking %s)',- (loadingId, checkId, expectedCheck, expectedLoading) => {- logic.actions.ensureSentimentLoaded(loadingId)- expect(logic.values.isTraceLoading(checkId)).toBe(expectedCheck)- expect(logic.values.isTraceLoading(loadingId)).toBe(expectedLoading)- }- )- })-- describe('getTraceSentiment selector', () => {- it('should return undefined when sentiment is not cached', () => {- expect(logic.values.getTraceSentiment('trace-1')).toBeUndefined()- })-- it('should return cached sentiment result', () => {- const mockResult: SentimentResult = {- label: 'positive',- score: 0.9,- scores: { positive: 0.9, negative: 0.05, neutral: 0.05 },- messages: {},- message_count: 1,- }-- logic.actions.loadSentimentBatchSuccess({ 'trace-1': mockResult }, ['trace-1'])- expect(logic.values.getTraceSentiment('trace-1')).toEqual(mockResult)- })-- it('should return null for failed traces', () => {- logic.actions.loadSentimentBatchFailure(['trace-1'])- expect(logic.values.getTraceSentiment('trace-1')).toBeNull()- })-- it('should return undefined while trace is loading', () => {- logic.actions.ensureSentimentLoaded('trace-1')- expect(logic.values.getTraceSentiment('trace-1')).toBeUndefined()- })-- it.each([- ['positive', 0.95, { positive: 0.95, negative: 0.03, neutral: 0.02 }],- ['negative', 0.88, { positive: 0.05, negative: 0.88, neutral: 0.07 }],- ['neutral', 0.75, { positive: 0.15, negative: 0.1, neutral: 0.75 }],- ])('should handle different sentiment labels (%s)', (label, score, scores) => {- const mockResult: SentimentResult = {- label,- score,- scores,- messages: {},- message_count: 1,- }-- logic.actions.loadSentimentBatchSuccess({ 'trace-1': mockResult }, ['trace-1'])- const result = logic.values.getTraceSentiment('trace-1')- expect(result?.label).toBe(label)- expect(result?.score).toBe(score)- expect(result?.scores).toEqual(scores)- })- })-- describe('edge cases', () => {- it('should handle empty batch success', async () => {- await expectLogic(logic, () => {- logic.actions.loadSentimentBatchSuccess({}, [])- }).toMatchValues({- sentimentByTraceId: {},- loadingTraceIds: new Set(),- })- })-- it('should handle empty batch failure', async () => {- await expectLogic(logic, () => {- logic.actions.loadSentimentBatchFailure([])- }).toMatchValues({- sentimentByTraceId: {},- loadingTraceIds: new Set(),- })- })-- it('should overwrite existing sentiment when loading same trace again', () => {- const result1: SentimentResult = {- label: 'positive',- score: 0.8,- scores: { positive: 0.8, negative: 0.1, neutral: 0.1 },- messages: {},- message_count: 1,- }-- const result2: SentimentResult = {- label: 'negative',- score: 0.9,- scores: { positive: 0.05, negative: 0.9, neutral: 0.05 },- messages: {},- message_count: 1,- }-- logic.actions.loadSentimentBatchSuccess({ 'trace-1': result1 }, ['trace-1'])- expect(logic.values.getTraceSentiment('trace-1')).toEqual(result1)-- logic.actions.loadSentimentBatchSuccess({ 'trace-1': result2 }, ['trace-1'])- expect(logic.values.getTraceSentiment('trace-1')).toEqual(result2)- })-- it('should cap concurrent in-flight sentiment batches at 2', async () => {- // Fake timers isolate this test from setTimeout leaks in prior cases- // (the listener doesn't cancel its batch timer on unmount).- jest.useFakeTimers()- let createSpy: jest.SpyInstance | undefined- try {- // Fifteen trace IDs at BATCH_MAX_SIZE=5 → three chunks. With the- // concurrency cap of 2, at most two api.create calls should be- // in flight at once; the third chunk must wait for a slot.- const release: Array<() => void> = []- let inFlight = 0- let peakInFlight = 0-- createSpy = jest.spyOn(api, 'create').mockImplementation(- () =>- new Promise((resolve) => {- inFlight++- peakInFlight = Math.max(peakInFlight, inFlight)- release.push(() => {- inFlight--- resolve({ results: {} } as any)- })- })- )-- const traceIds = Array.from({ length: 15 }, (_, i) => `trace-${i}`)- for (const id of traceIds) {- logic.actions.ensureSentimentLoaded(id)- }-- // Fire the listener's setTimeout(0) and let the first two- // runners start their api.create calls.- jest.advanceTimersByTime(0)- await Promise.resolve()- await Promise.resolve()-- expect(peakInFlight).toBe(2)- expect(createSpy).toHaveBeenCalledTimes(2)-- // Releasing the first in-flight promise frees a slot so the- // third chunk can start. Peak must remain at 2.- release.shift()!()- await Promise.resolve()- await Promise.resolve()- expect(peakInFlight).toBe(2)- expect(createSpy).toHaveBeenCalledTimes(3)-- while (release.length > 0) {- release.shift()!()- await Promise.resolve()- }- } finally {- createSpy?.mockRestore()- jest.useRealTimers()- }- })-- it('should handle partial batch success with some nulls', () => {- const result1: SentimentResult = {- label: 'positive',- score: 0.9,- scores: { positive: 0.9, negative: 0.05, neutral: 0.05 },- messages: {},- message_count: 1,- }-- logic.actions.loadSentimentBatchSuccess({ 'trace-1': result1 }, ['trace-1', 'trace-2', 'trace-3'])-- expect(logic.values.sentimentByTraceId).toEqual({- 'trace-1': result1,- 'trace-2': null,- 'trace-3': null,- })- })- })-})diff --git a/products/ai_observability/frontend/llmSentimentLazyLoaderLogic.ts b/products/ai_observability/frontend/llmSentimentLazyLoaderLogic.tsdeleted file mode 100644index 8c8de804f594..000000000000--- a/products/ai_observability/frontend/llmSentimentLazyLoaderLogic.ts+++ /dev/null@@ -1,219 +0,0 @@-import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'--import api from 'lib/api'-import { chunk } from 'lib/utils/arrays'-import { teamLogic } from 'scenes/teamLogic'--import type { llmSentimentLazyLoaderLogicType } from './llmSentimentLazyLoaderLogicType'-import { runWithConcurrency } from './utils'--export interface SentimentDateRange {- dateFrom?: string | null- dateTo?: string | null-}--export interface MessageSentiment {- label: string- score: number- scores?: Record<string, number>-}--export interface GenerationSentiment {- label: string- score: number- scores: Record<string, number>- messages: Record<string, MessageSentiment>- message_count?: number-}--export interface SentimentResult {- label: string- score: number- scores: Record<string, number>- messages: Record<string, MessageSentiment>- message_count: number-}--interface BatchSentimentResponse {- results: Record<string, SentimentResult | { error: string }>-}--function isValidSentimentResult(value: unknown): value is SentimentResult {- return !!value && typeof value === 'object' && 'label' in value && !('error' in value)-}--const BATCH_MAX_SIZE = 5-// Cap on in-flight sentiment requests per flush. Browsers limit to ~6 concurrent-// connections per origin; fanning out all chunks at once starves sibling lazy-// loaders (trace messages, persons) on page loads with many rows.-const MAX_CONCURRENT_BATCHES = 2--export const llmSentimentLazyLoaderLogic = kea<llmSentimentLazyLoaderLogicType>([- path(['products', 'ai_observability', 'frontend', 'llmSentimentLazyLoaderLogic']),-- connect({- values: [teamLogic, ['currentTeamId']],- }),-- actions({- ensureSentimentLoaded: (traceId: string, dateRange?: SentimentDateRange) => ({ traceId, dateRange }),- loadSentimentBatchSuccess: (results: Record<string, SentimentResult | null>, requestedTraceIds: string[]) => ({- results,- requestedTraceIds,- }),- loadSentimentBatchFailure: (requestedTraceIds: string[]) => ({ requestedTraceIds }),- clearLoadingTrace: (traceId: string) => ({ traceId }),- }),-- reducers({- sentimentByTraceId: [- {} as Record<string, SentimentResult | null>,- {- loadSentimentBatchSuccess: (state, { results, requestedTraceIds }) => {- const newState = { ...state }-- for (const traceId of requestedTraceIds) {- newState[traceId] = results[traceId] ?? null- }-- return newState- },- loadSentimentBatchFailure: (state, { requestedTraceIds }) => {- const newState = { ...state }-- for (const traceId of requestedTraceIds) {- newState[traceId] = null- }-- return newState- },- },- ],-- loadingTraceIds: [- new Set<string>(),- {- ensureSentimentLoaded: (state, { traceId }) => {- if (state.has(traceId)) {- return state- }-- const newSet = new Set(state)- newSet.add(traceId)- return newSet- },- loadSentimentBatchSuccess: (state, { requestedTraceIds }) => {- const newSet = new Set(state)-- for (const id of requestedTraceIds) {- newSet.delete(id)- }-- return newSet- },- loadSentimentBatchFailure: (state, { requestedTraceIds }) => {- const newSet = new Set(state)-- for (const id of requestedTraceIds) {- newSet.delete(id)- }-- return newSet- },- clearLoadingTrace: (state, { traceId }) => {- if (!state.has(traceId)) {- return state- }- const newSet = new Set(state)- newSet.delete(traceId)- return newSet- },- },- ],- }),-- selectors({- isTraceLoading: [- (s) => [s.loadingTraceIds],- (loadingTraceIds): ((traceId: string) => boolean) => {- return (traceId: string) => loadingTraceIds.has(traceId)- },- ],- getTraceSentiment: [- (s) => [s.sentimentByTraceId],- (sentimentByTraceId): ((traceId: string) => SentimentResult | null | undefined) => {- return (traceId: string) => sentimentByTraceId[traceId]- },- ],- }),-- listeners(({ values, actions }) => {- let pendingTraceIds = new Set<string>()- let batchTimer: ReturnType<typeof setTimeout> | null = null- let pendingDateRange: SentimentDateRange | undefined-- return {- ensureSentimentLoaded: ({ traceId, dateRange }) => {- if (values.sentimentByTraceId[traceId] !== undefined) {- actions.clearLoadingTrace(traceId)- return- }-- pendingTraceIds.add(traceId)- if (dateRange) {- pendingDateRange = dateRange- }-- if (batchTimer) {- return- }-- batchTimer = setTimeout(async () => {- const allIds = Array.from(pendingTraceIds)- const dateRangeForBatch = pendingDateRange- pendingTraceIds = new Set()- pendingDateRange = undefined- batchTimer = null-- if (allIds.length === 0) {- return- }-- const teamId = values.currentTeamId-- if (!teamId) {- return- }-- const chunks = chunk(allIds, BATCH_MAX_SIZE)-- await runWithConcurrency(chunks, MAX_CONCURRENT_BATCHES, async (batch) => {- try {- // nosemgrep: prefer-codegen-api- const response = await api.create<BatchSentimentResponse>(- `api/environments/${teamId}/llm_analytics/sentiment/`,- {- ids: batch,- analysis_level: 'trace',- date_from: dateRangeForBatch?.dateFrom || undefined,- date_to: dateRangeForBatch?.dateTo || undefined,- }- )-- const results: Record<string, SentimentResult | null> = {}-- for (const traceId of batch) {- const raw = response.results[traceId]- results[traceId] = isValidSentimentResult(raw) ? raw : null- }-- actions.loadSentimentBatchSuccess(results, batch)- } catch {- actions.loadSentimentBatchFailure(batch)- }- })- }, 0)- },- }- }),-])diff --git a/products/ai_observability/frontend/sentimentEvaluationAvailabilityLogic.ts b/products/ai_observability/frontend/sentimentEvaluationAvailabilityLogic.tsnew file mode 100644index 000000000000..61543b378f5b--- /dev/null+++ b/products/ai_observability/frontend/sentimentEvaluationAvailabilityLogic.ts@@ -0,0 +1,50 @@+import { afterMount, kea, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { getCurrentTeamId } from '~/lib/utils/getAppContext'++import { evaluationsList } from './generated/api'+import type { EvaluationApi } from './generated/api.schemas'+import type { sentimentEvaluationAvailabilityLogicType } from './sentimentEvaluationAvailabilityLogicType'++export const sentimentEvaluationAvailabilityLogic = kea<sentimentEvaluationAvailabilityLogicType>([+ path(['products', 'ai_observability', 'frontend', 'sentimentEvaluationAvailabilityLogic']),++ loaders({+ sentimentEvaluations: [+ [] as EvaluationApi[],+ {+ loadSentimentEvaluations: async () => {+ const response = await evaluationsList(String(getCurrentTeamId()), {+ evaluation_type: 'sentiment',+ limit: 1,+ })+ return response.results || []+ },+ },+ ],+ }),++ reducers({+ hasLoadedSentimentEvaluations: [+ false as boolean,+ {+ loadSentimentEvaluationsSuccess: () => true,+ loadSentimentEvaluationsFailure: () => true,+ },+ ],+ }),++ selectors({+ hasSentimentEvaluations: [+ (s) => [s.sentimentEvaluations],+ (sentimentEvaluations: EvaluationApi[]): boolean => sentimentEvaluations.length > 0,+ ],+ }),++ afterMount(({ actions, values }) => {+ if (!values.hasLoadedSentimentEvaluations && !values.sentimentEvaluationsLoading) {+ actions.loadSentimentEvaluations()+ }+ }),+])diff --git a/products/ai_observability/frontend/sentimentQueries.test.ts b/products/ai_observability/frontend/sentimentQueries.test.tsnew file mode 100644index 000000000000..254551e5f822--- /dev/null+++ b/products/ai_observability/frontend/sentimentQueries.test.ts@@ -0,0 +1,152 @@+import api from 'lib/api'++import { fetchSentimentGenerationsPage, fetchStoredGenerationSentiments } from './sentimentQueries'++jest.mock('lib/api')++const mockApi = api as jest.Mocked<typeof api>++describe('sentimentQueries', () => {+ beforeEach(() => {+ jest.resetAllMocks()+ })++ it('reads stored generation sentiment from ai_events first', async () => {+ jest.spyOn(mockApi, 'queryHogQL').mockResolvedValueOnce({+ results: [+ [+ 'trace-1',+ 'generation-uuid',+ 'positive',+ '0.91',+ { positive: 0.91, neutral: 0.08, negative: 0.01 },+ {+ '0': {+ label: 'positive',+ score: 0.91,+ scores: { positive: 0.91, neutral: 0.08, negative: 0.01 },+ },+ },+ 1,+ '2026-06-23T10:00:00Z',+ ],+ ],+ } as any)++ const results = await fetchStoredGenerationSentiments([+ {+ key: 'generation-uuid',+ traceId: 'trace-1',+ generationIds: ['generation-uuid'],+ },+ ])++ expect(results['generation-uuid']).toMatchObject({+ label: 'positive',+ score: 0.91,+ message_count: 1,+ })+ expect(mockApi.queryHogQL).toHaveBeenCalledTimes(1)+ const sentimentQuery = mockApi.queryHogQL.mock.calls[0][0]+ expect(sentimentQuery).toContain('FROM posthog.ai_events AS ai_events')+ expect(sentimentQuery).toContain("properties.$ai_evaluation_runtime = 'sentiment'")+ expect(sentimentQuery).toContain('properties.$ai_target_event_id')+ expect(sentimentQuery).not.toContain('properties.$ai_target_id')+ expect(sentimentQuery).not.toContain('properties.$ai_evaluation_result_type')+ })++ it('falls back to events when stored generation sentiment is missing from ai_events', async () => {+ jest.spyOn(mockApi, 'queryHogQL')+ .mockResolvedValueOnce({ results: [] } as any)+ .mockResolvedValueOnce({+ results: [+ [+ 'trace-1',+ 'generation-uuid',+ 'positive',+ '0.91',+ { positive: 0.91, neutral: 0.08, negative: 0.01 },+ {+ '0': {+ label: 'positive',+ score: 0.91,+ scores: { positive: 0.91, neutral: 0.08, negative: 0.01 },+ },+ },+ 1,+ '2026-06-23T10:00:00Z',+ ],+ ],+ } as any)++ const results = await fetchStoredGenerationSentiments([+ {+ key: 'generation-uuid',+ traceId: 'trace-1',+ generationIds: ['generation-uuid'],+ },+ ])++ expect(results['generation-uuid']).toMatchObject({+ label: 'positive',+ score: 0.91,+ message_count: 1,+ })+ expect(mockApi.queryHogQL).toHaveBeenCalledTimes(2)+ expect(mockApi.queryHogQL.mock.calls[0][0]).toContain('FROM posthog.ai_events AS ai_events')+ expect(mockApi.queryHogQL.mock.calls[1][0]).toContain('FROM events')+ })++ it('builds sentiment tab rows from evaluated generations and ai_events input', async () => {+ jest.spyOn(mockApi, 'query').mockResolvedValue({+ results: [['generation-uuid', 'trace-1', null, 'gpt-4.1', 'distinct-1', '2026-06-23T10:00:00Z']],+ } as any)+ jest.spyOn(mockApi, 'queryHogQL')+ .mockResolvedValueOnce({+ results: [+ [+ 'trace-1',+ 'generation-uuid',+ 'positive',+ '0.91',+ { positive: 0.91, neutral: 0.08, negative: 0.01 },+ {+ '0': {+ label: 'positive',+ score: 0.91,+ scores: { positive: 0.91, neutral: 0.08, negative: 0.01 },+ },+ },+ 1,+ '2026-06-23T10:00:01Z',+ ],+ ],+ } as any)+ .mockResolvedValueOnce({+ results: [+ ['generation-uuid', 'trace-1', JSON.stringify([{ role: 'user', content: 'this was great' }])],+ ],+ } as any)++ const page = await fetchSentimentGenerationsPage(+ {+ dateFilter: { dateFrom: '-7d', dateTo: null },+ shouldFilterTestAccounts: false,+ propertyFilters: [],+ },+ 0+ )++ expect(page.rawCount).toBe(1)+ expect(page.generations).toHaveLength(1)+ expect(page.generations[0]).toMatchObject({+ uuid: 'generation-uuid',+ traceId: 'trace-1',+ aiInput: JSON.stringify([{ role: 'user', content: 'this was great' }]),+ sentiment: {+ label: 'positive',+ score: 0.91,+ },+ })+ })+})diff --git a/products/ai_observability/frontend/sentimentQueries.ts b/products/ai_observability/frontend/sentimentQueries.tsnew file mode 100644index 000000000000..cd6a65eff6bf--- /dev/null+++ b/products/ai_observability/frontend/sentimentQueries.ts@@ -0,0 +1,366 @@+import api from 'lib/api'++import { EventsQuery, NodeKind, ProductKey } from '~/queries/schema/schema-general'+import { hogql } from '~/queries/utils'+import { AnyPropertyFilter } from '~/types'++import { normalizeSentimentResult, type GenerationSentiment } from './sentimentResults'++export const GENERATIONS_PAGE_SIZE = 200++const SENTIMENT_QUERY_TAGS = {+ productKey: ProductKey.AI_OBSERVABILITY,+ scene: 'ai_observability_sentiment',+}++const SENTIMENT_GENERATION_SELECT = [+ 'uuid',+ 'properties.$ai_trace_id',+ 'properties.$ai_generation_id',+ 'properties.$ai_model',+ 'distinct_id',+ 'timestamp',+] as const++const EVALUATION_TARGET_ID_SELECT = `+ ifNull(nullIf(nullIf(toString(properties.$ai_target_event_id), ''), 'null'), '')+`++type SentimentEvaluationQueryRow = [string, string, unknown, unknown, unknown, unknown, unknown, unknown]+type GenerationInputQueryRow = [string, string, unknown]++interface SentimentQuerySource {+ from: string+ traceIdExpression: string+}++interface GenerationInputQuerySource extends SentimentQuerySource {+ inputExpression: string+}++const AI_EVENTS_SOURCE: GenerationInputQuerySource = {+ from: 'posthog.ai_events AS ai_events',+ traceIdExpression: 'trace_id',+ inputExpression: 'input',+}++const EVENTS_SOURCE: GenerationInputQuerySource = {+ from: 'events',+ traceIdExpression: 'properties.$ai_trace_id',+ inputExpression: 'properties.$ai_input',+}++export interface GenerationSentimentLookup {+ key: string+ traceId: string+ generationIds: string[]+}++export interface SentimentGeneration {+ uuid: string+ traceId: string+ generationIds: string[]+ aiInput: unknown+ model: string | null+ distinctId: string+ timestamp: string+ /** Earliest event in the trace — used for trace deep-links (matches trace createdAt) */+ createdAt: string+ sentiment: GenerationSentiment | null+}++export interface SentimentGenerationsQueryValues {+ dateFilter: { dateFrom: string | null; dateTo: string | null }+ shouldFilterTestAccounts: boolean+ propertyFilters: AnyPropertyFilter[]+}++export interface SentimentGenerationsPage {+ generations: SentimentGeneration[]+ rawCount: number+}++function normalizeString(value: unknown): string {+ if (value === null || value === undefined) {+ return ''+ }++ const stringValue = String(value)+ return stringValue === 'null' ? '' : stringValue+}++function normalizeNullableString(value: unknown): string | null {+ const stringValue = normalizeString(value)+ return stringValue || null+}++function uniqueNonEmpty(values: string[]): string[] {+ return Array.from(new Set(values.filter(Boolean)))+}++function hasUsableInput(value: unknown): boolean {+ return value !== null && value !== undefined && value !== '' && value !== 'null'+}++function mapGenerationRow(row: unknown[]): SentimentGeneration | null {+ const uuid = normalizeString(row[0])+ const traceId = normalizeString(row[1])++ if (!uuid || !traceId) {+ return null+ }++ const generationPropertyId = normalizeString(row[2])+ const timestamp = normalizeString(row[5])++ return {+ uuid,+ traceId,+ generationIds: uniqueNonEmpty([uuid, generationPropertyId]),+ aiInput: null,+ model: normalizeNullableString(row[3]),+ distinctId: normalizeString(row[4]),+ timestamp,+ createdAt: timestamp,+ sentiment: null,+ }+}++async function queryStoredGenerationSentiments(+ normalizedLookups: GenerationSentimentLookup[],+ source: SentimentQuerySource+): Promise<Map<string, GenerationSentiment>> {+ const traceIds = uniqueNonEmpty(normalizedLookups.map((lookup) => lookup.traceId))+ const generationIds = uniqueNonEmpty(normalizedLookups.flatMap((lookup) => lookup.generationIds))++ if (traceIds.length === 0 || generationIds.length === 0) {+ return new Map()+ }++ const response = await api.queryHogQL<SentimentEvaluationQueryRow[]>(+ hogql`+ SELECT+ trace_id,+ generation_id,+ argMax(label, timestamp) AS label,+ argMax(score, timestamp) AS score,+ argMax(scores, timestamp) AS scores,+ argMax(messages, timestamp) AS messages,+ argMax(message_count, timestamp) AS message_count,+ max(timestamp) AS evaluation_timestamp+ FROM (+ SELECT+ ${hogql.raw(source.traceIdExpression)} AS trace_id,+ ${hogql.raw(EVALUATION_TARGET_ID_SELECT)} AS generation_id,+ timestamp,+ toString(properties.$ai_sentiment_label) AS label,+ toString(properties.$ai_sentiment_score) AS score,+ properties.$ai_sentiment_scores AS scores,+ properties.$ai_sentiment_messages AS messages,+ toString(properties.$ai_sentiment_message_count) AS message_count+ FROM ${hogql.raw(source.from)}+ WHERE event = '$ai_evaluation'+ AND properties.$ai_evaluation_runtime = 'sentiment'+ AND ${hogql.raw(source.traceIdExpression)} IN ${traceIds}+ )+ WHERE length(generation_id) > 0+ AND generation_id IN ${generationIds}+ GROUP BY trace_id, generation_id+ LIMIT ${Math.max(generationIds.length, 1)}+ `,+ { ...SENTIMENT_QUERY_TAGS, name: 'ai_observability_generation_sentiment_lookup' }+ )++ const sentimentByTargetId = new Map<string, GenerationSentiment>()+ for (const row of response.results || []) {+ const [, generationId, label, score, scores, messages, messageCount] = row+ const normalized = normalizeSentimentResult({+ label,+ score,+ scores,+ messages,+ message_count: messageCount,+ })++ if (generationId && normalized) {+ sentimentByTargetId.set(String(generationId), normalized)+ }+ }++ return sentimentByTargetId+}++function getUnresolvedLookups(+ lookups: GenerationSentimentLookup[],+ sentimentByTargetId: Map<string, GenerationSentiment>+): GenerationSentimentLookup[] {+ return lookups.filter(+ (lookup) => !lookup.generationIds.some((generationId) => sentimentByTargetId.has(generationId))+ )+}++export async function fetchStoredGenerationSentiments(+ lookups: GenerationSentimentLookup[]+): Promise<Record<string, GenerationSentiment | null>> {+ const normalizedLookups = lookups+ .map((lookup) => ({+ key: lookup.key,+ traceId: lookup.traceId,+ generationIds: uniqueNonEmpty(lookup.generationIds),+ }))+ .filter((lookup) => lookup.key && lookup.traceId && lookup.generationIds.length > 0)++ const results: Record<string, GenerationSentiment | null> = {}+ for (const lookup of normalizedLookups) {+ results[lookup.key] = null+ }++ if (normalizedLookups.length === 0) {+ return results+ }++ const sentimentByTargetId = await queryStoredGenerationSentiments(normalizedLookups, AI_EVENTS_SOURCE)+ const fallbackLookups = getUnresolvedLookups(normalizedLookups, sentimentByTargetId)++ if (fallbackLookups.length > 0) {+ const fallbackResults = await queryStoredGenerationSentiments(fallbackLookups, EVENTS_SOURCE)+ for (const [generationId, sentiment] of fallbackResults) {+ sentimentByTargetId.set(generationId, sentiment)+ }+ }++ for (const lookup of normalizedLookups) {+ for (const generationId of lookup.generationIds) {+ const sentiment = sentimentByTargetId.get(generationId)+ if (sentiment) {+ results[lookup.key] = sentiment+ break+ }+ }+ }++ return results+}++async function queryGenerationInputs(+ generations: SentimentGeneration[],+ source: GenerationInputQuerySource+): Promise<Map<string, unknown>> {+ const traceIds = uniqueNonEmpty(generations.map((generation) => generation.traceId))+ const generationEventIds = uniqueNonEmpty(generations.map((generation) => generation.uuid))++ if (traceIds.length === 0 || generationEventIds.length === 0) {+ return new Map()+ }++ const response = await api.queryHogQL<GenerationInputQueryRow[]>(+ hogql`+ SELECT+ uuid,+ trace_id,+ argMax(ai_input, timestamp) AS ai_input+ FROM (+ SELECT+ toString(uuid) AS uuid,+ ${hogql.raw(source.traceIdExpression)} AS trace_id,+ timestamp,+ ${hogql.raw(source.inputExpression)} AS ai_input+ FROM ${hogql.raw(source.from)}+ WHERE event = '$ai_generation'+ AND ${hogql.raw(source.traceIdExpression)} IN ${traceIds}+ AND toString(uuid) IN ${generationEventIds}+ )+ WHERE length(uuid) > 0+ AND length(trace_id) > 0+ GROUP BY uuid, trace_id+ LIMIT ${Math.max(generationEventIds.length, 1)}+ `,+ { ...SENTIMENT_QUERY_TAGS, name: 'ai_observability_generation_input_lookup' }+ )++ const inputs = new Map<string, unknown>()+ for (const [uuid, , aiInput] of response.results || []) {+ if (uuid && hasUsableInput(aiInput)) {+ inputs.set(String(uuid), aiInput)+ }+ }+ return inputs+}++async function fetchGenerationInputs(generations: SentimentGeneration[]): Promise<Record<string, unknown>> {+ const inputsByGenerationKey: Record<string, unknown> = {}+ const missingInputs = generations.filter((generation) => {+ if (hasUsableInput(generation.aiInput)) {+ inputsByGenerationKey[generation.uuid] = generation.aiInput+ return false+ }+ return true+ })++ if (missingInputs.length === 0) {+ return inputsByGenerationKey+ }++ const aiEventsInputs = await queryGenerationInputs(missingInputs, AI_EVENTS_SOURCE)+ for (const [uuid, aiInput] of aiEventsInputs) {+ inputsByGenerationKey[uuid] = aiInput+ }++ const fallbackGenerations = missingInputs.filter((generation) => !aiEventsInputs.has(generation.uuid))+ if (fallbackGenerations.length === 0) {+ return inputsByGenerationKey+ }++ const eventsInputs = await queryGenerationInputs(fallbackGenerations, EVENTS_SOURCE)+ for (const [uuid, aiInput] of eventsInputs) {+ inputsByGenerationKey[uuid] = aiInput+ }++ return inputsByGenerationKey+}++export async function fetchSentimentGenerationsPage(+ values: SentimentGenerationsQueryValues,+ offset: number+): Promise<SentimentGenerationsPage> {+ const generationsQuery: EventsQuery = {+ kind: NodeKind.EventsQuery,+ event: '$ai_generation',+ select: [...SENTIMENT_GENERATION_SELECT],+ orderBy: ['timestamp DESC', 'uuid DESC'],+ after: values.dateFilter.dateFrom || undefined,+ before: values.dateFilter.dateTo || undefined,+ filterTestAccounts: values.shouldFilterTestAccounts,+ properties: values.propertyFilters,+ limit: GENERATIONS_PAGE_SIZE,+ offset,+ tags: { ...SENTIMENT_QUERY_TAGS, name: 'ai_observability_sentiment_generations' },+ }++ const response = await api.query(generationsQuery)+ const generationRows = (response.results || [])+ .map((row) => mapGenerationRow(row))+ .filter((row): row is SentimentGeneration => row !== null)++ const [sentimentByGenerationKey, inputsByGenerationKey] = await Promise.all([+ fetchStoredGenerationSentiments(+ generationRows.map((generation) => ({+ key: generation.uuid,+ traceId: generation.traceId,+ generationIds: generation.generationIds,+ }))+ ),+ fetchGenerationInputs(generationRows),+ ])++ return {+ generations: generationRows+ .map((generation) => ({+ ...generation,+ aiInput: inputsByGenerationKey[generation.uuid] ?? generation.aiInput,+ sentiment: sentimentByGenerationKey[generation.uuid] ?? null,+ }))+ .filter((generation) => generation.sentiment !== null),+ rawCount: response.results?.length ?? 0,+ }+}diff --git a/products/ai_observability/frontend/sentimentResults.ts b/products/ai_observability/frontend/sentimentResults.tsnew file mode 100644index 000000000000..4f65183f3844--- /dev/null+++ b/products/ai_observability/frontend/sentimentResults.ts@@ -0,0 +1,99 @@+import { LLMSentimentMessage, LLMSentimentResult } from '~/queries/schema/schema-general'++export type MessageSentiment = LLMSentimentMessage+export type GenerationSentiment = LLMSentimentResult++export const GENERATION_SENTIMENT_SELECT = "'' -- Sentiment"++const SENTIMENT_LABELS = new Set(['positive', 'neutral', 'negative'])++export function normalizeSentimentResult(value: unknown): GenerationSentiment | null {+ if (!value || typeof value !== 'object') {+ return null+ }++ const raw = value as Record<string, unknown>+ const scores = normalizeScores(raw.scores)+ const label = normalizeLabel(raw.label)+ const score = normalizeNumber(raw.score) ?? scores[label] ?? 0+ const messages = normalizeMessages(raw.messages)++ return {+ label,+ score,+ scores,+ messages,+ message_count: normalizeInteger(raw.message_count) ?? Object.keys(messages).length,+ }+}++function normalizeJsonish(value: unknown): unknown {+ if (typeof value !== 'string') {+ return value+ }+ if (!value) {+ return null+ }+ try {+ return JSON.parse(value)+ } catch {+ return value+ }+}++function normalizeLabel(value: unknown): string {+ return typeof value === 'string' && SENTIMENT_LABELS.has(value) ? value : 'neutral'+}++function normalizeNumber(value: unknown): number | null {+ if (typeof value === 'number' && Number.isFinite(value)) {+ return value+ }+ if (typeof value === 'string') {+ const parsed = Number(value)+ return Number.isFinite(parsed) ? parsed : null+ }+ return null+}++function normalizeInteger(value: unknown): number | null {+ const parsed = normalizeNumber(value)+ return parsed === null ? null : Math.trunc(parsed)+}++function normalizeScores(value: unknown): Record<string, number> {+ const decoded = normalizeJsonish(value)+ if (!decoded || typeof decoded !== 'object' || Array.isArray(decoded)) {+ return { positive: 0, neutral: 0, negative: 0 }+ }++ const raw = decoded as Record<string, unknown>+ return {+ positive: normalizeNumber(raw.positive) ?? 0,+ neutral: normalizeNumber(raw.neutral) ?? 0,+ negative: normalizeNumber(raw.negative) ?? 0,+ }+}++function normalizeMessages(value: unknown): Record<string, MessageSentiment> {+ const decoded = normalizeJsonish(value)+ if (!decoded || typeof decoded !== 'object' || Array.isArray(decoded)) {+ return {}+ }++ const messages: Record<string, MessageSentiment> = {}+ for (const [key, rawMessage] of Object.entries(decoded as Record<string, unknown>)) {+ if (!rawMessage || typeof rawMessage !== 'object' || Array.isArray(rawMessage)) {+ continue+ }++ const message = rawMessage as Record<string, unknown>+ messages[key] = {+ label: normalizeLabel(message.label),+ score: normalizeNumber(message.score) ?? 0,+ scores: normalizeScores(message.scores),+ }+ }++ return messages+}diff --git a/products/ai_observability/frontend/sentimentUtils.ts b/products/ai_observability/frontend/sentimentUtils.tsindex 639949a71f12..a7018c5df6c8 100644--- a/products/ai_observability/frontend/sentimentUtils.ts+++ b/products/ai_observability/frontend/sentimentUtils.ts@@ -1,6 +1,3 @@-/** Tight date window around trace creation for sentiment ClickHouse queries. */-export const SENTIMENT_DATE_WINDOW_DAYS = 2-export type SentimentLabel = 'positive' | 'neutral' | 'negative'interface MessageScore {diff --git a/products/ai_observability/frontend/tabs/AIObservabilitySentiment.tsx b/products/ai_observability/frontend/tabs/AIObservabilitySentiment.tsxindex 0b796ade4165..7c50e87d505e 100644--- a/products/ai_observability/frontend/tabs/AIObservabilitySentiment.tsx+++ b/products/ai_observability/frontend/tabs/AIObservabilitySentiment.tsx@@ -1,6 +1,7 @@import { useActions, useValues } from 'kea'+import { combineUrl } from 'kea-router'-import { IconRefresh } from '@posthog/icons'+import { IconPlus, IconRefresh } from '@posthog/icons'import { LemonButton, Link, Spinner, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'@@ -13,12 +14,7 @@ import { extractContentText, formatScore } from '../sentimentUtils'import type { SentimentLabel } from '../sentimentUtils'import type { CompatMessage } from '../types'import { getTraceTimestamp } from '../utils'-import type {- GroupedSentimentCard,- SentimentCard,- SentimentCategory,- SentimentFeedbackLabel,-} from './aiObservabilitySentimentLogic'+import type { GroupedSentimentCard, SentimentCard, SentimentCategory } from './aiObservabilitySentimentLogic'import { CLASSIFIER_WINDOW, aiObservabilitySentimentLogic } from './aiObservabilitySentimentLogic'/**@@ -89,64 +85,6 @@ function ContextMessage({ aiInput, index }: { aiInput: unknown; index: number }))}-function SentimentFeedbackButtons({ card }: { card: SentimentCard }): JSX.Element {- const { feedbackByCardKey } = useValues(aiObservabilitySentimentLogic)- const { submitSentimentFeedback } = useActions(aiObservabilitySentimentLogic)- const cardKey = `${card.generation.uuid}:${card.messageIndex}`- const currentFeedback = feedbackByCardKey[cardKey]-- const options: {- label: SentimentFeedbackLabel- emoji: string- tooltip: string- selectedBg: string- hoverBg: string- }[] = [- {- label: 'negative',- emoji: '😠',- tooltip: 'Label as negative',- selectedBg: 'bg-danger-highlight',- hoverBg: 'hover:bg-danger/50',- },- {- label: 'neutral',- emoji: '😐',- tooltip: 'Label as neutral',- selectedBg: 'bg-border-light',- hoverBg: '',- },- {- label: 'positive',- emoji: '😊',- tooltip: 'Label as positive',- selectedBg: 'bg-success-highlight',- hoverBg: 'hover:bg-success/50',- },- ]-- return (- <span- className={`inline-flex items-center gap-0 ${currentFeedback ? 'opacity-100' : 'opacity-0 group-hover/card:opacity-100'} transition-opacity`}- onClick={(e) => e.stopPropagation()}- >- {options.map(({ label, emoji, tooltip, selectedBg, hoverBg }) => (- <Tooltip key={label} title={tooltip}>- <LemonButton- size="xsmall"- type="tertiary"- className={`rounded ${currentFeedback === label ? selectedBg : `opacity-60 ${hoverBg}`}`}- onClick={() => submitSentimentFeedback(cardKey, label, card)}- data-attr={`llma-sentiment-feedback-${label}`}- >- <span className="text-sm">{emoji}</span>- </LemonButton>- </Tooltip>- ))}- </span>- )-}-function SentimentCardRow({card,expanded,@@ -194,7 +132,6 @@ function SentimentCardRow({</span></Tooltip>)}- <SentimentFeedbackButtons card={card} /><MessageSentimentBar sentiment={sentiment} /><span className="text-xs text-muted whitespace-nowrap tabular-nums">{formatScore(sentiment.score)}@@ -242,7 +179,7 @@ const CATEGORY_CONFIG: { value: SentimentCategory; label: string; activeClass: s]function SentimentControls(): JSX.Element {- const { activeFilters, intensityThreshold, sentimentSummary, stillAnalyzing, generationsLoading } =+ const { activeFilters, intensityThreshold, sentimentSummary, generationsLoading } =useValues(aiObservabilitySentimentLogic)const { toggleSentimentCategory, setIntensityThreshold, loadGenerations } =useActions(aiObservabilitySentimentLogic)@@ -273,9 +210,9 @@ function SentimentControls(): JSX.Element {)})}</div>- {total > 0 && !stillAnalyzing && (+ {total > 0 && !generationsLoading && (<Tooltip- title={`${sentimentSummary.positive} positive, ${sentimentSummary.negative} negative, ${sentimentSummary.neutral} neutral messages across all analyzed generations`}+ title={`${sentimentSummary.positive} positive, ${sentimentSummary.negative} negative, ${sentimentSummary.neutral} neutral messages across all sentiment evaluation results`}><span className="text-xs text-muted tabular-nums ml-1">{total} total</span></Tooltip>@@ -310,19 +247,57 @@ function SentimentControls(): JSX.Element {)}+function SentimentEvaluationOnboarding(): JSX.Element {+ return (+ <div className="flex flex-col items-center justify-center text-center py-20 text-muted">+ <p className="text-lg font-medium mb-1 text-default">Create a sentiment evaluation</p>+ <p className="text-sm max-w-xl mb-4">+ This tab shows stored sentiment evaluation results from your AI generation events. Create a sentiment+ evaluation to start classifying user-message sentiment for matching generations.+ </p>+ <LemonButton+ type="primary"+ icon={<IconPlus />}+ to={combineUrl(urls.aiObservabilityEvaluation('new'), { type: 'sentiment' }).url}+ data-attr="llma-sentiment-create-evaluation"+ >+ Create sentiment evaluation+ </LemonButton>+ </div>+ )+}+export function AIObservabilitySentiment(): JSX.Element {const {generations,generationsLoading,generationsError,+ sentimentEvaluationsLoading,+ hasLoadedSentimentEvaluations,+ showSentimentEvaluationOnboarding,groupedSentimentCards,sentimentCards,- stillAnalyzing,expandedCardIds,hasMore,} = useValues(aiObservabilitySentimentLogic)const { loadMoreGenerations } = useActions(aiObservabilitySentimentLogic)+ if (sentimentEvaluationsLoading || !hasLoadedSentimentEvaluations) {+ return (+ <div className="flex items-center justify-center py-20" data-attr="llma-sentiment-tab">+ <Spinner className="text-4xl" captureTime />+ </div>+ )+ }++ if (showSentimentEvaluationOnboarding) {+ return (+ <div data-attr="llma-sentiment-tab">+ <SentimentEvaluationOnboarding />+ </div>+ )+ }+return (<div data-attr="llma-sentiment-tab"><SentimentControls />@@ -338,8 +313,8 @@ export function AIObservabilitySentiment(): JSX.Element {</div>) : generations.length === 0 ? (<div className="text-center py-20 text-muted">- <p className="text-lg font-medium mb-1">No generations with user input found</p>- <p className="text-sm">Try changing the date range or filters.</p>+ <p className="text-lg font-medium mb-1">No sentiment evaluation results found</p>+ <p className="text-sm">Try changing the date range or filters, or wait for matching generations.</p></div>) : (<>@@ -358,24 +333,23 @@ export function AIObservabilitySentiment(): JSX.Element {</div>)}- {(generationsLoading || stillAnalyzing) && (+ {generationsLoading && (<div className="flex items-center justify-center py-8 gap-2 text-muted"><Spinner className="text-lg" />- <span className="text-sm">- Analyzing sentiment on the fly, this can take a minute or two…- </span>+ <span className="text-sm">Loading sentiment evaluation results…</span></div>)}- {!generationsLoading && !stillAnalyzing && sentimentCards.length === 0 && (+ {!generationsLoading && sentimentCards.length === 0 && (<div className="text-center py-10 text-muted"><p className="text-sm">- No generations match the current sentiment filter. Try adjusting the controls above.+ No sentiment evaluation results match the current filter. Try adjusting the controls+ above.</p></div>)}- {!generationsLoading && !stillAnalyzing && hasMore && (+ {!generationsLoading && hasMore && (<div className="flex justify-center py-4"><LemonButtontype="secondary"diff --git a/products/ai_observability/frontend/tabs/aiObservabilityGenerationsLogic.ts b/products/ai_observability/frontend/tabs/aiObservabilityGenerationsLogic.tsindex 6a3d2ddb01d2..71efe0117ea9 100644--- a/products/ai_observability/frontend/tabs/aiObservabilityGenerationsLogic.ts+++ b/products/ai_observability/frontend/tabs/aiObservabilityGenerationsLogic.ts@@ -8,6 +8,7 @@ import { DataTableNode, LLMTrace, NodeKind, TraceQuery } from '~/queries/schema/import { SortDirection, SortState, aiObservabilitySharedLogic } from '../aiObservabilitySharedLogic'import { buildAiObservabilityStorageConfig } from '../preferenceStorage'+import { GENERATION_SENTIMENT_SELECT } from '../sentimentResults'import type { aiObservabilityGenerationsLogicType } from './aiObservabilityGenerationsLogicType'export type AIObservabilityGenerationsLogicProps = Record<string, never>@@ -17,7 +18,7 @@ export function getDefaultGenerationsColumns(): string[] {'uuid','properties.$ai_trace_id','person',- "'' -- Sentiment",+ GENERATION_SENTIMENT_SELECT,"f'{properties.$ai_model}' -- Model",'properties.$ai_tools_called',"if(properties.$ai_is_error = 'true', '❌', '') -- Error",@@ -65,7 +66,7 @@ export const aiObservabilityGenerationsLogic = kea<aiObservabilityGenerationsLoggenerationsColumns: [null as string[] | null,- buildAiObservabilityStorageConfig('generations.columns'),+ buildAiObservabilityStorageConfig('generations.columns.v4'),{setGenerationsColumns: (_, { columns }) => columns,},@@ -127,6 +128,7 @@ export const aiObservabilityGenerationsLogic = kea<aiObservabilityGenerationsLogconst traceQuery: TraceQuery = {kind: NodeKind.TraceQuery,traceId,+ includeSentiment: true,dateRange: {date_from: dateFrom,date_to: dateTo,diff --git a/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.test.ts b/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.test.tsnew file mode 100644index 000000000000..ab73843e250b--- /dev/null+++ b/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.test.ts@@ -0,0 +1,117 @@+import { expectLogic } from 'kea-test-utils'++import { initKeaTests } from '~/test/init'++import { evaluationsList } from '../generated/api'+import { sentimentEvaluationAvailabilityLogic } from '../sentimentEvaluationAvailabilityLogic'+import { fetchSentimentGenerationsPage } from '../sentimentQueries'+import type { SentimentGeneration } from '../sentimentQueries'+import { aiObservabilitySentimentLogic } from './aiObservabilitySentimentLogic'++jest.mock('../generated/api', () => ({+ evaluationsList: jest.fn(),+}))++jest.mock('../sentimentQueries', () => ({+ GENERATIONS_PAGE_SIZE: 200,+ fetchSentimentGenerationsPage: jest.fn(),+}))++const mockEvaluationsList = evaluationsList as jest.MockedFunction<typeof evaluationsList>+const mockFetchSentimentGenerationsPage = fetchSentimentGenerationsPage as jest.MockedFunction<+ typeof fetchSentimentGenerationsPage+>++const generationWithSentiment: SentimentGeneration = {+ uuid: 'generation-1',+ traceId: 'trace-1',+ generationIds: ['generation-1'],+ aiInput: [{ role: 'user', content: 'I love this' }],+ model: 'gpt-5-mini',+ distinctId: 'distinct-1',+ timestamp: '2026-06-23T00:00:00Z',+ createdAt: '2026-06-23T00:00:00Z',+ sentiment: {+ label: 'positive',+ score: 0.9,+ scores: { positive: 0.9, neutral: 0.08, negative: 0.02 },+ messages: {+ '0': {+ label: 'positive',+ score: 0.9,+ scores: { positive: 0.9, neutral: 0.08, negative: 0.02 },+ },+ },+ message_count: 1,+ },+}++describe('aiObservabilitySentimentLogic', () => {+ let logic: ReturnType<typeof aiObservabilitySentimentLogic.build> | null+ let availabilityLogic: ReturnType<typeof sentimentEvaluationAvailabilityLogic.build> | null++ beforeEach(() => {+ initKeaTests()+ mockEvaluationsList.mockResolvedValue({ count: 0, results: [] })+ mockFetchSentimentGenerationsPage.mockResolvedValue({ generations: [], rawCount: 0 })+ logic = null+ availabilityLogic = null+ })++ function mountLogics(): void {+ availabilityLogic = sentimentEvaluationAvailabilityLogic()+ availabilityLogic.mount()++ logic = aiObservabilitySentimentLogic()+ logic.mount()+ }++ afterEach(() => {+ logic?.unmount()+ availabilityLogic?.unmount()+ jest.clearAllMocks()+ })++ it('loads stored sentiment rows even without a configured sentiment evaluation', async () => {+ mockFetchSentimentGenerationsPage.mockResolvedValue({+ generations: [generationWithSentiment],+ rawCount: 1,+ })+ mountLogics()++ await expectLogic(logic!, () => {+ logic!.actions.activate()+ }).toFinishAllListeners()++ expect(mockFetchSentimentGenerationsPage).toHaveBeenCalled()+ expect(logic!.values.generations).toEqual([generationWithSentiment])+ expect(logic!.values.showSentimentEvaluationOnboarding).toBe(false)+ })++ it('shows onboarding only when no configured eval and no stored sentiment rows match', async () => {+ mountLogics()++ await expectLogic(logic!, () => {+ logic!.actions.activate()+ }).toFinishAllListeners()++ expect(logic!.values.hasSentimentEvaluations).toBe(false)+ expect(logic!.values.generations).toEqual([])+ expect(logic!.values.showSentimentEvaluationOnboarding).toBe(true)+ })++ it('does not show onboarding when a sentiment evaluation is configured', async () => {+ mockEvaluationsList.mockResolvedValue({+ results: [{ id: 'sentiment-eval', evaluation_type: 'sentiment' }],+ } as Awaited<ReturnType<typeof evaluationsList>>)+ mountLogics()++ await expectLogic(logic!, () => {+ logic!.actions.activate()+ }).toFinishAllListeners()++ expect(logic!.values.hasSentimentEvaluations).toBe(true)+ expect(logic!.values.generations).toEqual([])+ expect(logic!.values.showSentimentEvaluationOnboarding).toBe(false)+ })+})diff --git a/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.ts b/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.tsindex 757b48280103..fc74faee7da1 100644--- a/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.ts+++ b/products/ai_observability/frontend/tabs/aiObservabilitySentimentLogic.ts@@ -5,33 +5,22 @@ import posthog from 'posthog-js'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'-import { getCurrentTeamId } from '~/lib/utils/getAppContext'import { groupsModel } from '~/models/groupsModel'import { aiObservabilitySharedLogic } from '../aiObservabilitySharedLogic'-import { llmAnalyticsSentimentGenerationsCreate as aiObservabilitySentimentGenerationsCreate } from '../generated/api'-import { llmGenerationSentimentLazyLoaderLogic } from '../llmGenerationSentimentLazyLoaderLogic'-import type { GenerationSentiment, MessageSentiment } from '../llmSentimentLazyLoaderLogic'+import { sentimentEvaluationAvailabilityLogic } from '../sentimentEvaluationAvailabilityLogic'+import { fetchSentimentGenerationsPage, GENERATIONS_PAGE_SIZE, type SentimentGeneration } from '../sentimentQueries'+import type { MessageSentiment } from '../sentimentResults'import { extractContentText } from '../sentimentUtils'import type { aiObservabilitySentimentLogicType } from './aiObservabilitySentimentLogicType'+export type { SentimentGeneration } from '../sentimentQueries'+export type SentimentCategory = 'positive' | 'negative' | 'neutral'-export type SentimentFeedbackLabel = SentimentCategory/** @deprecated Use SentimentCategory with activeFilters set instead */export type SentimentFilterLabel = SentimentCategory | 'both'-export interface SentimentGeneration {- uuid: string- traceId: string- aiInput: unknown- model: string | null- distinctId: string- timestamp: string- /** Earliest event in the trace — used for trace deep-links (matches trace createdAt) */- createdAt: string-}-/** A generation paired with the index of the best matching message for display */export interface SentimentCard {generation: SentimentGeneration@@ -50,7 +39,6 @@ export interface GroupedSentimentCard {export type AIObservabilitySentimentLogicProps = Record<string, never>-const GENERATIONS_PAGE_SIZE = 200/** Stop auto-loading once we have at least this many visible cards */const MIN_VISIBLE_CARDS = 50/** Cap how many extra pages we fetch automatically to avoid runaway API calls */@@ -154,44 +142,10 @@ function captureEngagementEvents(}}-interface GenerationsQueryValues {- dateFilter: { dateFrom: string | null; dateTo: string | null }- shouldFilterTestAccounts: boolean- propertyFilters: unknown[]-}-// Tracks the raw (pre-dedup) count from the last loadMoreGenerations fetch,// so the listener can determine hasMore accurately despite deduplication.let lastRawFetchCount = 0--async function fetchGenerations(values: GenerationsQueryValues, cursor: string | null): Promise<SentimentGeneration[]> {- // Routed through `AIObservabilitySentimentViewSet.generations`, which wraps- // `query_ai_events` for consistent `ai_query_source` attribution and the- // retention-window fallback. Response shape is tuple-positional ([uuid, trace_id, ai_input,- // model, distinct_id, timestamp, created_at]) — the generated wrapper- // types `results` as `unknown[][]` so the position casts here are- // unavoidable until the response serializer declares per-element types.- const response = await aiObservabilitySentimentGenerationsCreate(String(getCurrentTeamId()), {- filters: {- dateRange: {- date_from: values.dateFilter.dateFrom || null,- date_to: cursor || values.dateFilter.dateTo || null,- },- filterTestAccounts: values.shouldFilterTestAccounts,- properties: values.propertyFilters,- },- })-- return (response.results || []).map((row: unknown[]) => ({- uuid: row[0] as string,- traceId: row[1] as string,- aiInput: row[2],- model: row[3] as string | null,- distinctId: row[4] as string,- timestamp: row[5] as string,- createdAt: row[6] as string,- }))-}+let nextGenerationsOffset = 0export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicType>([path(['products', 'ai_observability', 'frontend', 'tabs', 'aiObservabilitySentimentLogic']),@@ -202,10 +156,9 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTy['dateFilter', 'shouldFilterTestAccounts', 'propertyFilters', 'activeTab'],groupsModel,['groupsTaxonomicTypes'],- llmGenerationSentimentLazyLoaderLogic,- ['sentimentByGenerationId'],+ sentimentEvaluationAvailabilityLogic,+ ['hasLoadedSentimentEvaluations', 'hasSentimentEvaluations', 'sentimentEvaluationsLoading'],],- actions: [llmGenerationSentimentLazyLoaderLogic, ['ensureGenerationSentimentLoaded']],})),actions({@@ -218,11 +171,6 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTyloadMoreGenerations: true,setHasMore: (hasMore: boolean) => ({ hasMore }),trackTraceClicked: (card: SentimentCard) => ({ card }),- submitSentimentFeedback: (cardKey: string, feedbackLabel: SentimentFeedbackLabel, card: SentimentCard) => ({- cardKey,- feedbackLabel,- card,- }),}),reducers({@@ -277,16 +225,6 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTyloadGenerations: () => true,},],- feedbackByCardKey: [- {} as Record<string, SentimentFeedbackLabel>,- {- submitSentimentFeedback: (state, { cardKey, feedbackLabel }) => ({- ...state,- [cardKey]: feedbackLabel,- }),- loadGenerations: () => ({}),- },- ],autoLoadRounds: [0 as number,{@@ -315,16 +253,18 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTy[] as SentimentGeneration[],{loadGenerations: async () => {- return await fetchGenerations(values, null)+ const page = await fetchSentimentGenerationsPage(values, 0)+ lastRawFetchCount = page.rawCount+ nextGenerationsOffset = page.rawCount+ return page.generations},loadMoreGenerations: async () => {const existing = values.generations- const cursor = existing.length > 0 ? existing[existing.length - 1].timestamp : null- const newGenerations = await fetchGenerations(values, cursor)- lastRawFetchCount = newGenerations.length- // Dedupe by traceId in case of timestamp boundary overlap- const existingTraceIds = new Set(existing.map((g) => g.traceId))- const unique = newGenerations.filter((g) => !existingTraceIds.has(g.traceId))+ const page = await fetchSentimentGenerationsPage(values, nextGenerationsOffset)+ lastRawFetchCount = page.rawCount+ nextGenerationsOffset += page.rawCount+ const existingGenerationIds = new Set(existing.map((g) => g.uuid))+ const unique = page.generations.filter((g) => !existingGenerationIds.has(g.uuid))return [...existing, ...unique]},},@@ -343,16 +283,15 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTy],],sentimentCards: [- (s) => [s.generations, s.sentimentByGenerationId, s.activeFilters, s.intensityThreshold],+ (s) => [s.generations, s.activeFilters, s.intensityThreshold],(generations: SentimentGeneration[],- sentimentByGenerationId: Record<string, GenerationSentiment | null>,activeFilters: Set<SentimentCategory>,intensityThreshold: number): SentimentCard[] => {const cards: SentimentCard[] = []for (const gen of generations) {- const sentimentData = sentimentByGenerationId[gen.uuid]+ const sentimentData = gen.sentimentif (!sentimentData?.messages) {continue}@@ -384,15 +323,11 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTy],/** Counts of displayable cards per sentiment category (best-per-generation, matching sentimentCards logic) */sentimentSummary: [- (s) => [s.generations, s.sentimentByGenerationId, s.intensityThreshold],- (- generations: SentimentGeneration[],- sentimentByGenerationId: Record<string, GenerationSentiment | null>,- intensityThreshold: number- ): Record<SentimentCategory, number> => {+ (s) => [s.generations, s.intensityThreshold],+ (generations: SentimentGeneration[], intensityThreshold: number): Record<SentimentCategory, number> => {const counts: Record<SentimentCategory, number> = { positive: 0, negative: 0, neutral: 0 }for (const gen of generations) {- const sentimentData = sentimentByGenerationId[gen.uuid]+ const sentimentData = gen.sentimentif (!sentimentData?.messages) {continue}@@ -445,12 +380,35 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTyreturn result},],- stillAnalyzing: [- (s) => [s.generations, s.sentimentByGenerationId],+ stillAnalyzing: [(s) => [s.generationsLoading], (generationsLoading: boolean): boolean => generationsLoading],+ showSentimentEvaluationOnboarding: [+ (s) => [+ s.hasLoadedSentimentEvaluations,+ s.hasSentimentEvaluations,+ s.hasLoadedOnce,+ s.generations,+ s.generationsLoading,+ s.generationsError,+ s.hasMore,+ s.autoLoadRounds,+ ],(+ hasLoadedSentimentEvaluations: boolean,+ hasSentimentEvaluations: boolean,+ hasLoadedOnce: boolean,generations: SentimentGeneration[],- sentimentByGenerationId: Record<string, GenerationSentiment | null>- ): boolean => generations.some((gen) => sentimentByGenerationId[gen.uuid] === undefined),+ generationsLoading: boolean,+ generationsError: boolean,+ hasMore: boolean,+ autoLoadRounds: number+ ): boolean =>+ hasLoadedSentimentEvaluations &&+ hasLoadedOnce &&+ !hasSentimentEvaluations &&+ !generationsLoading &&+ !generationsError &&+ generations.length === 0 &&+ (!hasMore || autoLoadRounds >= MAX_AUTO_LOAD_ROUNDS),],}),@@ -461,21 +419,11 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTyactions.loadGenerations()}},- loadGenerationsSuccess: ({ generations }) => {- actions.setHasMore(generations.length >= GENERATIONS_PAGE_SIZE)- for (const gen of generations) {- if (values.sentimentByGenerationId[gen.uuid] === undefined) {- actions.ensureGenerationSentimentLoaded(gen.uuid, values.dateFilter)- }- }+ loadGenerationsSuccess: () => {+ actions.setHasMore(lastRawFetchCount >= GENERATIONS_PAGE_SIZE)},loadMoreGenerationsSuccess: () => {actions.setHasMore(lastRawFetchCount >= GENERATIONS_PAGE_SIZE)- for (const gen of values.generations) {- if (values.sentimentByGenerationId[gen.uuid] === undefined) {- actions.ensureGenerationSentimentLoaded(gen.uuid, values.dateFilter)- }- }},toggleCardExpanded: ({ cardKey: key }) => {// Only track when expanding (key is now in the set), not collapsing@@ -503,18 +451,6 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTyvalues.intensityThreshold)},- submitSentimentFeedback: ({ card, feedbackLabel }) => {- posthog.capture('llma sentiment feedback', {- generation_uuid: card.generation.uuid,- trace_id: card.generation.traceId,- message_index: card.messageIndex,- message_text_snippet: getSnippetFromCard(card),- model_prediction_label: card.sentiment.label,- model_prediction_score: card.sentiment.score,- user_label: feedbackLabel,- ai_model: card.generation.model,- })- },}}),@@ -545,9 +481,6 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTystillAnalyzing: (stillAnalyzing: boolean) => {if (wasAnalyzing && !stillAnalyzing && values.activeTab === 'sentiment') {const totalGenerations = values.generations.length- const failedCount = values.generations.filter(- (gen) => values.sentimentByGenerationId[gen.uuid] === null- ).lengthconst cardCount = values.sentimentCards.lengthconst visibleCards = values.groupedSentimentCards.length@@ -559,14 +492,8 @@ export const aiObservabilitySentimentLogic = kea<aiObservabilitySentimentLogicTyif ((totalGenerations === 0 || cardCount === 0) && !shouldAutoLoad) {posthog.capture('llma sentiment empty state', {- reason:- totalGenerations === 0- ? 'no_generations'- : failedCount === totalGenerations- ? 'all_classification_failed'- : 'no_matching_cards',+ reason: totalGenerations === 0 ? 'no_generations' : 'no_sentiment_results',total_generations: totalGenerations,- failed_classifications: failedCount,sentiment_filter: Array.from(values.activeFilters).sort().join(','),intensity_threshold: values.intensityThreshold,})diff --git a/products/ai_observability/frontend/tabs/aiObservabilitySessionsViewLogic.ts b/products/ai_observability/frontend/tabs/aiObservabilitySessionsViewLogic.tsindex 0432080d041a..b23ef79f8c28 100644--- a/products/ai_observability/frontend/tabs/aiObservabilitySessionsViewLogic.ts+++ b/products/ai_observability/frontend/tabs/aiObservabilitySessionsViewLogic.ts@@ -268,6 +268,7 @@ export const aiObservabilitySessionsViewLogic = kea<aiObservabilitySessionsViewLconst traceQuery: TraceQuery = {kind: NodeKind.TraceQuery,traceId,+ includeSentiment: true,dateRange: {date_from: dateFrom,date_to: dateTo,diff --git a/products/ai_observability/frontend/tabs/aiObservabilityTracesTabLogic.ts b/products/ai_observability/frontend/tabs/aiObservabilityTracesTabLogic.tsindex f1c63919851d..bd1076a7d046 100644--- a/products/ai_observability/frontend/tabs/aiObservabilityTracesTabLogic.ts+++ b/products/ai_observability/frontend/tabs/aiObservabilityTracesTabLogic.ts@@ -119,6 +119,7 @@ export const aiObservabilityTracesTabLogic = kea<aiObservabilityTracesTabLogicTypersonId: personId ?? undefined,groupKey: group?.groupKey,groupTypeIndex: group?.groupTypeIndex,+ includeSentiment: showSentimentColumn,},columns: ['id',diff --git a/products/ai_observability/mcp/tools.yaml b/products/ai_observability/mcp/tools.yamlindex 410b8f5d0e89..9c18f4d829e3 100644--- a/products/ai_observability/mcp/tools.yaml+++ b/products/ai_observability/mcp/tools.yaml@@ -32,9 +32,6 @@ tools:llm-analytics-parser-recipes-retrieve:operation: llm_analytics_parser_recipes_retrieveenabled: false- llm-analytics-sentiment-generations-create:- operation: llm_analytics_sentiment_generations_create- enabled: falsellma-clustering-config-get:operation: llm_analytics_clustering_config_retrieveenabled: false@@ -780,21 +777,6 @@ tools:Update a scorer's metadata: rename via `name`, edit `description`, or toggle `archived` to hide (`true`) orrestore (`false`). Archiving is reversible — there is no destroy endpoint. To change the scoring rulesinstead, call `llma-score-definition-new-version`. `kind` cannot be changed.- llma-sentiment-create:- operation: llm_analytics_sentiment_create- enabled: true- scopes:- - llm_analytics:write- annotations:- readOnly: false- destructive: false- idempotent: true- title: Analyze sentiment- description: >- Classify sentiment of LLM trace or generation user messages as positive, neutral, or negative. Pass a list- of trace or generation IDs and an analysis_level ("trace" or "generation"). Returns per-ID sentiment labels- with confidence scores and per-message breakdowns. Results are cached — use force_refresh to recompute.- Rate-limited.llma-summarization-batch-check-create:operation: llm_analytics_summarization_batch_check_createenabled: falsediff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 7a41f56f3aa5..f1f71dce67b5 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -4516,6 +4516,26 @@ export const AIEventTypeApi = {AiGenerationClusters: '$ai_generation_clusters',} as const+export type LLMSentimentMessageApiScores = { [key: string]: number } | null++export interface LLMSentimentMessageApi {+ label: string+ score: number+ scores?: LLMSentimentMessageApiScores+}++export type LLMSentimentResultApiMessages = { [key: string]: LLMSentimentMessageApi } | null++export type LLMSentimentResultApiScores = { [key: string]: number } | null++export interface LLMSentimentResultApi {+ label: string+ message_count?: number | null+ messages?: LLMSentimentResultApiMessages+ score: number+ scores?: LLMSentimentResultApiScores+}+export type LLMTraceEventApiProperties = { [key: string]: unknown }export interface LLMTraceEventApi {@@ -4523,6 +4543,7 @@ export interface LLMTraceEventApi {event: AIEventTypeApi | stringid: stringproperties: LLMTraceEventApiProperties+ sentiment?: LLMSentimentResultApi | null}export type LLMTracePersonApiProperties = { [key: string]: unknown }@@ -4550,6 +4571,7 @@ export interface LLMTraceApi {outputTokens?: number | nullperson?: LLMTracePersonApi | nullrequestCost?: number | null+ sentiment?: LLMSentimentResultApi | nulltools?: string[] | nulltotalCost?: number | nulltotalLatency?: number | null@@ -7164,6 +7186,8 @@ export interface TracesQueryApi {filterTestAccounts?: boolean | nullgroupKey?: string | nullgroupTypeIndex?: number | null+ /** Include stored sentiment evaluation results for returned traces and direct generation events. */+ includeSentiment?: boolean | nullkind?: 'TracesQuery'limit?: number | null/** Modifiers used when performing the query */@@ -7231,6 +7255,8 @@ export interface TraceQueryResponseApi {export interface TraceQueryApi {dateRange?: DateRangeApi | null+ /** Include stored sentiment evaluation results for the trace and its generations. */+ includeSentiment?: boolean | nullkind?: 'TraceQuery'/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiersApi | nulldiff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 114e28af9dbb..9edc39bb2732 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -3915,6 +3915,26 @@ export const AIEventTypeApi = {AiGenerationClusters: '$ai_generation_clusters',} as const+export type LLMSentimentMessageApiScores = { [key: string]: number } | null++export interface LLMSentimentMessageApi {+ label: string+ score: number+ scores?: LLMSentimentMessageApiScores+}++export type LLMSentimentResultApiMessages = { [key: string]: LLMSentimentMessageApi } | null++export type LLMSentimentResultApiScores = { [key: string]: number } | null++export interface LLMSentimentResultApi {+ label: string+ message_count?: number | null+ messages?: LLMSentimentResultApiMessages+ score: number+ scores?: LLMSentimentResultApiScores+}+export type LLMTraceEventApiProperties = { [key: string]: unknown }export interface LLMTraceEventApi {@@ -3922,6 +3942,7 @@ export interface LLMTraceEventApi {event: AIEventTypeApi | stringid: stringproperties: LLMTraceEventApiProperties+ sentiment?: LLMSentimentResultApi | null}export type LLMTracePersonApiProperties = { [key: string]: unknown }@@ -3949,6 +3970,7 @@ export interface LLMTraceApi {outputTokens?: number | nullperson?: LLMTracePersonApi | nullrequestCost?: number | null+ sentiment?: LLMSentimentResultApi | nulltools?: string[] | nulltotalCost?: number | nulltotalLatency?: number | null@@ -6563,6 +6585,8 @@ export interface TracesQueryApi {filterTestAccounts?: boolean | nullgroupKey?: string | nullgroupTypeIndex?: number | null+ /** Include stored sentiment evaluation results for returned traces and direct generation events. */+ includeSentiment?: boolean | nullkind?: 'TracesQuery'limit?: number | null/** Modifiers used when performing the query */@@ -6630,6 +6654,8 @@ export interface TraceQueryResponseApi {export interface TraceQueryApi {dateRange?: DateRangeApi | null+ /** Include stored sentiment evaluation results for the trace and its generations. */+ includeSentiment?: boolean | nullkind?: 'TraceQuery'/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiersApi | nulldiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex b864afcf2d7e..21d4fa277c09 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -4641,20 +4641,6 @@"readOnlyHint": false}},- "llma-sentiment-create": {- "description": "Classify sentiment of LLM trace or generation user messages as positive, neutral, or negative. Pass a list of trace or generation IDs and an analysis_level (\"trace\" or \"generation\"). Returns per-ID sentiment labels with confidence scores and per-message breakdowns. Results are cached — use force_refresh to recompute. Rate-limited.",- "category": "AI observability",- "feature": "llm_analytics",- "summary": "Analyze sentiment",- "title": "Analyze sentiment",- "required_scopes": ["llm_analytics:write"],- "annotations": {- "destructiveHint": false,- "idempotentHint": true,- "openWorldHint": true,- "readOnlyHint": false- }- },"llma-summarization-create": {"description": "Generate an AI-powered summary of an LLM trace or generation. Pass a trace_id or generation_id with a date_from — the backend fetches the data and returns a structured summary with title, flow diagram, summary bullets, and interesting notes. Results are cached. Use mode \"minimal\" (default) for 3-5 points or \"detailed\" for 5-10 points. Rate-limited; requires AI data processing approval for the organization.","category": "AI observability",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 9fa28763ced4..a3fe8ef5809e 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -4937,20 +4937,6 @@"readOnlyHint": false}},- "llma-sentiment-create": {- "description": "Classify sentiment of LLM trace or generation user messages as positive, neutral, or negative. Pass a list of trace or generation IDs and an analysis_level (\"trace\" or \"generation\"). Returns per-ID sentiment labels with confidence scores and per-message breakdowns. Results are cached — use force_refresh to recompute. Rate-limited.",- "category": "AI observability",- "feature": "llm_analytics",- "summary": "Analyze sentiment",- "title": "Analyze sentiment",- "required_scopes": ["llm_analytics:write"],- "annotations": {- "destructiveHint": false,- "idempotentHint": true,- "openWorldHint": true,- "readOnlyHint": false- }- },"llma-skill-archive": {"description": "DEPRECATED: renamed to skill-archive. This alias forwards to skill-archive and will be removed. Call skill-archive directly with the same arguments.","category": "Skills",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 00365984327a..6ce117a3d3c2 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -5243,6 +5243,26 @@ export namespace Schemas {warnings?: DataWarehouseSyncWarning[] | null;}+ export type LLMSentimentMessageScores = {[key: string]: number} | null;++ export interface LLMSentimentMessage {+ label: string;+ score: number;+ scores?: LLMSentimentMessageScores;+ }++ export type LLMSentimentResultMessages = {[key: string]: LLMSentimentMessage} | null;++ export type LLMSentimentResultScores = {[key: string]: number} | null;++ export interface LLMSentimentResult {+ label: string;+ message_count?: number | null;+ messages?: LLMSentimentResultMessages;+ score: number;+ scores?: LLMSentimentResultScores;+ }+export type LLMTraceEventProperties = { [key: string]: unknown };export interface LLMTraceEvent {@@ -5250,6 +5270,7 @@ export namespace Schemas {event: AIEventType | string;id: string;properties: LLMTraceEventProperties;+ sentiment?: LLMSentimentResult | null;}export type LLMTracePersonProperties = { [key: string]: unknown };@@ -5277,6 +5298,7 @@ export namespace Schemas {outputTokens?: number | null;person?: LLMTracePerson | null;requestCost?: number | null;+ sentiment?: LLMSentimentResult | null;tools?: string[] | null;totalCost?: number | null;totalLatency?: number | null;@@ -6756,6 +6778,8 @@ export namespace Schemas {filterTestAccounts?: boolean | null;groupKey?: string | null;groupTypeIndex?: number | null;+ /** Include stored sentiment evaluation results for returned traces and direct generation events. */+ includeSentiment?: boolean | null;kind?: 'TracesQuery';limit?: number | null;/** Modifiers used when performing the query */@@ -6800,6 +6824,8 @@ export namespace Schemas {export interface TraceQuery {dateRange?: DateRange | null;+ /** Include stored sentiment evaluation results for the trace and its generations. */+ includeSentiment?: boolean | null;kind?: 'TraceQuery';/** Modifiers used when performing the query */modifiers?: HogQLQueryModifiers | null;@@ -9184,6 +9210,20 @@ export namespace Schemas {breakdown_results?: BreakdownSimulationResult[];}+ /**+ * * `trace` - trace+ * * `generation` - generation+ * * `evaluation` - evaluation+ */+ export type AnalysisLevelEnum = typeof AnalysisLevelEnum[keyof typeof AnalysisLevelEnum];+++ export const AnalysisLevelEnum = {+ Trace: 'trace',+ Generation: 'generation',+ Evaluation: 'evaluation',+ } as const;+/*** * `USR` - user* * `GIT` - GitHub@@ -12613,25 +12653,11 @@ export namespace Schemas {truncated: boolean;}- /**- * * `trace` - trace- * * `generation` - generation- * * `evaluation` - evaluation- */- export type ClusteringJobAnalysisLevelEnum = typeof ClusteringJobAnalysisLevelEnum[keyof typeof ClusteringJobAnalysisLevelEnum];--- export const ClusteringJobAnalysisLevelEnum = {- Trace: 'trace',- Generation: 'generation',- Evaluation: 'evaluation',- } as const;-export interface ClusteringJob {readonly id: string;/** @maxLength 100 */name: string;- analysis_level: ClusteringJobAnalysisLevelEnum;+ analysis_level: AnalysisLevelEnum;event_filters?: unknown;enabled?: boolean;readonly created_at: string;@@ -28749,14 +28775,6 @@ export namespace Schemas {preferences: unknown;}- export type MessageSentimentScores = {[key: string]: number};-- export interface MessageSentiment {- label: string;- score: number;- scores: MessageSentimentScores;- }-/*** * `liquid` - liquid*/@@ -35262,7 +35280,7 @@ export namespace Schemas {readonly id?: string;/** @maxLength 100 */name?: string;- analysis_level?: ClusteringJobAnalysisLevelEnum;+ analysis_level?: AnalysisLevelEnum;event_filters?: unknown;enabled?: boolean;readonly created_at?: string;@@ -46545,77 +46563,6 @@ export namespace Schemas {send_async?: boolean;}- export type SentimentResultScores = {[key: string]: number};-- export type SentimentResultMessages = {[key: string]: MessageSentiment};-- export interface SentimentResult {- label: string;- score: number;- scores: SentimentResultScores;- messages: SentimentResultMessages;- message_count: number;- }-- export type SentimentBatchResponseResults = {[key: string]: SentimentResult};-- export interface SentimentBatchResponse {- results: SentimentBatchResponseResults;- }-- /**- * Filter shape mirrors the previous frontend `api.query({filters: ...})` payload.- *- * `filters` accepts the same `HogQLFilters` schema that the legacy frontend HogQL- * path used (dateRange, filterTestAccounts, properties), so the migration is- * behaviour-preserving for callers that pass a request unchanged.- */- export interface SentimentGenerationsRequest {- filters?: unknown;- }-- export interface SentimentGenerationsResponse {- results: unknown[][];- }-- /**- * * `trace` - trace- * * `generation` - generation- */- export type SentimentRequestAnalysisLevelEnum = typeof SentimentRequestAnalysisLevelEnum[keyof typeof SentimentRequestAnalysisLevelEnum];--- export const SentimentRequestAnalysisLevelEnum = {- Trace: 'trace',- Generation: 'generation',- } as const;-- export interface SentimentRequest {- /**- * Trace IDs (analysis_level=trace) or generation event UUIDs (analysis_level=generation).- * @minItems 1- * @maxItems 5- */- ids: string[];- /** Whether the IDs are 'trace' IDs or 'generation' IDs.- *- * * `trace` - trace- * * `generation` - generation */- analysis_level?: SentimentRequestAnalysisLevelEnum;- /** If true, bypass cache and reclassify. */- force_refresh?: boolean;- /**- * Start of date range for the lookup (e.g. '-7d' or '2026-01-01'). Defaults to -30d.- * @nullable- */- date_from?: string | null;- /**- * End of date range for the lookup. Defaults to now.- * @nullable- */- date_to?: string | null;- }-export interface SessionGroupSummary {readonly id: string;/** Title of the group session summary */@@ -54211,6 +54158,14 @@ export namespace Schemas {* Filter by enabled status*/enabled?: boolean;+ /**+ * Filter by evaluation type+ *+ * * `llm_judge` - LLM as a judge+ * * `hog` - Hog+ * * `sentiment` - Sentiment analysis+ */+ evaluation_type?: EnvironmentsEvaluationsListEvaluationType;/*** Multiple values may be separated by commas.*/@@ -54240,6 +54195,15 @@ export namespace Schemas {search?: string;};+ export type EnvironmentsEvaluationsListEvaluationType = typeof EnvironmentsEvaluationsListEvaluationType[keyof typeof EnvironmentsEvaluationsListEvaluationType];+++ export const EnvironmentsEvaluationsListEvaluationType = {+ Hog: 'hog',+ LlmJudge: 'llm_judge',+ Sentiment: 'sentiment',+ } as const;+export type EnvironmentsEventsListParams = {/*** Only return events with a timestamp after this time. Default: now() - 24 hours.@@ -55989,14 +55953,6 @@ export namespace Schemas {search?: string;};- export type EnvironmentsLlmAnalyticsSentimentCreate400 = { [key: string]: unknown };-- export type EnvironmentsLlmAnalyticsSentimentCreate500 = { [key: string]: unknown };-- export type EnvironmentsLlmAnalyticsSentimentGenerationsCreate400 = { [key: string]: unknown };-- export type EnvironmentsLlmAnalyticsSentimentGenerationsCreate500 = { [key: string]: unknown };-export type EnvironmentsLlmAnalyticsSummarizationCreate400 = { [key: string]: unknown };export type EnvironmentsLlmAnalyticsSummarizationCreate403 = { [key: string]: unknown };@@ -60171,6 +60127,14 @@ export namespace Schemas {* Filter by enabled status*/enabled?: boolean;+ /**+ * Filter by evaluation type+ *+ * * `llm_judge` - LLM as a judge+ * * `hog` - Hog+ * * `sentiment` - Sentiment analysis+ */+ evaluation_type?: EvaluationsListEvaluationType;/*** Multiple values may be separated by commas.*/@@ -60200,6 +60164,15 @@ export namespace Schemas {search?: string;};+ export type EvaluationsListEvaluationType = typeof EvaluationsListEvaluationType[keyof typeof EvaluationsListEvaluationType];+++ export const EvaluationsListEvaluationType = {+ Hog: 'hog',+ LlmJudge: 'llm_judge',+ Sentiment: 'sentiment',+ } as const;+export type EventDefinitionsListParams = {/*** When true, omit events that have been explicitly hidden by a team admin (Enterprise only).@@ -62405,14 +62378,6 @@ export namespace Schemas {search?: string;};- export type LlmAnalyticsSentimentCreate400 = { [key: string]: unknown };-- export type LlmAnalyticsSentimentCreate500 = { [key: string]: unknown };-- export type LlmAnalyticsSentimentGenerationsCreate400 = { [key: string]: unknown };-- export type LlmAnalyticsSentimentGenerationsCreate500 = { [key: string]: unknown };-export type LlmAnalyticsSummarizationCreate400 = { [key: string]: unknown };export type LlmAnalyticsSummarizationCreate403 = { [key: string]: unknown };diff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.tsindex 1b682293c434..76114fa1d00d 100644--- a/services/mcp/src/generated/ai_observability/api.ts+++ b/services/mcp/src/generated/ai_observability/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 51 enabled ops+ * PostHog API - MCP 50 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -97,6 +97,12 @@ export const EvaluationsListParams = /* @__PURE__ */ zod.object({export const EvaluationsListQueryParams = /* @__PURE__ */ zod.object({enabled: zod.boolean().optional().describe('Filter by enabled status'),+ evaluation_type: zod+ .enum(['hog', 'llm_judge', 'sentiment'])+ .optional()+ .describe(+ 'Filter by evaluation type\n\n* `llm_judge` - LLM as a judge\n* `hog` - Hog\n* `sentiment` - Sentiment analysis'+ ),id__in: zod.array(zod.string()).optional().describe('Multiple values may be separated by commas.'),limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),@@ -1172,43 +1178,6 @@ export const LlmAnalyticsScoreDefinitionsNewVersionCreateBody = /* @__PURE__ */),})-export const LlmAnalyticsSentimentCreateParams = /* @__PURE__ */ zod.object({- project_id: zod- .string()- .describe(- "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."- ),-})--export const llmAnalyticsSentimentCreateBodyIdsMax = 5--export const llmAnalyticsSentimentCreateBodyAnalysisLevelDefault = `trace`-export const llmAnalyticsSentimentCreateBodyForceRefreshDefault = false--export const LlmAnalyticsSentimentCreateBody = /* @__PURE__ */ zod.object({- ids: zod- .array(zod.string())- .min(1)- .max(llmAnalyticsSentimentCreateBodyIdsMax)- .describe('Trace IDs (analysis_level=trace) or generation event UUIDs (analysis_level=generation).'),- analysis_level: zod- .enum(['trace', 'generation'])- .describe('* `trace` - trace\n* `generation` - generation')- .default(llmAnalyticsSentimentCreateBodyAnalysisLevelDefault)- .describe(- "Whether the IDs are 'trace' IDs or 'generation' IDs.\n\n* `trace` - trace\n* `generation` - generation"- ),- force_refresh: zod- .boolean()- .default(llmAnalyticsSentimentCreateBodyForceRefreshDefault)- .describe('If true, bypass cache and reclassify.'),- date_from: zod- .string()- .nullish()- .describe("Start of date range for the lookup (e.g. '-7d' or '2026-01-01'). Defaults to -30d."),- date_to: zod.string().nullish().describe('End of date range for the lookup. Defaults to now.'),-})-/**** Generate an AI-powered summary of an LLM trace or event.diff --git a/services/mcp/src/tools/generated/ai_observability.ts b/services/mcp/src/tools/generated/ai_observability.tsindex ce328149fe3f..330b101465d0 100644--- a/services/mcp/src/tools/generated/ai_observability.ts+++ b/services/mcp/src/tools/generated/ai_observability.ts@@ -45,7 +45,6 @@ import {LlmAnalyticsScoreDefinitionsPartialUpdateBody,LlmAnalyticsScoreDefinitionsPartialUpdateParams,LlmAnalyticsScoreDefinitionsRetrieveParams,- LlmAnalyticsSentimentCreateBody,LlmAnalyticsSummarizationCreateBody,LlmAnalyticsTraceReviewsCreateBody,LlmAnalyticsTraceReviewsDestroyParams,@@ -253,6 +252,7 @@ const llmaEvaluationList = (): ToolBase<typeof LlmaEvaluationListSchema, Schemaspath: `/api/projects/${encodeURIComponent(String(projectId))}/evaluations/`,query: {enabled: params.enabled,+ evaluation_type: params.evaluation_type,id__in: Array.isArray(params.id__in) ? params.id__in.join(',') || undefined : params.id__in,limit: params.limit,offset: params.offset,@@ -1119,38 +1119,6 @@ const llmaScoreDefinitionUpdate = (): ToolBase<typeof LlmaScoreDefinitionUpdateS},})-const LlmaSentimentCreateSchema = LlmAnalyticsSentimentCreateBody--const llmaSentimentCreate = (): ToolBase<typeof LlmaSentimentCreateSchema, Schemas.SentimentBatchResponse> => ({- name: 'llma-sentiment-create',- schema: LlmaSentimentCreateSchema,- handler: async (context: Context, params: z.infer<typeof LlmaSentimentCreateSchema>) => {- const projectId = await context.stateManager.getProjectId()- const body: Record<string, unknown> = {}- if (params.ids !== undefined) {- body['ids'] = params.ids- }- if (params.analysis_level !== undefined) {- body['analysis_level'] = params.analysis_level- }- if (params.force_refresh !== undefined) {- body['force_refresh'] = params.force_refresh- }- if (params.date_from !== undefined) {- body['date_from'] = params.date_from- }- if (params.date_to !== undefined) {- body['date_to'] = params.date_to- }- const result = await context.api.request<Schemas.SentimentBatchResponse>({- method: 'POST',- path: `/api/projects/${encodeURIComponent(String(projectId))}/llm_analytics/sentiment/`,- body,- })- return result- },-})-const LlmaSummarizationCreateSchema = LlmAnalyticsSummarizationCreateBodyconst llmaSummarizationCreate = (): ToolBase<typeof LlmaSummarizationCreateSchema, Schemas.SummarizeResponse> => ({@@ -1468,7 +1436,6 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'llma-score-definition-list': llmaScoreDefinitionList,'llma-score-definition-new-version': llmaScoreDefinitionNewVersion,'llma-score-definition-update': llmaScoreDefinitionUpdate,- 'llma-sentiment-create': llmaSentimentCreate,'llma-summarization-create': llmaSummarizationCreate,'llma-tagger-create': llmaTaggerCreate,'llma-tagger-list': llmaTaggerList,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-list.jsonindex 3bba74b76799..c52e707df84d 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-list.json@@ -5,6 +5,11 @@"description": "Filter by enabled status","type": "boolean"},+ "evaluation_type": {+ "description": "Filter by evaluation type\n\n* `llm_judge` - LLM as a judge\n* `hog` - Hog\n* `sentiment` - Sentiment analysis",+ "enum": ["hog", "llm_judge", "sentiment"],+ "type": "string"+ },"id__in": {"description": "Multiple values may be separated by commas.","items": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-sentiment-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-sentiment-create.jsondeleted file mode 100644index b1445526c0fc..000000000000--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-sentiment-create.json+++ /dev/null@@ -1,49 +0,0 @@-{- "$schema": "https://json-schema.org/draft/2020-12/schema",- "properties": {- "analysis_level": {- "default": "trace",- "description": "Whether the IDs are 'trace' IDs or 'generation' IDs.\n\n* `trace` - trace\n* `generation` - generation",- "enum": ["trace", "generation"],- "type": "string"- },- "date_from": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "description": "Start of date range for the lookup (e.g. '-7d' or '2026-01-01'). Defaults to -30d."- },- "date_to": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "description": "End of date range for the lookup. Defaults to now."- },- "force_refresh": {- "default": false,- "description": "If true, bypass cache and reclassify.",- "type": "boolean"- },- "ids": {- "description": "Trace IDs (analysis_level=trace) or generation event UUIDs (analysis_level=generation).",- "items": {- "type": "string"- },- "maxItems": 5,- "minItems": 1,- "type": "array"- }- },- "required": ["ids"],- "type": "object"-}