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): make null eval and tagger model config provider-aware (#65185)

Carlos Marchal25a5ae9f53da
diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.py
index 7251a36e2b10..7952b5588af6 100644
--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py
+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py
@@ -3,8 +3,6 @@ from dataclasses import dataclass
from datetime import timedelta
from typing import Any
-from django.utils import timezone
-
import structlog
import temporalio
import posthoganalytics
@@ -22,8 +20,9 @@ from posthog.temporal.ai_observability.metrics import (
increment_provider_model,
increment_tokens,
)
+from posthog.temporal.ai_observability.model_resolution import model_spec
-from products.ai_observability.backend.llm import TRIAL_MODEL_IDS, Client, CompletionRequest
+from products.ai_observability.backend.llm import DEFAULT_MODEL_BY_PROVIDER, Client, CompletionRequest
from products.ai_observability.backend.llm.config import get_eval_config
from products.ai_observability.backend.llm.errors import (
AuthenticationError,
@@ -33,12 +32,10 @@ from products.ai_observability.backend.llm.errors import (
RateLimitError,
StructuredOutputParseError,
)
-from products.ai_observability.backend.models.evaluation_config import EvaluationConfig
-from products.ai_observability.backend.models.provider_keys import LLMProviderKey
logger = structlog.get_logger(__name__)
-DEFAULT_JUDGE_MODEL = "gpt-5-mini"
+DEFAULT_JUDGE_MODEL = DEFAULT_MODEL_BY_PROVIDER["openai"]
LLM_JUDGE_RETRY_POLICY = RetryPolicy(
maximum_attempts=3,
@@ -212,82 +209,11 @@ def _execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> EvaluationActi
return _build_errored_trace_result(allows_na)
team_id = evaluation["team_id"]
- model_configuration = evaluation.get("model_configuration")
-
- def _get_legacy_provider_key() -> LLMProviderKey | None:
- config, _ = EvaluationConfig.objects.get_or_create(team_id=team_id)
-
- if config.active_provider_key:
- key = config.active_provider_key
- if key.state == LLMProviderKey.State.OK:
- key.last_used_at = timezone.now()
- key.save(update_fields=["last_used_at"])
- return key
- raise ApplicationError(
- f"This API key has been disabled (status: {key.state}). Re-validate to recover, or replace it.",
- {"error_type": "key_invalid", "key_id": str(key.id), "key_state": key.state},
- non_retryable=True,
- )
-
- if config.trial_evals_used >= config.trial_eval_limit:
- raise ApplicationError(
- f"Trial evaluation limit ({config.trial_eval_limit}) reached. Add your own API key to continue.",
- {"error_type": "trial_limit_reached", "trial_eval_limit": config.trial_eval_limit},
- non_retryable=True,
- )
-
- return None
-
- def _get_provider_key_by_id(key_id: str) -> LLMProviderKey:
- try:
- key = LLMProviderKey.objects.get(id=key_id, team_id=team_id)
- if key.state != LLMProviderKey.State.OK:
- raise ApplicationError(
- f"This API key has been disabled (status: {key.state}). Re-validate to recover, or replace it.",
- {"error_type": "key_invalid", "key_id": str(key.id), "key_state": key.state},
- non_retryable=True,
- )
- key.last_used_at = timezone.now()
- key.save(update_fields=["last_used_at"])
- return key
- except LLMProviderKey.DoesNotExist:
- raise ApplicationError(
- "Provider key not found.",
- {"error_type": "key_not_found", "key_id": key_id},
- non_retryable=True,
- )
-
- def _check_trial_quota() -> None:
- config, _ = EvaluationConfig.objects.get_or_create(team_id=team_id)
- if config.trial_evals_used >= config.trial_eval_limit:
- raise ApplicationError(
- f"Trial evaluation limit ({config.trial_eval_limit}) reached. Add your own API key to continue.",
- {"error_type": "trial_limit_reached", "trial_eval_limit": config.trial_eval_limit},
- non_retryable=True,
- )
-
- if model_configuration:
- provider = model_configuration["provider"]
- model = model_configuration["model"]
- provider_key_id = model_configuration.get("provider_key_id")
-
- if provider_key_id:
- provider_key = _get_provider_key_by_id(provider_key_id)
- else:
- if model not in TRIAL_MODEL_IDS:
- raise ApplicationError(
- f"Model '{model}' is not available on the trial plan. Please add your own API key to use this model.",
- {"error_type": "model_not_allowed", "model": model},
- non_retryable=True,
- )
- _check_trial_quota()
- provider_key = None
- else:
- provider = "openai"
- model = DEFAULT_JUDGE_MODEL
- provider_key = _get_legacy_provider_key()
-
- is_byok = provider_key is not None
+ resolved = model_spec(evaluation.get("model_configuration")).resolve(team_id)
+ provider = resolved.provider
+ model = resolved.model
+ provider_key = resolved.provider_key
+ is_byok = resolved.is_byok
key_id = str(provider_key.id) if provider_key else None
input_raw, output_raw = extract_event_io(event_type, properties)
diff --git a/posthog/temporal/ai_observability/model_resolution.py b/posthog/temporal/ai_observability/model_resolution.py
new file mode 100644
index 000000000000..9431b2af92d7
--- /dev/null
+++ b/posthog/temporal/ai_observability/model_resolution.py
@@ -0,0 +1,134 @@
+"""Resolves which provider, model and key an eval or tagger run should use.
+
+`model_configuration` is optional on both `Evaluation` and `Tagger`. A null value is not
+"unconfigured" — it means "defer to the team's active key, falling back to PostHog trial
+credits". `model_spec()` turns the (possibly null) serialized config into a `ModelSpec`
+whose `resolve()` produces a concrete `ResolvedModel`, so judge and tagger share one
+definition of what null means instead of each re-deriving it.
+
+Lives in the temporal layer because `resolve()` raises Temporal `ApplicationError`s whose
+`error_type` details the workflows pattern-match on (disable, key-state updates, emails).
+"""
+
+from dataclasses import dataclass
+from typing import Any, Protocol
+
+from django.utils import timezone
+
+from temporalio.exceptions import ApplicationError
+
+from products.ai_observability.backend.llm import DEFAULT_MODEL_BY_PROVIDER, TRIAL_MODEL_IDS
+from products.ai_observability.backend.models.evaluation_config import EvaluationConfig
+from products.ai_observability.backend.models.provider_keys import LLMProviderKey
+
+# Provider PostHog funds when a team brought no key of its own. Its default model must stay
+# on the trial allowlist so the trial-quota path can never bill a model PostHog isn't paying for.
+TRIAL_DEFAULT_PROVIDER = "openai"
+assert DEFAULT_MODEL_BY_PROVIDER[TRIAL_DEFAULT_PROVIDER] in TRIAL_MODEL_IDS
+
+
+@dataclass(frozen=True)
+class ResolvedModel:
+ provider: str
+ model: str
+ provider_key: LLMProviderKey | None
+
+ @property
+ def is_byok(self) -> bool:
+ return self.provider_key is not None
+
+
+class ModelSpec(Protocol):
+ def resolve(self, team_id: int) -> ResolvedModel: ...
+
+
+@dataclass(frozen=True)
+class ExplicitModelSpec:
+ """The eval/tagger pinned its own provider and model. Trust the stored pairing."""
+
+ provider: str
+ model: str
+ provider_key_id: str | None
+
+ def resolve(self, team_id: int) -> ResolvedModel:
+ if self.provider_key_id:
+ return ResolvedModel(self.provider, self.model, _resolve_key_by_id(team_id, self.provider_key_id))
+
+ if self.model not in TRIAL_MODEL_IDS:
+ raise ApplicationError(
+ f"Model '{self.model}' is not available on the trial plan. "
+ "Please add your own API key to use this model.",
+ {"error_type": "model_not_allowed", "model": self.model},
+ non_retryable=True,
+ )
+ _assert_trial_quota(_eval_config(team_id))
+ return ResolvedModel(self.provider, self.model, None)
+
+
+@dataclass(frozen=True)
+class DefaultModelSpec:
+ """Null config: defer to the team's active BYOK key, else PostHog trial credits."""
+
+ def resolve(self, team_id: int) -> ResolvedModel:
+ config = _eval_config(team_id)
+ key = config.active_provider_key
+ if key is None:
+ _assert_trial_quota(config)
+ return ResolvedModel(TRIAL_DEFAULT_PROVIDER, DEFAULT_MODEL_BY_PROVIDER[TRIAL_DEFAULT_PROVIDER], None)
+
+ model = DEFAULT_MODEL_BY_PROVIDER.get(key.provider)
+ if model is None:
+ raise ApplicationError(
+ f"No default model is available for provider '{key.provider}'. Set a model on the evaluation.",
+ {"error_type": "no_default_model", "provider": key.provider},
+ non_retryable=True,
+ )
+ return ResolvedModel(key.provider, model, _ensure_usable(key))
+
+
+def model_spec(model_configuration: dict[str, Any] | None) -> ModelSpec:
+ if model_configuration:
+ return ExplicitModelSpec(
+ provider=model_configuration["provider"],
+ model=model_configuration["model"],
+ provider_key_id=model_configuration.get("provider_key_id"),
+ )
+ return DefaultModelSpec()
+
+
+def _eval_config(team_id: int) -> EvaluationConfig:
+ config, _ = EvaluationConfig.objects.get_or_create(team_id=team_id)
+ return config
+
+
+def _assert_trial_quota(config: EvaluationConfig) -> None:
+ if config.trial_evals_used >= config.trial_eval_limit:
+ raise ApplicationError(
+ f"Trial evaluation limit ({config.trial_eval_limit}) reached. Add your own API key to continue.",
+ {"error_type": "trial_limit_reached", "trial_eval_limit": config.trial_eval_limit},
+ non_retryable=True,
+ )
+
+
+def _resolve_key_by_id(team_id: int, key_id: str) -> LLMProviderKey:
+ try:
+ key = LLMProviderKey.objects.get(id=key_id, team_id=team_id)
+ except LLMProviderKey.DoesNotExist:
+ raise ApplicationError(
+ "Provider key not found.",
+ {"error_type": "key_not_found", "key_id": key_id},
+ non_retryable=True,
+ )
+ return _ensure_usable(key)
+
+
+def _ensure_usable(key: LLMProviderKey) -> LLMProviderKey:
+ if key.state != LLMProviderKey.State.OK:
+ raise ApplicationError(
+ f"This API key has been disabled (status: {key.state}). Re-validate to recover, or replace it.",
+ {"error_type": "key_invalid", "key_id": str(key.id), "key_state": key.state},
+ non_retryable=True,
+ )
+ key.last_used_at = timezone.now()
+ key.save(update_fields=["last_used_at"])
+ return key
diff --git a/posthog/temporal/ai_observability/run_evaluation.py b/posthog/temporal/ai_observability/run_evaluation.py
index 3c80a96a3f31..a4e99aa814e0 100644
--- a/posthog/temporal/ai_observability/run_evaluation.py
+++ b/posthog/temporal/ai_observability/run_evaluation.py
@@ -140,8 +140,14 @@ class RunEvaluationWorkflow(PostHogWorkflow):
details = e.cause.details[0]
error_type = details.get("error_type")
- if error_type in ("trial_limit_reached", "key_invalid", "parse_error", "model_not_allowed"):
- if error_type in ("trial_limit_reached", "model_not_allowed"):
+ if error_type in (
+ "trial_limit_reached",
+ "key_invalid",
+ "parse_error",
+ "model_not_allowed",
+ "no_default_model",
+ ):
+ if error_type in ("trial_limit_reached", "model_not_allowed", "no_default_model"):
await temporalio.workflow.execute_activity(
disable_evaluation_activity,
args=[evaluation["id"], evaluation["team_id"], error_type],
@@ -163,7 +169,7 @@ class RunEvaluationWorkflow(PostHogWorkflow):
"Failed to send trial exhausted email",
team_id=evaluation["team_id"],
)
- else:
+ elif error_type == "model_not_allowed":
if temporalio.workflow.patched("eval-disabled-email"):
model = details.get("model", "the selected model")
try:
diff --git a/posthog/temporal/ai_observability/run_tagger.py b/posthog/temporal/ai_observability/run_tagger.py
index 0b8ba90607e0..218bb6864774 100644
--- a/posthog/temporal/ai_observability/run_tagger.py
+++ b/posthog/temporal/ai_observability/run_tagger.py
@@ -21,10 +21,11 @@ from posthog.temporal.ai_observability.evaluation_workflow_activities import (
update_key_state_activity,
)
from posthog.temporal.ai_observability.message_utils import extract_text_from_messages
+from posthog.temporal.ai_observability.model_resolution import model_spec
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.scoped import scoped_temporal
-from products.ai_observability.backend.llm import TRIAL_MODEL_IDS, Client, CompletionRequest
+from products.ai_observability.backend.llm import DEFAULT_MODEL_BY_PROVIDER, Client, CompletionRequest
from products.ai_observability.backend.llm.config import get_eval_config
from products.ai_observability.backend.llm.errors import (
AuthenticationError,
@@ -34,18 +35,14 @@ from products.ai_observability.backend.llm.errors import (
RateLimitError,
StructuredOutputParseError,
)
-from products.ai_observability.backend.models.evaluation_config import EvaluationConfig
from products.ai_observability.backend.models.provider_keys import LLMProviderKey
from products.ai_observability.backend.models.taggers import Tagger
logger = structlog.get_logger(__name__)
-DEFAULT_TAGGER_MODEL = "gpt-5-mini"
-# Trial-funded fallback when no model_configuration is set — must stay on the allowlist
-# so a future default-model bump can't silently bypass the TRIAL_MODEL_IDS guard.
-assert DEFAULT_TAGGER_MODEL in TRIAL_MODEL_IDS, (
- f"DEFAULT_TAGGER_MODEL ({DEFAULT_TAGGER_MODEL}) must be in TRIAL_MODEL_IDS"
-)
+# Attribution fallback for $ai_tag events if a result omits its model. The model actually
+# used is resolved per-run by model_spec() (see posthog.temporal.ai_observability.model_resolution).
+DEFAULT_TAGGER_MODEL = DEFAULT_MODEL_BY_PROVIDER["openai"]
LLM_TAGGER_RETRY_POLICY = RetryPolicy(
maximum_attempts=3,
@@ -200,8 +197,6 @@ class ExecuteTaggerInputs:
@scoped_temporal()
async def execute_tagger_activity(inputs: ExecuteTaggerInputs) -> dict[str, Any]:
"""Execute LLM tagger to classify the target event."""
- from django.utils import timezone
-
tagger = inputs.tagger
event_data = inputs.event_data
@@ -217,63 +212,15 @@ async def execute_tagger_activity(inputs: ExecuteTaggerInputs) -> dict[str, Any]
min_tags = tagger_config.get("min_tags", 0)
max_tags = tagger_config.get("max_tags")
- # Resolve model configuration and API key
+ # Resolve model configuration and API key. A null model_configuration defers to the team's
+ # active key (provider-aware), matching execute_llm_judge_activity.
team_id = tagger["team_id"]
model_configuration = tagger.get("model_configuration")
-
- def _get_provider_key_by_id(key_id: str) -> LLMProviderKey:
- try:
- key = LLMProviderKey.objects.get(id=key_id, team_id=team_id)
- if key.state != LLMProviderKey.State.OK:
- raise ApplicationError(
- f"This API key has been disabled (status: {key.state}). Re-validate to recover, or replace it.",
- {"error_type": "key_invalid", "key_id": str(key.id), "key_state": key.state},
- non_retryable=True,
- )
- key.last_used_at = timezone.now()
- key.save(update_fields=["last_used_at"])
- return key
- except LLMProviderKey.DoesNotExist:
- raise ApplicationError(
- "Provider key not found.",
- {"error_type": "key_not_found", "key_id": key_id},
- non_retryable=True,
- )
-
- def _check_trial_quota() -> None:
- config, _ = EvaluationConfig.objects.get_or_create(team_id=team_id)
- if config.trial_evals_used >= config.trial_eval_limit:
- raise ApplicationError(
- f"Trial limit ({config.trial_eval_limit}) reached. Add your own API key to continue.",
- {"error_type": "trial_limit_reached", "trial_eval_limit": config.trial_eval_limit},
- non_retryable=True,
- )
-
- if model_configuration:
- provider = model_configuration["provider"]
- model = model_configuration["model"]
- provider_key_id = model_configuration.get("provider_key_id")
-
- if provider_key_id:
- provider_key = await database_sync_to_async(_get_provider_key_by_id)(provider_key_id)
- else:
- # Trial mode — enforce allowlist so teams can't run expensive non-trial
- # models on PostHog-funded credits. Matches the guard in execute_llm_judge_activity.
- if model not in TRIAL_MODEL_IDS:
- raise ApplicationError(
- f"Model '{model}' is not available on the trial plan. Please add your own API key to use this model.",
- {"error_type": "model_not_allowed", "model": model},
- non_retryable=True,
- )
- await database_sync_to_async(_check_trial_quota)()
- provider_key = None
- else:
- provider = "openai"
- model = DEFAULT_TAGGER_MODEL
- await database_sync_to_async(_check_trial_quota)()
- provider_key = None
-
- is_byok = provider_key is not None
+ resolved = await database_sync_to_async(lambda: model_spec(model_configuration).resolve(team_id))()
+ provider = resolved.provider
+ model = resolved.model
+ provider_key = resolved.provider_key
+ is_byok = resolved.is_byok
key_id = str(provider_key.id) if provider_key else None
# Build context from event
@@ -669,15 +616,24 @@ class RunTaggerWorkflow(PostHogWorkflow):
details = e.cause.details[0]
error_type = details.get("error_type")
- if error_type in ("trial_limit_reached", "key_invalid", "parse_error", "model_not_allowed"):
- if error_type in ("trial_limit_reached", "model_not_allowed"):
+ if error_type in (
+ "trial_limit_reached",
+ "key_invalid",
+ "parse_error",
+ "model_not_allowed",
+ "no_default_model",
+ ):
+ if error_type in ("trial_limit_reached", "model_not_allowed", "no_default_model"):
await temporalio.workflow.execute_activity(
disable_tagger_activity,
args=[tagger["id"], tagger["team_id"]],
schedule_to_close_timeout=timedelta(seconds=30),
retry_policy=RetryPolicy(maximum_attempts=2),
)
- if temporalio.workflow.patched("trial-usage-email"):
+ if error_type in (
+ "trial_limit_reached",
+ "model_not_allowed",
+ ) and temporalio.workflow.patched("trial-usage-email"):
try:
await temporalio.workflow.execute_activity(
send_trial_usage_email_activity,
diff --git a/posthog/temporal/ai_observability/test_model_resolution.py b/posthog/temporal/ai_observability/test_model_resolution.py
new file mode 100644
index 000000000000..32a1739fde7d
--- /dev/null
+++ b/posthog/temporal/ai_observability/test_model_resolution.py
@@ -0,0 +1,137 @@
+import uuid
+
+import pytest
+
+from temporalio.exceptions import ApplicationError
+
+from posthog.models import Organization, Team
+from posthog.temporal.ai_observability.model_resolution import DefaultModelSpec, ExplicitModelSpec, model_spec
+
+from products.ai_observability.backend.llm import DEFAULT_MODEL_BY_PROVIDER
+from products.ai_observability.backend.models.evaluation_config import EvaluationConfig
+from products.ai_observability.backend.models.provider_keys import LLMProviderKey
+
+
+def team():
+ organization = Organization.objects.create(name="Test Org")
+ return Team.objects.create(organization=organization, name="Test Team")
+
+
+def _key(team, provider, state=LLMProviderKey.State.OK):
+ return LLMProviderKey.objects.create(
+ team=team,
+ provider=provider,
+ name=f"{provider} key",
+ state=state,
+ encrypted_config={"api_key": "sk-test"},
+ )
+
+
+def _error_type(exc_info):
+ return exc_info.value.details[0]["error_type"]
+
+
+class TestModelSpecFactory:
+ def test_null_config_returns_default_spec(self):
+ assert isinstance(model_spec(None), DefaultModelSpec)
+
+ def test_present_config_returns_explicit_spec(self):
+ spec = model_spec({"provider": "openai", "model": "gpt-5-mini", "provider_key_id": None})
+ assert spec == ExplicitModelSpec(provider="openai", model="gpt-5-mini", provider_key_id=None)
+
+
+class TestExplicitModelSpec:
+ def test_byok_resolves_to_pinned_key_and_touches_last_used(self, team):
+ key = _key(team, "anthropic")
+ resolved = ExplicitModelSpec("anthropic", "claude-opus-4-8", str(key.id)).resolve(team.id)
+
+ assert resolved.provider == "anthropic"
+ assert resolved.model == "claude-opus-4-8"
+ assert resolved.provider_key == key
+ assert resolved.is_byok
+ key.refresh_from_db()
+ assert key.last_used_at is not None
+
+ def test_byok_missing_key_raises_key_not_found(self, team):
+ with pytest.raises(ApplicationError) as exc_info:
+ 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):
+ 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"
+
+ def test_trial_allowlisted_model_resolves_without_key(self, team):
+ resolved = ExplicitModelSpec("openai", "gpt-5-mini", None).resolve(team.id)
+ assert resolved.provider_key is None
+ assert not resolved.is_byok
+
+ def test_trial_non_allowlisted_model_raises_model_not_allowed(self, team):
+ with pytest.raises(ApplicationError) as exc_info:
+ ExplicitModelSpec("openai", "gpt-5", None).resolve(team.id)
+ assert _error_type(exc_info) == "model_not_allowed"
+
+ def test_trial_quota_exhausted_raises_trial_limit_reached(self, team):
+ EvaluationConfig.objects.create(team=team, trial_eval_limit=100, trial_evals_used=100)
+ with pytest.raises(ApplicationError) as exc_info:
+ ExplicitModelSpec("openai", "gpt-5-mini", None).resolve(team.id)
+ assert _error_type(exc_info) == "trial_limit_reached"
+
+
+class TestDefaultModelSpec:
+ def test_no_active_key_falls_back_to_posthog_trial(self, team):
+ resolved = DefaultModelSpec().resolve(team.id)
+ assert resolved.provider == "openai"
+ assert resolved.model == DEFAULT_MODEL_BY_PROVIDER["openai"]
+ assert resolved.provider_key is None
+ assert not resolved.is_byok
+
+ def test_no_active_key_with_exhausted_quota_raises_trial_limit_reached(self, team):
+ EvaluationConfig.objects.create(team=team, trial_eval_limit=100, trial_evals_used=100)
+ with pytest.raises(ApplicationError) as exc_info:
+ DefaultModelSpec().resolve(team.id)
+ assert _error_type(exc_info) == "trial_limit_reached"
+
+ def test_anthropic_active_key_resolves_to_anthropic_default(self, team):
+ # Regression: a null config with an Anthropic active key used to resolve to openai/gpt-5-mini
+ # and raise ProviderMismatchError on every generation. It must now follow the key's provider.
+ key = _key(team, "anthropic")
+ EvaluationConfig.objects.create(team=team, active_provider_key=key)
+
+ resolved = DefaultModelSpec().resolve(team.id)
+
+ assert resolved.provider == "anthropic"
+ assert resolved.model == DEFAULT_MODEL_BY_PROVIDER["anthropic"]
+ assert resolved.provider_key == key
+ assert resolved.is_byok
+
+ def test_gemini_active_key_resolves_to_gemini_default(self, team):
+ key = _key(team, "gemini")
+ EvaluationConfig.objects.create(team=team, active_provider_key=key)
+
+ resolved = DefaultModelSpec().resolve(team.id)
+
+ assert resolved.provider == "gemini"
+ assert resolved.model == DEFAULT_MODEL_BY_PROVIDER["gemini"]
+ assert resolved.provider_key == key
+
+ def test_active_key_for_provider_without_default_raises_no_default_model(self, team):
+ key = _key(team, "openrouter")
+ EvaluationConfig.objects.create(team=team, active_provider_key=key)
+
+ with pytest.raises(ApplicationError) as exc_info:
+ DefaultModelSpec().resolve(team.id)
+ assert _error_type(exc_info) == "no_default_model"
+
+ def test_disabled_active_key_raises_key_invalid(self, team):
+ key = _key(team, "anthropic", state=LLMProviderKey.State.INVALID)
+ EvaluationConfig.objects.create(team=team, active_provider_key=key)
+
+ with pytest.raises(ApplicationError) as exc_info:
+ DefaultModelSpec().resolve(team.id)
+ assert _error_type(exc_info) == "key_invalid"
diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.py
index b6dbc1e3fd4c..0eaf99928ab5 100644
--- a/posthog/temporal/ai_observability/test_run_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_evaluation.py
@@ -1619,7 +1619,7 @@ class TestJudgePromptAssembly:
with (
patch(
- "posthog.temporal.ai_observability.evaluation_llm_judge.EvaluationConfig.objects.get_or_create"
+ "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,
):
@@ -1673,7 +1673,7 @@ class TestJudgePromptAssembly:
with (
patch(
- "posthog.temporal.ai_observability.evaluation_llm_judge.EvaluationConfig.objects.get_or_create"
+ "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,
):
diff --git a/posthog/temporal/ai_observability/test_run_tagger.py b/posthog/temporal/ai_observability/test_run_tagger.py
index 0cec4c0271d8..49f413d7177a 100644
--- a/posthog/temporal/ai_observability/test_run_tagger.py
+++ b/posthog/temporal/ai_observability/test_run_tagger.py
@@ -178,8 +178,9 @@ class TestRunTaggerWorkflow:
mock_response.usage = MagicMock(input_tokens=100, output_tokens=20, total_tokens=120)
mock_client.complete.return_value = mock_response
- with patch("posthog.temporal.ai_observability.run_tagger.EvaluationConfig") as mock_eval_config:
+ with patch("posthog.temporal.ai_observability.model_resolution.EvaluationConfig") as mock_eval_config:
mock_config = MagicMock()
+ mock_config.active_provider_key = None
mock_config.trial_evals_used = 0
mock_config.trial_eval_limit = 100
mock_eval_config.objects.get_or_create.return_value = (mock_config, False)
@@ -219,8 +220,9 @@ class TestRunTaggerWorkflow:
mock_response.usage = MagicMock(input_tokens=10, output_tokens=5, total_tokens=15)
mock_client.complete.return_value = mock_response
- with patch("posthog.temporal.ai_observability.run_tagger.EvaluationConfig") as mock_eval_config:
+ with patch("posthog.temporal.ai_observability.model_resolution.EvaluationConfig") as mock_eval_config:
mock_config = MagicMock()
+ mock_config.active_provider_key = None
mock_config.trial_evals_used = 0
mock_config.trial_eval_limit = 100
mock_eval_config.objects.get_or_create.return_value = (mock_config, False)
@@ -261,8 +263,9 @@ class TestRunTaggerWorkflow:
mock_response.usage = MagicMock(input_tokens=10, output_tokens=5, total_tokens=15)
mock_client.complete.return_value = mock_response
- with patch("posthog.temporal.ai_observability.run_tagger.EvaluationConfig") as mock_eval_config:
+ with patch("posthog.temporal.ai_observability.model_resolution.EvaluationConfig") as mock_eval_config:
mock_config = MagicMock()
+ mock_config.active_provider_key = None
mock_config.trial_evals_used = 0
mock_config.trial_eval_limit = 100
mock_eval_config.objects.get_or_create.return_value = (mock_config, False)
@@ -287,13 +290,14 @@ class TestRunTaggerWorkflow:
event_data = create_mock_event_data(team.id)
- with patch("posthog.temporal.ai_observability.run_tagger.EvaluationConfig") as mock_eval_config:
+ with patch("posthog.temporal.ai_observability.model_resolution.EvaluationConfig") as mock_eval_config:
mock_config = MagicMock()
+ mock_config.active_provider_key = None
mock_config.trial_evals_used = 100
mock_config.trial_eval_limit = 100
mock_eval_config.objects.get_or_create.return_value = (mock_config, False)
- with pytest.raises(ApplicationError, match="Trial limit"):
+ with pytest.raises(ApplicationError, match="Trial evaluation limit"):
await execute_tagger_activity(ExecuteTaggerInputs(tagger=tagger, event_data=event_data))
@pytest.mark.asyncio
diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.py
index e5635eecc94c..75ed392d7f96 100644
--- a/products/ai_observability/backend/api/evaluations.py
+++ b/products/ai_observability/backend/api/evaluations.py
@@ -341,6 +341,19 @@ class EvaluationSerializer(serializers.ModelSerializer):
}
)
+ # No default model: the team's active key is for a provider we have no default model for, and
+ # the eval left its model unset. Require an explicit model so it can't immediately re-disable.
+ if status_reason == "no_default_model":
+ has_model_configuration = bool(data.get("model_configuration")) or bool(
+ self.instance and self.instance.model_configuration_id
+ )
+ if not has_model_configuration:
+ raise serializers.ValidationError(
+ {
+ "enabled": "This evaluation's provider has no default model. Set a model on the evaluation before re-enabling."
+ }
+ )
+
def _has_byok_key(self, data: dict) -> bool:
"""Check if the evaluation will have a BYOK key after this update."""
model_config_data = data.get("model_configuration")
diff --git a/products/ai_observability/backend/llm/__init__.py b/products/ai_observability/backend/llm/__init__.py
index 7e70892fad84..d9eb8b362ae1 100644
--- a/products/ai_observability/backend/llm/__init__.py
+++ b/products/ai_observability/backend/llm/__init__.py
@@ -60,6 +60,12 @@ TRIAL_MODELS_BY_PROVIDER: dict[str, list[str]] = {
display_name.lower(): config.TRIAL_MODELS for display_name, config in PROVIDERS
}
+# Model picked when an eval/tagger has no explicit model_configuration and the provider is
+# dictated by the team's active key (e.g. an Anthropic BYOK key implies an Anthropic model).
+DEFAULT_MODEL_BY_PROVIDER: dict[str, str] = {
+ display_name.lower(): config.DEFAULT_MODEL for display_name, config in PROVIDERS
+}
+
__all__ = [
"Client",
@@ -75,6 +81,7 @@ __all__ = [
"SUPPORTED_MODELS_WITH_THINKING",
"TRIAL_MODEL_IDS",
"TRIAL_MODELS_BY_PROVIDER",
+ "DEFAULT_MODEL_BY_PROVIDER",
"get_default_models",
"get_trial_models",
"OpenAIConfig",
diff --git a/products/ai_observability/backend/llm/providers/anthropic.py b/products/ai_observability/backend/llm/providers/anthropic.py
index 8566a5dfedd8..f67ebcb86fed 100644
--- a/products/ai_observability/backend/llm/providers/anthropic.py
+++ b/products/ai_observability/backend/llm/providers/anthropic.py
@@ -59,6 +59,8 @@ class AnthropicConfig:
"claude-haiku-4-5",
]
+ DEFAULT_MODEL: str = "claude-haiku-4-5"
+
SUPPORTED_MODELS_WITH_CACHE_CONTROL: list[str] = [
"claude-opus-4-8",
"claude-opus-4-7",
diff --git a/products/ai_observability/backend/llm/providers/gemini.py b/products/ai_observability/backend/llm/providers/gemini.py
index b04fe70cae73..452339bee23f 100644
--- a/products/ai_observability/backend/llm/providers/gemini.py
+++ b/products/ai_observability/backend/llm/providers/gemini.py
@@ -62,6 +62,8 @@ class GeminiConfig:
"gemini-1.5-flash",
]
+ DEFAULT_MODEL: str = "gemini-2.5-flash"
+
class GeminiAdapter:
"""Gemini provider implementing the unified Client interface."""
diff --git a/products/ai_observability/backend/llm/providers/openai.py b/products/ai_observability/backend/llm/providers/openai.py
index d1aa124441bd..aa83407953bd 100644
--- a/products/ai_observability/backend/llm/providers/openai.py
+++ b/products/ai_observability/backend/llm/providers/openai.py
@@ -82,6 +82,8 @@ class OpenAIConfig:
"o4-mini",
]
+ DEFAULT_MODEL: str = "gpt-5-mini"
+
SUPPORTED_MODELS_WITH_THINKING: list[str] = [
"gpt-5.4",
"gpt-5.2",
diff --git a/products/ai_observability/backend/migrations/0008_alter_evaluation_status_reason.py b/products/ai_observability/backend/migrations/0008_alter_evaluation_status_reason.py
new file mode 100644
index 000000000000..5855f0a02f91
--- /dev/null
+++ b/products/ai_observability/backend/migrations/0008_alter_evaluation_status_reason.py
@@ -0,0 +1,28 @@
+# Generated by Django 5.2.14 on 2026-06-22 10:51
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("ai_observability", "0007_retire_reports_for_deleted_evaluations")]
+
+ operations = [
+ migrations.AlterField(
+ model_name="evaluation",
+ name="status_reason",
+ field=models.CharField(
+ blank=True,
+ choices=[
+ ("trial_limit_reached", "Trial evaluation limit reached"),
+ ("model_not_allowed", "Model not available on the trial plan"),
+ ("provider_key_deleted", "Provider API key was deleted"),
+ (
+ "no_default_model",
+ "No default model available for the selected provider",
+ ),
+ ],
+ max_length=50,
+ null=True,
+ ),
+ ),
+ ]
diff --git a/products/ai_observability/backend/migrations/max_migration.txt b/products/ai_observability/backend/migrations/max_migration.txt
index f026d25f2d16..f2d21a21035a 100644
--- a/products/ai_observability/backend/migrations/max_migration.txt
+++ b/products/ai_observability/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0007_retire_reports_for_deleted_evaluations
+0008_alter_evaluation_status_reason
diff --git a/products/ai_observability/backend/models/evaluations.py b/products/ai_observability/backend/models/evaluations.py
index e8429b04da05..21433f5af298 100644
--- a/products/ai_observability/backend/models/evaluations.py
+++ b/products/ai_observability/backend/models/evaluations.py
@@ -33,6 +33,7 @@ class EvaluationStatusReason(models.TextChoices):
TRIAL_LIMIT_REACHED = "trial_limit_reached", "Trial evaluation limit reached"
MODEL_NOT_ALLOWED = "model_not_allowed", "Model not available on the trial plan"
PROVIDER_KEY_DELETED = "provider_key_deleted", "Provider API key was deleted"
+ NO_DEFAULT_MODEL = "no_default_model", "No default model available for the selected provider"
class Evaluation(ModelActivityMixin, UUIDTModel):
diff --git a/products/ai_observability/frontend/evaluations/statusDisplay.test.ts b/products/ai_observability/frontend/evaluations/statusDisplay.test.ts
index 9e4953ffcc8a..08909693e451 100644
--- a/products/ai_observability/frontend/evaluations/statusDisplay.test.ts
+++ b/products/ai_observability/frontend/evaluations/statusDisplay.test.ts
@@ -5,6 +5,7 @@ describe('statusReasonLabel', () => {
['trial_limit_reached' as const, 'Trial evaluation limit reached'],
['model_not_allowed' as const, 'Model not available on the trial plan'],
['provider_key_deleted' as const, 'Provider API key was deleted'],
+ ['no_default_model' as const, 'No default model available for the selected provider'],
])('maps %s to user-facing copy', (reason, expected) => {
expect(statusReasonLabel(reason)).toBe(expected)
})
diff --git a/products/ai_observability/frontend/evaluations/statusDisplay.ts b/products/ai_observability/frontend/evaluations/statusDisplay.ts
index d665b2b69722..6dc8609959b0 100644
--- a/products/ai_observability/frontend/evaluations/statusDisplay.ts
+++ b/products/ai_observability/frontend/evaluations/statusDisplay.ts
@@ -4,6 +4,7 @@ const REASON_LABELS: Record<EvaluationStatusReason, string> = {
trial_limit_reached: 'Trial evaluation limit reached',
model_not_allowed: 'Model not available on the trial plan',
provider_key_deleted: 'Provider API key was deleted',
+ no_default_model: 'No default model available for the selected provider',
}
export function statusReasonLabel(reason: EvaluationStatusReason | null | undefined): string {
diff --git a/products/ai_observability/frontend/evaluations/types.ts b/products/ai_observability/frontend/evaluations/types.ts
index df25bb1b3883..429a92955fe1 100644
--- a/products/ai_observability/frontend/evaluations/types.ts
+++ b/products/ai_observability/frontend/evaluations/types.ts
@@ -5,7 +5,11 @@ import { LLMProvider } from '../settings/llmProviderKeysLogic'
export type EvaluationType = 'llm_judge' | 'hog' | 'sentiment'
export type EvaluationOutputType = 'boolean' | 'sentiment'
export type EvaluationStatus = 'active' | 'paused' | 'error'
-export type EvaluationStatusReason = 'trial_limit_reached' | 'model_not_allowed' | 'provider_key_deleted'
+export type EvaluationStatusReason =
+ | 'trial_limit_reached'
+ | 'model_not_allowed'
+ | 'provider_key_deleted'
+ | 'no_default_model'
export interface ModelConfiguration {
provider: LLMProvider
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index f5748cc85da0..871eee56f97b 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -329,6 +329,7 @@ export const EvaluationStatusEnumApi = {
* * `trial_limit_reached` - Trial evaluation limit reached
* * `model_not_allowed` - Model not available on the trial plan
* * `provider_key_deleted` - Provider API key was deleted
+ * * `no_default_model` - No default model available for the selected provider
*/
export type StatusReasonEnumApi = (typeof StatusReasonEnumApi)[keyof typeof StatusReasonEnumApi]
@@ -336,6 +337,7 @@ export const StatusReasonEnumApi = {
TrialLimitReached: 'trial_limit_reached',
ModelNotAllowed: 'model_not_allowed',
ProviderKeyDeleted: 'provider_key_deleted',
+ NoDefaultModel: 'no_default_model',
} as const
/**
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 61d7c3ed6dce..be7c67b67287 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -19649,6 +19649,7 @@ export namespace Schemas {
* * `trial_limit_reached` - Trial evaluation limit reached
* * `model_not_allowed` - Model not available on the trial plan
* * `provider_key_deleted` - Provider API key was deleted
+ * * `no_default_model` - No default model available for the selected provider
*/
export type StatusReasonEnum = typeof StatusReasonEnum[keyof typeof StatusReasonEnum];
@@ -19657,6 +19658,7 @@ export namespace Schemas {
TrialLimitReached: 'trial_limit_reached',
ModelNotAllowed: 'model_not_allowed',
ProviderKeyDeleted: 'provider_key_deleted',
+ NoDefaultModel: 'no_default_model',
} as const;
/**