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): skip content-filter refusals in taggers and judges (#108472)

Carlos Marchal23c9479078a3
diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.py
index 1b7dad28fb87..0701d33d7ba6 100644
--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py
+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py
@@ -50,6 +50,7 @@ from posthog.temporal.common.utils import close_db_connections
from products.ai_observability.backend.llm import DEFAULT_MODEL_BY_PROVIDER, Client, CompletionRequest, Usage
from products.ai_observability.backend.llm.errors import (
AuthenticationError,
+ ContentFilteredError,
ContextWindowExceededError,
ModelNotFoundError,
ModelPermissionError,
@@ -348,6 +349,24 @@ def _build_output_limit_skip_result(
return result
+def _build_content_filtered_skip_result(
+ allows_na: bool, *, is_byok: bool, key_id: str | None, provider: str, model: str, output_type: str = "boolean"
+) -> EvaluationActivityResult:
+ """Per-item skip for a judge call the provider's content filter refused.
+
+ Backfills treat it as covered, like an over-window prompt, because a re-run sends the same
+ content to the same filter.
+ """
+ result = build_skipped_evaluation_result(
+ output_type=output_type,
+ allows_na=allows_na,
+ reasoning="Evaluation model's content filter refused the input; evaluation skipped.",
+ skip_reason="content_filtered",
+ )
+ result.update({"is_byok": is_byok, "key_id": key_id, "model": model, "provider": provider})
+ return result
+
+
def _build_unparsable_response_skip_result(
allows_na: bool,
*,
@@ -882,6 +901,21 @@ def call_llm_judge(
allows_na, is_byok=is_byok, key_id=key_id, provider=provider, model=model, output_type=output_type
)
+ except ContentFilteredError as e:
+ # Skip rather than raise: the refusal comes from customer content, so a retry rarely
+ # changes it, and raising files a new error tracking issue per call site.
+ increment_errors("content_filtered", provider=provider)
+ logger.warning(
+ "LLM judge request was refused by the provider content filter",
+ evaluation_id=evaluation["id"],
+ provider=provider,
+ model=model,
+ error=str(e),
+ )
+ return _build_content_filtered_skip_result(
+ allows_na, is_byok=is_byok, key_id=key_id, provider=provider, model=model, output_type=output_type
+ )
+
except ProviderConnectionError as e:
# Transient transport failure (connection reset, read timeout). Retrying usually succeeds,
# so track it as a metric and re-raise for the retry policy. `TransientJudgeError` keeps it
diff --git a/posthog/temporal/ai_observability/run_tagger.py b/posthog/temporal/ai_observability/run_tagger.py
index b4300e5807cb..b5f8ba6d6bb5 100644
--- a/posthog/temporal/ai_observability/run_tagger.py
+++ b/posthog/temporal/ai_observability/run_tagger.py
@@ -24,6 +24,7 @@ from posthog.temporal.common.utils import close_db_connections
from products.ai_observability.backend.llm import DEFAULT_MODEL_BY_PROVIDER, Client, CompletionRequest
from products.ai_observability.backend.llm.errors import (
AuthenticationError,
+ ContentFilteredError,
ModelNotFoundError,
ModelPermissionError,
OutputTokenLimitError,
@@ -347,9 +348,9 @@ Output: {output_data}"""
type=TAGGER_REQUEST_REJECTED_ERROR_TYPE,
non_retryable=True,
) from e
- except (OutputTokenLimitError, StructuredOutputParseError) as e:
- # A reply cut off at the output limit reaches the tagger as unusable output, same as a
- # malformed one, so both take the parse path.
+ 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.
logger.warning("LLM tagger returned unusable output", tagger_id=tagger["id"], model=model, error=str(e))
raise ApplicationError(
str(e),
diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.py
index 08f1083827d2..1f02e9958732 100644
--- a/posthog/temporal/ai_observability/test_run_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_evaluation.py
@@ -33,6 +33,7 @@ from posthog.temporal.common.errors import NonReportableError
from products.access_control.backend.models.access_control import AccessControl
from products.ai_observability.backend.llm.errors import (
AuthenticationError,
+ ContentFilteredError,
ContextWindowExceededError,
ModelNotFoundError,
ModelPermissionError,
@@ -1212,6 +1213,38 @@ class TestRunEvaluationWorkflow:
assert "model" not in result
mock_client.complete.assert_called_once()
+ @pytest.mark.django_db(transaction=True)
+ def test_execute_llm_judge_activity_skips_on_content_filter(self, setup_data, active_key_config):
+ team = setup_data["team"]
+ evaluation = {
+ "id": str(setup_data["evaluation"].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": [{"role": "user", "content": "What is 2+2?"}],
+ "$ai_output_choices": [{"role": "assistant", "content": "4"}],
+ },
+ )
+
+ with patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class:
+ mock_client_class.return_value.complete.side_effect = ContentFilteredError(
+ "Could not parse response content as the request was rejected by the content filter"
+ )
+
+ result = execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))
+
+ assert result["skipped"] is True
+ assert result["skip_reason"] == "content_filtered"
+ assert result.get("terminal_user_error") is not True
+ assert result["model"]
+
@pytest.mark.parametrize(
"output_config,expected_verdict,expected_applicable",
[
diff --git a/posthog/temporal/ai_observability/test_run_tagger.py b/posthog/temporal/ai_observability/test_run_tagger.py
index 05e613e86295..8a833ffb7d08 100644
--- a/posthog/temporal/ai_observability/test_run_tagger.py
+++ b/posthog/temporal/ai_observability/test_run_tagger.py
@@ -16,6 +16,7 @@ from posthog.sync import database_sync_to_async
from posthog.temporal.common.posthog_client import EXPECTED_CONTROL_FLOW_ERROR_TYPES, is_expected_activity_failure
from products.ai_observability.backend.llm.errors import (
+ ContentFilteredError,
OutputTokenLimitError,
ProviderRequestRejectedError,
StructuredOutputParseError,
@@ -820,6 +821,7 @@ class TestSkippedResultsStayOutOfErrorTracking:
[
(OutputTokenLimitError("The model reached its output token limit."), "parse_error"),
(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"),
],
)
diff --git a/products/ai_observability/backend/backfill_candidates.py b/products/ai_observability/backend/backfill_candidates.py
index ffb71afbdd59..ecc7b089d6c2 100644
--- a/products/ai_observability/backend/backfill_candidates.py
+++ b/products/ai_observability/backend/backfill_candidates.py
@@ -112,7 +112,8 @@ GROUP BY unit_id
"""
# Unparsable or truncated judge responses can succeed on a later run, so they do not count
-# as evaluated. A trace that errored or a prompt over the context window skips again.
+# as evaluated. A trace that errored, a prompt over the context window, or a
+# content-filter refusal skips again.
# Reads the shared events table rather than ai_events: the verdict rows must stay visible past the
# ai_events retention window, so a re-run of an old backfill still sees what it already covered.
_ALREADY_EVALUATED_SQL = """
diff --git a/products/ai_observability/backend/llm/errors.py b/products/ai_observability/backend/llm/errors.py
index e9fa593091f9..88743853602f 100644
--- a/products/ai_observability/backend/llm/errors.py
+++ b/products/ai_observability/backend/llm/errors.py
@@ -142,6 +142,14 @@ def is_output_limit_error_message(message: str) -> bool:
return any(marker in lowered for marker in _OUTPUT_LIMIT_ERROR_MARKERS)
+class ContentFilteredError(LLMError):
+ """Raised when the provider's content filter refused the prompt or withheld the reply.
+
+ The prompt is usually built from customer trace content, so the refusal is not a PostHog
+ defect. Callers should skip the item rather than report one.
+ """
+
+
class ModelPermissionError(LLMError):
"""Raised when the API key doesn't have permission to access a model"""
@@ -203,6 +211,8 @@ def user_facing_error_message(error: Exception | None) -> str:
return "This conversation is too long for the model's context window. Shorten it, then try again."
if isinstance(error, OutputTokenLimitError):
return "The model ran out of room before it finished its reply. Ask for a shorter answer, then try again."
+ if isinstance(error, ContentFilteredError):
+ return "The provider's content filter refused this request. Change the input, then try again."
if isinstance(error, (ProviderTimeoutError, ProviderRequestRejectedError)):
return str(error)
if isinstance(error, ProviderConnectionError):
diff --git a/products/ai_observability/backend/llm/providers/openai.py b/products/ai_observability/backend/llm/providers/openai.py
index 8dbe78fa0b68..4893cdea6ab0 100644
--- a/products/ai_observability/backend/llm/providers/openai.py
+++ b/products/ai_observability/backend/llm/providers/openai.py
@@ -21,6 +21,7 @@ from pydantic import BaseModel, ValidationError
from products.ai_observability.backend.llm.errors import (
AuthenticationError,
+ ContentFilteredError,
ContextWindowExceededError,
LLMError,
ModelNotFoundError,
@@ -197,6 +198,8 @@ class OpenAIAdapter:
# The reply was cut off at the output limit, so the JSON it carries is truncated.
# Report the limit rather than the unreadable JSON it produced.
raise OutputTokenLimitError(str(e)) from e
+ except openai.ContentFilterFinishReasonError as e:
+ raise ContentFilteredError(str(e)) from e
except ValidationError as e:
# json_schema does not enforce cross-field validators, so a schema-valid reply can
# still fail our model. Normalize it so callers skip invalid output.
@@ -252,6 +255,10 @@ class OpenAIAdapter:
return ContextWindowExceededError(str(error))
if is_output_limit_error_message(str(error)):
return OutputTokenLimitError(str(error))
+ # Azure OpenAI rejects a prompt that its filter blocks with a 400, before any
+ # completion exists to carry a `content_filter` finish reason.
+ if error.code == "content_filter":
+ return ContentFilteredError(str(error))
# OpenRouter returns 402 when the key can't afford the requested
# max_tokens (or is out of credits). Retrying never helps — mirror
# the quota path so the workflow marks the key errored and stops.
@@ -288,7 +295,11 @@ Return ONLY the JSON object, no other text or markdown formatting."""
**(self._build_analytics_kwargs(analytics, client)),
)
- content = create_response.choices[0].message.content or ""
+ choice = create_response.choices[0]
+ if choice.finish_reason == "content_filter":
+ # A refused reply has no content, so parsing it would report the refusal as malformed JSON.
+ raise ContentFilteredError("The request was rejected by the content filter.")
+ content = choice.message.content or ""
usage = self._extract_usage(create_response.usage)
# Parse the JSON response
diff --git a/products/ai_observability/backend/llm/providers/test/test_openai_adapter.py b/products/ai_observability/backend/llm/providers/test/test_openai_adapter.py
index 5ed5fab249ba..a364e990a5df 100644
--- a/products/ai_observability/backend/llm/providers/test/test_openai_adapter.py
+++ b/products/ai_observability/backend/llm/providers/test/test_openai_adapter.py
@@ -13,6 +13,7 @@ from posthoganalytics.ai.openai import (
from pydantic import BaseModel, ValidationError, model_validator
from products.ai_observability.backend.llm.errors import (
+ ContentFilteredError,
ContextWindowExceededError,
OutputTokenLimitError,
QuotaExceededError,
@@ -113,6 +114,13 @@ def _make_bad_request_error(message: str) -> openai.BadRequestError:
return openai.BadRequestError(message, response=response, body={"error": {"message": message}})
+def _content_filter_bad_request_error() -> openai.BadRequestError:
+ body = {"message": "The response was filtered by the content management policy.", "code": "content_filter"}
+ request = httpx.Request("POST", "https://example.invalid/v1/chat/completions")
+ response = httpx.Response(status_code=400, request=request, json={"error": body})
+ return openai.BadRequestError("Error code: 400", response=response, body=body)
+
+
class _Verdict(BaseModel):
verdict: bool
@@ -252,6 +260,38 @@ class TestOpenAIAdapterErrorMapping:
with pytest.raises(OutputTokenLimitError):
adapter.complete(request, api_key="sk-test", analytics=AnalyticsContext(capture=False))
+ @parameterized.expand(
+ [
+ ("finish_reason", openai.ContentFilterFinishReasonError, None),
+ ("prompt_rejected_400", _content_filter_bad_request_error, None),
+ (
+ "json_fallback_finish_reason",
+ lambda: _make_bad_request_error("Invalid parameter: 'response_format' of type 'json_schema'"),
+ "content_filter",
+ ),
+ ]
+ )
+ def test_content_filter_refusal_maps_to_content_filtered(
+ self, _name: str, make_parse_error: Callable[[], Exception], fallback_finish_reason: str | None
+ ) -> None:
+ adapter = OpenAIAdapter()
+ mock_client = MagicMock()
+ mock_client.beta.chat.completions.parse.side_effect = make_parse_error()
+ fallback_choice = mock_client.chat.completions.create.return_value.choices[0]
+ fallback_choice.finish_reason = fallback_finish_reason
+ fallback_choice.message.content = None
+ request = CompletionRequest(
+ model="gpt-5-mini",
+ system="s",
+ messages=[{"role": "user", "content": "x"}],
+ provider="openai",
+ response_format=_Verdict,
+ )
+
+ with patch("products.ai_observability.backend.llm.providers.openai.openai.OpenAI", return_value=mock_client):
+ with pytest.raises(ContentFilteredError):
+ adapter.complete(request, api_key="sk-test", analytics=AnalyticsContext(capture=False))
+
class TestOpenAIStreamErrorSurfacing:
def test_model_404_yields_actionable_message_instead_of_raw_sdk_text(self):
diff --git a/products/ai_observability/backend/llm/test/test_errors.py b/products/ai_observability/backend/llm/test/test_errors.py
index a8d0b4e4b9ae..a77419ac2a77 100644
--- a/products/ai_observability/backend/llm/test/test_errors.py
+++ b/products/ai_observability/backend/llm/test/test_errors.py
@@ -6,6 +6,7 @@ from parameterized import parameterized
from products.ai_observability.backend.llm.errors import (
AuthenticationError,
+ ContentFilteredError,
ContextWindowExceededError,
LLMError,
ModelNotFoundError,
@@ -136,6 +137,7 @@ class TestUserFacingErrorMessage(SimpleTestCase):
(RateLimitError("429"),),
(ContextWindowExceededError("too long"),),
(OutputTokenLimitError("output limit was reached"),),
+ (ContentFilteredError("rejected by the content filter"),),
(ProviderConnectionError("reset by peer"),),
(StructuredOutputParseError("bad json"),),
]
diff --git a/products/ai_observability/backend/test/test_backfill_candidates.py b/products/ai_observability/backend/test/test_backfill_candidates.py
index 480a8a8b46d3..d50690b053f7 100644
--- a/products/ai_observability/backend/test/test_backfill_candidates.py
+++ b/products/ai_observability/backend/test/test_backfill_candidates.py
@@ -234,9 +234,10 @@ class TestBackfillCandidates(ClickhouseTestMixin, APIBaseTest):
# A judge response nobody could read may parse on a later run, so the unit is still owed a verdict.
("unparsable_response", 4),
("output_limit_exceeded", 4),
- # These two skip the same way every run, so re-offering them would never produce a verdict.
+ # These skip the same way every run, so re-offering them would never produce a verdict.
("context_window_exceeded", 3),
("trace_errored", 3),
+ ("content_filtered", 3),
]
)
def test_only_a_transient_skip_leaves_the_unit_a_candidate(self, skip_reason: str, expected: int) -> None: