: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): preserve generation outputs in judge transcripts (#102349)
Radu Raicea94c8d5753140
diff --git a/docs/internal/ai-observability-judge-inputs.md b/docs/internal/ai-observability-judge-inputs.mdindex b2659842f403..f2adaa6ca809 100644--- a/docs/internal/ai-observability-judge-inputs.md+++ b/docs/internal/ai-observability-judge-inputs.md@@ -17,10 +17,14 @@ This attempt stops when the text exceeds the budget, before assembling the complIf the complete rendered transcript fits its budget, the evaluation uses that text.For sessions, this check includes every trace and the separators between traces, so a large trace can use space left by smaller traces.-If the transcript exceeds its budget, the evaluation formats it again with message truncation enabled.-Each affected content block retains its first 500 and last 500 characters, with a `... (X chars truncated) ...` marker in between.-The formatter then samples lines if the text still exceeds its budget.-Oversized sessions divide their budget evenly across traces, with a minimum allocation of 2,000 characters per trace.+If the transcript exceeds its budget, the evaluation retries with input history and span content truncated, while keeping generation outputs complete.+Each truncated content block retains its first 500 and last 500 characters, with a `... (X chars truncated) ...` marker in between.+This attempt also stops at the budget and does not sample lines, so a long input does not unnecessarily damage the answer being graded.+Sessions share the full budget across traces during this attempt.++If the transcript still exceeds its budget, the evaluation also truncates generation outputs and samples lines as needed.+This final fallback can omit parts of an answer. It is used only when complete outputs and shortened inputs cannot fit.+In this fallback, sessions divide their budget evenly across traces, with a minimum allocation of 2,000 characters per trace.If the assembled fallback session still exceeds 500,000 characters, the evaluation skips it with `session_too_long_to_judge`.## Generation formattingdiff --git a/posthog/temporal/ai_observability/run_session_evaluation.py b/posthog/temporal/ai_observability/run_session_evaluation.pyindex a8e9937fc70a..85cdf69d7836 100644--- a/posthog/temporal/ai_observability/run_session_evaluation.py+++ b/posthog/temporal/ai_observability/run_session_evaluation.py@@ -337,9 +337,9 @@ user's conversation, in order — according to this criteria:def format_session_for_judge(traces: list[LLMTrace]) -> str | None:"""Render a session as the canonical text representation, one section per trace.- Preserve message content when the full session fits, including when one trace uses more- than an equal share of the budget. Oversized sessions split the budget evenly across traces- so one long trace cannot crowd out the opening and closing turns.+ Preserve generation outputs across the full session before truncating them, including+ when one trace uses more than an equal share of the budget. If trimming input history+ is insufficient, split the budget evenly so one trace cannot crowd out the others.Returns `None` when the fallback transcript still overshoots the budget, meaning a final slicewould silently drop trailing traces. The caller must treat that as a `session_too_long_to_judge`@@ -353,20 +353,21 @@ def format_session_for_judge(traces: list[LLMTrace]) -> str | None:if not traces:return ""per_trace_budget = max(JUDGE_SESSION_MAX_CHARS // len(traces), _MIN_TRACE_CHARS_IN_SESSION)- for truncated in (False, True):+ for truncated, preserve_generation_output in ((False, True), (True, True), (True, False)):options: FormatterOptions = {"include_markers": False,"collapsed": False,"truncated": truncated,+ "preserve_generation_output": preserve_generation_output,"include_line_numbers": True,- "max_length": per_trace_budget if truncated else None,+ "max_length": None if preserve_generation_output else per_trace_budget,}sections: list[str] = []rendered_length = 0for index, trace in enumerate(traces, start=1):header = f"=== Trace {index} of {len(traces)} (id: {trace.id}) ===\n"rendered_length += len(header) + (2 if sections else 0)- if not truncated:+ if preserve_generation_output:options["max_render_length"] = JUDGE_SESSION_MAX_CHARS - rendered_lengthtrace_dict, hierarchy = llm_trace_to_formatter_format(trace)try:diff --git a/posthog/temporal/ai_observability/run_trace_evaluation.py b/posthog/temporal/ai_observability/run_trace_evaluation.pyindex f9433b1dbfb8..fbedbe859422 100644--- a/posthog/temporal/ai_observability/run_trace_evaluation.py+++ b/posthog/temporal/ai_observability/run_trace_evaluation.py@@ -473,27 +473,29 @@ def build_trace_system_prompt(prompt: str, allows_na: bool) -> str:def format_trace_for_judge(trace: LLMTrace) -> str:"""Serialize a trace into the canonical text representation for the LLM judge.- Preserve message content when the full transcript fits so the judge does not lose evidence- unnecessarily. Oversized transcripts use the shared formatter's truncation and sampling- to bound judge cost and context.+ Preserve complete generation outputs before truncating them so the judge does not grade+ formatting artifacts as model mistakes. Truncate input history first; use message+ truncation and sampling only if the outputs still cannot fit the transcript budget."""trace_dict, hierarchy = llm_trace_to_formatter_format(trace)options: FormatterOptions = {"include_markers": False,"collapsed": False,- "truncated": False,+ "preserve_generation_output": True,"include_line_numbers": True,"max_length": None,"max_render_length": JUDGE_TRACE_MAX_CHARS,}- try:- text, _ = format_trace_text_repr(trace_dict, hierarchy, options)- return text- except RenderBudgetExceeded:- pass+ for truncated in (False, True):+ options["truncated"] = truncated+ try:+ text, _ = format_trace_text_repr(trace_dict, hierarchy, options)+ return text+ except RenderBudgetExceeded:+ passdel options["max_render_length"]- options["truncated"] = True+ options["preserve_generation_output"] = Falseoptions["max_length"] = JUDGE_TRACE_MAX_CHARStext, _ = format_trace_text_repr(trace_dict, hierarchy, options)return textdiff --git a/posthog/temporal/ai_observability/test_run_session_evaluation.py b/posthog/temporal/ai_observability/test_run_session_evaluation.pyindex f0b32026ba3d..bd3309a07c72 100644--- a/posthog/temporal/ai_observability/test_run_session_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_session_evaluation.py@@ -134,19 +134,27 @@ class TestFormatSessionForJudge:assert len(rendered) <= JUDGE_SESSION_MAX_CHARSassert "t399" in rendered- @pytest.mark.parametrize("content_length,should_truncate", [(300_000, False), (600_000, True)])+ @pytest.mark.parametrize(+ "content_length,output_length,should_truncate,should_truncate_output",+ [(300_000, 4_000, False, False), (600_000, 300_000, True, False), (600_000, 600_000, True, True)],+ )def test_preserves_every_trace_and_only_truncates_content_when_the_session_exceeds_budget(- self, content_length: int, should_truncate: bool+ self, content_length: int, output_length: int, should_truncate: bool, should_truncate_output: bool) -> None:traces = [_trace("t-alpha", cost=0, latency=0), _trace("t-beta", cost=0, latency=0)]content = "start " + "x" * (content_length // 2) + " critical evidence " + "y" * (content_length // 2) + " end"traces[0].events[0].properties["$ai_input"] = [{"role": "user", "content": content}]+ output = "a" * (output_length // 2) + "\n- Required output evidence.\n" + "b" * (output_length // 2)+ traces[0].events[0].properties["$ai_output_choices"] = [{"role": "assistant", "content": output}]rendered = format_session_for_judge(traces)assert rendered is not Noneassert "t-alpha" in renderedassert "t-beta" in renderedassert ("chars truncated" in rendered) == should_truncateassert ("critical evidence" in rendered) == (not should_truncate)+ assert ("- Required output evidence." in rendered) == (not should_truncate_output)+ if not should_truncate_output:+ assert all(line in rendered for line in output.splitlines())assert "start " in renderedassert " end" in renderedassert len(rendered) <= JUDGE_SESSION_MAX_CHARSdiff --git a/posthog/temporal/ai_observability/test_run_trace_evaluation.py b/posthog/temporal/ai_observability/test_run_trace_evaluation.pyindex ce091a5e128d..29b95a8e8ad4 100644--- a/posthog/temporal/ai_observability/test_run_trace_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_trace_evaluation.py@@ -159,19 +159,42 @@ class TestFormatTraceForJudge:assert "search_docs" in transcript- @pytest.mark.parametrize("content_length,should_truncate", [(50_000, False), (200_000, True)])+ @pytest.mark.parametrize("output_property", ["$ai_output", "$ai_output_choices"])+ @pytest.mark.parametrize(+ "content_length,output_length,should_truncate,should_truncate_output",+ [(50_000, 4_000, False, False), (200_000, 4_000, True, False), (200_000, 200_000, True, True)],+ )def test_truncates_long_event_io_only_when_the_trace_exceeds_budget(- self, content_length: int, should_truncate: bool+ self,+ output_property: str,+ content_length: int,+ output_length: int,+ should_truncate: bool,+ should_truncate_output: bool,) -> None:content = "start " + "x" * (content_length // 2) + " critical evidence " + "y" * (content_length // 2) + " end"+ output = "a" * (output_length // 2) + "\n- Required output evidence.\n" + "b" * (output_length // 2)+ output_value = (+ output+ if output_property == "$ai_output"+ else [{"role": "assistant", "content": [{"type": "text", "text": output}]}]+ )trace = create_trace(- [create_trace_event("$ai_generation", **{"$ai_input": [{"role": "user", "content": content}]})]+ [+ create_trace_event(+ "$ai_generation",+ **{"$ai_input": [{"role": "user", "content": content}], output_property: output_value},+ )+ ])transcript = format_trace_for_judge(trace)assert ("chars truncated" in transcript) == should_truncateassert ("critical evidence" in transcript) == (not should_truncate)+ assert ("- Required output evidence." in transcript) == (not should_truncate_output)+ if not should_truncate_output:+ assert all(line in transcript for line in output.splitlines())assert "start " in transcriptassert " end" in transcriptassert len(transcript) <= JUDGE_TRACE_MAX_CHARS@@ -187,12 +210,15 @@ class TestFormatTraceForJudge:assert len(transcript) <= JUDGE_TRACE_MAX_CHARSassert "SAMPLED VIEW" in transcript+ @pytest.mark.parametrize("message_property", ["$ai_input", "$ai_output_choices"])@pytest.mark.parametrize("event_count,message_count", [(50, 1), (1, 50)])- def test_oversized_messages_do_not_allocate_the_full_transcript(self, event_count: int, message_count: int) -> None:+ def test_oversized_messages_do_not_allocate_the_full_transcript(+ self, message_property: str, event_count: int, message_count: int+ ) -> None:content = "start " + "x" * 500_000 + " end"messages = [{"role": "user", "content": content} for _ in range(message_count)]trace = create_trace(- [create_trace_event("$ai_generation", **{"$ai_input": messages}) for _ in range(event_count)]+ [create_trace_event("$ai_generation", **{message_property: messages}) for _ in range(event_count)])tracemalloc.start()diff --git a/products/ai_observability/backend/text_repr/formatters/event_formatter.py b/products/ai_observability/backend/text_repr/formatters/event_formatter.pyindex f633f5cb60ee..9ec2c3c8b939 100644--- a/products/ai_observability/backend/text_repr/formatters/event_formatter.py+++ b/products/ai_observability/backend/text_repr/formatters/event_formatter.py@@ -122,7 +122,10 @@ def format_generation_text_repr(event: dict[str, Any], options: FormatterOptionslines.extend(input_lines)# Output messages- output_lines = format_output_messages(props.get("$ai_output"), props.get("$ai_output_choices"), options)+ output_options: FormatterOptions | None = (+ {**options, "truncated": False} if options and options.get("preserve_generation_output") else options+ )+ output_lines = format_output_messages(props.get("$ai_output"), props.get("$ai_output_choices"), output_options)if output_lines:if lines:lines.append("")diff --git a/products/ai_observability/backend/text_repr/formatters/message_formatter.py b/products/ai_observability/backend/text_repr/formatters/message_formatter.pyindex 0cb6c8d10151..7a13cca1c8bf 100644--- a/products/ai_observability/backend/text_repr/formatters/message_formatter.py+++ b/products/ai_observability/backend/text_repr/formatters/message_formatter.py@@ -39,6 +39,7 @@ class FormatterOptions(TypedDict, total=False):"""Options for formatting text representations."""truncated: bool # Use truncation for long content (default: True)+ preserve_generation_output: bool # Keep answers intact while truncating input history for judgestruncate_buffer: int # Chars to show at start/end (default: 1000)include_markers: bool # Use interactive markers vs plain text (default: True)collapsed: bool # Show full hierarchy vs summary (default: False)