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(llma): classify eval errors by exception class and provider (#58106)

Carlos Marchal056b223c59bb
diff --git a/posthog/temporal/llm_analytics/metrics.py b/posthog/temporal/llm_analytics/metrics.py
index 2dfe82e94e32..c088a6e46767 100644
--- a/posthog/temporal/llm_analytics/metrics.py
+++ b/posthog/temporal/llm_analytics/metrics.py
@@ -88,11 +88,18 @@ def increment_provider_model(provider: str, model: str) -> None:
counter.add(1)
-def increment_errors(error_type: str) -> None:
- """Track error categorization. Safe to call outside Temporal context (no-ops)."""
+def increment_errors(error_type: str, *, provider: str | None = None) -> None:
+ """Track error categorization. Safe to call outside Temporal context (no-ops).
+
+ Pass `provider` so dashboards can isolate a single misbehaving upstream
+ (e.g. an OpenAI 5xx storm) without grepping logs.
+ """
if not activity.in_activity() and not workflow.in_workflow():
return
- meter = get_metric_meter({"error_type": error_type})
+ attrs: dict[str, str | int | float | bool] = {"error_type": error_type}
+ if provider is not None:
+ attrs["provider"] = provider
+ meter = get_metric_meter(attrs)
counter = meter.create_counter("llma_eval_errors", "Error counts by type")
counter.add(1)
@@ -288,5 +295,4 @@ class _EvalsMetricsWorkflowInterceptor(WorkflowInboundInterceptor):
except Exception:
status = "FAILED"
increment_workflow_finished(status)
- increment_errors("workflow_exception")
raise
diff --git a/posthog/temporal/llm_analytics/run_evaluation.py b/posthog/temporal/llm_analytics/run_evaluation.py
index baf9d081fe18..aba45711e8a6 100644
--- a/posthog/temporal/llm_analytics/run_evaluation.py
+++ b/posthog/temporal/llm_analytics/run_evaluation.py
@@ -706,7 +706,7 @@ async def execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> LLMJudgeR
)
)
except AuthenticationError:
- increment_errors("auth_error")
+ increment_errors("auth_error", provider=provider)
if is_byok:
raise ApplicationError(
"API key is invalid or has been deleted.",
@@ -715,7 +715,7 @@ async def execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> LLMJudgeR
)
raise
except ModelPermissionError:
- increment_errors("permission_error")
+ increment_errors("permission_error", provider=provider)
if is_byok:
raise ApplicationError(
"API key doesn't have access to this model.",
@@ -724,7 +724,7 @@ async def execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> LLMJudgeR
)
raise
except QuotaExceededError:
- increment_errors("quota_error")
+ increment_errors("quota_error", provider=provider)
if is_byok:
raise ApplicationError(
"API key has exceeded its quota.",
@@ -733,7 +733,7 @@ async def execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> LLMJudgeR
)
raise
except RateLimitError:
- increment_errors("rate_limit")
+ increment_errors("rate_limit", provider=provider)
if is_byok:
raise ApplicationError(
"API key is being rate limited.",
@@ -742,21 +742,28 @@ async def execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> LLMJudgeR
)
raise
except ModelNotFoundError:
- increment_errors("model_not_found")
+ increment_errors("model_not_found", provider=provider)
raise ApplicationError(
f"Model '{model}' not found.",
non_retryable=True,
)
except StructuredOutputParseError as e:
- increment_errors("parse_error")
+ increment_errors("parse_error", provider=provider)
raise ApplicationError(
str(e),
{"error_type": "parse_error"},
non_retryable=True,
) from e
- except Exception:
- increment_errors("unknown_error")
+ except Exception as e:
+ logger.exception(
+ "Unhandled error from LLM client",
+ evaluation_id=evaluation["id"],
+ provider=provider,
+ model=model,
+ error_class=type(e).__name__,
+ )
+ increment_errors(type(e).__name__, provider=provider)
raise
# Parse structured output
@@ -1282,7 +1289,7 @@ class RunEvaluationWorkflow(PostHogWorkflow):
retry_policy=RetryPolicy(maximum_attempts=3),
)
except Exception:
- increment_errors("emit_evaluation_event_failed")
+ increment_errors("emit_evaluation_event_failed", provider=result.get("provider"))
raise
# Activity 5: Emit internal telemetry (fire-and-forget). Internal telemetry tracks model,
diff --git a/posthog/temporal/llm_analytics/test_run_evaluation.py b/posthog/temporal/llm_analytics/test_run_evaluation.py
index 60d87b5e07a9..6b8a16b9c52c 100644
--- a/posthog/temporal/llm_analytics/test_run_evaluation.py
+++ b/posthog/temporal/llm_analytics/test_run_evaluation.py
@@ -681,6 +681,46 @@ class TestRunEvaluationWorkflow:
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",
+ [
+ pytest.param(RuntimeError("network down"), "RuntimeError", id="runtime_error"),
+ pytest.param(ValueError("bad payload"), "ValueError", id="value_error"),
+ pytest.param(TimeoutError("read timeout"), "TimeoutError", id="timeout_error"),
+ ],
+ )
+ @pytest.mark.asyncio
+ @pytest.mark.django_db(transaction=True)
+ async def test_execute_llm_judge_activity_unhandled_exception_uses_class_name(
+ self, raised_exception: Exception, expected_label: str, setup_data
+ ):
+ evaluation_obj = setup_data["evaluation"]
+ team = setup_data["team"]
+
+ evaluation = {
+ "id": str(evaluation_obj.id),
+ "name": "Test Evaluation",
+ "evaluation_type": "llm_judge",
+ "evaluation_config": {"prompt": "Is this accurate?"},
+ "output_type": "boolean",
+ "output_config": {},
+ "team_id": team.id,
+ }
+ event_data = create_mock_event_data(team.id)
+
+ with (
+ patch("posthog.temporal.llm_analytics.run_evaluation.Client") as mock_client_class,
+ patch("posthog.temporal.llm_analytics.run_evaluation.increment_errors") as mock_increment_errors,
+ ):
+ mock_client = MagicMock()
+ mock_client_class.return_value = mock_client
+ mock_client.complete.side_effect = raised_exception
+
+ with pytest.raises(type(raised_exception)):
+ await execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))
+
+ mock_increment_errors.assert_called_once_with(expected_label, provider="openai")
+
@pytest.mark.asyncio
@pytest.mark.django_db(transaction=True)
async def test_execute_llm_judge_activity_rejects_non_trial_model_on_posthog_key(self, setup_data):