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): make playground and evaluation key errors actionable (#85322)

Carlos Marchalf95ea99e8076
diff --git a/posthog/temporal/ai_observability/evaluation_errors.py b/posthog/temporal/ai_observability/evaluation_errors.py
index 7b910ab02939..e70f20aa24a3 100644
--- a/posthog/temporal/ai_observability/evaluation_errors.py
+++ b/posthog/temporal/ai_observability/evaluation_errors.py
@@ -48,7 +48,7 @@ USER_ERROR_SPECS: dict[str, EvaluationErrorSpec] = {
"key_invalid": EvaluationErrorSpec(
error_type="key_invalid",
owner="user",
- safe_message="The provider API key is disabled. Re-validate or replace the key.",
+ safe_message="The provider API key cannot be used. Re-validate or replace the key.",
status_reason=EvaluationStatusReason.PROVIDER_KEY_INVALID,
disables_evaluation=True,
),
diff --git a/posthog/temporal/ai_observability/model_resolution.py b/posthog/temporal/ai_observability/model_resolution.py
index a3ad0f1b5f91..acf08528a0d1 100644
--- a/posthog/temporal/ai_observability/model_resolution.py
+++ b/posthog/temporal/ai_observability/model_resolution.py
@@ -131,10 +131,34 @@ def _resolve_key_by_id(team_id: int, key_id: str) -> LLMProviderKey:
return _ensure_usable(key)
+# A key that was never validated is not the same thing as one the provider rejected: the state
+# decides whether the user should validate, re-validate, or replace it. Annotated as `dict[str, str]`
+# because the enum members would otherwise infer `State` keys and the lookup on the stored string
+# would not typecheck.
+_UNUSABLE_KEY_MESSAGES: dict[str, str] = {
+ LLMProviderKey.State.UNKNOWN: (
+ "This API key has not been validated yet. Validate it in AI observability settings, "
+ "then re-enable this evaluation."
+ ),
+ LLMProviderKey.State.INVALID: (
+ "This API key was rejected by the provider. Re-validate it, or replace it, then re-enable this evaluation."
+ ),
+ LLMProviderKey.State.ERROR: (
+ "This API key last failed with a provider error. Check its status in AI observability "
+ "settings, then re-validate it."
+ ),
+}
+
+
def _ensure_usable(key: LLMProviderKey) -> LLMProviderKey:
if key.state != LLMProviderKey.State.OK:
+ # A state added later still has to produce a message rather than a KeyError.
+ message = _UNUSABLE_KEY_MESSAGES.get(
+ key.state,
+ "This API key cannot be used. Re-validate it, or replace it, then re-enable this evaluation.",
+ )
raise ApplicationError(
- f"This API key has been disabled (status: {key.state}). Re-validate to recover, or replace it.",
+ message,
{"error_type": "key_invalid", "key_id": str(key.id), "key_state": key.state},
non_retryable=True,
)
diff --git a/posthog/temporal/ai_observability/test_model_resolution.py b/posthog/temporal/ai_observability/test_model_resolution.py
index 7a02c6186425..ef9ae5527f2f 100644
--- a/posthog/temporal/ai_observability/test_model_resolution.py
+++ b/posthog/temporal/ai_observability/test_model_resolution.py
@@ -89,12 +89,30 @@ class TestExplicitModelSpec:
ExplicitModelSpec("openai", "gpt-5", str(uuid.uuid4())).resolve(team.id)
assert _error_type(exc_info) == "key_not_found"
- def test_byok_disabled_key_raises_key_invalid(self, team):
+ def test_byok_invalid_key_raises_key_invalid(self, team):
key = _key(team, "openai", state=LLMProviderKey.State.INVALID)
with pytest.raises(ApplicationError) as exc_info:
ExplicitModelSpec("openai", "gpt-5", str(key.id)).resolve(team.id)
assert _error_type(exc_info) == "key_invalid"
+ @pytest.mark.parametrize(
+ "state,expected_phrase",
+ [
+ (LLMProviderKey.State.UNKNOWN, "has not been validated yet"),
+ (LLMProviderKey.State.INVALID, "was rejected by the provider"),
+ (LLMProviderKey.State.ERROR, "last failed with a provider error"),
+ ],
+ )
+ def test_unusable_key_message_names_the_actual_state(self, team, state, expected_phrase):
+ # Every non-OK state used to report "This API key has been disabled", sending a user with
+ # a never-validated key looking for a setting that does not exist.
+ key = _key(team, "openai", state=state)
+ with pytest.raises(ApplicationError) as exc_info:
+ ExplicitModelSpec("openai", "gpt-5", str(key.id)).resolve(team.id)
+
+ assert expected_phrase in exc_info.value.message
+ assert "disabled" not in exc_info.value.message
+
def test_keyless_requires_provider_key(self, team):
# No pinned key: resolution has no PostHog-funded fallback and must ask for a key.
with pytest.raises(ApplicationError) as exc_info:
@@ -174,7 +192,7 @@ class TestDefaultModelSpec:
DefaultModelSpec().resolve(team.id)
assert _error_type(exc_info) == "no_default_model"
- def test_disabled_active_key_raises_key_invalid(self, team):
+ def test_invalid_active_key_raises_key_invalid(self, team):
key = _key(team, "anthropic", state=LLMProviderKey.State.INVALID)
EvaluationConfig.objects.create(team=team, active_provider_key=key)
diff --git a/products/ai_observability/backend/llm/errors.py b/products/ai_observability/backend/llm/errors.py
index 8a06c62f89ae..c5a89ba2f124 100644
--- a/products/ai_observability/backend/llm/errors.py
+++ b/products/ai_observability/backend/llm/errors.py
@@ -1,3 +1,8 @@
+import logging
+
+from products.ai_observability.backend.llm.types import StreamChunk
+
+
class LLMError(Exception):
"""Base exception for LLM client errors"""
@@ -86,3 +91,90 @@ class ModelPermissionError(LLMError):
f"API key doesn't have access to model '{model}'" if model else "API key doesn't have access to this model"
)
super().__init__(msg)
+
+
+def provider_error_detail(error: Exception | None) -> str | None:
+ """The provider's own sentence, without the SDK's `Error code: NNN - {...}` wrapper.
+
+ `str(e)` on an OpenAI or Anthropic error embeds the whole response dict, so read the parsed
+ body instead. google-genai carries the same text on `message`.
+ """
+ body = getattr(error, "body", None)
+ if isinstance(body, dict):
+ detail = body.get("error")
+ if isinstance(detail, dict):
+ detail = detail.get("message")
+ if isinstance(detail, str) and detail.strip():
+ return detail.strip()
+ message = getattr(error, "message", None)
+ if isinstance(message, str) and message.strip():
+ return message.strip()
+ return None
+
+
+def user_facing_error_message(error: Exception | None) -> str:
+ """Turn a provider failure into copy someone can act on.
+
+ Streaming has no exception channel, so whatever text goes onto the wire is the whole
+ explanation the user gets. Raw SDK output leaks provider internals without naming a next
+ step, so every branch here says what to do instead.
+
+ A failure with no branch keeps the provider's own reason. Most of those are 400s the request
+ itself caused — an unsupported parameter, a malformed tool schema — where "try again" is
+ advice that cannot work and the provider's sentence is the only actionable thing we have.
+ """
+ if isinstance(error, ModelNotFoundError):
+ return f"Model '{error.model}' is not available. Pick a different model and try again."
+ if isinstance(error, UnsupportedModelError):
+ return f"Model '{error.model}' is not supported. Pick a different model and try again."
+ if isinstance(error, ModelPermissionError):
+ if error.model:
+ return f"Your API key does not have access to '{error.model}'. Pick a different model, or use a key with access to it."
+ return (
+ "Your API key does not have access to this model. Pick a different model, or use a key with access to it."
+ )
+ if isinstance(error, AuthenticationError):
+ return "Your provider API key was rejected. Check the key in AI observability settings."
+ if isinstance(error, QuotaExceededError):
+ return "Your provider API key is out of quota. Check your billing with the provider, then try again."
+ if isinstance(error, RateLimitError):
+ 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, ProviderConnectionError):
+ return "Could not reach the model provider. Try again."
+ if isinstance(error, StructuredOutputParseError):
+ return "The model returned a response we could not read. Try again."
+ if isinstance(error, UnsupportedProviderError):
+ return f"Provider '{error.provider}' is not supported. Pick a model from another provider."
+ if isinstance(error, ProviderMismatchError):
+ return (
+ f"This key is for {error.key_provider}, but the request asks for {error.request_provider}. "
+ "Pick a model from the key's provider, or switch keys."
+ )
+ detail = provider_error_detail(error)
+ if detail:
+ return f"The model provider rejected this request: {detail}"
+ return "The request to the model provider failed. Try again."
+
+
+def stream_error_chunk(
+ error: Exception,
+ mapped: LLMError | None,
+ *,
+ logger: logging.Logger,
+ provider: str,
+) -> StreamChunk:
+ """Log a streaming failure and render the one chunk that has to explain it to the user.
+
+ A connection error usually resolves on the next attempt, so it stays a warning rather than
+ spamming error tracking.
+ """
+ if isinstance(mapped, ProviderConnectionError):
+ logger.warning(f"{provider} connection error when streaming response: {error}")
+ else:
+ logger.exception(f"{provider} API error when streaming response: {error}")
+ return StreamChunk(
+ type="error",
+ data={"error": user_facing_error_message(mapped if mapped is not None else error)},
+ )
diff --git a/products/ai_observability/backend/llm/providers/anthropic.py b/products/ai_observability/backend/llm/providers/anthropic.py
index 1ee15d4807da..5d1463f6ea30 100644
--- a/products/ai_observability/backend/llm/providers/anthropic.py
+++ b/products/ai_observability/backend/llm/providers/anthropic.py
@@ -17,11 +17,15 @@ from pydantic import BaseModel
from products.ai_observability.backend.llm.errors import (
AuthenticationError,
ContextWindowExceededError,
+ LLMError,
+ ModelNotFoundError,
+ ModelPermissionError,
ProviderConnectionError,
QuotaExceededError,
RateLimitError,
StructuredOutputParseError,
is_context_window_error_message,
+ stream_error_chunk,
)
from products.ai_observability.backend.llm.types import (
AnalyticsContext,
@@ -185,22 +189,42 @@ class AnthropicAdapter:
usage=usage,
parsed=parsed,
)
- except anthropic.AuthenticationError as e:
- raise AuthenticationError(str(e))
- except anthropic.BadRequestError as e:
- if _is_quota_or_billing_error(e):
- raise QuotaExceededError(str(e)) from e
- if is_context_window_error_message(str(e)):
- raise ContextWindowExceededError(str(e)) from e
+ except Exception as e:
+ mapped = self._mapped_error(e, request.model)
+ if mapped is not None:
+ raise mapped from e
raise
- except anthropic.RateLimitError as e:
- if _is_quota_or_billing_error(e):
- raise QuotaExceededError(str(e)) from e
- raise RateLimitError(str(e)) from e
- except anthropic.APIConnectionError as e:
+
+ def _mapped_error(self, error: Exception, model: str) -> LLMError | None:
+ """Normalize a provider exception into the shared taxonomy, or None when it isn't ours.
+
+ `complete` and `stream` both route through this, so the same provider failure reads the
+ same way whether the caller streamed it or not.
+ """
+ if isinstance(error, anthropic.AuthenticationError):
+ return AuthenticationError(str(error))
+ if isinstance(error, anthropic.NotFoundError):
+ # Anthropic answers a retired or misspelled model with a 404. Without this the
+ # workflow burns its retries on an unmapped exception instead of telling the user
+ # to pick another model.
+ return ModelNotFoundError(model)
+ if isinstance(error, anthropic.PermissionDeniedError):
+ return ModelPermissionError(model)
+ if isinstance(error, anthropic.BadRequestError):
+ if _is_quota_or_billing_error(error):
+ return QuotaExceededError(str(error))
+ if is_context_window_error_message(str(error)):
+ return ContextWindowExceededError(str(error))
+ return None
+ if isinstance(error, anthropic.RateLimitError):
+ if _is_quota_or_billing_error(error):
+ return QuotaExceededError(str(error))
+ return RateLimitError(str(error))
+ if isinstance(error, anthropic.APIConnectionError):
# Transient transport failure (connection reset, read timeout). Map to a quiet
# retryable error so the caller retries silently instead of spamming error tracking.
- raise ProviderConnectionError(str(e)) from e
+ return ProviderConnectionError(str(error))
+ return None
def stream(
self,
@@ -281,68 +305,69 @@ class AnthropicAdapter:
)
else:
stream = client.messages.create(**common_kwargs)
- except Exception as e:
- logger.exception(f"Anthropic API error: {e}")
- yield StreamChunk(type="error", data={"error": "Anthropic API error"})
- return
-
- for chunk in stream:
- if chunk.type == "message_start":
- usage = chunk.message.usage
- yield StreamChunk(
- type="usage",
- data={
- "input_tokens": usage.input_tokens or 0,
- "output_tokens": usage.output_tokens or 0,
- "cache_write_tokens": getattr(usage, "cache_creation_input_tokens", None) or 0,
- "cache_read_tokens": getattr(usage, "cache_read_input_tokens", None) or 0,
- },
- )
-
- elif chunk.type == "message_delta":
- yield StreamChunk(
- type="usage",
- data={"input_tokens": 0, "output_tokens": chunk.usage.output_tokens or 0},
- )
- elif chunk.type == "content_block_start":
- if chunk.content_block.type == "thinking":
- yield StreamChunk(type="reasoning", data={"reasoning": chunk.content_block.thinking or ""})
- elif chunk.content_block.type == "redacted_thinking":
- yield StreamChunk(type="reasoning", data={"reasoning": "[Redacted thinking block]"})
- elif chunk.content_block.type == "text":
- if chunk.index > 0:
- yield StreamChunk(type="text", data={"text": "\n"})
- yield StreamChunk(type="text", data={"text": chunk.content_block.text})
- elif chunk.content_block.type == "tool_use":
+ # Inside the try: Anthropic reports an overload or a mid-request failure by raising
+ # partway through iteration, which is the point where the user has nothing else to
+ # read but this generator's chunks.
+ for chunk in stream:
+ if chunk.type == "message_start":
+ usage = chunk.message.usage
yield StreamChunk(
- type="tool_call",
+ type="usage",
data={
- "id": chunk.content_block.id,
- "function": {
- "name": chunk.content_block.name,
- "arguments": "",
- },
+ "input_tokens": usage.input_tokens or 0,
+ "output_tokens": usage.output_tokens or 0,
+ "cache_write_tokens": getattr(usage, "cache_creation_input_tokens", None) or 0,
+ "cache_read_tokens": getattr(usage, "cache_read_input_tokens", None) or 0,
},
)
- elif chunk.type == "content_block_delta":
- if chunk.delta.type == "thinking_delta":
- yield StreamChunk(type="reasoning", data={"reasoning": chunk.delta.thinking})
- elif chunk.delta.type == "text_delta":
- yield StreamChunk(type="text", data={"text": chunk.delta.text})
- elif chunk.delta.type == "input_json_delta":
+ elif chunk.type == "message_delta":
yield StreamChunk(
- type="tool_call",
- data={
- "id": None,
- "function": {
- "name": "",
- "arguments": chunk.delta.partial_json,
- },
- },
+ type="usage",
+ data={"input_tokens": 0, "output_tokens": chunk.usage.output_tokens or 0},
)
+ elif chunk.type == "content_block_start":
+ if chunk.content_block.type == "thinking":
+ yield StreamChunk(type="reasoning", data={"reasoning": chunk.content_block.thinking or ""})
+ elif chunk.content_block.type == "redacted_thinking":
+ yield StreamChunk(type="reasoning", data={"reasoning": "[Redacted thinking block]"})
+ elif chunk.content_block.type == "text":
+ if chunk.index > 0:
+ yield StreamChunk(type="text", data={"text": "\n"})
+ yield StreamChunk(type="text", data={"text": chunk.content_block.text})
+ elif chunk.content_block.type == "tool_use":
+ yield StreamChunk(
+ type="tool_call",
+ data={
+ "id": chunk.content_block.id,
+ "function": {
+ "name": chunk.content_block.name,
+ "arguments": "",
+ },
+ },
+ )
+
+ elif chunk.type == "content_block_delta":
+ if chunk.delta.type == "thinking_delta":
+ yield StreamChunk(type="reasoning", data={"reasoning": chunk.delta.thinking})
+ elif chunk.delta.type == "text_delta":
+ yield StreamChunk(type="text", data={"text": chunk.delta.text})
+ elif chunk.delta.type == "input_json_delta":
+ yield StreamChunk(
+ type="tool_call",
+ data={
+ "id": None,
+ "function": {
+ "name": "",
+ "arguments": chunk.delta.partial_json,
+ },
+ },
+ )
+ except Exception as e:
+ yield stream_error_chunk(e, self._mapped_error(e, model_id), logger=logger, provider=self.name)
+
@staticmethod
def validate_key(api_key: str, **kwargs: Any) -> tuple[str, str | None]:
"""Validate an Anthropic API key by making a lightweight API call."""
diff --git a/products/ai_observability/backend/llm/providers/gemini.py b/products/ai_observability/backend/llm/providers/gemini.py
index 1e379b9564fd..cf6649524d7d 100644
--- a/products/ai_observability/backend/llm/providers/gemini.py
+++ b/products/ai_observability/backend/llm/providers/gemini.py
@@ -18,12 +18,14 @@ from pydantic import BaseModel
from products.ai_observability.backend.llm.errors import (
AuthenticationError,
+ LLMError,
ModelNotFoundError,
ModelPermissionError,
ProviderConnectionError,
QuotaExceededError,
RateLimitError,
StructuredOutputParseError,
+ stream_error_chunk,
)
from products.ai_observability.backend.llm.types import (
AnalyticsContext,
@@ -137,28 +139,41 @@ class GeminiAdapter:
usage=usage,
parsed=parsed,
)
- except APIError as e:
- error_message = str(e).lower()
- status_code = getattr(e, "code", None) or getattr(e, "status_code", None)
+ except Exception as e:
+ mapped = self._mapped_error(e, request.model)
+ if mapped is not None:
+ raise mapped from e
+ raise
+
+ def _mapped_error(self, error: Exception, model: str) -> LLMError | None:
+ """Normalize a provider exception into the shared taxonomy, or None when it isn't ours.
+
+ `complete` and `stream` both route through this, so the same provider failure reads the
+ same way whether the caller streamed it or not.
+ """
+ if isinstance(error, APIError):
+ error_message = str(error).lower()
+ status_code = getattr(error, "code", None) or getattr(error, "status_code", None)
if status_code == 401 or "authentication" in error_message or "api key" in error_message:
- raise AuthenticationError(str(e))
+ return AuthenticationError(str(error))
if status_code == 403 or "permission denied" in error_message:
- raise ModelPermissionError(request.model)
+ return ModelPermissionError(model)
if status_code == 429 or "rate limit" in error_message or "resource exhausted" in error_message:
if "quota" in error_message or "billing" in error_message:
- raise QuotaExceededError(str(e))
- raise RateLimitError(str(e))
+ return QuotaExceededError(str(error))
+ return RateLimitError(str(error))
# Google returns a 404-class error (often with "no longer available") when a
# model is retired/deprecated. Map it so call_llm_judge disables the eval
# gracefully instead of burning Temporal retries on an unhandled exception.
if status_code == 404 or "no longer available" in error_message or "not found" in error_message:
- raise ModelNotFoundError(request.model)
- raise
- except httpx.TransportError as e:
+ return ModelNotFoundError(model)
+ return None
+ if isinstance(error, httpx.TransportError):
# google-genai doesn't wrap httpx transport failures (connection reset, read timeout)
# in APIError, so without this they escape as an unmapped exception and spam error
# tracking. Map to a quiet retryable error so the caller retries silently.
- raise ProviderConnectionError(str(e)) from e
+ return ProviderConnectionError(str(error))
+ return None
def stream(
self,
@@ -220,12 +235,8 @@ class GeminiAdapter:
},
)
- except APIError as e:
- logger.exception(f"Gemini API error when streaming response: {e}")
- yield StreamChunk(type="error", data={"error": "Gemini API error"})
except Exception as e:
- logger.exception(f"Unexpected error when streaming response: {e}")
- yield StreamChunk(type="error", data={"error": "Unexpected error"})
+ yield stream_error_chunk(e, self._mapped_error(e, model_id), logger=logger, provider=self.name)
@staticmethod
def validate_key(api_key: str, **kwargs: Any) -> tuple[str, str | None]:
diff --git a/products/ai_observability/backend/llm/providers/openai.py b/products/ai_observability/backend/llm/providers/openai.py
index e081fba6de85..5aee2c59fb1b 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,
ContextWindowExceededError,
+ LLMError,
ModelNotFoundError,
ModelPermissionError,
ProviderConnectionError,
@@ -28,6 +29,7 @@ from products.ai_observability.backend.llm.errors import (
RateLimitError,
StructuredOutputParseError,
is_context_window_error_message,
+ stream_error_chunk,
)
from products.ai_observability.backend.llm.types import (
AnalyticsContext,
@@ -194,31 +196,43 @@ class OpenAIAdapter:
model=request.model,
usage=usage,
)
- except openai.AuthenticationError as e:
- raise AuthenticationError(str(e))
- except openai.NotFoundError:
- raise ModelNotFoundError(request.model)
- except openai.PermissionDeniedError:
- raise ModelPermissionError(request.model)
- except openai.RateLimitError as e:
- error_body = getattr(e, "body", {}) or {}
+ except Exception as e:
+ mapped = self._mapped_error(e, request.model)
+ if mapped is not None:
+ raise mapped from e
+ raise
+
+ def _mapped_error(self, error: Exception, model: str) -> LLMError | None:
+ """Normalize a provider exception into the shared taxonomy, or None when it isn't ours.
+
+ `complete` and `stream` both route through this, so the same provider failure reads the
+ same way whether the caller streamed it or not.
+ """
+ if isinstance(error, openai.AuthenticationError):
+ return AuthenticationError(str(error))
+ if isinstance(error, openai.NotFoundError):
+ return ModelNotFoundError(model)
+ if isinstance(error, openai.PermissionDeniedError):
+ return ModelPermissionError(model)
+ if isinstance(error, openai.RateLimitError):
+ error_body = getattr(error, "body", {}) or {}
error_code = error_body.get("code", "") or error_body.get("error", {}).get("code", "")
if error_code == "insufficient_quota":
- raise QuotaExceededError(str(e))
- raise RateLimitError(str(e))
- except openai.APIConnectionError as e:
+ return QuotaExceededError(str(error))
+ return RateLimitError(str(error))
+ if isinstance(error, openai.APIConnectionError):
# Transient transport failure (connection reset, read timeout). Map to a quiet
# retryable error so the caller retries silently instead of spamming error tracking.
- raise ProviderConnectionError(str(e)) from e
- except openai.APIStatusError as e:
- if isinstance(e, openai.BadRequestError) and is_context_window_error_message(str(e)):
- raise ContextWindowExceededError(str(e)) from e
+ 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))
# 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.
- if getattr(e, "status_code", None) == 402:
- raise QuotaExceededError(str(e))
- raise
+ if getattr(error, "status_code", None) == 402:
+ return QuotaExceededError(str(error))
+ return None
def _complete_with_json_fallback(
self,
@@ -361,8 +375,7 @@ Return ONLY the JSON object, no other text or markdown formatting."""
yield from self._yield_usage_chunks(chunk.usage)
except Exception as e:
- logger.exception(f"OpenAI API error: {e}")
- yield StreamChunk(type="error", data={"error": str(e)})
+ yield stream_error_chunk(e, self._mapped_error(e, model_id), logger=logger, provider=self.name)
@staticmethod
def validate_key(api_key: str, **kwargs: Any) -> tuple[str, str | None]:
diff --git a/products/ai_observability/backend/llm/providers/test/test_anthropic.py b/products/ai_observability/backend/llm/providers/test/test_anthropic.py
index a2151ceeb612..bd8fb9e2104d 100644
--- a/products/ai_observability/backend/llm/providers/test/test_anthropic.py
+++ b/products/ai_observability/backend/llm/providers/test/test_anthropic.py
@@ -5,7 +5,11 @@ import httpx
import anthropic
from parameterized import parameterized
-from products.ai_observability.backend.llm.errors import ContextWindowExceededError
+from products.ai_observability.backend.llm.errors import (
+ ContextWindowExceededError,
+ ModelNotFoundError,
+ ModelPermissionError,
+)
from products.ai_observability.backend.llm.providers.anthropic import AnthropicAdapter, AnthropicConfig
from products.ai_observability.backend.llm.types import AnalyticsContext, CompletionRequest
@@ -143,6 +147,26 @@ def _make_bad_request_error(message: str) -> anthropic.BadRequestError:
return anthropic.BadRequestError(message, response=response, body={"error": {"message": message}})
+def _make_not_found_error(model: str) -> anthropic.NotFoundError:
+ request = httpx.Request("POST", "https://api.anthropic.com/v1/messages")
+ message = f"model: {model}"
+ response = httpx.Response(status_code=404, request=request, json={"error": {"message": message}})
+ return anthropic.NotFoundError(message, response=response, body={"error": {"message": message}})
+
+
+def _make_permission_denied_error(model: str) -> anthropic.PermissionDeniedError:
+ request = httpx.Request("POST", "https://api.anthropic.com/v1/messages")
+ message = f"Your API key does not have access to {model}"
+ response = httpx.Response(status_code=403, request=request, json={"error": {"message": message}})
+ return anthropic.PermissionDeniedError(message, response=response, body={"error": {"message": message}})
+
+
+def _raising_stream(error: Exception):
+ """A stream that fails partway through iteration, the way an overload does."""
+ yield MagicMock(type="message_start", message=MagicMock(usage=MagicMock(input_tokens=1, output_tokens=0)))
+ raise error
+
+
class TestAnthropicErrorMapping:
@parameterized.expand(
[
@@ -167,3 +191,100 @@ class TestAnthropicErrorMapping:
api_key="sk-ant-test",
analytics=AnalyticsContext(capture=False),
)
+
+ 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.
+ 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_not_found_error("claude-3-sonnet-20240229")
+
+ with pytest.raises(ModelNotFoundError):
+ AnthropicAdapter().complete(
+ CompletionRequest(
+ model="claude-3-sonnet-20240229",
+ messages=[{"role": "user", "content": "hi"}],
+ provider="anthropic",
+ system="s",
+ ),
+ api_key="sk-ant-test",
+ analytics=AnalyticsContext(capture=False),
+ )
+
+ def test_model_403_maps_to_model_permission_error(self):
+ # A 403 resolves to the `permission_error` spec, which disables the evaluation and marks
+ # the key errored — so this mapping decides more than the wording of a message.
+ 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_permission_denied_error("claude-opus-4-5")
+
+ with pytest.raises(ModelPermissionError):
+ AnthropicAdapter().complete(
+ CompletionRequest(
+ model="claude-opus-4-5",
+ messages=[{"role": "user", "content": "hi"}],
+ provider="anthropic",
+ system="s",
+ ),
+ api_key="sk-ant-test",
+ analytics=AnalyticsContext(capture=False),
+ )
+
+
+class TestAnthropicStreamErrorSurfacing:
+ def test_model_404_yields_actionable_message_instead_of_discarding_the_reason(self):
+ # Streaming has no exception channel, so this chunk is the entire explanation the user
+ # gets in the playground.
+ 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_not_found_error("claude-3-sonnet-20240229")
+
+ chunks = list(
+ AnthropicAdapter().stream(
+ CompletionRequest(
+ model="claude-3-sonnet-20240229",
+ messages=[{"role": "user", "content": "hi"}],
+ provider="anthropic",
+ system="s",
+ ),
+ api_key="sk-ant-test",
+ analytics=AnalyticsContext(capture=False),
+ )
+ )
+
+ errors = [chunk.data["error"] for chunk in chunks if chunk.type == "error"]
+ assert errors == ["Model 'claude-3-sonnet-20240229' is not available. Pick a different model and try again."]
+
+ def test_error_raised_partway_through_the_stream_still_reaches_the_user(self):
+ # An overload arrives during iteration, not when the request is made. That path used to
+ # sit outside the try, so the generator raised and the playground showed nothing at all.
+ request = httpx.Request("POST", "https://api.anthropic.com/v1/messages")
+ overloaded = anthropic.RateLimitError(
+ "Overloaded",
+ response=httpx.Response(status_code=429, request=request, json={"error": {"message": "Overloaded"}}),
+ body={"error": {"message": "Overloaded"}},
+ )
+
+ 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.return_value = _raising_stream(overloaded)
+
+ chunks = list(
+ AnthropicAdapter().stream(
+ CompletionRequest(
+ model="claude-haiku-4-5",
+ messages=[{"role": "user", "content": "hi"}],
+ provider="anthropic",
+ system="s",
+ ),
+ api_key="sk-ant-test",
+ analytics=AnalyticsContext(capture=False),
+ )
+ )
+
+ errors = [chunk.data["error"] for chunk in chunks if chunk.type == "error"]
+ assert errors == ["The provider is rate limiting this key. Wait a moment, then try again."]
diff --git a/products/ai_observability/backend/llm/providers/test/test_gemini_adapter.py b/products/ai_observability/backend/llm/providers/test/test_gemini_adapter.py
index 05a327fa9646..13b6df24fc8a 100644
--- a/products/ai_observability/backend/llm/providers/test/test_gemini_adapter.py
+++ b/products/ai_observability/backend/llm/providers/test/test_gemini_adapter.py
@@ -80,3 +80,27 @@ class TestGeminiAdapterErrorMapping:
with patch("products.ai_observability.backend.llm.providers.gemini.genai.Client", return_value=mock_client):
with pytest.raises(ProviderConnectionError):
adapter.complete(request, api_key="test-key", analytics=AnalyticsContext(capture=False))
+
+
+class TestGeminiStreamErrorSurfacing:
+ def test_retired_model_yields_actionable_message_instead_of_discarding_the_reason(self):
+ # Streaming has no exception channel, so this chunk is the entire explanation the user
+ # gets in the playground.
+ request = CompletionRequest(
+ model="gemini-1.0-pro",
+ system="s",
+ messages=[{"role": "user", "content": "hi"}],
+ provider="gemini",
+ )
+ mock_client = MagicMock()
+ mock_client.models.generate_content_stream.side_effect = _make_client_error(
+ 404, "NOT_FOUND", "models/gemini-1.0-pro is not found"
+ )
+
+ with patch("products.ai_observability.backend.llm.providers.gemini.genai.Client", return_value=mock_client):
+ chunks = list(
+ GeminiAdapter().stream(request, api_key="test-key", analytics=AnalyticsContext(capture=False))
+ )
+
+ errors = [chunk.data["error"] for chunk in chunks if chunk.type == "error"]
+ assert errors == ["Model 'gemini-1.0-pro' is not available. Pick a different model and try again."]
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 975e2a752803..bd097a240497 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
@@ -226,3 +226,58 @@ class TestOpenAIAdapterErrorMapping:
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))
+
+
+class TestOpenAIStreamErrorSurfacing:
+ def test_model_404_yields_actionable_message_instead_of_raw_sdk_text(self):
+ # Streaming has no exception channel, so this chunk is the entire explanation the user
+ # gets in the playground.
+ request = CompletionRequest(
+ model="gpt-4-turbo-2024-04-09",
+ system="s",
+ messages=[{"role": "user", "content": "hi"}],
+ provider="openai",
+ )
+ http_request = httpx.Request("POST", "https://example.invalid/v1/chat/completions")
+ response = httpx.Response(status_code=404, request=http_request, json={"error": {"message": "does not exist"}})
+ mock_client = MagicMock()
+ mock_client.chat.completions.create.side_effect = openai.NotFoundError(
+ "Error code: 404 - the model `gpt-4-turbo-2024-04-09` does not exist",
+ response=response,
+ body=None,
+ )
+
+ with patch("products.ai_observability.backend.llm.providers.openai.openai.OpenAI", return_value=mock_client):
+ chunks = list(OpenAIAdapter().stream(request, api_key="sk-test", analytics=AnalyticsContext(capture=False)))
+
+ errors = [chunk.data["error"] for chunk in chunks if chunk.type == "error"]
+ 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):
+ # 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.
+ request = CompletionRequest(
+ model="gpt-5",
+ system="s",
+ 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()
+ mock_client.chat.completions.create.side_effect = openai.BadRequestError(
+ f"Error code: 400 - {body}",
+ response=httpx.Response(status_code=400, request=http_request, json=body),
+ body=body,
+ )
+
+ with patch("products.ai_observability.backend.llm.providers.openai.openai.OpenAI", return_value=mock_client):
+ chunks = list(OpenAIAdapter().stream(request, api_key="sk-test", analytics=AnalyticsContext(capture=False)))
+
+ errors = [chunk.data["error"] for chunk in chunks if chunk.type == "error"]
+ assert len(errors) == 1
+ assert detail in errors[0]
+ assert "Error code: 400" not in errors[0]
diff --git a/products/ai_observability/backend/llm/test/test_errors.py b/products/ai_observability/backend/llm/test/test_errors.py
index 0ab675bebc67..3443a275ac24 100644
--- a/products/ai_observability/backend/llm/test/test_errors.py
+++ b/products/ai_observability/backend/llm/test/test_errors.py
@@ -1,19 +1,27 @@
from django.test import SimpleTestCase
+import httpx
+import openai
from parameterized import parameterized
from products.ai_observability.backend.llm.errors import (
AuthenticationError,
+ ContextWindowExceededError,
LLMError,
ModelNotFoundError,
ModelPermissionError,
+ ProviderConnectionError,
ProviderMismatchError,
QuotaExceededError,
RateLimitError,
+ StructuredOutputParseError,
UnsupportedModelError,
UnsupportedProviderError,
+ user_facing_error_message,
)
+GENERIC_MESSAGE = "The request to the model provider failed. Try again."
+
class TestLLMErrors(SimpleTestCase):
def test_llm_error_is_exception(self):
@@ -111,3 +119,63 @@ class TestErrorHierarchy(SimpleTestCase):
except LLMError:
caught = True
assert caught
+
+
+class TestUserFacingErrorMessage(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (ModelNotFoundError("gpt-4-turbo"),),
+ (UnsupportedModelError("gpt-99"),),
+ (UnsupportedProviderError("cohere"),),
+ (ModelPermissionError("o3-pro"),),
+ (ModelPermissionError(),),
+ (ProviderMismatchError("openai", "anthropic"),),
+ (AuthenticationError("401"),),
+ (QuotaExceededError("insufficient_quota"),),
+ (RateLimitError("429"),),
+ (ContextWindowExceededError("too long"),),
+ (ProviderConnectionError("reset by peer"),),
+ (StructuredOutputParseError("bad json"),),
+ ]
+ )
+ def test_every_error_in_the_taxonomy_gets_its_own_copy(self, error):
+ assert user_facing_error_message(error) != GENERIC_MESSAGE
+
+ @parameterized.expand(
+ [
+ (ModelNotFoundError("gpt-4-turbo"),),
+ (UnsupportedModelError("gpt-99"),),
+ (ModelPermissionError("o3-pro"),),
+ ]
+ )
+ def test_copy_about_a_model_names_the_model(self, error):
+ assert error.model in user_facing_error_message(error)
+
+ def test_unmapped_provider_error_keeps_the_providers_reason(self):
+ # A 400 caused by the request itself — an unsupported parameter, a malformed tool schema —
+ # has no branch in the taxonomy, and retrying it can only fail the same way. The provider's
+ # own sentence is the only actionable thing left, so it has to survive.
+ detail = "Unsupported value: 'temperature' does not support 0.7 with this model."
+ body = {"error": {"message": detail}}
+ request = httpx.Request("POST", "https://api.openai.com/v1/chat/completions")
+ error = openai.BadRequestError(
+ f"Error code: 400 - {body}",
+ response=httpx.Response(status_code=400, request=request, json=body),
+ body=body,
+ )
+
+ message = user_facing_error_message(error)
+
+ assert detail in message
+ assert "Error code: 400" not in message
+
+ def test_google_style_error_exposes_its_reason_through_the_message_attribute(self):
+ # google-genai puts the text on `message` rather than in a parsed `body`.
+ class FakeAPIError(Exception):
+ message = "models/gemini-1.0-pro is not found for API version v1beta"
+
+ assert "models/gemini-1.0-pro is not found" in user_facing_error_message(FakeAPIError())
+
+ @parameterized.expand([(None,), (RuntimeError("boom"),), (ValueError(""),)])
+ def test_error_with_no_readable_reason_falls_back_to_the_generic_message(self, error):
+ assert user_facing_error_message(error) == GENERIC_MESSAGE
diff --git a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.test.ts b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.test.ts
index a52978bc3cb2..9f1192b10016 100644
--- a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.test.ts
+++ b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.test.ts
@@ -10,7 +10,13 @@ import { initKeaTests } from '~/test/init'
import { AccessControlLevel } from '~/types'
import { llmPlaygroundPromptsLogic } from './llmPlaygroundPromptsLogic'
-import { appendToolCallChunk, describeError, llmPlaygroundRunLogic, mergeUsage } from './llmPlaygroundRunLogic'
+import {
+ appendToolCallChunk,
+ describeError,
+ escapeMarkdownInline,
+ llmPlaygroundRunLogic,
+ mergeUsage,
+} from './llmPlaygroundRunLogic'
function setPlaygroundAccessLevel(level: AccessControlLevel): void {
window.POSTHOG_APP_CONTEXT = {
@@ -228,6 +234,39 @@ describe('llmPlaygroundRunLogic', () => {
captureExceptionSpy.mockRestore()
})
+ it('names the model when it is not one of the available models', async () => {
+ // The model can arrive without passing through the picker — from a trace, or a saved
+ // prompt written when the key set still offered it.
+ const streamSpy = jest.spyOn(api, 'stream')
+ const toastSpy = jest.spyOn(lemonToast, 'error').mockImplementation(() => 'toast-id')
+
+ const logic = llmPlaygroundRunLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ llmPlaygroundPromptsLogic.actions.setModel('claude-3-sonnet-20240229')
+ llmPlaygroundPromptsLogic.actions.setMessages([{ role: 'user', content: 'hello' }])
+ llmPlaygroundRunLogic.actions.submitPrompt()
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ const items = llmPlaygroundRunLogic.values.comparisonItems
+ expect(items).toHaveLength(1)
+ expect(items[0].error).toBe(true)
+ // The toast is plain text; the card is markdown, so the model id reaches it escaped.
+ expect(toastSpy).toHaveBeenCalledWith(
+ "Model 'claude-3-sonnet-20240229' is not one of your available models. Pick a different model and try again."
+ )
+ expect(items[0].response).toContain(
+ "**Error:** Model 'claude\\-3\\-sonnet\\-20240229' is not one of your available models."
+ )
+ expect(streamSpy).not.toHaveBeenCalled()
+
+ logic.unmount()
+ streamSpy.mockRestore()
+ toastSpy.mockRestore()
+ })
+
describe('describeError', () => {
it('prefers structured backend error string over detail and message', () => {
const err = new ApiError('fallback', 400, undefined, { error: 'backend says no' })
@@ -250,4 +289,18 @@ describe('llmPlaygroundRunLogic', () => {
expect(describeError('nope', 'fallback')).toEqual({ message: 'fallback' })
})
})
+
+ describe('escapeMarkdownInline', () => {
+ // A model id can reach the result card straight from an ingested `$ai_model` property,
+ // and that card renders markdown with images enabled.
+ it('defuses image syntax so an ingested model id cannot issue a request', () => {
+ expect(escapeMarkdownInline('![x](https://example.com/pixel)')).toBe(
+ '\\!\\[x\\]\\(https\\:\\/\\/example\\.com\\/pixel\\)'
+ )
+ })
+
+ it('leaves an ordinary model id alone apart from its punctuation', () => {
+ expect(escapeMarkdownInline('gpt-4-turbo')).toBe('gpt\\-4\\-turbo')
+ })
+ })
})
diff --git a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts
index 09743874ce6c..39237ca9df8d 100644
--- a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts
+++ b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts
@@ -74,6 +74,17 @@ export function appendToolCallChunk(state: AggregatedToolCall[], toolCall: ToolC
return updated
}
+/** Neutralize markdown syntax in a value we did not author.
+ *
+ * A result card renders its text with `LemonMarkdown`, images included, so a model id taken from
+ * an ingested `$ai_model` property would otherwise turn `![x](https://…)` into a live request off
+ * an analyst's browser. CommonMark treats a backslash before any ASCII punctuation as a literal,
+ * so escaping the whole punctuation range covers link, image, and emphasis syntax at once.
+ */
+export function escapeMarkdownInline(value: string): string {
+ return value.replace(/[!-/:-@[-`{-~]/g, '\\$&')
+}
+
export function describeError(err: unknown, fallbackMessage: string): { message: string; status?: number } {
if (err instanceof ApiError) {
const dataError = typeof err.data?.error === 'string' ? err.data.error : null
@@ -378,8 +389,14 @@ export const llmPlaygroundRunLogic = kea<llmPlaygroundRunLogicType>([
(m) => m.id === prompt.model
)
if (!selectedModel?.provider) {
- lemonToast.error('Selected model not found in available models')
- responseText = '**Error:** Selected model not available.'
+ // Reachable without the model ever being picked here: opening a trace in
+ // the playground, or loading a saved prompt, can carry a model the current
+ // key set no longer offers. Name it so the user knows what to change.
+ const describeMissingModel = (model: string): string =>
+ `Model '${model}' is not one of your available models. Pick a different model and try again.`
+ // The toast renders as text, the result card renders as markdown.
+ lemonToast.error(describeMissingModel(prompt.model))
+ responseText = `**Error:** ${describeMissingModel(escapeMarkdownInline(prompt.model))}`
responseHasError = true
upsertLiveItem()
return