: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(llma): classify evaluation user errors (#66413)
Radu Raiceace5f2ef1040a
diff --git a/common/hogvm/python/stl/__init__.py b/common/hogvm/python/stl/__init__.pyindex 7c0f94f8c06c..54f26e4407d4 100644--- a/common/hogvm/python/stl/__init__.py+++ b/common/hogvm/python/stl/__init__.py@@ -11,7 +11,7 @@ from typing import TYPE_CHECKING, Any, Optionalimport pytzfrom ..objects import is_hog_callable, is_hog_closure, is_hog_error, new_hog_error, to_hog_interval-from ..utils import get_nested_value, like+from ..utils import HogVMException, get_nested_value, likefrom .crypto import md5, sha256, sha256HmacChainfrom .date import (formatDateTime,@@ -109,6 +109,12 @@ def empty(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]],return not bool(args[0])+def length(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float):+ if args[0] is None:+ raise HogVMException("Can not call length on null")+ return len(args[0])++def sleep(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float):time.sleep(args[0])return None@@ -988,7 +994,7 @@ STL: dict[str, STLFunction] = {"ifNull": STLFunction(fn=ifNull, minArgs=2, maxArgs=2),"isNull": STLFunction(fn=lambda args, team, stdout, timeout: args[0] is None, minArgs=1, maxArgs=1),"isNotNull": STLFunction(fn=lambda args, team, stdout, timeout: args[0] is not None, minArgs=1, maxArgs=1),- "length": STLFunction(fn=lambda args, team, stdout, timeout: len(args[0]), minArgs=1, maxArgs=1),+ "length": STLFunction(fn=length, minArgs=1, maxArgs=1),"empty": STLFunction(fn=empty, minArgs=1, maxArgs=1),"notEmpty": STLFunction(fn=lambda args, team, stdout, timeout: not empty(args, team, stdout, timeout), minArgs=1, maxArgs=1diff --git a/common/hogvm/python/test/test_execute.py b/common/hogvm/python/test/test_execute.pyindex 51a51c2ce051..8ac10fc70db9 100644--- a/common/hogvm/python/test/test_execute.py+++ b/common/hogvm/python/test/test_execute.py@@ -15,7 +15,7 @@ from common.hogvm.python.operation import (HOGQL_BYTECODE_VERSION as VERSION,Operation as op,)-from common.hogvm.python.utils import UncaughtHogVMException+from common.hogvm.python.utils import HogVMException, UncaughtHogVMExceptionclass TestBytecodeExecute:@@ -670,6 +670,10 @@ class TestBytecodeExecute:assert self._run_program("if (lower('Tdd4gh') == 'tdd4gh') return upper('test');") == "TEST"assert self._run_program("return reverse('spinner');") == "rennips"+ def test_bytecode_length_null_raises_hogvm_exception(self):+ with pytest.raises(HogVMException, match="Can not call length on null"):+ self._run_program("return length(null);")+def test_random_float(self):for _ in range(50):value = self._run_program("return randomFloat();")diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex c12e3d9fe0ce..1c254b105e7a 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -960,30 +960,41 @@ class TestRunEvaluationWorkflow:evaluation.refresh_from_db()assert evaluation.enabled is True- @pytest.mark.django_db(transaction=True)- def test_execute_llm_judge_activity_parse_error_raises_non_retryable(self, setup_data):- evaluation_obj = setup_data["evaluation"]- team = setup_data["team"]-+ def test_execute_llm_judge_activity_parse_error_raises_non_retryable(self):evaluation = {- "id": str(evaluation_obj.id),+ "id": "eval-123","name": "Test Evaluation","evaluation_type": "llm_judge","evaluation_config": {"prompt": "Is this response factually accurate?"},"output_type": "boolean","output_config": {},- "team_id": team.id,+ "team_id": 1,+ "model_configuration": {+ "provider": "openai",+ "model": "gpt-4.1",+ "provider_key_id": None,+ },}event_data = create_mock_event_data(- team.id,+ 1,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:+ with (+ patch(+ "posthog.temporal.ai_observability.model_resolution.EvaluationConfig.objects.get_or_create"+ ) as mock_get_or_create,+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class,+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.increment_errors") as mock_increment_errors,+ ):+ mock_get_or_create.return_value = (+ MagicMock(active_provider_key=None, trial_evals_used=0, trial_eval_limit=100),+ False,+ )mock_client = MagicMock()mock_client_class.return_value = mock_clientmock_client.complete.side_effect = StructuredOutputParseError(@@ -993,8 +1004,9 @@ class TestRunEvaluationWorkflow:with pytest.raises(ApplicationError, match="Failed to parse structured output") as exc_info:execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))- assert exc_info.value.non_retryable is True- assert exc_info.value.details[0] == {"error_type": "parse_error"}+ mock_increment_errors.assert_called_once_with("parse_error", provider="openai")+ assert exc_info.value.non_retryable is True+ assert exc_info.value.details[0] == {"error_type": "parse_error"}@pytest.mark.parametrize("raised_exception, expected_label",@@ -1387,25 +1399,48 @@ class TestExecuteHogEvalActivity:assert "Global variable not found" in result["reasoning"]@pytest.mark.asyncio- @pytest.mark.django_db(transaction=True)- async def test_hog_eval_unexpected_error_raises(self, setup_data):- team = setup_data["team"]+ async def test_hog_eval_length_null_returns_skipped(self):+ from posthog.cdp.validation import compile_hog++ bytecode = compile_hog("return length(null) > 0", "destination")+ evaluation = {+ "id": "eval-id",+ "name": "Hog Eval",+ "evaluation_type": "hog",+ "evaluation_config": {"source": "return length(null) > 0", "bytecode": bytecode},+ "output_type": "boolean",+ "output_config": {},+ "team_id": 1,+ }+ result = await execute_hog_eval_activity(evaluation, create_mock_event_data(1))++ assert result["skipped"] is True+ assert result["skip_reason"] == "hog_error"+ assert result["terminal_user_error"] is True+ assert result["status_reason"] == "hog_error"+ assert result["verdict"] is False+ assert "Runtime error: Can not call length on null" in result["reasoning"]+ assert "TypeError" not in result["reasoning"]+ assert "NoneType" not in result["reasoning"]++ @pytest.mark.asyncio+ async def test_hog_eval_unexpected_error_raises(self):from posthog.cdp.validation import compile_hogbytecode = compile_hog("return true", "destination")evaluation = {- "id": str(setup_data["evaluation"].id),+ "id": "eval-id","name": "Hog Eval","evaluation_type": "hog","evaluation_config": {"source": "return true", "bytecode": bytecode},"output_type": "boolean","output_config": {},- "team_id": team.id,+ "team_id": 1,}- event_data = create_mock_event_data(team.id)+ event_data = create_mock_event_data(1)# An unexpected error is a bug in our code, so it must still surface to error tracking.unexpected_error = {diff --git a/products/ai_observability/backend/llm/providers/anthropic.py b/products/ai_observability/backend/llm/providers/anthropic.pyindex f67ebcb86fed..47ea9b3eca69 100644--- a/products/ai_observability/backend/llm/providers/anthropic.py+++ b/products/ai_observability/backend/llm/providers/anthropic.py@@ -31,6 +31,11 @@ from products.ai_observability.backend.llm.types import (logger = logging.getLogger(__name__)+def _is_quota_or_billing_error(error: Exception) -> bool:+ error_message = str(error).lower()+ return any(token in error_message for token in ("quota", "credit", "billing"))++class AnthropicConfig:MAX_TOKENS: int = 8192MAX_THINKING_TOKENS: int = 4096@@ -175,11 +180,14 @@ class AnthropicAdapter:)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+ raiseexcept anthropic.RateLimitError as e:- error_message = str(e).lower()- if "quota" in error_message or "credit" in error_message or "billing" in error_message:- raise QuotaExceededError(str(e))- raise RateLimitError(str(e))+ if _is_quota_or_billing_error(e):+ raise QuotaExceededError(str(e)) from e+ raise RateLimitError(str(e)) from edef stream(self,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 dff759617f77..bcfe4110ec16 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@@ -1,9 +1,11 @@import pytestfrom unittest.mock import MagicMock, patch+import httpx+import anthropicfrom pydantic import BaseModel-from products.ai_observability.backend.llm.errors import StructuredOutputParseError+from products.ai_observability.backend.llm.errors import QuotaExceededError, StructuredOutputParseErrorfrom products.ai_observability.backend.llm.providers.anthropic import AnthropicAdapterfrom products.ai_observability.backend.llm.types import AnalyticsContext, CompletionRequest@@ -224,3 +226,48 @@ class TestStructuredOutputComplete:assert result.parsed is not Noneassert isinstance(result.parsed, BooleanEvalResult)assert result.parsed.result is False+++def _make_anthropic_bad_request(message: str) -> anthropic.BadRequestError:+ body = {+ "type": "error",+ "error": {"type": "invalid_request_error", "message": message},+ "request_id": "req_test",+ }+ request = httpx.Request("POST", "https://api.anthropic.com/v1/messages")+ response = httpx.Response(400, request=request, json=body)+ return anthropic.BadRequestError(f"Error code: 400 - {body}", response=response, body=body)+++class TestAnthropicAdapterErrorMapping:+ def _make_request(self) -> CompletionRequest:+ return CompletionRequest(+ model="claude-haiku-4-5",+ messages=[{"role": "user", "content": "hi"}],+ provider="anthropic",+ system="s",+ )++ @patch("products.ai_observability.backend.llm.providers.anthropic.anthropic.Anthropic")+ def test_low_credit_bad_request_is_mapped_to_quota_exceeded(self, mock_anthropic_cls):+ mock_client = MagicMock()+ mock_client.messages.create.side_effect = _make_anthropic_bad_request(+ "Your credit balance is too low to access the Anthropic API."+ )+ mock_anthropic_cls.return_value = mock_client++ adapter = AnthropicAdapter()++ with pytest.raises(QuotaExceededError, match="credit balance"):+ adapter.complete(self._make_request(), api_key="sk-ant-test", analytics=AnalyticsContext(capture=False))++ @patch("products.ai_observability.backend.llm.providers.anthropic.anthropic.Anthropic")+ def test_other_bad_request_is_not_swallowed(self, mock_anthropic_cls):+ mock_client = MagicMock()+ mock_client.messages.create.side_effect = _make_anthropic_bad_request("Request payload is invalid.")+ mock_anthropic_cls.return_value = mock_client++ adapter = AnthropicAdapter()++ with pytest.raises(anthropic.BadRequestError, match="Request payload is invalid"):+ adapter.complete(self._make_request(), api_key="sk-ant-test", analytics=AnalyticsContext(capture=False))