Skip to content

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

fix(aio): keep low-confidence sentiment in neutral (#71483)

Carlos Marchal74e6cac6b393
diff --git a/posthog/hogql_queries/ai/sentiment_evaluations.py b/posthog/hogql_queries/ai/sentiment_evaluations.py
index 9c639479c43f..6f070232f55f 100644
--- a/posthog/hogql_queries/ai/sentiment_evaluations.py
+++ b/posthog/hogql_queries/ai/sentiment_evaluations.py
@@ -10,6 +10,7 @@ from posthog.hogql import ast
from posthog.hogql.parser import parse_select
from posthog.hogql_queries.ai.ai_table_resolver import query_ai_events
+from posthog.hogql_queries.ai.sentiment_labeling import select_sentiment_label
if TYPE_CHECKING:
from posthog.hogql.constants import LimitContext
@@ -79,6 +80,7 @@ WHERE event = '$ai_evaluation'
AND length(toString(properties.$ai_target_event_id)) > 0
AND {generation_filter}
GROUP BY trace_id, toString(properties.$ai_target_event_id)
+HAVING message_count != '0'
LIMIT {limit}
"""
@@ -101,6 +103,7 @@ FROM (
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)
+ HAVING message_count != '0'
)
GROUP BY trace_id
LIMIT {limit}
@@ -291,11 +294,7 @@ def _aggregate_trace_sentiment(generation_results: list[tuple[str, SentimentResu
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"
- )
+ label = select_sentiment_label(scores) if _has_score_signal(scores) else "neutral"
return {
"label": label,
"score": scores[label],
diff --git a/posthog/hogql_queries/ai/sentiment_labeling.py b/posthog/hogql_queries/ai/sentiment_labeling.py
new file mode 100644
index 000000000000..a3c7be30b164
--- /dev/null
+++ b/posthog/hogql_queries/ai/sentiment_labeling.py
@@ -0,0 +1,30 @@
+"""Shared sentiment label selection.
+
+Used both when writing evaluations (the sentiment eval activity) and when
+aggregating them on read (trace sentiment), so a low-confidence polar score
+resolves to neutral consistently on both sides. Kept here, off the temporal
+package, so the read path doesn't drag the AI-observability workflow graph.
+"""
+
+# A polar label (negative/positive) must beat neutral by more than this margin to be
+# assigned; otherwise the message is treated as neutral. Short, task-focused messages
+# often split near-evenly between neutral and a polar label, and promoting those
+# coin-flips to negative/positive is the main source of false polar labels.
+SENTIMENT_NEUTRAL_MARGIN = 0.15
+
+
+def select_sentiment_label(scores: dict[str, float], neutral_margin: float = SENTIMENT_NEUTRAL_MARGIN) -> str:
+ """Pick a sentiment label, keeping low-confidence polar calls in neutral.
+
+ Returns the top-scoring label, except when it is a polar label (negative/positive)
+ that does not beat neutral by more than `neutral_margin` — those near-ties (and exact
+ ties at the margin) resolve to neutral rather than being promoted to a polar label the
+ model is barely confident about. The gap is rounded to the 4 decimals the scores already
+ carry, so the boundary decision doesn't hinge on floating-point error.
+ """
+ top_label = max(scores, key=scores.get) # type: ignore
+ if top_label == "neutral":
+ return "neutral"
+ if round(scores[top_label] - scores.get("neutral", 0.0), 4) <= neutral_margin:
+ return "neutral"
+ return top_label
diff --git a/posthog/hogql_queries/ai/test/test_sentiment_evaluations.py b/posthog/hogql_queries/ai/test/test_sentiment_evaluations.py
index a5518fa7ffbd..da3ef6009d16 100644
--- a/posthog/hogql_queries/ai/test/test_sentiment_evaluations.py
+++ b/posthog/hogql_queries/ai/test/test_sentiment_evaluations.py
@@ -106,6 +106,27 @@ def test_load_trace_sentiment_evaluations_aggregates_generation_tuples() -> None
"neutral",
0.0,
),
+ (
+ "low_confidence_polar_aggregate_resolves_to_neutral",
+ [
+ (
+ "generation-1",
+ "negative",
+ 0.504,
+ {"positive": 0.028, "neutral": 0.468, "negative": 0.504},
+ {
+ "0": {
+ "label": "negative",
+ "score": 0.504,
+ "scores": {"positive": 0.028, "neutral": 0.468, "negative": 0.504},
+ }
+ },
+ 1,
+ )
+ ],
+ "neutral",
+ 0.468,
+ ),
]
)
def test_load_trace_sentiment_evaluations_handles_sparse_scores(
diff --git a/posthog/temporal/ai_observability/sentiment/model.py b/posthog/temporal/ai_observability/sentiment/model.py
index a701d6743461..4386c35aab79 100644
--- a/posthog/temporal/ai_observability/sentiment/model.py
+++ b/posthog/temporal/ai_observability/sentiment/model.py
@@ -14,6 +14,7 @@ from typing import Any
import structlog
+from posthog.hogql_queries.ai.sentiment_labeling import select_sentiment_label
from posthog.temporal.ai_observability.sentiment.constants import (
CLASSIFY_BATCH_SIZE,
LABELS,
@@ -99,8 +100,8 @@ def _parse_single_result(scores_list: list[dict[str, Any]]) -> SentimentResult:
if label not in scores:
scores[label] = 0.0
- top_label = max(scores, key=scores.get) # type: ignore
- return SentimentResult(label=top_label, score=scores[top_label], scores=scores)
+ label = select_sentiment_label(scores)
+ return SentimentResult(label=label, score=scores[label], scores=scores)
def classify(texts: list[str]) -> list[SentimentResult]:
diff --git a/posthog/temporal/ai_observability/sentiment/tests/test_model.py b/posthog/temporal/ai_observability/sentiment/tests/test_model.py
index 7acdeeb73f2d..cdb7c8e192d9 100644
--- a/posthog/temporal/ai_observability/sentiment/tests/test_model.py
+++ b/posthog/temporal/ai_observability/sentiment/tests/test_model.py
@@ -71,6 +71,24 @@ class TestClassifyBatch:
assert r.label == e.label
assert r.score == e.score
+ @patch("posthog.temporal.ai_observability.sentiment.model._load_pipeline")
+ def test_low_confidence_polar_score_resolves_to_neutral(self, mock_load: MagicMock):
+ # A near-tie that argmaxes to negative must come back neutral — guards the wiring
+ # of the neutral-margin gate into the model's result parsing.
+ mock_pipe = MagicMock()
+ mock_pipe.return_value = [
+ [
+ {"label": "negative", "score": 0.504},
+ {"label": "neutral", "score": 0.468},
+ {"label": "positive", "score": 0.028},
+ ]
+ ]
+ mock_load.return_value = mock_pipe
+
+ result = classify(["retention graph for these people"])
+
+ assert result[0].label == "neutral"
+
@patch("posthog.temporal.ai_observability.sentiment.model._load_pipeline")
def test_missing_labels_filled_with_zero(self, mock_load: MagicMock):
mock_pipe = MagicMock()
diff --git a/posthog/temporal/ai_observability/sentiment/tests/test_utils.py b/posthog/temporal/ai_observability/sentiment/tests/test_utils.py
new file mode 100644
index 000000000000..3dbe34ca09fc
--- /dev/null
+++ b/posthog/temporal/ai_observability/sentiment/tests/test_utils.py
@@ -0,0 +1,44 @@
+from parameterized import parameterized
+
+from posthog.hogql_queries.ai.sentiment_labeling import select_sentiment_label
+from posthog.temporal.ai_observability.sentiment.schema import PendingClassification, SentimentResult
+from posthog.temporal.ai_observability.sentiment.utils import build_generation_result
+
+
+class TestSelectSentimentLabel:
+ @parameterized.expand(
+ [
+ # Near-tie between a polar label and neutral resolves to neutral (the terse-query case).
+ ("coin_flip_negative", {"negative": 0.504, "neutral": 0.468, "positive": 0.028}, "neutral"),
+ ("coin_flip_positive", {"negative": 0.02, "neutral": 0.49, "positive": 0.49}, "neutral"),
+ # Confident polar labels are kept.
+ ("clear_negative", {"negative": 0.8, "neutral": 0.15, "positive": 0.05}, "negative"),
+ ("clear_positive", {"negative": 0.05, "neutral": 0.15, "positive": 0.8}, "positive"),
+ # Neutral winner is always neutral.
+ ("neutral_winner", {"negative": 0.2, "neutral": 0.7, "positive": 0.1}, "neutral"),
+ # A gap exactly at the margin is not enough to promote (must beat it).
+ ("exactly_at_margin", {"negative": 0.55, "neutral": 0.4, "positive": 0.05}, "neutral"),
+ # A gap just past the margin promotes the polar label.
+ ("just_past_margin", {"negative": 0.57, "neutral": 0.4, "positive": 0.03}, "negative"),
+ ]
+ )
+ def test_select_sentiment_label(self, _name: str, scores: dict[str, float], expected: str):
+ assert select_sentiment_label(scores) == expected
+
+
+class TestBuildGenerationResult:
+ def test_applies_neutral_margin_to_generation_label(self):
+ pending = [
+ PendingClassification(trace_id="t", gen_uuid="g", msg_index=17, text="retention graph for these people")
+ ]
+ # Coin-flip scores that argmax to negative but should resolve to neutral.
+ classification = [
+ SentimentResult(
+ label="neutral", score=0.468, scores={"negative": 0.504, "neutral": 0.468, "positive": 0.028}
+ )
+ ]
+
+ result = build_generation_result("g", pending, classification)
+
+ assert result["label"] == "neutral"
+ assert result["messages"]["17"]["scores"] == {"negative": 0.504, "neutral": 0.468, "positive": 0.028}
diff --git a/posthog/temporal/ai_observability/sentiment/utils.py b/posthog/temporal/ai_observability/sentiment/utils.py
index 7a024aba59c6..59fdf49e91a8 100644
--- a/posthog/temporal/ai_observability/sentiment/utils.py
+++ b/posthog/temporal/ai_observability/sentiment/utils.py
@@ -2,6 +2,7 @@
from typing import Any
+from posthog.hogql_queries.ai.sentiment_labeling import select_sentiment_label
from posthog.temporal.ai_observability.sentiment.schema import PendingClassification
@@ -49,7 +50,7 @@ def build_generation_result(
all_scores.append(result.scores)
gen_scores = average_score_dicts(all_scores)
- gen_label = max(gen_scores, key=gen_scores.get) # type: ignore
+ gen_label = select_sentiment_label(gen_scores)
return {
"label": gen_label,