: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(aio): cap single-event LLM judge input like the trace-level judge (#69023)
Carlos Marchal7356572faf66
diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.pyindex c9cfc5857af3..08659e60bb9c 100644--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py@@ -39,11 +39,15 @@ from products.ai_observability.backend.llm.errors import (RateLimitError,StructuredOutputParseError,)+from products.ai_observability.backend.text_repr.formatters import add_line_numbers, reduce_by_uniform_samplinglogger = structlog.get_logger(__name__)DEFAULT_JUDGE_MODEL = DEFAULT_MODEL_BY_PROVIDER["openai"]+# Same cap as the trace-level judge (JUDGE_TRACE_MAX_CHARS).+JUDGE_EVENT_MAX_CHARS = 150_000+LLM_JUDGE_RETRY_POLICY = RetryPolicy(maximum_attempts=3,initial_interval=timedelta(seconds=10),@@ -230,6 +234,12 @@ def _execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> EvaluationActisections.append(f"Tools available:\n{tools_data}")sections.append(f"Output: {output_data}")user_prompt = "\n\n".join(sections)+ if len(user_prompt) > JUDGE_EVENT_MAX_CHARS:+ # Line-number first so the sampler's "gaps indicate omitted content" header is truthful,+ # then hard-truncate to guarantee the cap for low-newline payloads the sampler leaves whole.+ user_prompt = add_line_numbers(user_prompt)+ user_prompt, _ = reduce_by_uniform_sampling(user_prompt, JUDGE_EVENT_MAX_CHARS)+ user_prompt = user_prompt[:JUDGE_EVENT_MAX_CHARS]return call_llm_judge(evaluation=evaluation,diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex 8c283a25759c..1acae3d9a05b 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -36,6 +36,7 @@ from .evaluation_errors import (status_reason_detail_for_terminal_user_error,terminal_user_error_result_from_application_error,)+from .evaluation_llm_judge import JUDGE_EVENT_MAX_CHARSfrom .run_evaluation import (BooleanEvalResult,BooleanWithNAEvalResult,@@ -204,6 +205,54 @@ class TestRunEvaluationWorkflow:assert result["reasoning"] == "The answer is correct"mock_client.complete.assert_called_once()+ @pytest.mark.parametrize(+ "oversized_input",+ [+ pytest.param(+ [{"role": "user", "content": f"message {i}: " + "x" * 200} for i in range(3000)],+ id="many_lines",+ ),+ pytest.param([{"role": "user", "content": "x" * 600_000}], id="single_line_blob"),+ ],+ )+ @pytest.mark.django_db(transaction=True)+ def test_execute_llm_judge_activity_bounds_oversized_input(self, oversized_input, setup_data):+ team = setup_data["team"]+ evaluation_obj = setup_data["evaluation"]++ evaluation = {+ "id": str(evaluation_obj.id),+ "name": "Test Evaluation",+ "evaluation_type": "llm_judge",+ "evaluation_config": {"prompt": "Is this response factually accurate?"},+ "output_type": "boolean",+ "output_config": {},+ "team_id": team.id,+ }++ event_data = create_mock_event_data(+ team.id,+ properties={+ "$ai_input": oversized_input,+ "$ai_output_choices": [{"role": "assistant", "content": "ok"}],+ },+ )++ with patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class:+ mock_client = MagicMock()+ mock_client_class.return_value = mock_client+ mock_response = MagicMock()+ mock_response.parsed = BooleanEvalResult(verdict=True, reasoning="ok")+ mock_response.usage = MagicMock(input_tokens=1, output_tokens=1, total_tokens=1)+ mock_client.complete.return_value = mock_response++ execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))++ sent_prompt = mock_client.complete.call_args.args[0].messages[0]["content"]+ raw_size = sum(len(message["content"]) for message in oversized_input)+ assert len(sent_prompt) <= JUDGE_EVENT_MAX_CHARS+ assert len(sent_prompt) < raw_size+@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)async def test_emit_evaluation_event_activity(self, setup_data):diff --git a/products/ai_observability/backend/text_repr/formatters/__init__.py b/products/ai_observability/backend/text_repr/formatters/__init__.pyindex bcda0bf3f3f5..fed997e12d9f 100644--- a/products/ai_observability/backend/text_repr/formatters/__init__.py+++ b/products/ai_observability/backend/text_repr/formatters/__init__.py@@ -15,11 +15,12 @@ Main entry points:"""from .event_formatter import format_event_text_repr, format_event_text_repr_from_ai_events_row-from .message_formatter import FormatterOptions, reduce_by_uniform_sampling+from .message_formatter import FormatterOptions, add_line_numbers, reduce_by_uniform_samplingfrom .trace_formatter import format_trace_text_repr, llm_trace_to_formatter_format__all__ = ["FormatterOptions",+ "add_line_numbers","format_event_text_repr","format_event_text_repr_from_ai_events_row","format_trace_text_repr",