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): truncate tagger prompts and skip context window overflows (#117554)

Carlos Marchaldc6c1727afe8
diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.py
index 880bfe0dfdda..c07e592d123b 100644
--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py
+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py
@@ -79,15 +79,12 @@ from products.ai_observability.backend.models.evaluation_configs import (
NumericOutputConfig,
NumericScoreOutOfBounds,
)
-from products.ai_observability.backend.text_repr.formatters import add_line_numbers, reduce_by_uniform_sampling
+from products.ai_observability.backend.text_repr.formatters import EVENT_TEXT_MAX_CHARS, truncate_by_line_sampling
logger = 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),
@@ -520,12 +517,7 @@ def _execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> EvaluationActi
sections.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]
+ user_prompt = truncate_by_line_sampling(user_prompt, EVENT_TEXT_MAX_CHARS)
return call_llm_judge(
evaluation=evaluation,
diff --git a/posthog/temporal/ai_observability/run_tagger.py b/posthog/temporal/ai_observability/run_tagger.py
index df0c496e42fd..ebd7d9fc30b2 100644
--- a/posthog/temporal/ai_observability/run_tagger.py
+++ b/posthog/temporal/ai_observability/run_tagger.py
@@ -29,6 +29,7 @@ from products.ai_observability.backend.llm import DEFAULT_MODEL_BY_PROVIDER, Cli
from products.ai_observability.backend.llm.errors import (
AuthenticationError,
ContentFilteredError,
+ ContextWindowExceededError,
ModelNotFoundError,
ModelPermissionError,
OutputTokenLimitError,
@@ -40,6 +41,7 @@ from products.ai_observability.backend.llm.errors import (
)
from products.ai_observability.backend.models.provider_keys import LLMProviderKey
from 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
logger = structlog.get_logger(__name__)
@@ -57,6 +59,7 @@ LLM_TAGGER_RETRY_POLICY = RetryPolicy(
TAGGER_DISABLED_ERROR_TYPE = "tagger_disabled"
TAGGER_PARSE_ERROR_TYPE = "tagger_parse_error"
TAGGER_REQUEST_REJECTED_ERROR_TYPE = "tagger_request_rejected"
+TAGGER_CONTEXT_WINDOW_ERROR_TYPE = "tagger_context_window_exceeded"
# model_resolution is shared with evaluations, so the tagger types its skip reasons on the way out.
MODEL_RESOLUTION_SKIP_ERROR_TYPES = {
"provider_key_required": "tagger_provider_key_required",
@@ -69,6 +72,7 @@ SKIPPED_RESULT_ERROR_TYPES = frozenset(
TAGGER_DISABLED_ERROR_TYPE,
TAGGER_PARSE_ERROR_TYPE,
TAGGER_REQUEST_REJECTED_ERROR_TYPE,
+ TAGGER_CONTEXT_WINDOW_ERROR_TYPE,
*MODEL_RESOLUTION_SKIP_ERROR_TYPES.values(),
}
)
@@ -108,6 +112,18 @@ def build_tag_result_schema(tag_names: list[str], min_tags: int = 0, max_tags: i
return DynamicTagResult
+def _render_tagger_user_prompt(input_data: str, output_data: str) -> str:
+ return f"Input: {input_data}\n\nOutput: {output_data}"
+
+
+def build_tagger_user_prompt(input_data: str, output_data: str) -> str:
+ budget = EVENT_TEXT_MAX_CHARS - len(_render_tagger_user_prompt("", ""))
+ # 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)
+
+
def build_tagger_system_prompt(prompt: str, tags: list[dict[str, str]], min_tags: int, max_tags: int | None) -> str:
"""Build the system prompt for the LLM tagger."""
tag_lines = []
@@ -280,9 +296,7 @@ def execute_tagger_activity(inputs: ExecuteTaggerInputs) -> dict[str, Any]:
tag_names = [tag["name"] for tag in tags]
response_format = build_tag_result_schema(tag_names, min_tags, max_tags)
- user_prompt = f"""Input: {input_data}
-
-Output: {output_data}"""
+ user_prompt = build_tagger_user_prompt(input_data, output_data)
config = None
@@ -352,6 +366,14 @@ Output: {output_data}"""
type=TAGGER_REQUEST_REJECTED_ERROR_TYPE,
non_retryable=True,
) from e
+ except ContextWindowExceededError as e:
+ # Skip rather than retry: retrying can't fix an over-window prompt and just spams error tracking.
+ raise ApplicationError(
+ str(e),
+ {"error_type": "context_window_exceeded"},
+ type=TAGGER_CONTEXT_WINDOW_ERROR_TYPE,
+ non_retryable=True,
+ ) from e
except (OutputTokenLimitError, StructuredOutputParseError, ContentFilteredError) as e:
# A reply cut off at the output limit or refused by the content filter reaches the tagger
# as unusable output, same as a malformed one, so all take the parse path.
@@ -684,6 +706,7 @@ class RunTaggerWorkflow(PostHogWorkflow):
"parse_error",
"no_default_model",
"request_rejected",
+ "context_window_exceeded",
):
if error_type in (
"provider_key_required",
diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.py
index d3ef64ff0304..952faab24a22 100644
--- a/posthog/temporal/ai_observability/test_run_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_evaluation.py
@@ -55,6 +55,7 @@ from products.ai_observability.backend.models.evaluation_config import Evaluatio
from products.ai_observability.backend.models.evaluation_directories import EvaluationDirectory
from products.ai_observability.backend.models.evaluations import Evaluation
from products.ai_observability.backend.models.provider_keys import LLMProviderKey
+from products.ai_observability.backend.text_repr.formatters import EVENT_TEXT_MAX_CHARS
from . import run_evaluation as run_evaluation_module
from .evaluation_errors import (
@@ -65,7 +66,6 @@ from .evaluation_errors import (
)
from .evaluation_event_io import GENERATION_NOT_FOUND_RETRY_DELAY, hydrate_event_reference
from .evaluation_llm_judge import (
- JUDGE_EVENT_MAX_CHARS,
NumericWithNAEvalResult,
TransientJudgeError,
_build_errored_trace_result,
@@ -1428,7 +1428,7 @@ class TestRunEvaluationWorkflow:
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) <= EVENT_TEXT_MAX_CHARS
assert len(sent_prompt) < raw_size
@pytest.mark.parametrize(
diff --git a/posthog/temporal/ai_observability/test_run_tagger.py b/posthog/temporal/ai_observability/test_run_tagger.py
index e5e52ed553ac..c9da1ea798b5 100644
--- a/posthog/temporal/ai_observability/test_run_tagger.py
+++ b/posthog/temporal/ai_observability/test_run_tagger.py
@@ -20,12 +20,14 @@ from posthog.temporal.common.posthog_client import EXPECTED_CONTROL_FLOW_ERROR_T
from products.ai_observability.backend.llm.errors import (
ContentFilteredError,
+ ContextWindowExceededError,
OutputTokenLimitError,
ProviderRequestRejectedError,
StructuredOutputParseError,
)
from products.ai_observability.backend.models.provider_keys import LLMProviderKey
from products.ai_observability.backend.models.taggers import Tagger
+from products.ai_observability.backend.text_repr.formatters import EVENT_TEXT_MAX_CHARS
from .run_tagger import (
SKIPPED_RESULT_ERROR_TYPES,
@@ -236,6 +238,41 @@ class TestRunTaggerWorkflow:
assert result["output_tokens"] == 20
assert called_on_event_loop == [False]
+ @pytest.mark.django_db(transaction=True)
+ def test_execute_tagger_truncates_oversized_prompt(self, setup_data: SetupData) -> None:
+ team = setup_data["team"]
+ tagger = {
+ "id": str(setup_data["tagger"].id),
+ "name": "Feature Tagger",
+ "tagger_config": make_tagger_config(),
+ "team_id": team.id,
+ }
+ long_input = "\n".join(f"line {i} " + "x" * 100 for i in range(5_000))
+ event_data = create_mock_event_data(
+ team.id,
+ properties={
+ "$ai_input": [{"role": "user", "content": long_input}],
+ "$ai_output_choices": [{"role": "assistant", "content": "Short reply."}],
+ },
+ )
+
+ with (
+ patch("posthog.temporal.ai_observability.run_tagger.Client") as mock_client_class,
+ patch("posthog.temporal.ai_observability.model_resolution.EvaluationConfig") as mock_eval_config,
+ ):
+ mock_complete = mock_client_class.return_value.complete
+ mock_complete.return_value = MagicMock(
+ parsed=TagResult(tags=["billing"], reasoning="ok"),
+ usage=MagicMock(input_tokens=100, output_tokens=20, total_tokens=120),
+ )
+ mock_eval_config.objects.get_or_create.return_value = (_mock_config_with_active_key(), False)
+
+ execute_tagger_activity(ExecuteTaggerInputs(tagger=tagger, event_data=event_data))
+
+ user_prompt = mock_complete.call_args.args[0].messages[0]["content"]
+ assert len(user_prompt) <= EVENT_TEXT_MAX_CHARS
+ assert user_prompt.endswith("Output: assistant: Short reply.")
+
@pytest.mark.django_db(transaction=True)
def test_execute_tagger_strips_unknown_tags(self, setup_data):
tagger_obj = setup_data["tagger"]
@@ -940,6 +977,10 @@ class TestSkippedResultsStayOutOfErrorTracking:
(StructuredOutputParseError("The reply did not match the schema."), "parse_error"),
(ContentFilteredError("The request was rejected by the content filter."), "parse_error"),
(ProviderRequestRejectedError("The response exceeds the limit."), "request_rejected"),
+ (
+ ContextWindowExceededError("The prompt is too long for the context window."),
+ "context_window_exceeded",
+ ),
],
)
@pytest.mark.django_db(transaction=True)
diff --git a/posthog/temporal/common/posthog_client.py b/posthog/temporal/common/posthog_client.py
index f89f28f2e15b..1c323117bb41 100644
--- a/posthog/temporal/common/posthog_client.py
+++ b/posthog/temporal/common/posthog_client.py
@@ -50,6 +50,7 @@ EXPECTED_CONTROL_FLOW_ERROR_TYPES = frozenset(
"tagger_disabled",
"tagger_parse_error",
"tagger_request_rejected",
+ "tagger_context_window_exceeded",
"tagger_provider_key_required",
"tagger_key_invalid",
"tagger_no_default_model",
diff --git a/products/ai_observability/backend/text_repr/formatters/__init__.py b/products/ai_observability/backend/text_repr/formatters/__init__.py
index 24cbb9a7fe27..78711e04f4b0 100644
--- a/products/ai_observability/backend/text_repr/formatters/__init__.py
+++ b/products/ai_observability/backend/text_repr/formatters/__init__.py
@@ -16,15 +16,18 @@ Main entry points:
from .event_formatter import format_event_text_repr, format_event_text_repr_from_ai_events_row
from .message_formatter import (
+ EVENT_TEXT_MAX_CHARS,
FormatterOptions,
RenderBudgetExceeded,
add_line_numbers,
reduce_by_uniform_sampling,
sanitize_surrogates,
+ truncate_by_line_sampling,
)
from .trace_formatter import format_trace_text_repr, llm_trace_to_formatter_format
__all__ = [
+ "EVENT_TEXT_MAX_CHARS",
"FormatterOptions",
"RenderBudgetExceeded",
"add_line_numbers",
@@ -34,4 +37,5 @@ __all__ = [
"llm_trace_to_formatter_format",
"reduce_by_uniform_sampling",
"sanitize_surrogates",
+ "truncate_by_line_sampling",
]
diff --git a/products/ai_observability/backend/text_repr/formatters/message_formatter.py b/products/ai_observability/backend/text_repr/formatters/message_formatter.py
index 18af5519498e..49f9e69cd75a 100644
--- a/products/ai_observability/backend/text_repr/formatters/message_formatter.py
+++ b/products/ai_observability/backend/text_repr/formatters/message_formatter.py
@@ -167,6 +167,17 @@ def reduce_by_uniform_sampling(
SURROGATE_REGEX = re.compile("[\ud800-\udfff]")
+EVENT_TEXT_MAX_CHARS = 150_000
+
+
+def truncate_by_line_sampling(text: str, max_length: int) -> str:
+ if len(text) <= max_length:
+ return text
+ # Line-number first so the sampler's "gaps indicate omitted content" header is truthful.
+ sampled, _ = reduce_by_uniform_sampling(add_line_numbers(text), max_length)
+ return sampled
+
+
def sanitize_surrogates(text: str) -> str:
"""Make `text` encodable as UTF-8.