: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): sanitize surrogates in judge and tagger prompts (#122549)
Bernat Torres221f6c59fdf2
diff --git a/docs/internal/ai-observability-judge-inputs.md b/docs/internal/ai-observability-judge-inputs.mdindex a3da16392aed..eedc7c90fc2a 100644--- a/docs/internal/ai-observability-judge-inputs.md+++ b/docs/internal/ai-observability-judge-inputs.md@@ -38,6 +38,9 @@ Generation evaluations extract message text without the per-message character cuThey reserve space for the complete output, then sample input and tool definitions into the remaining space within the 150,000-character limit.If the output and section labels alone exceed that limit, the run is skipped with reason `generation_output_too_long` without calling the judge.+Generation evaluation and LLM tagger user prompts repair UTF-16 surrogate sequences after sampling.+Lone surrogates become replacement characters (`�`), while valid pairs become their Unicode character.+Implementation: [trace judge](../../posthog/temporal/ai_observability/run_trace_evaluation.py), [session judge](../../posthog/temporal/ai_observability/run_session_evaluation.py), and [generation judge](../../posthog/temporal/ai_observability/evaluation_llm_judge.py).## OpenAI-compatible judgesdiff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.pyindex 6eff5f45e0aa..d7cfbfd6be72 100644--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py@@ -84,7 +84,11 @@ from products.ai_observability.backend.models.evaluation_configs import (NumericOutputConfig,NumericScoreOutOfBounds,)-from products.ai_observability.backend.text_repr.formatters import EVENT_TEXT_MAX_CHARS, truncate_by_line_sampling+from products.ai_observability.backend.text_repr.formatters import (+ EVENT_TEXT_MAX_CHARS,+ sanitize_surrogates,+ truncate_by_line_sampling,+)logger = structlog.get_logger(__name__)@@ -553,7 +557,7 @@ def _execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> EvaluationActisections.append(f"Tools available:\n{tools_data}")# Keep the full answer being graded outside the sampled context.context = truncate_by_line_sampling("\n\n".join(sections), context_budget)- user_prompt = f"Input: {context}{output_section}"+ user_prompt = sanitize_surrogates(f"Input: {context}{output_section}")return call_llm_judge(evaluation=evaluation,diff --git a/posthog/temporal/ai_observability/run_tagger.py b/posthog/temporal/ai_observability/run_tagger.pyindex 3da7901899d5..e5ef202ddd23 100644--- a/posthog/temporal/ai_observability/run_tagger.py+++ b/posthog/temporal/ai_observability/run_tagger.py@@ -47,7 +47,11 @@ from products.ai_observability.backend.llm.errors import ()from products.ai_observability.backend.models.provider_keys import LLMProviderKeyfrom products.ai_observability.backend.models.taggers import Tagger-from products.ai_observability.backend.text_repr.formatters import EVENT_TEXT_MAX_CHARS, truncate_by_line_sampling+from products.ai_observability.backend.text_repr.formatters import (+ EVENT_TEXT_MAX_CHARS,+ sanitize_surrogates,+ truncate_by_line_sampling,+)logger = structlog.get_logger(__name__)@@ -127,7 +131,7 @@ def build_tagger_user_prompt(input_data: str, output_data: str) -> str:# Budget each side separately, because sampling the joined text can drop a short output at its end.output_data = truncate_by_line_sampling(output_data, max(budget // 2, budget - len(input_data)))input_data = truncate_by_line_sampling(input_data, budget - len(output_data))- return _render_tagger_user_prompt(input_data, output_data)+ return sanitize_surrogates(_render_tagger_user_prompt(input_data, output_data))def build_tagger_system_prompt(prompt: str, tags: list[dict[str, str]], min_tags: int, max_tags: int | None) -> str:diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex debb51292861..bf2b79264a54 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -4563,7 +4563,15 @@ class TestJudgePromptAssembly:skip_reason="generation_output_too_long",)- def test_prompt_contains_input_tools_and_output_sections_in_order(self):+ @pytest.mark.parametrize(+ "text,expected_text",+ [+ pytest.param("Hello 👋", "Hello 👋", id="unicode"),+ pytest.param("Hello \ud835", "Hello \ufffd", id="lone_surrogate"),+ pytest.param("Hello \ud83d\ude00", "Hello 😀", id="surrogate_pair"),+ ],+ )+ def test_prompt_contains_input_tools_and_output_sections_in_order(self, text: str, expected_text: str) -> None:evaluation = {"id": "eval-123","name": "Test Evaluation",@@ -4577,7 +4585,7 @@ class TestJudgePromptAssembly:1,properties={"$ai_input": [- {"role": "user", "content": "Send the welcome email."},+ {"role": "user", "content": f"Send the welcome email. {text}"},{"role": "assistant","content": None,@@ -4591,9 +4599,9 @@ class TestJudgePromptAssembly:},{"role": "tool", "tool_call_id": "call_1", "content": "ok"},],- "$ai_output_choices": [{"role": "assistant", "content": "Done."}],+ "$ai_output_choices": [{"role": "assistant", "content": f"Done. {text}"}],"$ai_tools": [- {"type": "function", "function": {"name": "send_email", "description": "Send an email."}},+ {"type": "function", "function": {"name": "send_email", "description": f"Send an email. {text}"}},{"type": "function", "function": {"name": "lookup_user", "description": "Look up a user."}},],},@@ -4617,6 +4625,10 @@ class TestJudgePromptAssembly:completion_request = mock_client.complete.call_args[0][0]user_prompt = completion_request.messages[0]["content"]+ user_prompt.encode("utf-8")+ assert f"Send the welcome email. {expected_text}" in user_prompt+ assert f"Send an email. {expected_text}" in user_prompt+ assert f"Done. {expected_text}" in user_prompt# Section ordering: Input first, then Tools available, then Output.input_idx = user_prompt.index("Input:")diff --git a/posthog/temporal/ai_observability/test_run_tagger.py b/posthog/temporal/ai_observability/test_run_tagger.pyindex c9da1ea798b5..7c1d3a8cf292 100644--- a/posthog/temporal/ai_observability/test_run_tagger.py+++ b/posthog/temporal/ai_observability/test_run_tagger.py@@ -38,6 +38,7 @@ from .run_tagger import (TagResult,build_tag_result_schema,build_tagger_system_prompt,+ build_tagger_user_prompt,disable_tagger_activity,emit_tagger_event_activity,execute_hog_tagger_activity,@@ -152,6 +153,23 @@ class TestBuildTaggerSystemPrompt:assert excluded not in prompt+class TestBuildTaggerUserPrompt:+ @pytest.mark.parametrize(+ "text,expected_text",+ [+ pytest.param("Hello 👋", "Hello 👋", id="unicode"),+ pytest.param("Hello \ud835", "Hello \ufffd", id="lone_high_surrogate"),+ pytest.param("Hello \udc00", "Hello \ufffd", id="lone_low_surrogate"),+ pytest.param("Hello \ud83d\ude00", "Hello 😀", id="surrogate_pair"),+ ],+ )+ def test_prompt_is_utf8_encodable(self, text: str, expected_text: str) -> None:+ user_prompt = build_tagger_user_prompt(text, text)++ user_prompt.encode("utf-8")+ assert user_prompt == f"Input: {expected_text}\n\nOutput: {expected_text}"++class TestRunTaggerWorkflow:@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)