: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
fix(llma): bound sentiment eval inputs (#64976)
Radu Raicea71e7e28dc975
diff --git a/posthog/temporal/ai_observability/evaluation_sentiment.py b/posthog/temporal/ai_observability/evaluation_sentiment.pyindex f3a902fc36c7..ff070b139270 100644--- a/posthog/temporal/ai_observability/evaluation_sentiment.py+++ b/posthog/temporal/ai_observability/evaluation_sentiment.py@@ -7,10 +7,7 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.temporal.ai_observability.evaluation_event_io import extract_event_iofrom posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResult-from posthog.temporal.ai_observability.sentiment.extraction import (- extract_user_messages_individually,- truncate_to_token_limit,-)+from posthog.temporal.ai_observability.sentiment.extraction import extract_sentiment_eval_messagesfrom posthog.temporal.ai_observability.sentiment.schema import PendingClassification, SentimentResultfrom posthog.temporal.ai_observability.sentiment.utils import build_generation_result@@ -97,11 +94,11 @@ async def execute_sentiment_eval_activity(input_raw, _output_raw = extract_event_io(event_data["event"], properties)event_uuid = event_data["uuid"]trace_id = properties.get("$ai_trace_id", event_uuid)- user_messages = extract_user_messages_individually(input_raw)+ user_messages = extract_sentiment_eval_messages(input_raw)if not user_messages:return _neutral_sentiment_activity_result("No user messages found; sentiment defaults to neutral.")- texts = [truncate_to_token_limit(text) for _message_index, text in user_messages]+ texts = [text for _message_index, text in user_messages]from posthog.temporal.ai_observability.sentiment.model import classify # noqa: PLC0415 -- loads ONNX deps lazilydiff --git a/posthog/temporal/ai_observability/sentiment/constants.py b/posthog/temporal/ai_observability/sentiment/constants.pyindex 339a22bb740a..020dd29382bc 100644--- a/posthog/temporal/ai_observability/sentiment/constants.py+++ b/posthog/temporal/ai_observability/sentiment/constants.py@@ -23,6 +23,9 @@ ONNX_INTER_OP_NUM_THREADS = _positive_int_env("POSTHOG_SENTIMENT_ONNX_INTER_OP_N# Extraction boundsMAX_USER_MESSAGES = 50MAX_MESSAGE_CHARS = 2000+SENTIMENT_EVAL_MAX_USER_MESSAGES = 1+SENTIMENT_EVAL_MAX_MESSAGE_CHARS = 1000+SENTIMENT_EVAL_MESSAGE_HEAD_CHARS = 300# Batch classificationCLASSIFY_BATCH_SIZE = 32 # texts per ONNX forward passdiff --git a/posthog/temporal/ai_observability/sentiment/extraction.py b/posthog/temporal/ai_observability/sentiment/extraction.pyindex 1717a1d3ab7f..322fa0aa4fdd 100644--- a/posthog/temporal/ai_observability/sentiment/extraction.py+++ b/posthog/temporal/ai_observability/sentiment/extraction.py@@ -1,7 +1,15 @@"""Extract user messages from $ai_input for sentiment classification."""from posthog.temporal.ai_observability.message_utils import _extract_content_text-from posthog.temporal.ai_observability.sentiment.constants import MAX_MESSAGE_CHARS, MAX_USER_MESSAGES+from posthog.temporal.ai_observability.sentiment.constants import (+ MAX_MESSAGE_CHARS,+ MAX_USER_MESSAGES,+ SENTIMENT_EVAL_MAX_MESSAGE_CHARS,+ SENTIMENT_EVAL_MAX_USER_MESSAGES,+ SENTIMENT_EVAL_MESSAGE_HEAD_CHARS,+)++HEAD_TAIL_SEPARATOR = "\n...\n"def _is_tool_result_message(content: object) -> bool:@@ -67,3 +75,35 @@ def truncate_to_token_limit(text: str, max_chars: int = MAX_MESSAGE_CHARS) -> stif len(text) <= max_chars:return textreturn text[-max_chars:]+++def truncate_to_head_tail(+ text: str,+ max_chars: int = SENTIMENT_EVAL_MAX_MESSAGE_CHARS,+ head_chars: int = SENTIMENT_EVAL_MESSAGE_HEAD_CHARS,+) -> str:+ """Keep the opening and ending context while bounding classifier input."""+ if len(text) <= max_chars:+ return text++ if head_chars <= 0:+ return text[-max_chars:]++ if max_chars <= len(HEAD_TAIL_SEPARATOR):+ return text[:max_chars]++ head_count = min(head_chars, max_chars - len(HEAD_TAIL_SEPARATOR))+ tail_count = max_chars - len(HEAD_TAIL_SEPARATOR) - head_count+ if tail_count <= 0:+ return text[:max_chars]++ return f"{text[:head_count]}{HEAD_TAIL_SEPARATOR}{text[-tail_count:]}"+++def extract_sentiment_eval_messages(ai_input: object) -> list[tuple[int, str]]:+ """Extract and bound the last user message for sentiment evals."""+ user_messages = extract_user_messages_individually(ai_input)+ return [+ (message_index, truncate_to_head_tail(text))+ for message_index, text in user_messages[-SENTIMENT_EVAL_MAX_USER_MESSAGES:]+ ]diff --git a/posthog/temporal/ai_observability/sentiment/tests/test_extraction.py b/posthog/temporal/ai_observability/sentiment/tests/test_extraction.pyindex be078b7f6f92..13aa847ba311 100644--- a/posthog/temporal/ai_observability/sentiment/tests/test_extraction.py+++ b/posthog/temporal/ai_observability/sentiment/tests/test_extraction.py@@ -1,8 +1,17 @@from parameterized import parameterized+from posthog.temporal.ai_observability.sentiment.constants import (+ MAX_MESSAGE_CHARS,+ MAX_USER_MESSAGES,+ SENTIMENT_EVAL_MAX_MESSAGE_CHARS,+ SENTIMENT_EVAL_MESSAGE_HEAD_CHARS,+)from posthog.temporal.ai_observability.sentiment.extraction import (+ HEAD_TAIL_SEPARATOR,_is_tool_result_message,+ extract_sentiment_eval_messages,extract_user_messages_individually,+ truncate_to_head_tail,truncate_to_token_limit,)@@ -76,8 +85,6 @@ class TestExtractUserMessagesIndividually:assert extract_user_messages_individually(ai_input) == expecteddef test_limits_to_max_user_messages(self):- from posthog.temporal.ai_observability.sentiment.constants import MAX_USER_MESSAGES-messages = [{"role": "user", "content": f"msg-{i}"} for i in range(MAX_USER_MESSAGES + 10)]result = extract_user_messages_individually(messages)assert len(result) == MAX_USER_MESSAGES@@ -128,10 +135,50 @@ class TestTruncateToTokenLimit:assert truncate_to_token_limit(text, max_chars=max_chars) == expecteddef test_default_max_chars_from_constants(self):- from posthog.temporal.ai_observability.sentiment.constants import MAX_MESSAGE_CHARS-short_text = "x" * (MAX_MESSAGE_CHARS - 1)assert truncate_to_token_limit(short_text) == short_textlong_text = "x" * (MAX_MESSAGE_CHARS + 100)assert len(truncate_to_token_limit(long_text)) == MAX_MESSAGE_CHARS+++class TestTruncateToHeadTail:+ def test_keeps_short_text_unchanged(self):+ assert truncate_to_head_tail("short", max_chars=100, head_chars=30) == "short"++ def test_keeps_head_and_tail_within_max_chars(self):+ text = ("h" * 400) + ("m" * 400) + ("t" * 800)+ result = truncate_to_head_tail(text, max_chars=1000, head_chars=300)+ tail_chars = 1000 - len(HEAD_TAIL_SEPARATOR) - 300++ assert len(result) == 1000+ assert result.startswith("h" * 300)+ assert HEAD_TAIL_SEPARATOR in result+ assert result.endswith("t" * tail_chars)++ def test_falls_back_to_tail_when_head_chars_is_zero(self):+ text = "abcdefgh"+ assert truncate_to_head_tail(text, max_chars=5, head_chars=0) == "defgh"+++class TestExtractSentimentEvalMessages:+ def test_keeps_only_last_user_message(self):+ messages = [+ {"role": "user", "content": "first"},+ {"role": "assistant", "content": "reply"},+ {"role": "user", "content": "second"},+ ]++ assert extract_sentiment_eval_messages(messages) == [(2, "second")]++ def test_applies_head_tail_truncation_to_last_user_message(self):+ long_message = ("h" * 400) + ("m" * 400) + ("t" * 800)+ result = extract_sentiment_eval_messages([{"role": "user", "content": long_message}])+ tail_chars = SENTIMENT_EVAL_MAX_MESSAGE_CHARS - len(HEAD_TAIL_SEPARATOR) - SENTIMENT_EVAL_MESSAGE_HEAD_CHARS++ assert len(result) == 1+ message_index, text = result[0]+ assert message_index == 0+ assert len(text) == SENTIMENT_EVAL_MAX_MESSAGE_CHARS+ assert text.startswith("h" * SENTIMENT_EVAL_MESSAGE_HEAD_CHARS)+ assert text.endswith("t" * tail_chars)diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex 7cf16be0c275..b6dbc1e3fd4c 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -11,6 +11,7 @@ from parameterized import parameterizedfrom temporalio.exceptions import ApplicationErrorfrom posthog.models import Organization, Team+from posthog.temporal.ai_observability.sentiment.extraction import truncate_to_head_tailfrom posthog.temporal.ai_observability.sentiment.schema import SentimentResultfrom products.ai_observability.backend.llm.errors import StructuredOutputParseError@@ -1109,6 +1110,45 @@ class TestExecuteSentimentEvalActivity:assert result["sentiment_message_count"] == 1assert result["sentiment_messages"]["1"]["label"] == "positive"+ @pytest.mark.asyncio+ async def test_sentiment_eval_classifies_only_last_user_message(self):+ evaluation = {+ "id": "sentiment-eval-id",+ "name": "Sentiment Eval",+ "evaluation_type": "sentiment",+ "evaluation_config": {"source": "user_messages"},+ "output_type": "sentiment",+ "output_config": {},+ "team_id": 1,+ }+ last_message = ("I am really frustrated. " * 20) + ("Here are logs: " * 80) + "please fix this"+ event_data = create_mock_event_data(+ 1,+ properties={+ "$ai_input": [+ {"role": "user", "content": "Earlier context that should not be classified."},+ {"role": "assistant", "content": "Can you share more detail?"},+ {"role": "user", "content": last_message},+ ],+ "$ai_output": "I can help.",+ },+ )++ classification = SentimentResult(+ label="negative",+ score=0.8,+ scores={"positive": 0.05, "neutral": 0.15, "negative": 0.8},+ )+ with patch(+ "posthog.temporal.ai_observability.sentiment.model.classify", return_value=[classification]+ ) as mock_classify:+ result = await execute_sentiment_eval_activity(evaluation, event_data)++ mock_classify.assert_called_once_with([truncate_to_head_tail(last_message)])+ assert result["sentiment_label"] == "negative"+ assert result["sentiment_message_count"] == 1+ assert result["sentiment_messages"]["2"]["label"] == "negative"+@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)async def test_sentiment_eval_defaults_to_neutral_without_user_messages(self, setup_data):