: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): map model output-limit failures to one error type (#104014)
Radu Raicea53c89d92e090
diff --git a/docs/internal/ai-observability-judge-inputs.md b/docs/internal/ai-observability-judge-inputs.mdindex f2adaa6ca809..db977f1b3c6d 100644--- a/docs/internal/ai-observability-judge-inputs.md+++ b/docs/internal/ai-observability-judge-inputs.md@@ -33,3 +33,13 @@ Generation evaluations extract message text without the per-message character cuThey sample the combined input, tool definitions, and output only when that text exceeds 150,000 characters, with a final character slice enforcing the limit.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).++## Model output limits++When the judge reply reaches the model's output limit, the evaluation skips that item with `output_limit_exceeded`.+For Anthropic structured replies, `stop_reason="max_tokens"` triggers this skip before JSON parsing.+Historical runs still include these items, as they do for `unparsable_response`, because neither skip produces a verdict.+Users do not need to include items that already have a result to retry them.++A provider rejection of an invalid token setting does not count as a truncated reply.+The playground keeps the provider's explanation so users can correct the setting before trying again.diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.pyindex b29f68e0dc7b..cdeb4c156e7c 100644--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py@@ -40,6 +40,7 @@ from products.ai_observability.backend.llm.errors import (ContextWindowExceededError,ModelNotFoundError,ModelPermissionError,+ OutputTokenLimitError,ProviderConnectionError,QuotaExceededError,RateLimitError,@@ -236,6 +237,35 @@ def _build_context_window_skip_result(return result+def _build_output_limit_skip_result(+ allows_na: bool, *, is_byok: bool, key_id: str | None, provider: str, model: str+) -> EvaluationActivityResult:+ """Per-item skip for a judge reply that hit the model's output limit.++ Carries `model` and `provider` for the same reason the unparsable skip does: the model ran+ and the call was billed. The provider reports no usage counts on this path, because the+ failure reaches us as an exception.+ """+ result: EvaluationActivityResult = {+ "result_type": "boolean",+ "verdict": None if allows_na else False,+ "reasoning": "Evaluation model hit its output limit before it finished; evaluation skipped.",+ "input_tokens": 0,+ "output_tokens": 0,+ "total_tokens": 0,+ "is_byok": is_byok,+ "key_id": key_id,+ "allows_na": allows_na,+ "model": model,+ "provider": provider,+ "skipped": True,+ "skip_reason": "output_limit_exceeded",+ }+ if allows_na:+ result["applicable"] = False+ return result++def _build_unparsable_response_skip_result(allows_na: bool, *, is_byok: bool, key_id: str | None, provider: str, model: str, usage: Usage | None) -> EvaluationActivityResult:@@ -484,6 +514,21 @@ def call_llm_judge(increment_errors("context_window_exceeded", provider=provider)return _build_context_window_skip_result(allows_na, is_byok=is_byok, key_id=key_id)+ except OutputTokenLimitError as e:+ # Avoid automatic retries of a billed generation; a later backfill can retry it.+ # Providers word this failure differently, so raising creates separate error tracking issues.+ increment_errors("output_limit_exceeded", provider=provider)+ logger.warning(+ "LLM judge response hit the model output limit",+ evaluation_id=evaluation["id"],+ provider=provider,+ model=model,+ error=str(e),+ )+ return _build_output_limit_skip_result(+ allows_na, is_byok=is_byok, key_id=key_id, provider=provider, model=model+ )+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 itdiff --git a/posthog/temporal/ai_observability/run_tagger.py b/posthog/temporal/ai_observability/run_tagger.pyindex d5117e9ed0f1..198a5c3da485 100644--- a/posthog/temporal/ai_observability/run_tagger.py+++ b/posthog/temporal/ai_observability/run_tagger.py@@ -25,6 +25,7 @@ from products.ai_observability.backend.llm.errors import (AuthenticationError,ModelNotFoundError,ModelPermissionError,+ OutputTokenLimitError,QuotaExceededError,RateLimitError,StructuredOutputParseError,@@ -295,7 +296,9 @@ Output: {output_data}"""f"Model '{model}' not found.",non_retryable=True,)- except StructuredOutputParseError as 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.raise ApplicationError(str(e),{"error_type": "parse_error"},diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex 52a46f8f11fb..e2063a6b0bc2 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -26,6 +26,7 @@ from products.ai_observability.backend.llm.errors import (ContextWindowExceededError,ModelNotFoundError,ModelPermissionError,+ OutputTokenLimitError,ProviderConnectionError,QuotaExceededError,RateLimitError,@@ -457,6 +458,56 @@ class TestRunEvaluationWorkflow:assert "model" not in resultmock_client.complete.assert_called_once()+ @pytest.mark.parametrize(+ "output_config,expected_verdict,expected_applicable",+ [+ pytest.param({}, False, None, id="without_na"),+ pytest.param({"allows_na": True}, None, False, id="with_na"),+ ],+ )+ @pytest.mark.django_db(transaction=True)+ def test_execute_llm_judge_activity_skips_on_output_limit(+ self, output_config, expected_verdict, expected_applicable, setup_data, active_key_config+ ):+ 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": 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 = MagicMock()+ mock_client_class.return_value = mock_client+ mock_client.complete.side_effect = OutputTokenLimitError(+ "Could not finish the message because max_tokens or model output limit was reached."+ )++ result = execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))++ assert result["skipped"] is True+ assert result["skip_reason"] == "output_limit_exceeded"+ assert result["verdict"] is expected_verdict+ assert result.get("applicable") is expected_applicable+ assert result.get("terminal_user_error") is not True+ # The model ran and the call was billed, so attribution stays on the result.+ assert result["model"]+ assert result["provider"]+ mock_client.complete.assert_called_once()+@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/backfill_candidates.py b/products/ai_observability/backend/backfill_candidates.pyindex 16de8fc967ff..ba107c06ded1 100644--- a/products/ai_observability/backend/backfill_candidates.py+++ b/products/ai_observability/backend/backfill_candidates.py@@ -111,7 +111,7 @@ WHERE event = '$ai_generation'GROUP BY unit_id"""-# An unparsable judge response is the one skip a later run can resolve, so it does not count+# 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.# 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.@@ -124,7 +124,7 @@ WHERE event = '$ai_evaluation'AND timestamp >= {window_start}AND timestamp < {verdict_end}AND (isNull(properties.$ai_evaluation_skip_reason)- OR properties.$ai_evaluation_skip_reason != 'unparsable_response')+ OR properties.$ai_evaluation_skip_reason NOT IN ('unparsable_response', 'output_limit_exceeded'))"""diff --git a/products/ai_observability/backend/llm/errors.py b/products/ai_observability/backend/llm/errors.pyindex c5a89ba2f124..8931b4c0654a 100644--- a/products/ai_observability/backend/llm/errors.py+++ b/products/ai_observability/backend/llm/errors.py@@ -82,6 +82,23 @@ def is_context_window_error_message(message: str) -> bool:return any(marker in lowered for marker in _CONTEXT_WINDOW_ERROR_MARKERS)+class OutputTokenLimitError(LLMError):+ """Raised when the model stopped because it hit its output token limit.++ Providers report an exhausted output budget in a 400 or through a `length` finish reason,+ which the OpenAI SDK raises as `LengthFinishReasonError`. Rejected token settings stay+ separate because the request must change before the model can generate a reply.+ """+++_OUTPUT_LIMIT_ERROR_MARKERS = ("output limit was reached",)+++def is_output_limit_error_message(message: str) -> bool:+ lowered = message.lower()+ return any(marker in lowered for marker in _OUTPUT_LIMIT_ERROR_MARKERS)++class ModelPermissionError(LLMError):"""Raised when the API key doesn't have permission to access a model"""@@ -141,6 +158,8 @@ def user_facing_error_message(error: Exception | None) -> str:return "The provider is rate limiting this key. Wait a moment, then try again."if isinstance(error, ContextWindowExceededError):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, ProviderConnectionError):return "Could not reach the model provider. Try again."if isinstance(error, StructuredOutputParseError):diff --git a/products/ai_observability/backend/llm/providers/anthropic.py b/products/ai_observability/backend/llm/providers/anthropic.pyindex 31a0070402ec..75a85f906595 100644--- a/products/ai_observability/backend/llm/providers/anthropic.py+++ b/products/ai_observability/backend/llm/providers/anthropic.py@@ -20,11 +20,13 @@ from products.ai_observability.backend.llm.errors import (LLMError,ModelNotFoundError,ModelPermissionError,+ OutputTokenLimitError,ProviderConnectionError,QuotaExceededError,RateLimitError,StructuredOutputParseError,is_context_window_error_message,+ is_output_limit_error_message,stream_error_chunk,)from products.ai_observability.backend.llm.types import (@@ -177,6 +179,8 @@ class AnthropicAdapter:parsed: BaseModel | None = Noneif use_structured:+ if response.stop_reason == "max_tokens":+ raise OutputTokenLimitError("The model reached its output token limit.")assert request.response_format is not Nonetry:parsed = request.response_format.model_validate_json(content)@@ -215,6 +219,8 @@ class AnthropicAdapter:return QuotaExceededError(str(error))if is_context_window_error_message(str(error)):return ContextWindowExceededError(str(error))+ if is_output_limit_error_message(str(error)):+ return OutputTokenLimitError(str(error))return Noneif isinstance(error, anthropic.RateLimitError):if _is_quota_or_billing_error(error):diff --git a/products/ai_observability/backend/llm/providers/openai.py b/products/ai_observability/backend/llm/providers/openai.pyindex 49e5a1d588a1..6b465f91c969 100644--- a/products/ai_observability/backend/llm/providers/openai.py+++ b/products/ai_observability/backend/llm/providers/openai.py@@ -24,11 +24,13 @@ from products.ai_observability.backend.llm.errors import (LLMError,ModelNotFoundError,ModelPermissionError,+ OutputTokenLimitError,ProviderConnectionError,QuotaExceededError,RateLimitError,StructuredOutputParseError,is_context_window_error_message,+ is_output_limit_error_message,stream_error_chunk,)from products.ai_observability.backend.llm.types import (@@ -173,13 +175,19 @@ class OpenAIAdapter:except openai.BadRequestError as e:if is_context_window_error_message(str(e)):raise ContextWindowExceededError(str(e)) from e+ if is_output_limit_error_message(str(e)):+ raise OutputTokenLimitError(str(e)) from e# Fall back to manual JSON parsing for older models that don't support json_schemaif "response_format" in str(e).lower() or "json_schema" in str(e).lower():return self._complete_with_json_fallback(client, request, messages, analytics)raise- except (ValidationError, openai.LengthFinishReasonError) as e:- # json_schema does not enforce cross-field validators, while the SDK raises a separate- # exception for length-limited output. Normalize both so callers skip invalid output.+ except openai.LengthFinishReasonError as e:+ # 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 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.raise StructuredOutputParseError(f"Failed to parse structured output: {e}") from eelse:create_response = client.chat.completions.create(@@ -225,8 +233,11 @@ class OpenAIAdapter:# retryable error so the caller retries silently instead of spamming error tracking.return ProviderConnectionError(str(error))if isinstance(error, openai.APIStatusError):- if isinstance(error, openai.BadRequestError) and is_context_window_error_message(str(error)):- return ContextWindowExceededError(str(error))+ if isinstance(error, openai.BadRequestError):+ if is_context_window_error_message(str(error)):+ return ContextWindowExceededError(str(error))+ if is_output_limit_error_message(str(error)):+ return OutputTokenLimitError(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.diff --git a/products/ai_observability/backend/llm/providers/test/test_anthropic.py b/products/ai_observability/backend/llm/providers/test/test_anthropic.pyindex bd8fb9e2104d..887f4ed4c229 100644--- a/products/ai_observability/backend/llm/providers/test/test_anthropic.py+++ b/products/ai_observability/backend/llm/providers/test/test_anthropic.py@@ -9,6 +9,7 @@ from products.ai_observability.backend.llm.errors import (ContextWindowExceededError,ModelNotFoundError,ModelPermissionError,+ OutputTokenLimitError,)from products.ai_observability.backend.llm.providers.anthropic import AnthropicAdapter, AnthropicConfigfrom products.ai_observability.backend.llm.types import AnalyticsContext, CompletionRequest@@ -192,6 +193,50 @@ class TestAnthropicErrorMapping:analytics=AnalyticsContext(capture=False),)+ @parameterized.expand(+ [+ (+ "truncated_reply",+ "Could not finish the message because max_tokens or model output limit was reached.",+ OutputTokenLimitError,+ "The model ran out of room before it finished its reply. Ask for a shorter answer, then try again.",+ ),+ (+ "invalid_token_limit",+ "max_tokens: 8192 > 4096, which is the maximum allowed number of output tokens for this model",+ anthropic.BadRequestError,+ "The model provider rejected this request: max_tokens: 8192 > 4096, "+ "which is the maximum allowed number of output tokens for this model",+ ),+ ]+ )+ def test_token_limit_400_preserves_the_failure_reason(+ self, _name: str, message: str, expected_error: type[Exception], expected_stream_error: str+ ) -> None:+ with patch("products.ai_observability.backend.llm.providers.anthropic.anthropic.Anthropic") as mock_cls:+ mock_client = MagicMock()+ mock_cls.return_value = mock_client+ mock_client.messages.create.side_effect = _make_bad_request_error(message)+ request = CompletionRequest(+ model="claude-haiku-4-5",+ messages=[{"role": "user", "content": "hi"}],+ provider="anthropic",+ system="s",+ )++ with pytest.raises(expected_error):+ AnthropicAdapter().complete(+ request,+ api_key="sk-ant-test",+ analytics=AnalyticsContext(capture=False),+ )++ chunks = list(+ AnthropicAdapter().stream(request, api_key="sk-ant-test", analytics=AnalyticsContext(capture=False))+ )++ assert [chunk.data["error"] for chunk in chunks if chunk.type == "error"] == [expected_stream_error]+def test_model_404_maps_to_model_not_found(self):# A retired or misspelled model comes back as a 404. Unmapped, an evaluation burned its# Temporal retries instead of disabling itself with a reason.diff --git a/products/ai_observability/backend/llm/providers/test/test_anthropic_structured_output.py b/products/ai_observability/backend/llm/providers/test/test_anthropic_structured_output.pyindex bcfe4110ec16..6a5c41d33003 100644--- a/products/ai_observability/backend/llm/providers/test/test_anthropic_structured_output.py+++ b/products/ai_observability/backend/llm/providers/test/test_anthropic_structured_output.py@@ -3,9 +3,14 @@ from unittest.mock import MagicMock, patchimport httpximport anthropic+from parameterized import parameterizedfrom pydantic import BaseModel-from products.ai_observability.backend.llm.errors import QuotaExceededError, StructuredOutputParseError+from products.ai_observability.backend.llm.errors import (+ OutputTokenLimitError,+ QuotaExceededError,+ StructuredOutputParseError,+)from products.ai_observability.backend.llm.providers.anthropic import AnthropicAdapterfrom products.ai_observability.backend.llm.types import AnalyticsContext, CompletionRequest@@ -63,11 +68,12 @@ class TestStructuredOutputComplete:response_format=response_format,)- def _make_mock_response(self, text: str):+ def _make_mock_response(self, text: str, stop_reason: str = "end_turn") -> MagicMock:mock_block = MagicMock()mock_block.text = textmock_response = MagicMock()mock_response.content = [mock_block]+ mock_response.stop_reason = stop_reasonmock_response.usage.input_tokens = 10mock_response.usage.output_tokens = 20return mock_response@@ -118,16 +124,50 @@ class TestStructuredOutputComplete:assert result.parsed.result is Trueassert result.parsed.reason == "The sky is blue"+ @parameterized.expand(+ [+ (+ "invalid_json",+ "not valid json at all",+ "end_turn",+ StructuredOutputParseError,+ "Failed to parse structured output",+ ),+ (+ "truncated_json",+ '{"result": true, "reason": "The sky',+ "max_tokens",+ OutputTokenLimitError,+ "output token limit",+ ),+ (+ "valid_json_at_limit",+ '{"result": true, "reason": "The sky is blue"}',+ "max_tokens",+ OutputTokenLimitError,+ "output token limit",+ ),+ ]+ )@patch("products.ai_observability.backend.llm.providers.anthropic.settings")@patch("products.ai_observability.backend.llm.providers.anthropic.anthropic.Anthropic")- def test_structured_output_raises_on_invalid_json(self, mock_anthropic_cls, mock_settings):+ def test_structured_output_distinguishes_parse_errors_from_output_limits(+ self,+ _name: str,+ text: str,+ stop_reason: str,+ expected_error: type[Exception],+ expected_message: str,+ mock_anthropic_cls: MagicMock,+ mock_settings: MagicMock,+ ) -> None:mock_settings.ANTHROPIC_API_KEY = "sk-ant-test"mock_client = MagicMock()mock_anthropic_cls.return_value = mock_client- mock_client.messages.create.return_value = self._make_mock_response("not valid json at all")+ mock_client.messages.create.return_value = self._make_mock_response(text, stop_reason=stop_reason)adapter = AnthropicAdapter()- with pytest.raises(StructuredOutputParseError, match="Failed to parse structured output"):+ with pytest.raises(expected_error, match=expected_message):adapter.complete(self._make_request(response_format=BooleanEvalResult),api_key="sk-ant-test",@@ -150,13 +190,16 @@ class TestStructuredOutputComplete:analytics=AnalyticsContext(capture=False),)+ @parameterized.expand(["end_turn", "max_tokens"])@patch("products.ai_observability.backend.llm.providers.anthropic.settings")@patch("products.ai_observability.backend.llm.providers.anthropic.anthropic.Anthropic")- def test_non_structured_output_returns_text(self, mock_anthropic_cls, mock_settings):+ def test_non_structured_output_returns_text(+ self, stop_reason: str, mock_anthropic_cls: MagicMock, mock_settings: MagicMock+ ) -> None:mock_settings.ANTHROPIC_API_KEY = "sk-ant-test"mock_client = MagicMock()mock_anthropic_cls.return_value = mock_client- mock_client.messages.create.return_value = self._make_mock_response("The sky is blue.")+ mock_client.messages.create.return_value = self._make_mock_response("The sky is blue.", stop_reason=stop_reason)adapter = AnthropicAdapter()result = adapter.complete(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.pyindex bd097a240497..5ed5fab249ba 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@@ -14,6 +14,7 @@ from pydantic import BaseModel, ValidationError, model_validatorfrom products.ai_observability.backend.llm.errors import (ContextWindowExceededError,+ OutputTokenLimitError,QuotaExceededError,StructuredOutputParseError,)@@ -203,15 +204,39 @@ class TestOpenAIAdapterErrorMapping:with pytest.raises(ContextWindowExceededError):adapter.complete(request, api_key="sk-test", analytics=AnalyticsContext(capture=False))+ def test_structured_output_parse_errors_map_to_parse_error(self) -> None:+ adapter = OpenAIAdapter()+ mock_client = MagicMock()+ mock_client.beta.chat.completions.parse.side_effect = _cross_field_error()+ 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(StructuredOutputParseError):+ adapter.complete(request, api_key="sk-test", analytics=AnalyticsContext(capture=False))+@parameterized.expand([("length_finish_reason", _length_finish_reason_error),- ("cross_field_validator", _cross_field_error),+ (+ "output_limit_400",+ lambda: _make_bad_request_error(+ "Error code: 400 - {'error': {'message': 'Could not finish the message because max_tokens "+ "or model output limit was reached. Please try again with higher max_tokens.'}}"+ ),+ ),])- def test_structured_output_parse_errors_map_to_parse_error(+ def test_output_limit_failures_map_to_output_token_limit(self, _name: str, make_error: Callable[[], Exception]) -> None:+ # Both shapes are one condition — the reply did not fit. One error type keeps them in one+ # error tracking issue instead of one per provider wording.adapter = OpenAIAdapter()mock_client = MagicMock()mock_client.beta.chat.completions.parse.side_effect = make_error()@@ -224,7 +249,7 @@ class TestOpenAIAdapterErrorMapping:)with patch("products.ai_observability.backend.llm.providers.openai.openai.OpenAI", return_value=mock_client):- with pytest.raises(StructuredOutputParseError):+ with pytest.raises(OutputTokenLimitError):adapter.complete(request, api_key="sk-test", analytics=AnalyticsContext(capture=False))@@ -254,7 +279,17 @@ class TestOpenAIStreamErrorSurfacing:assert errors == ["Model 'gpt-4-turbo-2024-04-09' is not available. Pick a different model and try again."]assert "Error code: 404" not in errors[0]- def test_unmapped_400_keeps_the_providers_reason_instead_of_telling_the_user_to_retry(self):+ @parameterized.expand(+ [+ ("unsupported_temperature", "Unsupported value: 'temperature' does not support 0.7 with this model."),+ ("invalid_token_limit", "Invalid 'max_output_tokens': integer below minimum value. Expected >= 16, got 8."),+ ("excessive_token_limit", "Requested max_tokens exceeds the model output limit. Reduce max_tokens."),+ ("higher_token_setting", "This model does not support higher max_tokens values. Reduce max_tokens."),+ ]+ )+ def test_unmapped_400_keeps_the_providers_reason_instead_of_telling_the_user_to_retry(+ self, _name: str, detail: str+ ) -> None:# An unsupported parameter is the most common way a playground run fails, and it has no# branch in the taxonomy. "Try again" would be advice that cannot work, so the provider's# sentence has to come through — without the SDK's `Error code: 400 - {...}` wrapper.@@ -264,7 +299,6 @@ class TestOpenAIStreamErrorSurfacing:messages=[{"role": "user", "content": "hi"}],provider="openai",)- detail = "Unsupported value: 'temperature' does not support 0.7 with this model."body = {"error": {"message": detail}}http_request = httpx.Request("POST", "https://example.invalid/v1/chat/completions")mock_client = MagicMock()diff --git a/products/ai_observability/backend/llm/test/test_errors.py b/products/ai_observability/backend/llm/test/test_errors.pyindex 3443a275ac24..a8d0b4e4b9ae 100644--- a/products/ai_observability/backend/llm/test/test_errors.py+++ b/products/ai_observability/backend/llm/test/test_errors.py@@ -10,6 +10,7 @@ from products.ai_observability.backend.llm.errors import (LLMError,ModelNotFoundError,ModelPermissionError,+ OutputTokenLimitError,ProviderConnectionError,ProviderMismatchError,QuotaExceededError,@@ -134,6 +135,7 @@ class TestUserFacingErrorMessage(SimpleTestCase):(QuotaExceededError("insufficient_quota"),),(RateLimitError("429"),),(ContextWindowExceededError("too long"),),+ (OutputTokenLimitError("output limit was reached"),),(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.pyindex 56b99fb9764f..12f0aa5e5b75 100644--- a/products/ai_observability/backend/test/test_backfill_candidates.py+++ b/products/ai_observability/backend/test/test_backfill_candidates.py@@ -228,6 +228,7 @@ 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.("context_window_exceeded", 3),("trace_errored", 3),