: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
chore(aio): remove trial evaluations (#71518)
Carlos Marchalfb633ba8189e
diff --git a/posthog/settings/base_variables.py b/posthog/settings/base_variables.pyindex 81108fdacc3d..148a9c1f916b 100644--- a/posthog/settings/base_variables.py+++ b/posthog/settings/base_variables.py@@ -1,6 +1,5 @@import osimport sys-from datetime import datetimeimport structlog@@ -73,14 +72,6 @@ LLM_ANALYTICS_INTERNAL_TEAM_ID: int = 2# Must hold the same value in both regions; unset disables the proxy.PERSONAL_SPEND_CROSS_REGION_SECRET: str = get_from_env("PERSONAL_SPEND_CROSS_REGION_SECRET", "")-# Override for the AI observability trial-eval deprecation cutoff-AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE: str | None = get_from_env(- "AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE", optional=True-)-if AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE:- # Fail at boot on a malformed value rather than 500ing requests and temporal runs later.- datetime.fromisoformat(AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE)-# Duckgres - URL, internal secret, and PG endpoint for the managed warehouse serviceDUCKGRES_API_URL: str | None = get_from_env("DUCKGRES_API_URL", optional=True)DUCKGRES_INTERNAL_SECRET: str | None = get_from_env("DUCKGRES_INTERNAL_SECRET", optional=True)diff --git a/posthog/tasks/ai_observability_usage_report.py b/posthog/tasks/ai_observability_usage_report.pyindex 542f97050c39..9f4d258f9192 100644--- a/posthog/tasks/ai_observability_usage_report.py+++ b/posthog/tasks/ai_observability_usage_report.py@@ -92,7 +92,6 @@ class TeamMetrics:ai_feedback_count: int = 0ai_evaluation_count: int = 0ai_is_error_count: int = 0- ai_trial_evaluation_count: int = 0ai_llm_judge_evaluation_count: int = 0ai_hog_evaluation_count: int = 0ai_sentiment_evaluation_count: int = 0@@ -341,13 +340,10 @@ def _combine_all_metrics_results(results_list: list) -> dict[int, TeamMetrics]:# Error count (index 26)metrics.ai_is_error_count += row[26] or 0- # Trial evaluation count (index 27)- metrics.ai_trial_evaluation_count += row[27] or 0-- # Evaluation runtime counts (indices 28-30)- metrics.ai_llm_judge_evaluation_count += row[28] or 0- metrics.ai_hog_evaluation_count += row[29] or 0- metrics.ai_sentiment_evaluation_count += row[30] or 0+ # Evaluation runtime counts (indices 27-29)+ metrics.ai_llm_judge_evaluation_count += row[27] or 0+ metrics.ai_hog_evaluation_count += row[28] or 0+ metrics.ai_sentiment_evaluation_count += row[29] or 0return team_metrics@@ -408,7 +404,6 @@ def get_all_ai_metrics(-- Error countcountIf({prop("$ai_is_error")} = 'true') as ai_is_error_count,-- Evaluation counts- countIf(event = '$ai_evaluation' AND {prop("$ai_evaluation_key_type")} = 'posthog') as ai_trial_evaluation_count,countIf(event = '$ai_evaluation' AND {prop("$ai_evaluation_runtime")} = 'llm_judge') as ai_llm_judge_evaluation_count,countIf(event = '$ai_evaluation' AND {prop("$ai_evaluation_runtime")} = 'hog') as ai_hog_evaluation_count,countIf(event = '$ai_evaluation' AND {prop("$ai_evaluation_runtime")} = 'sentiment') as ai_sentiment_evaluation_count@@ -799,7 +794,6 @@ def _get_all_ai_observability_reports("ai_feedback_count": 0,"ai_evaluation_count": 0,"ai_is_error_count": 0,- "ai_trial_evaluation_count": 0,"ai_llm_judge_evaluation_count": 0,"ai_hog_evaluation_count": 0,"ai_sentiment_evaluation_count": 0,@@ -847,7 +841,6 @@ def _get_all_ai_observability_reports(report["ai_feedback_count"] += metrics.ai_feedback_countreport["ai_evaluation_count"] += metrics.ai_evaluation_countreport["ai_is_error_count"] += metrics.ai_is_error_count- report["ai_trial_evaluation_count"] += metrics.ai_trial_evaluation_countreport["ai_llm_judge_evaluation_count"] += metrics.ai_llm_judge_evaluation_countreport["ai_hog_evaluation_count"] += metrics.ai_hog_evaluation_countreport["ai_sentiment_evaluation_count"] += metrics.ai_sentiment_evaluation_countdiff --git a/posthog/tasks/test/test_ai_observability_usage_report.py b/posthog/tasks/test/test_ai_observability_usage_report.pyindex e5446416c6b2..d52995a0bb17 100644--- a/posthog/tasks/test/test_ai_observability_usage_report.py+++ b/posthog/tasks/test/test_ai_observability_usage_report.py@@ -12,8 +12,6 @@ from posthog.test.base import ()from unittest.mock import MagicMock, patch-from parameterized import parameterized-from posthog.clickhouse.client import sync_executefrom posthog.models import Organization, Teamfrom posthog.models.event.util import create_event@@ -141,7 +139,6 @@ class TestAIObservabilityUsageReport(APIBaseTest, ClickhouseTestMixin, Clickhousassert metrics.ai_metric_count == 1assert metrics.ai_feedback_count == 4assert metrics.ai_evaluation_count == 6- assert metrics.ai_trial_evaluation_count == 3assert metrics.ai_llm_judge_evaluation_count == 3assert metrics.ai_hog_evaluation_count == 2assert metrics.ai_sentiment_evaluation_count == 1@@ -568,7 +565,6 @@ class TestAIObservabilityUsageReport(APIBaseTest, ClickhouseTestMixin, Clickhousassert org_1_report["organization_name"] == self.organization.nameassert org_1_report["ai_generation_count"] == 13 # 10 + 3assert org_1_report["ai_evaluation_count"] == 5- assert org_1_report["ai_trial_evaluation_count"] == 3assert org_1_report["ai_llm_judge_evaluation_count"] == 3assert org_1_report["ai_hog_evaluation_count"] == 1assert org_1_report["ai_sentiment_evaluation_count"] == 1@@ -726,7 +722,6 @@ class TestAIObservabilityUsageReport(APIBaseTest, ClickhouseTestMixin, Clickhous# Counts should be aggregated across both teamsassert org_report["ai_generation_count"] == 15 # 10 + 5assert org_report["ai_evaluation_count"] == 5 # 3 + 2- assert org_report["ai_trial_evaluation_count"] == 3assert org_report["ai_llm_judge_evaluation_count"] == 3assert org_report["ai_hog_evaluation_count"] == 0assert org_report["ai_sentiment_evaluation_count"] == 2@@ -1099,46 +1094,3 @@ class TestAIObservabilityUsageReport(APIBaseTest, ClickhouseTestMixin, Clickhousreport_dict = call_args[1]["report_dict"]assert report_dict["ai_generation_count"] == 5assert report_dict["ai_embedding_count"] == 0 # Jan 9th events not included-- @parameterized.expand(- [- ("mixed", 5, 3, 2, 5),- ("only_byok", 0, 4, 0, 0),- ("only_posthog", 3, 0, 0, 3),- ("no_key_type", 0, 0, 5, 0),- ],- )- def test_trial_evaluation_count(- self, _name: str, posthog_count: int, byok_count: int, no_key_count: int, expected: int- ) -> None:- distinct_id = str(uuid4())- _create_person(distinct_ids=[distinct_id], team=self.team)-- period_start, period_end = get_previous_day()-- if posthog_count:- self._create_ai_events(- self.team,- distinct_id,- "$ai_evaluation",- posthog_count,- properties={"$ai_evaluation_key_type": "posthog"},- )- if byok_count:- self._create_ai_events(- self.team,- distinct_id,- "$ai_evaluation",- byok_count,- properties={"$ai_evaluation_key_type": "byok"},- )- if no_key_count:- self._create_ai_events(self.team, distinct_id, "$ai_evaluation", no_key_count)-- team_ids = get_teams_with_ai_events(period_start, period_end, AI_OBSERVABILITY_REPORT_TRIGGER_EVENTS)- all_metrics = get_all_ai_metrics(period_start, period_end, team_ids)-- total = posthog_count + byok_count + no_key_count- metrics = all_metrics[self.team.id]- assert metrics.ai_evaluation_count == total- assert metrics.ai_trial_evaluation_count == expecteddiff --git a/posthog/templates/email/ai_observability_trial_exhausted.html b/posthog/templates/email/ai_observability_trial_exhausted.htmldeleted file mode 100644index 7b202799c88a..000000000000--- a/posthog/templates/email/ai_observability_trial_exhausted.html+++ /dev/null@@ -1,39 +0,0 @@-{% extends "email/base.html" %} {% load posthog_assets %} {% load posthog_filters %}-{% block preheader %}Your trial evaluations for AI observability have been used up{% endblock %}-{% block heading %}Your trial evaluations have been used up{% endblock %}-{% block section %}-{% if affected_evals %}-<p>- Your team has used all <strong>{{ trial_eval_limit }}</strong> trial evaluations for AI observability. The following evaluations have been disabled:-</p>-<ul>- {% for eval_name in affected_evals %}<li>{{ eval_name }}</li>{% endfor %}- {% if affected_evals_overflow %}<li><em>and {{ affected_evals_overflow }} more</em></li>{% endif %}-</ul>-{% else %}-<p>- Your team has used all <strong>{{ trial_eval_limit }}</strong> trial evaluations for AI observability. Evaluations using trial credits have been disabled.-</p>-{% endif %}-<p>- To continue running evaluations, add your own provider API key in the <a href="{% absolute_uri settings_url %}">AI observability settings</a>. Once added, you can re-enable your evaluations.-</p>-<div class="mb mt text-center">- <a class="button" href="{% absolute_uri settings_url %}">Add your API key</a>-</div>-<div class="mt">- <p>- If the button above doesn't work, paste this link into your browser:<br />- <a href="{% absolute_uri settings_url %}">{% absolute_uri settings_url %}</a>- </p>-</div>-{% endblock %}--{% block footer %}-Need help?-<a href="https://posthog.com/questions?{{ utm_tags }}"- target="_blank"><b>Visit support</b></a>-or-<a href="https://posthog.com/docs/ai-engineering?{{ utm_tags }}"- target="_blank"><b>read our documentation</b></a>.-{% endblock %}diff --git a/posthog/templates/email/ai_observability_trial_warning.html b/posthog/templates/email/ai_observability_trial_warning.htmldeleted file mode 100644index 207774de66a5..000000000000--- a/posthog/templates/email/ai_observability_trial_warning.html+++ /dev/null@@ -1,42 +0,0 @@-{% extends "email/base.html" %} {% load posthog_assets %} {% load posthog_filters %}-{% block preheader %}You've used {{ threshold_pct }}% of your AI observability trial evaluations{% endblock %}-{% block heading %}You've used {{ threshold_pct }}% of your trial evaluations{% endblock %}-{% block section %}-<p>- Your team has used <strong>{{ trial_evals_used }}</strong> of <strong>{{ trial_eval_limit }}</strong> trial evaluations for AI observability, with <strong>{{ trial_evals_remaining }}</strong> remaining.-</p>-{% if affected_evals %}-<p>- Once your trial evaluations run out, the following evaluations will be disabled:-</p>-<ul>- {% for eval_name in affected_evals %}<li>{{ eval_name }}</li>{% endfor %}- {% if affected_evals_overflow %}<li><em>and {{ affected_evals_overflow }} more</em></li>{% endif %}-</ul>-{% else %}-<p>- Once your trial evaluations run out, evaluations using trial credits will be disabled.-</p>-{% endif %}-<p>- To ensure uninterrupted evaluations, add your own provider API key in the <a href="{% absolute_uri settings_url %}">AI observability settings</a>.-</p>-<div class="mb mt text-center">- <a class="button" href="{% absolute_uri settings_url %}">Add your API key</a>-</div>-<div class="mt">- <p>- If the button above doesn't work, paste this link into your browser:<br />- <a href="{% absolute_uri settings_url %}">{% absolute_uri settings_url %}</a>- </p>-</div>-{% endblock %}--{% block footer %}-Need help?-<a href="https://posthog.com/questions?{{ utm_tags }}"- target="_blank"><b>Visit support</b></a>-or-<a href="https://posthog.com/docs/ai-engineering?{{ utm_tags }}"- target="_blank"><b>read our documentation</b></a>.-{% endblock %}diff --git a/posthog/temporal/ai_observability/__init__.py b/posthog/temporal/ai_observability/__init__.pyindex ce4e6824d199..df13008704d7 100644--- a/posthog/temporal/ai_observability/__init__.py+++ b/posthog/temporal/ai_observability/__init__.py@@ -89,9 +89,10 @@ EVAL_WORKFLOWS = [EVAL_ACTIVITIES = [fetch_evaluation_activity,+ # Trial-eval no-op stubs, kept registered so runs started on the previous release can finish.increment_trial_eval_count_activity,- disable_evaluation_activity,send_trial_usage_email_activity,+ disable_evaluation_activity,send_evaluation_disabled_email_activity,update_key_state_activity,execute_llm_judge_activity,diff --git a/posthog/temporal/ai_observability/evaluation_errors.py b/posthog/temporal/ai_observability/evaluation_errors.pyindex 9ddb1cf2efe8..807107ac579d 100644--- a/posthog/temporal/ai_observability/evaluation_errors.py+++ b/posthog/temporal/ai_observability/evaluation_errors.py@@ -27,7 +27,6 @@ class EvaluationErrorSpec:status_reason: str | None = Nonedisables_evaluation: bool = Falseprovider_key_state: str | None = None- send_trial_usage_email: bool = FalseUSER_ERROR_SPECS: dict[str, EvaluationErrorSpec] = {@@ -38,21 +37,6 @@ USER_ERROR_SPECS: dict[str, EvaluationErrorSpec] = {status_reason=EvaluationStatusReason.PROVIDER_KEY_REQUIRED,disables_evaluation=True,),- "trial_limit_reached": EvaluationErrorSpec(- error_type="trial_limit_reached",- owner="user",- safe_message="Trial evaluation limit reached. Add a provider API key to continue.",- status_reason=EvaluationStatusReason.TRIAL_LIMIT_REACHED,- disables_evaluation=True,- send_trial_usage_email=True,- ),- "model_not_allowed": EvaluationErrorSpec(- error_type="model_not_allowed",- owner="user",- safe_message="The selected model is not available on the trial plan.",- status_reason=EvaluationStatusReason.MODEL_NOT_ALLOWED,- disables_evaluation=True,- ),"no_default_model": EvaluationErrorSpec(error_type="no_default_model",owner="user",diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.pyindex 9ab440296dc6..f50d6b5ff7e2 100644--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py@@ -30,7 +30,6 @@ from posthog.temporal.ai_observability.model_resolution import model_specfrom posthog.temporal.common.utils import close_db_connectionsfrom products.ai_observability.backend.llm import DEFAULT_MODEL_BY_PROVIDER, Client, CompletionRequest-from products.ai_observability.backend.llm.config import get_eval_configfrom products.ai_observability.backend.llm.errors import (AuthenticationError,ContextWindowExceededError,@@ -304,7 +303,7 @@ def call_llm_judge(type_config = get_output_type_config(allows_na)response_format = type_config.response_format- config = get_eval_config(provider) if provider_key is None else None+ config = Noneclient = Client(provider_key=provider_key,diff --git a/posthog/temporal/ai_observability/evaluation_workflow_activities.py b/posthog/temporal/ai_observability/evaluation_workflow_activities.pyindex df1a528c6dbc..bdd350d0750f 100644--- a/posthog/temporal/ai_observability/evaluation_workflow_activities.py+++ b/posthog/temporal/ai_observability/evaluation_workflow_activities.py@@ -4,7 +4,7 @@ from datetime import UTC, datetimefrom typing import Anyfrom django.conf import settings-from django.db import models, transaction+from django.db import transactionimport structlogimport temporalio@@ -17,14 +17,12 @@ from posthog.temporal.ai_observability.evaluation_llm_judge import DEFAULT_JUDGEfrom posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResultfrom posthog.temporal.ai_observability.metrics import increment_emit_event_outcome-from products.ai_observability.backend.models.evaluation_config import EvaluationConfigfrom products.ai_observability.backend.models.evaluations import Evaluation, EvaluationStatusfrom products.ai_observability.backend.models.provider_keys import LLMProviderKeylogger = structlog.get_logger(__name__)SOURCE_AI_PROPERTIES_TO_COPY = ("$ai_prompt_name", "$ai_prompt_version")-TRIAL_NOTIFICATION_THRESHOLDS = [50, 75, 100]@dataclass@@ -96,35 +94,25 @@ async def update_key_state_activity(key_id: str, state: str, error_message: strawait database_sync_to_async(_update)()+@dataclass+class SendTrialUsageEmailInputs:+ team_id: int+ threshold_pct: int++@temporalio.activity.defnasync def increment_trial_eval_count_activity(team_id: int) -> int | None:- """Increment trial eval counter after successful execution with PostHog key."""- from django.db import connection-- def _increment() -> int | None:- table = EvaluationConfig._meta.db_table- with connection.cursor() as cursor:- cursor.execute(- f"""- UPDATE {table}- SET trial_evals_used = trial_evals_used + 1- WHERE team_id = %s- RETURNING trial_evals_used, trial_eval_limit- """,- [team_id],- )- row = cursor.fetchone()- if row is None:- logger.warning("No EvaluationConfig found for team during trial increment", team_id=team_id)- return None- trial_evals_used, trial_eval_limit = row+ """No-op stub kept registered so evaluation runs started on the previous release can finish+ during the rollout. Returning None means no usage email follows. The follow-up column-drop PR+ deletes it."""+ return None- for pct in TRIAL_NOTIFICATION_THRESHOLDS:- if trial_evals_used == round(trial_eval_limit * pct / 100):- return pct- return None- return await database_sync_to_async(_increment)()+async def send_trial_usage_email_activity(inputs: SendTrialUsageEmailInputs) -> None:+ """No-op stub kept registered so evaluation runs started on the previous release can finish+ during the rollout. The follow-up column-drop PR deletes it."""+ return None@temporalio.activity.defn@@ -154,95 +142,6 @@ async def disable_evaluation_activity(return await database_sync_to_async(_disable)()-@dataclass-class SendTrialUsageEmailInputs:- team_id: int- threshold_pct: int---async def send_trial_usage_email_activity(inputs: SendTrialUsageEmailInputs) -> None:- """Send an email to org members about trial evaluation usage."""-- def _send() -> None:- from posthog.email import EmailMessage, is_email_available-- if not is_email_available(with_absolute_urls=True):- logger.info(- "Email not available, skipping trial usage notification",- team_id=inputs.team_id,- threshold_pct=inputs.threshold_pct,- )- return-- try:- team = Team.objects.select_related("organization").get(id=inputs.team_id)- except Team.DoesNotExist:- logger.warning("Team not found for trial usage email", team_id=inputs.team_id)- return-- config = EvaluationConfig.objects.filter(team_id=inputs.team_id).first()- if not config:- return-- # provider_key_required disables also route here with threshold 100, but they can fire for- # teams cut off mid-trial at the deprecation date or that never started — for those, "used- # up" would be false, so only send when the trial was actually exhausted.- if inputs.threshold_pct >= 100 and config.trial_evals_used < config.trial_eval_limit:- return-- max_listed = 20- affected_qs = Evaluation.objects.filter(- team_id=inputs.team_id,- enabled=True,- deleted=False,- ).filter(models.Q(model_configuration__isnull=True) | models.Q(model_configuration__provider_key__isnull=True))- total_affected = affected_qs.count()- affected_evals = list(affected_qs.values_list("name", flat=True)[:max_listed])- affected_evals_overflow = max(0, total_affected - max_listed)-- settings_url = f"/project/{team.pk}/settings/project-ai-observability#ai-observability-byok"- campaign_key = f"llm_analytics_trial_{inputs.threshold_pct}pct_{team.id}"- is_exhausted = inputs.threshold_pct >= 100-- if is_exhausted:- subject = "Your AI observability trial evaluations have been used up"- template_name = "ai_observability_trial_exhausted"- else:- subject = f"You've used {inputs.threshold_pct}% of your AI observability trial evaluations"- template_name = "ai_observability_trial_warning"-- message = EmailMessage(- campaign_key=campaign_key,- subject=subject,- template_name=template_name,- template_context={- "trial_eval_limit": config.trial_eval_limit,- "trial_evals_used": config.trial_evals_used,- "trial_evals_remaining": config.trial_evals_remaining,- "threshold_pct": inputs.threshold_pct,- "settings_url": settings_url,- "affected_evals": affected_evals,- "affected_evals_overflow": affected_evals_overflow,- },- )-- for user in team.organization.members.all():- message.add_user_recipient(user)-- if message.to:- message.send()- logger.info(- "Sent trial usage email",- team_id=inputs.team_id,- org_id=str(team.organization_id),- threshold_pct=inputs.threshold_pct,- recipient_count=len(message.to),- )-- await database_sync_to_async(_send)()--@dataclassclass SendEvaluationDisabledEmailInputs:team_id: int@@ -255,7 +154,6 @@ class SendEvaluationDisabledEmailInputs:_STATUS_REASON_SUBJECTS = {"provider_key_required": "Your AI observability evaluation was disabled because it has no provider API key",- "model_not_allowed": "Your AI observability evaluation was disabled because its model isn't supported on the trial plan","no_default_model": "Your AI observability evaluation was disabled because no default model is configured","provider_key_deleted": "Your AI observability evaluation was disabled because its provider API key was removed","provider_key_invalid": "Your AI observability evaluation was disabled because its provider API key is invalid",@@ -269,7 +167,7 @@ _STATUS_REASON_SUBJECTS = {@temporalio.activity.defnasync def send_evaluation_disabled_email_activity(inputs: SendEvaluationDisabledEmailInputs) -> None:- """Email org members when an evaluation enters the ERROR state for a reason other than trial exhaustion."""+ """Email org members when an evaluation enters the ERROR state."""def _send() -> None:from posthog.email import EmailMessage, is_email_availablediff --git a/posthog/temporal/ai_observability/metrics.py b/posthog/temporal/ai_observability/metrics.pyindex 1d1c26092fed..10fa4d6c34ef 100644--- a/posthog/temporal/ai_observability/metrics.py+++ b/posthog/temporal/ai_observability/metrics.py@@ -30,8 +30,6 @@ EVAL_ACTIVITY_TYPES = {"execute_sentiment_eval_activity","emit_evaluation_event_activity","emit_internal_telemetry_activity",- "increment_trial_eval_count_activity",- "send_trial_usage_email_activity","update_key_state_activity","emit_eval_signal_activity",}@@ -63,7 +61,7 @@ def increment_verdict(verdict: str, evaluation_type: str = "llm_judge") -> None:def increment_key_type(key_type: str) -> None:- """Track BYOK vs PostHog trial usage."""+ """Track BYOK vs PostHog-funded key usage."""meter = get_metric_meter({"key_type": key_type})counter = meter.create_counter("llma_eval_key_type", "API key type usage")counter.add(1)diff --git a/posthog/temporal/ai_observability/model_resolution.py b/posthog/temporal/ai_observability/model_resolution.pyindex 4321b08d19f1..a74497225855 100644--- a/posthog/temporal/ai_observability/model_resolution.py+++ b/posthog/temporal/ai_observability/model_resolution.py@@ -1,11 +1,12 @@"""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 while the team is still grandfathered into the trial (see `is_trial_grandfathered`)".-`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.+"unconfigured" — it means "defer to the team's active key". `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.++Evaluations and taggers require the team's own provider key: a keyless resolution (no pinned key+and no team active key) raises `provider_key_required`.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).@@ -18,15 +19,10 @@ from django.utils import timezonefrom temporalio.exceptions import ApplicationError-from products.ai_observability.backend.llm import DEFAULT_MODEL_BY_PROVIDER, TRIAL_MODEL_IDS+from products.ai_observability.backend.llm import DEFAULT_MODEL_BY_PROVIDERfrom products.ai_observability.backend.models.evaluation_config import EvaluationConfigfrom 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:@@ -55,32 +51,20 @@ class ExplicitModelSpec:if self.provider_key_id:return ResolvedModel(self.provider, self.model, _resolve_key_by_id(team_id, self.provider_key_id))- config = _eval_config(team_id)- fallback = active_key_fallback(config, self.provider)- if fallback is not None:- return ResolvedModel(self.provider, self.model, _ensure_usable(fallback))-- _assert_funded_inference_allowed(config)- 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,- )- return ResolvedModel(self.provider, self.model, None)+ fallback = active_key_fallback(_eval_config(team_id), self.provider)+ if fallback is None:+ raise _provider_key_required()+ return ResolvedModel(self.provider, self.model, _ensure_usable(fallback))@dataclass(frozen=True)class DefaultModelSpec:- """Null config: defer to the team's active BYOK key, else PostHog trial credits while grandfathered."""+ """Null config: defer to the team's active BYOK key."""def resolve(self, team_id: int) -> ResolvedModel:- config = _eval_config(team_id)- key = config.active_provider_key+ key = _eval_config(team_id).active_provider_keyif key is None:- _assert_funded_inference_allowed(config)- return ResolvedModel(TRIAL_DEFAULT_PROVIDER, DEFAULT_MODEL_BY_PROVIDER[TRIAL_DEFAULT_PROVIDER], None)+ raise _provider_key_required()model = DEFAULT_MODEL_BY_PROVIDER.get(key.provider)if model is None:@@ -103,7 +87,7 @@ def model_spec(model_configuration: dict[str, Any] | None) -> ModelSpec:def active_key_fallback(config: EvaluationConfig, provider: str) -> LLMProviderKey | None:- """The BYOK key a config with no pinned key resolves to, or None for the trial path."""+ """The BYOK key a config with no pinned key resolves to, or None when there is no usable active key."""key = config.active_provider_keyreturn key if key is not None and key.provider == provider else None@@ -113,13 +97,12 @@ def _eval_config(team_id: int) -> EvaluationConfig:return config-def _assert_funded_inference_allowed(config: EvaluationConfig) -> None:- if not config.is_trial_grandfathered:- raise ApplicationError(- "Add a provider API key to run this evaluation.",- {"error_type": "provider_key_required"},- non_retryable=True,- )+def _provider_key_required() -> ApplicationError:+ return ApplicationError(+ "Add a provider API key to run this evaluation.",+ {"error_type": "provider_key_required"},+ non_retryable=True,+ )def _resolve_key_by_id(team_id: int, key_id: str) -> LLMProviderKey:diff --git a/posthog/temporal/ai_observability/run_evaluation.py b/posthog/temporal/ai_observability/run_evaluation.pyindex eccca272fb0f..63225e3f1046 100644--- a/posthog/temporal/ai_observability/run_evaluation.py+++ b/posthog/temporal/ai_observability/run_evaluation.py@@ -198,7 +198,17 @@ async def handle_terminal_user_error_result(retry_policy=RetryPolicy(maximum_attempts=2),)- if spec and spec.send_trial_usage_email and temporalio.workflow.patched("trial-usage-email"):+ # Replay-only compatibility for runs started before trial evals were removed: reproduce the+ # commands the old code scheduled for trial-era errors, without resurrecting their specs.+ # workflow.patched returns False only when replaying pre-patch histories, so fresh runs never+ # take the legacy branches. Remove together with the columns in the follow-up PR.+ legacy_trial_era = not temporalio.workflow.patched("remove-trial-evals")+ skip_reason_str = str(skip_reason) if skip_reason else None+ if (+ legacy_trial_era+ and skip_reason_str == "trial_limit_reached"+ and temporalio.workflow.patched("trial-usage-email")+ ):try:await temporalio.workflow.execute_activity(send_trial_usage_email_activity,@@ -214,16 +224,17 @@ async def handle_terminal_user_error_result()dedupe_disabled_email = temporalio.workflow.patched("eval-disabled-email-on-disable-transition")+ legacy_model_not_allowed = legacy_trial_era and skip_reason_str == "model_not_allowed"should_send_disabled_email = (- spec is not None- and spec.disables_evaluation+ ((spec is not None and spec.disables_evaluation) or legacy_model_not_allowed)and bool(status_reason)and (disabled_evaluation or not dedupe_disabled_email)- and not spec.send_trial_usage_emailand temporalio.workflow.patched("eval-disabled-email"))if should_send_disabled_email:- assert spec is not None+ human_readable_reason = (+ spec.safe_message if spec is not None else "The selected model is not available on the trial plan."+ )email_status_reason = str(status_reason)try:await temporalio.workflow.execute_activity(@@ -233,7 +244,7 @@ async def handle_terminal_user_error_result(evaluation_id=evaluation["id"],evaluation_name=evaluation.get("name", "Unknown evaluation"),status_reason=email_status_reason,- human_readable_reason=spec.safe_message,+ human_readable_reason=human_readable_reason,disabled_at=temporalio.workflow.now(),),activity_id=f"send-eval-disabled-email-{evaluation['id']}-{email_status_reason}",@@ -259,10 +270,10 @@ async def handle_terminal_user_error_result(async def increment_trial_usage_and_notify(evaluation: dict[str, Any]) -> None:- """Increment the team's trial eval counter and send threshold emails. Must run inside a- workflow context. Shared by the single-event and trace-level workflows; callers gate on- `is_byok` / `skipped` so only PostHog-key LLM judge runs consume quota.- """+ """Replay-only compatibility for runs started before trial evals were removed: reproduces the+ activity commands the old code scheduled after a PostHog-key LLM judge run. Callers gate on+ `workflow.patched("remove-trial-evals")`, so fresh runs never reach this. Must run inside a+ workflow context. Remove together with the columns in the follow-up PR."""threshold_pct = await temporalio.workflow.execute_activity(increment_trial_eval_count_activity,evaluation["team_id"],@@ -337,7 +348,12 @@ class RunEvaluationWorkflow(PostHogWorkflow):return handledraise- if not result.get("is_byok") and not result.get("skipped"):+ # Replay-only; see increment_trial_usage_and_notify.+ if (+ not temporalio.workflow.patched("remove-trial-evals")+ and not result.get("is_byok")+ and not result.get("skipped")+ ):await increment_trial_usage_and_notify(evaluation)else:raise ApplicationError(diff --git a/posthog/temporal/ai_observability/run_tagger.py b/posthog/temporal/ai_observability/run_tagger.pyindex 8fda4281aef3..aff98c5f27cf 100644--- a/posthog/temporal/ai_observability/run_tagger.py+++ b/posthog/temporal/ai_observability/run_tagger.py@@ -26,7 +26,6 @@ from posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.scoped import scoped_temporalfrom products.ai_observability.backend.llm import DEFAULT_MODEL_BY_PROVIDER, Client, CompletionRequest-from products.ai_observability.backend.llm.config import get_eval_configfrom products.ai_observability.backend.llm.errors import (AuthenticationError,ModelNotFoundError,@@ -149,7 +148,7 @@ async def fetch_tagger_activity(inputs: RunTaggerInputs) -> dict[str, Any]:logger.exception("Tagger not found", tagger_id=inputs.tagger_id)raise ValueError(f"Tagger {inputs.tagger_id} not found")- # Short-circuit when the tagger has been disabled (e.g. by a prior trial-limit+ # Short-circuit when the tagger has been disabled (e.g. by a prior missing-key# trip) before we run a lagging event through it. The workflow surfaces this# as a skipped result rather than an error.if not tagger.enabled:@@ -241,7 +240,7 @@ async def execute_tagger_activity(inputs: ExecuteTaggerInputs) -> dict[str, Any]Output: {output_data}"""- config = get_eval_config(provider) if provider_key is None else None+ config = Noneclient = Client(provider_key=provider_key,@@ -538,7 +537,7 @@ async def emit_tagger_event_activity(inputs: EmitTaggerEventInputs) -> None:@temporalio.activity.defnasync def disable_tagger_activity(tagger_id: str, team_id: int) -> None:- """Disable a tagger when trial limit is reached.+ """Disable a tagger when its provider key is missing or invalid.Uses ``.update()`` to bypass ``Tagger.save()``'s bytecode recompilation (matching``disable_evaluation_activity``'s pattern), then publishes the reload-taggers@@ -616,19 +615,24 @@ class RunTaggerWorkflow(PostHogWorkflow):details = e.cause.details[0]error_type = details.get("error_type")+ # Replay-only compatibility for runs started before trial evals were removed:+ # reproduce the commands the old code scheduled for trial-era errors.+ # workflow.patched returns False only when replaying pre-patch histories, so+ # fresh runs never take the legacy branches. Remove in the follow-up PR.+ legacy_trial_era = not temporalio.workflow.patched("remove-trial-evals")+ legacy_trial_error_types = ("trial_limit_reached", "model_not_allowed") if legacy_trial_era else ()+if error_type in ("provider_key_required",- "trial_limit_reached","key_invalid","parse_error",- "model_not_allowed","no_default_model",+ *legacy_trial_error_types,):if error_type in ("provider_key_required",- "trial_limit_reached",- "model_not_allowed","no_default_model",+ *legacy_trial_error_types,):await temporalio.workflow.execute_activity(disable_tagger_activity,@@ -636,11 +640,11 @@ class RunTaggerWorkflow(PostHogWorkflow):schedule_to_close_timeout=timedelta(seconds=30),retry_policy=RetryPolicy(maximum_attempts=2),)- if error_type in (- "provider_key_required",- "trial_limit_reached",- "model_not_allowed",- ) and temporalio.workflow.patched("trial-usage-email"):+ if (+ legacy_trial_era+ and error_type in ("provider_key_required", "trial_limit_reached", "model_not_allowed")+ and temporalio.workflow.patched("trial-usage-email")+ ):try:await temporalio.workflow.execute_activity(send_trial_usage_email_activity,@@ -676,8 +680,9 @@ class RunTaggerWorkflow(PostHogWorkflow):)raise- # Increment trial counter if using PostHog key (LLM taggers only — Hog taggers have no LLM cost)- if tagger_type != "hog" and not result.get("is_byok"):+ # Replay-only trial counting for runs started before trial evals were removed; the+ # activities are no-op stubs. Remove in the follow-up PR.+ if not temporalio.workflow.patched("remove-trial-evals") and tagger_type != "hog" and not result.get("is_byok"):threshold_pct = await temporalio.workflow.execute_activity(increment_trial_eval_count_activity,tagger["team_id"],diff --git a/posthog/temporal/ai_observability/run_trace_evaluation.py b/posthog/temporal/ai_observability/run_trace_evaluation.pyindex 9f5c10cebdaa..037a95c600ee 100644--- a/posthog/temporal/ai_observability/run_trace_evaluation.py+++ b/posthog/temporal/ai_observability/run_trace_evaluation.py@@ -529,9 +529,12 @@ class RunTraceEvaluationWorkflow(PostHogWorkflow):return handledraise- # Trial quota: same gating as the single-event workflow — only PostHog-key LLM- # judge runs that actually called the API consume quota.- if not result.get("is_byok") and not result.get("skipped"):+ # Replay-only; see increment_trial_usage_and_notify.+ if (+ not temporalio.workflow.patched("remove-trial-evals")+ and not result.get("is_byok")+ and not result.get("skipped")+ ):await increment_trial_usage_and_notify(evaluation)if is_terminal_user_error_result(result):diff --git a/posthog/temporal/ai_observability/test_metrics.py b/posthog/temporal/ai_observability/test_metrics.pyindex 6e41836a3782..ee54739ddfad 100644--- a/posthog/temporal/ai_observability/test_metrics.py+++ b/posthog/temporal/ai_observability/test_metrics.py@@ -102,8 +102,6 @@ class TestActivityTypes:"execute_sentiment_eval_activity","emit_evaluation_event_activity","emit_internal_telemetry_activity",- "increment_trial_eval_count_activity",- "send_trial_usage_email_activity","update_key_state_activity","emit_eval_signal_activity",}diff --git a/posthog/temporal/ai_observability/test_model_resolution.py b/posthog/temporal/ai_observability/test_model_resolution.pyindex 5748724a137a..44e817be20aa 100644--- a/posthog/temporal/ai_observability/test_model_resolution.py+++ b/posthog/temporal/ai_observability/test_model_resolution.py@@ -12,13 +12,6 @@ from products.ai_observability.backend.models.evaluation_config import Evaluatiofrom products.ai_observability.backend.models.provider_keys import LLMProviderKey[email protected](autouse=True)-def _future_deprecation_date(settings):- # Pin the trial cutoff far in the future so grandfathering (0 < used < limit) is deterministic- # regardless of the wall clock the suite runs on. Cutoff-specific tests override this locally.- settings.AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE = "2999-12-31T00:00:00+00:00"--@pytest.fixturedef team():organization = Organization.objects.create(name="Test Org")@@ -35,10 +28,6 @@ def _key(team, provider, state=LLMProviderKey.State.OK):)-def _grandfathered_config(team, **kwargs):- return EvaluationConfig.objects.create(team=team, trial_eval_limit=100, trial_evals_used=50, **kwargs)--def _error_type(exc_info):return exc_info.value.details[0]["error_type"]@@ -76,41 +65,17 @@ class TestExplicitModelSpec:ExplicitModelSpec("openai", "gpt-5", str(key.id)).resolve(team.id)assert _error_type(exc_info) == "key_invalid"- def test_grandfathered_trial_allowlisted_model_resolves_without_key(self, team):- _grandfathered_config(team)- resolved = ExplicitModelSpec("openai", "gpt-5-mini", None).resolve(team.id)- assert resolved.provider_key is None- assert not resolved.is_byok-- def test_grandfathered_non_allowlisted_model_raises_model_not_allowed(self, team):- _grandfathered_config(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_no_trial_usage_requires_provider_key(self, team):+ 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:ExplicitModelSpec("openai", "gpt-5-mini", None).resolve(team.id)assert _error_type(exc_info) == "provider_key_required"- def test_exhausted_trial_requires_provider_key(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) == "provider_key_required"-- def test_past_cutoff_requires_provider_key(self, team, settings):- settings.AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE = "2000-01-01T00:00:00+00:00"- _grandfathered_config(team)- with pytest.raises(ApplicationError) as exc_info:- ExplicitModelSpec("openai", "gpt-5-mini", None).resolve(team.id)- assert _error_type(exc_info) == "provider_key_required"-- def test_null_key_falls_back_to_matching_active_key_despite_exhausted_quota(self, team):- # Regression: an eval whose model config pinned a model but no key was blocked with- # trial_limit_reached even though the team had a healthy active key for that provider.+ def test_null_key_falls_back_to_matching_active_key(self, team):+ # An eval whose model config pinned a model but no key resolves to the team's healthy+ # active key for that provider.key = _key(team, "openai")- EvaluationConfig.objects.create(team=team, active_provider_key=key, trial_eval_limit=100, trial_evals_used=100)+ EvaluationConfig.objects.create(team=team, active_provider_key=key)resolved = ExplicitModelSpec("openai", "gpt-5-mini", None).resolve(team.id)@@ -119,31 +84,17 @@ class TestExplicitModelSpec:def test_null_key_ignores_active_key_of_a_different_provider(self, team):key = _key(team, "anthropic")- _grandfathered_config(team, active_provider_key=key)-- resolved = ExplicitModelSpec("openai", "gpt-5-mini", None).resolve(team.id)+ EvaluationConfig.objects.create(team=team, active_provider_key=key)- assert resolved.provider_key is None- assert not resolved.is_byok+ with pytest.raises(ApplicationError) as exc_info:+ ExplicitModelSpec("openai", "gpt-5-mini", None).resolve(team.id)+ assert _error_type(exc_info) == "provider_key_required"@pytest.mark.django_dbclass TestDefaultModelSpec:- def test_grandfathered_no_active_key_falls_back_to_posthog_trial(self, team):- _grandfathered_config(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_no_trial_usage_requires_provider_key(self, team):- with pytest.raises(ApplicationError) as exc_info:- DefaultModelSpec().resolve(team.id)- assert _error_type(exc_info) == "provider_key_required"-- def test_no_active_key_exhausted_requires_provider_key(self, team):- EvaluationConfig.objects.create(team=team, trial_eval_limit=100, trial_evals_used=100)+ def test_no_active_key_requires_provider_key(self, team):+ # Null config, no team active key — must bring a key.with pytest.raises(ApplicationError) as exc_info:DefaultModelSpec().resolve(team.id)assert _error_type(exc_info) == "provider_key_required"diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex 208a1e74a1ba..d8902a172998 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -28,7 +28,6 @@ from products.ai_observability.backend.llm.errors import ()from products.ai_observability.backend.models.evaluation_config import EvaluationConfigfrom products.ai_observability.backend.models.evaluations import Evaluation-from products.ai_observability.backend.models.model_configuration import LLMModelConfigurationfrom products.ai_observability.backend.models.provider_keys import LLMProviderKeyfrom .evaluation_errors import (@@ -47,7 +46,6 @@ from .run_evaluation import (RunEvaluationInputs,RunEvaluationWorkflow,SendEvaluationDisabledEmailInputs,- SendTrialUsageEmailInputs,WorkflowResult,disable_evaluation_activity,emit_evaluation_event_activity,@@ -56,13 +54,17 @@ from .run_evaluation import (execute_sentiment_eval_activity,extract_event_tools,fetch_evaluation_activity,- increment_trial_eval_count_activity,run_hog_eval,send_evaluation_disabled_email_activity,- send_trial_usage_email_activity,)+def _mock_config_with_active_key(provider: str = "openai") -> MagicMock:+ """A mocked EvaluationConfig whose active key resolves via DefaultModelSpec (usable, right provider)."""+ key = MagicMock(provider=provider, state=LLMProviderKey.State.OK)+ return MagicMock(active_provider_key=key)++def test_status_reason_detail_for_terminal_user_error_only_keeps_truncated_hog_errors():hog_spec = require_user_error_spec("hog_error")permission_spec = require_user_error_spec("permission_error")@@ -130,10 +132,17 @@ def setup_data():@pytest.fixture-def grandfathered(setup_data, settings):- # A team mid-trial before the cutoff keeps PostHog-funded inference, so trial/keyless judges run.- settings.AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE = "2999-12-31T00:00:00+00:00"- EvaluationConfig.objects.create(team=setup_data["team"], trial_eval_limit=100, trial_evals_used=50)+def active_key_config(setup_data):+ """Give the team a healthy active provider key so a null-config judge resolves via DefaultModelSpec."""+ team = setup_data["team"]+ key = LLMProviderKey.objects.create(+ team=team,+ provider="openai",+ name="openai key",+ state=LLMProviderKey.State.OK,+ encrypted_config={"api_key": "sk-test"},+ )+ EvaluationConfig.objects.create(team=team, active_provider_key=key)class TestRunEvaluationWorkflow:@@ -172,7 +181,7 @@ class TestRunEvaluationWorkflow:assert result["output_config"] == {"allows_na": False}@pytest.mark.django_db(transaction=True)- def test_execute_llm_judge_activity(self, setup_data, grandfathered):+ def test_execute_llm_judge_activity(self, setup_data, active_key_config):"""Test LLM judge execution with realistic message array format"""evaluation_obj = setup_data["evaluation"]team = setup_data["team"]@@ -224,7 +233,7 @@ class TestRunEvaluationWorkflow:],)@pytest.mark.django_db(transaction=True)- def test_execute_llm_judge_activity_bounds_oversized_input(self, oversized_input, setup_data, grandfathered):+ def test_execute_llm_judge_activity_bounds_oversized_input(self, oversized_input, setup_data, active_key_config):team = setup_data["team"]evaluation_obj = setup_data["evaluation"]@@ -270,7 +279,7 @@ class TestRunEvaluationWorkflow:)@pytest.mark.django_db(transaction=True)def test_execute_llm_judge_activity_skips_on_context_window_exceeded(- self, output_config, expected_verdict, expected_applicable, setup_data, grandfathered+ self, output_config, expected_verdict, expected_applicable, setup_data, active_key_config):team = setup_data["team"]evaluation_obj = setup_data["evaluation"]@@ -667,7 +676,7 @@ class TestRunEvaluationWorkflow:assert result["skip_reason"] == "hog_error"@pytest.mark.django_db(transaction=True)- def test_execute_llm_judge_activity_allows_na_applicable(self, setup_data, grandfathered):+ def test_execute_llm_judge_activity_allows_na_applicable(self, setup_data, active_key_config):"""Test LLM judge execution with allows_na=True when applicable"""evaluation_obj = setup_data["evaluation"]team = setup_data["team"]@@ -709,7 +718,7 @@ class TestRunEvaluationWorkflow:assert result["allows_na"] is True@pytest.mark.django_db(transaction=True)- def test_execute_llm_judge_activity_allows_na_not_applicable(self, setup_data, grandfathered):+ def test_execute_llm_judge_activity_allows_na_not_applicable(self, setup_data, active_key_config):"""Test LLM judge execution with allows_na=True when not applicable"""evaluation_obj = setup_data["evaluation"]team = setup_data["team"]@@ -849,7 +858,7 @@ class TestRunEvaluationWorkflow:)@pytest.mark.django_db(transaction=True)def test_execute_llm_judge_activity_does_not_skip_when_not_errored(- self, error_props: dict[str, Any], setup_data, grandfathered+ self, error_props: dict[str, Any], setup_data, active_key_config):"""Sanity check: traces without `$ai_is_error=true` still flow through to the LLM judge."""evaluation_obj = setup_data["evaluation"]@@ -1076,11 +1085,6 @@ class TestRunEvaluationWorkflow:"output_type": "boolean","output_config": {},"team_id": 1,- "model_configuration": {- "provider": "openai",- "model": "gpt-4.1",- "provider_key_id": None,- },}event_data = create_mock_event_data(@@ -1098,10 +1102,7 @@ class TestRunEvaluationWorkflow: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_get_or_create.return_value = (_mock_config_with_active_key("openai"), False)mock_client = MagicMock()mock_client_class.return_value = mock_clientmock_client.complete.side_effect = StructuredOutputParseError(@@ -1125,7 +1126,7 @@ class TestRunEvaluationWorkflow:)@pytest.mark.django_db(transaction=True)def test_execute_llm_judge_activity_unhandled_exception_uses_class_name(- self, raised_exception: Exception, expected_label: str, setup_data, grandfathered+ self, raised_exception: Exception, expected_label: str, setup_data, active_key_config):evaluation_obj = setup_data["evaluation"]team = setup_data["team"]@@ -1154,46 +1155,6 @@ class TestRunEvaluationWorkflow:mock_increment_errors.assert_called_once_with(expected_label, provider="openai")- @pytest.mark.django_db(transaction=True)- def test_execute_llm_judge_activity_rejects_non_trial_model_on_posthog_key(self, setup_data, settings):- team = setup_data["team"]- # Only a grandfathered team gets past the funded gate to the model-allowlist check.- settings.AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE = "2999-12-31T00:00:00+00:00"- EvaluationConfig.objects.create(team=team, trial_eval_limit=100, trial_evals_used=50)-- evaluation = {- "id": str(setup_data["evaluation"].id),- "name": "Test Evaluation",- "evaluation_type": "llm_judge",- "evaluation_config": {"prompt": "Is this accurate?"},- "output_type": "boolean",- "output_config": {},- "team_id": team.id,- "model_configuration": {- "provider": "openai",- "model": "gpt-5.4",- "provider_key_id": None,- },- }-- event_data = create_mock_event_data(team.id)-- with (- patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class,- patch("posthog.temporal.ai_observability.evaluation_llm_judge.increment_user_errors") as mock_user_errors,- patch("posthog.temporal.ai_observability.evaluation_llm_judge.increment_errors") as mock_errors,- ):- result = execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))-- mock_client_class.assert_not_called()- mock_user_errors.assert_called_once_with("model_not_allowed", provider=None)- mock_errors.assert_not_called()- assert result["terminal_user_error"] is True- assert result["skipped"] is True- assert result["skip_reason"] == "model_not_allowed"- assert result["status_reason"] == "model_not_allowed"- assert result["verdict"] is None-@pytest.mark.django_db(transaction=True)def test_execute_llm_judge_activity_terminal_team_requires_provider_key(self, setup_data):team = setup_data["team"]@@ -1947,185 +1908,6 @@ class TestExecuteHogEvalActivityAllowsNA:assert "Must return boolean" in result["reasoning"]-class TestIncrementTrialEvalCountActivity:- @pytest.mark.asyncio- @pytest.mark.django_db(transaction=True)- @pytest.mark.parametrize(- "trial_eval_limit, trial_evals_used, expected_threshold, expected_used_after",- [- (100, 0, None, 1),- (100, 49, 50, 50),- (100, 74, 75, 75),- (100, 99, 100, 100),- (100, 100, None, 101), # already exceeded — should not re-trigger- (100, 50, None, 51), # just past 50% — no threshold- (10, 4, 50, 5), # 50% of 10- (10, 7, 75, 8), # round(10 * 75 / 100) = round(7.5) = 8- (10, 9, 100, 10), # 100% of 10- ],- ids=[- "no_threshold",- "50pct_reached",- "75pct_reached",- "100pct_reached",- "already_exceeded",- "past_50pct",- "small_limit_50pct",- "small_limit_75pct_rounds",- "small_limit_100pct",- ],- )- async def test_increment_trial_eval_count(- self, setup_data, trial_eval_limit, trial_evals_used, expected_threshold, expected_used_after- ):- team = setup_data["team"]- config, _ = await sync_to_async(EvaluationConfig.objects.get_or_create)(team_id=team.id)- config.trial_eval_limit = trial_eval_limit- config.trial_evals_used = trial_evals_used- await sync_to_async(config.save)()-- result = await increment_trial_eval_count_activity(team.id)-- assert result == expected_threshold- config = await sync_to_async(EvaluationConfig.objects.get)(team_id=team.id)- assert config.trial_evals_used == expected_used_after---class TestSendTrialUsageEmailActivity:- @pytest.mark.asyncio- @pytest.mark.django_db(transaction=True)- @pytest.mark.parametrize(- "threshold_pct, expected_template",- [- (50, "ai_observability_trial_warning"),- (75, "ai_observability_trial_warning"),- (100, "ai_observability_trial_exhausted"),- ],- ids=["50pct_warning", "75pct_warning", "100pct_exhausted"],- )- async def test_sends_correct_template_for_threshold(self, setup_data, threshold_pct, expected_template):- team = setup_data["team"]- await sync_to_async(EvaluationConfig.objects.get_or_create)(team_id=team.id, defaults={"trial_evals_used": 100})-- with (- patch("posthog.email.is_email_available", return_value=True),- patch("posthog.email.EmailMessage") as mock_email_class,- ):- mock_message = MagicMock()- mock_email_class.return_value = mock_message-- await send_trial_usage_email_activity(- SendTrialUsageEmailInputs(team_id=team.id, threshold_pct=threshold_pct)- )-- mock_email_class.assert_called_once()- call_kwargs = mock_email_class.call_args[1]- assert call_kwargs["template_name"] == expected_template- mock_message.send.assert_called_once()-- @pytest.mark.asyncio- @pytest.mark.django_db(transaction=True)- async def test_skips_exhausted_email_when_trial_not_actually_exhausted(self, setup_data):- # provider_key_required disables route here with threshold 100 for teams cut off mid-trial- # at the deprecation date or that never started — "used up" would be false for them.- team = setup_data["team"]- await sync_to_async(EvaluationConfig.objects.get_or_create)(team_id=team.id, defaults={"trial_evals_used": 50})-- with (- patch("posthog.email.is_email_available", return_value=True),- patch("posthog.email.EmailMessage") as mock_email_class,- ):- await send_trial_usage_email_activity(SendTrialUsageEmailInputs(team_id=team.id, threshold_pct=100))-- mock_email_class.assert_not_called()-- @pytest.mark.asyncio- @pytest.mark.django_db(transaction=True)- async def test_skips_when_email_not_available(self, setup_data):- team = setup_data["team"]- await sync_to_async(EvaluationConfig.objects.get_or_create)(team_id=team.id)-- with (- patch("posthog.email.is_email_available", return_value=False),- patch("posthog.email.EmailMessage") as mock_email_class,- ):- await send_trial_usage_email_activity(SendTrialUsageEmailInputs(team_id=team.id, threshold_pct=50))-- mock_email_class.assert_not_called()-- @pytest.mark.asyncio- @pytest.mark.django_db(transaction=True)- @pytest.mark.parametrize("threshold_pct", [50, 75, 100], ids=["50pct", "75pct", "100pct"])- async def test_campaign_key_includes_threshold_and_team(self, setup_data, threshold_pct):- team = setup_data["team"]- await sync_to_async(EvaluationConfig.objects.get_or_create)(team_id=team.id, defaults={"trial_evals_used": 100})-- with (- patch("posthog.email.is_email_available", return_value=True),- patch("posthog.email.EmailMessage") as mock_email_class,- ):- mock_message = MagicMock()- mock_email_class.return_value = mock_message-- await send_trial_usage_email_activity(- SendTrialUsageEmailInputs(team_id=team.id, threshold_pct=threshold_pct)- )-- call_kwargs = mock_email_class.call_args[1]- assert call_kwargs["campaign_key"] == f"llm_analytics_trial_{threshold_pct}pct_{team.id}"-- @pytest.mark.asyncio- @pytest.mark.django_db(transaction=True)- async def test_includes_affected_eval_names_in_context(self, setup_data):- team = setup_data["team"]- await sync_to_async(EvaluationConfig.objects.get_or_create)(team_id=team.id)-- # Trial eval (no provider_key) — should be included- mc_trial = await sync_to_async(LLMModelConfiguration.objects.create)(- team=team, provider="openai", model="gpt-4o-mini"- )- await sync_to_async(Evaluation.objects.create)(- team=team,- name="My Trial Eval",- evaluation_type="llm_judge",- output_type="boolean",- model_configuration=mc_trial,- enabled=True,- )- # Legacy eval (no model_configuration) — should be included- await sync_to_async(Evaluation.objects.create)(- team=team,- name="Legacy Eval",- evaluation_type="llm_judge",- output_type="boolean",- model_configuration=None,- enabled=True,- )- # Disabled eval — should NOT be included- await sync_to_async(Evaluation.objects.create)(- team=team,- name="Disabled Eval",- evaluation_type="llm_judge",- output_type="boolean",- model_configuration=mc_trial,- enabled=False,- )-- with (- patch("posthog.email.is_email_available", return_value=True),- patch("posthog.email.EmailMessage") as mock_email_class,- ):- mock_message = MagicMock()- mock_email_class.return_value = mock_message-- await send_trial_usage_email_activity(SendTrialUsageEmailInputs(team_id=team.id, threshold_pct=75))-- call_kwargs = mock_email_class.call_args[1]- affected = call_kwargs["template_context"]["affected_evals"]- assert "My Trial Eval" in affected- assert "Legacy Eval" in affected--class TestSendEvaluationDisabledEmailActivity:@pytest.fixturedef setup_data(self, db):@@ -2153,8 +1935,8 @@ class TestSendEvaluationDisabledEmailActivity:team_id=team.id,evaluation_id="eval-123",evaluation_name="My Eval",- status_reason="model_not_allowed",- human_readable_reason="The model 'gpt-9' isn't available on the trial plan.",+ status_reason="provider_key_required",+ human_readable_reason="Add a provider API key to run this evaluation.",disabled_at=datetime(2026, 6, 25, 12, 0, 0, tzinfo=UTC),))@@ -2163,9 +1945,9 @@ class TestSendEvaluationDisabledEmailActivity:call_kwargs = mock_email_class.call_args[1]assert call_kwargs["template_name"] == "ai_observability_evaluation_disabled"assert call_kwargs["template_context"]["evaluation_name"] == "My Eval"- assert "isn't available on the trial plan" in call_kwargs["template_context"]["disabled_reason"]+ assert "Add a provider API key" in call_kwargs["template_context"]["disabled_reason"]# Campaign key must include the reason so a later different-reason error triggers a fresh email.- assert "model_not_allowed" in call_kwargs["campaign_key"]+ assert "provider_key_required" in call_kwargs["campaign_key"]# It also includes the disable timestamp so a later same-reason disable sends a fresh email.assert "1782388800000000" in call_kwargs["campaign_key"]mock_message.send.assert_called_once()@@ -2184,7 +1966,7 @@ class TestSendEvaluationDisabledEmailActivity:team_id=team.id,evaluation_id="eval-123",evaluation_name="My Eval",- status_reason="model_not_allowed",+ status_reason="provider_key_required",human_readable_reason="reason",))@@ -2253,10 +2035,7 @@ class TestJudgePromptAssembly:) as mock_get_or_create,patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class,):- mock_get_or_create.return_value = (- MagicMock(active_provider_key=None, trial_evals_used=0, trial_eval_limit=100),- False,- )+ mock_get_or_create.return_value = (_mock_config_with_active_key("openai"), False)mock_client = MagicMock()mock_client_class.return_value = mock_clientmock_response = MagicMock()@@ -2307,10 +2086,7 @@ class TestJudgePromptAssembly:) as mock_get_or_create,patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class,):- mock_get_or_create.return_value = (- MagicMock(active_provider_key=None, trial_evals_used=0, trial_eval_limit=100),- False,- )+ mock_get_or_create.return_value = (_mock_config_with_active_key("openai"), False)mock_client = MagicMock()mock_client_class.return_value = mock_clientmock_response = MagicMock()diff --git a/posthog/temporal/ai_observability/test_run_tagger.py b/posthog/temporal/ai_observability/test_run_tagger.pyindex f6097ee6e9e3..0bb2fd6a4b60 100644--- a/posthog/temporal/ai_observability/test_run_tagger.py+++ b/posthog/temporal/ai_observability/test_run_tagger.py@@ -10,6 +10,7 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.models import Organization, Team+from products.ai_observability.backend.models.provider_keys import LLMProviderKeyfrom products.ai_observability.backend.models.taggers import Taggerfrom .run_tagger import (@@ -41,6 +42,12 @@ def create_mock_event_data(team_id: int, **overrides: Any) -> dict[str, Any]:return {**defaults, **overrides}+def _mock_config_with_active_key(provider: str = "openai") -> MagicMock:+ """A mocked EvaluationConfig whose active key resolves via DefaultModelSpec (usable, right provider)."""+ key = MagicMock(provider=provider, state=LLMProviderKey.State.OK)+ return MagicMock(active_provider_key=key)++def make_tagger_config():return {"prompt": "Which product features were discussed?",@@ -179,10 +186,7 @@ class TestRunTaggerWorkflow:mock_client.complete.return_value = mock_responsewith patch("posthog.temporal.ai_observability.model_resolution.EvaluationConfig") as mock_eval_config:- mock_config = MagicMock()- mock_config.active_provider_key = None- # A bare MagicMock auto-returns a truthy child for the real @property — pin it explicitly.- mock_config.is_trial_grandfathered = True+ mock_config = _mock_config_with_active_key()mock_eval_config.objects.get_or_create.return_value = (mock_config, False)result = await execute_tagger_activity(ExecuteTaggerInputs(tagger=tagger, event_data=event_data))@@ -221,9 +225,7 @@ class TestRunTaggerWorkflow:mock_client.complete.return_value = mock_responsewith patch("posthog.temporal.ai_observability.model_resolution.EvaluationConfig") as mock_eval_config:- mock_config = MagicMock()- mock_config.active_provider_key = None- mock_config.is_trial_grandfathered = True+ mock_config = _mock_config_with_active_key()mock_eval_config.objects.get_or_create.return_value = (mock_config, False)result = await execute_tagger_activity(ExecuteTaggerInputs(tagger=tagger, event_data=event_data))@@ -263,9 +265,7 @@ class TestRunTaggerWorkflow:mock_client.complete.return_value = mock_responsewith patch("posthog.temporal.ai_observability.model_resolution.EvaluationConfig") as mock_eval_config:- mock_config = MagicMock()- mock_config.active_provider_key = None- mock_config.is_trial_grandfathered = True+ mock_config = _mock_config_with_active_key()mock_eval_config.objects.get_or_create.return_value = (mock_config, False)result = await execute_tagger_activity(ExecuteTaggerInputs(tagger=tagger, event_data=event_data))@@ -291,8 +291,6 @@ class TestRunTaggerWorkflow:with patch("posthog.temporal.ai_observability.model_resolution.EvaluationConfig") as mock_eval_config:mock_config = MagicMock()mock_config.active_provider_key = None- # A bare MagicMock would return a truthy child and silently pass the funded gate.- mock_config.is_trial_grandfathered = Falsemock_eval_config.objects.get_or_create.return_value = (mock_config, False)with pytest.raises(ApplicationError) as exc_info:diff --git a/posthog/temporal/ai_observability/test_run_trace_evaluation.py b/posthog/temporal/ai_observability/test_run_trace_evaluation.pyindex 1c9be99c311f..e23eedfc590f 100644--- a/posthog/temporal/ai_observability/test_run_trace_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_trace_evaluation.py@@ -13,6 +13,7 @@ from posthog.models import Organization, Teamfrom products.ai_observability.backend.models.evaluation_config import EvaluationConfigfrom products.ai_observability.backend.models.evaluations import Evaluation+from products.ai_observability.backend.models.provider_keys import LLMProviderKeyfrom .evaluation_llm_judge import BooleanEvalResultfrom .evaluation_types import EvaluationActivityResult@@ -74,10 +75,17 @@ def setup_data():@pytest.fixture-def grandfathered(setup_data, settings):- # A team mid-trial before the cutoff keeps PostHog-funded inference, so trial/keyless judges run.- settings.AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE = "2999-12-31T00:00:00+00:00"- EvaluationConfig.objects.create(team=setup_data["team"], trial_eval_limit=100, trial_evals_used=50)+def active_key_config(setup_data):+ """Give the team a healthy active provider key so a null-config judge resolves via DefaultModelSpec."""+ team = setup_data["team"]+ key = LLMProviderKey.objects.create(+ team=team,+ provider="openai",+ name="openai key",+ state=LLMProviderKey.State.OK,+ encrypted_config={"api_key": "sk-test"},+ )+ EvaluationConfig.objects.create(team=team, active_provider_key=key)def evaluation_dict(setup_data: dict, **overrides: Any) -> dict[str, Any]:@@ -258,7 +266,7 @@ class TestFetchTraceForEvaluation:class TestExecuteTraceLLMJudgeActivity:@pytest.mark.django_db(transaction=True)- def test_judges_full_trace_transcript(self, setup_data, grandfathered):+ def test_judges_full_trace_transcript(self, setup_data, active_key_config):trace = create_trace([create_trace_event("$ai_generation", **{"$ai_input": "What is 2+2?", "$ai_output": "4"}),diff --git a/posthog/test/activity_logging/test_evaluation_activity_logging.py b/posthog/test/activity_logging/test_evaluation_activity_logging.pyindex c63af4979c8e..51b2aa080269 100644--- a/posthog/test/activity_logging/test_evaluation_activity_logging.py+++ b/posthog/test/activity_logging/test_evaluation_activity_logging.py@@ -1,7 +1,5 @@from typing import Any-from django.test import override_settings-from rest_framework import statusfrom posthog.test.activity_log_utils import ActivityLogTestHelper@@ -34,13 +32,13 @@ def _create_evaluation_payload(**overrides: Any) -> dict[str, Any]:return payload-# The create payloads are keyless llm_judge with enabled=True, which only validates for a-# grandfathered team.-@override_settings(AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE="2999-12-31T00:00:00+00:00")+# The create payloads are keyless llm_judge with enabled=True, which only validates when the+# team's active provider key covers them.class TestEvaluationActivityLogging(ActivityLogTestHelper):def setUp(self) -> None:super().setUp()- EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=50)+ active_key = self._create_provider_key(name="Active key")+ EvaluationConfig.objects.create(team=self.team, active_provider_key=active_key)def _create_evaluation(self, **overrides: Any) -> dict[str, Any]:response = self.client.post(@@ -207,35 +205,6 @@ class TestEvaluationActivityLogging(ActivityLogTestHelper):defaults.update(overrides)return Evaluation.objects.create(**defaults)- def test_assigning_provider_key_clears_error_status_in_activity_log(self):- # An errored eval cleared via provider-key assignment goes through QuerySet.update(), which- # bypasses ModelActivityMixin.save(). The viewset must log the status transition explicitly.- key = self._create_provider_key()- mc = LLMModelConfiguration.objects.create(team=self.team, provider="openai", model="gpt-5-mini")- evaluation = self._create_evaluation_orm(- model_configuration=mc,- enabled=False,- status="error",- status_reason="provider_key_deleted",- )- self.clear_activity_logs()-- response = self.client.post(- f"/api/environments/{self.team.id}/llm_analytics/provider_keys/{key.id}/assign/",- {"evaluation_ids": [str(evaluation.id)]},- format="json",- )- self.assertEqual(response.status_code, status.HTTP_200_OK)-- logs = self.get_activity_logs_for_item("Evaluation", str(evaluation.id))- self.assertEqual(len(logs), 1)- fields = {c["field"]: c for c in logs[0].detail["changes"]}- self.assertEqual(fields["status"]["before"], "error")- self.assertEqual(fields["status"]["after"], "paused")- self.assertEqual(fields["status_reason"]["before"], "provider_key_deleted")- self.assertIsNone(fields["status_reason"]["after"])- self.assertNotIn("enabled", fields) # error -> paused both have enabled=False-def test_deleting_provider_key_logs_active_to_error_transition(self):key = self._create_provider_key()mc = LLMModelConfiguration.objects.create(diff --git a/products/ai_observability/backend/api/evaluation_config.py b/products/ai_observability/backend/api/evaluation_config.pyindex 76f671c3024a..5b1c54d3e15e 100644--- a/products/ai_observability/backend/api/evaluation_config.py+++ b/products/ai_observability/backend/api/evaluation_config.py@@ -1,7 +1,4 @@-from datetime import datetime--from drf_spectacular.types import OpenApiTypes-from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field, extend_schema_serializer+from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_serializerfrom rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.permissions import IsAuthenticated@@ -15,7 +12,6 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.event_usage import report_user_actionfrom posthog.permissions import AccessControlPermission-from ..constants import trial_eval_deprecation_datefrom ..models.evaluation_config import EvaluationConfigfrom ..models.provider_keys import LLMProviderKeyfrom .metrics import llma_track_latency@@ -24,56 +20,25 @@ from .provider_keys import LLMProviderKeySerializer@extend_schema_serializer(many=False)class EvaluationConfigSerializer(serializers.ModelSerializer):- trial_evals_remaining = serializers.IntegerField(- read_only=True,- help_text="Trial runs remaining — a getting-started affordance only; evals should use the team's own provider key.",- )- trial_grandfathered = serializers.BooleanField(- source="is_trial_grandfathered",- read_only=True,- help_text="True while this team keeps PostHog-funded trial inference during the deprecation window (i.e. it is mid-trial and the cutoff has not passed). False means the team must use its own provider key.",- )- trial_deprecation_date = serializers.SerializerMethodField(- help_text="Timestamp after which trial evaluations are fully removed and every team must use its own provider key.",- )active_provider_key = LLMProviderKeySerializer(read_only=True,allow_null=True,help_text="Provider key used to run llm_judge evals; null if none configured yet.",)- @extend_schema_field(OpenApiTypes.DATETIME)- def get_trial_deprecation_date(self, _obj: EvaluationConfig) -> datetime:- return trial_eval_deprecation_date()-class Meta:model = EvaluationConfigfields = [- "trial_eval_limit",- "trial_evals_used",- "trial_evals_remaining",- "trial_grandfathered",- "trial_deprecation_date","active_provider_key","created_at","updated_at",]read_only_fields = [- "trial_eval_limit",- "trial_evals_used",- "trial_evals_remaining",- "trial_grandfathered","active_provider_key","created_at","updated_at",]extra_kwargs = {- "trial_eval_limit": {- "help_text": "Cap on trial runs — a getting-started affordance only, not for ongoing evals (use the team's own key).",- },- "trial_evals_used": {- "help_text": "Trial runs consumed (getting-started affordance only).",- },"created_at": {"help_text": "Timestamp when the evaluation config row was created."},"updated_at": {"help_text": "Timestamp when the evaluation config row was last modified."},}diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.pyindex 405916c740fc..dfeb8f0172b7 100644--- a/products/ai_observability/backend/api/evaluations.py+++ b/products/ai_observability/backend/api/evaluations.py@@ -26,7 +26,7 @@ from posthog.temporal.ai_observability.model_resolution import active_key_fallbafrom posthog.temporal.ai_observability.run_evaluation import extract_event_io, run_hog_evalfrom ..hog import compile_ai_observability_hog-from ..llm import DEFAULT_MODEL_BY_PROVIDER, TRIAL_MODEL_IDS+from ..llm import DEFAULT_MODEL_BY_PROVIDERfrom ..models.evaluation_config import EvaluationConfigfrom ..models.evaluation_configs import (TRACE_EVAL_DEFAULT_WINDOW_SECONDS,@@ -424,47 +424,28 @@ class EvaluationSerializer(serializers.ModelSerializer):"""Mirror the runtime model resolution for evals with no usable provider key (see`posthog/temporal/ai_observability/model_resolution.py`). A pinned key, or an explicitconfig's active-key fallback, is already handled by `_validate_can_run`; this covers what- is left: a null config resolves via the team's active key, else PostHog-funded trial- inference while the team is still grandfathered; an explicit config that reached here has- no active-key fallback, so it resolves via funded inference only, and only for models on- the trial allowlist."""+ is left: a null config resolves via the team's active key, and anything else must add a+ provider key of its own."""add_key_message = "Add a provider API key to enable this evaluation."team = self.context["get_team"]()config = EvaluationConfig.objects.filter(team=team).first()- is_grandfathered = config is not None and config.is_trial_grandfatheredexplicit_config = self._effective_model_configuration(data)- if explicit_config is None:- active_key = config.active_provider_key if config else None- if active_key is not None:- # DefaultModelSpec never falls back to funded inference when an active key exists,- # so an unhealthy key blocks the enable regardless of grandfathering.- if active_key.state != LLMProviderKey.State.OK:- raise serializers.ValidationError(- {"enabled": "Attach a working provider API key to enable this evaluation."}- )- if DEFAULT_MODEL_BY_PROVIDER.get(active_key.provider) is None:- raise serializers.ValidationError(- {- "enabled": "This evaluation's provider has no default model. Set a model on the evaluation before enabling it."- }- )- return- if is_grandfathered:- return+ if explicit_config is not None:raise serializers.ValidationError({"enabled": add_key_message})- if not is_grandfathered:+ active_key = config.active_provider_key if config else None+ if active_key is None:raise serializers.ValidationError({"enabled": add_key_message})- model = explicit_config.get("model")- if model and model not in TRIAL_MODEL_IDS:+ if active_key.state != LLMProviderKey.State.OK:+ raise serializers.ValidationError(+ {"enabled": "Attach a working provider API key to enable this evaluation."}+ )+ if DEFAULT_MODEL_BY_PROVIDER.get(active_key.provider) is None:raise serializers.ValidationError({- "enabled": (- f"Model '{model}' is not available on the trial plan. "- "Either choose a supported trial model or add a provider API key."- )+ "enabled": "This evaluation's provider has no default model. Set a model on the evaluation before enabling it."})diff --git a/products/ai_observability/backend/api/models.py b/products/ai_observability/backend/api/models.pyindex 12f881bb8c79..5d046e234669 100644--- a/products/ai_observability/backend/api/models.py+++ b/products/ai_observability/backend/api/models.py@@ -10,8 +10,6 @@ from posthog.api.monitoring import monitorfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.permissions import AccessControlPermission-from ..llm import TRIAL_MODELS_BY_PROVIDER-from ..models.evaluation_config import EvaluationConfigfrom ..models.model_configuration import LLMModelConfigurationfrom ..models.provider_keys import LLMProvider, LLMProviderKeyfrom .metrics import llma_track_latency@@ -21,9 +19,6 @@ class LLMModelInfoSerializer(serializers.Serializer):id = serializers.CharField(help_text="Provider-specific model identifier (e.g. 'gpt-4o-mini', 'claude-3-5-sonnet-20241022').")- posthog_available = serializers.BooleanField(- help_text="True if the model can run without a provider key on PostHog-funded trial credits. Only true for teams still grandfathered into the deprecating trial; every other team must use its own key."- )@extend_schema_serializer(many=False)@@ -105,11 +100,4 @@ class LLMModelsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):)available = config.get_available_models()- # A team with no config row was never mid-trial, so a read-only lookup suffices.- eval_config = EvaluationConfig.objects.filter(team_id=self.team_id).first()- is_grandfathered = eval_config is not None and eval_config.is_trial_grandfathered- posthog_allowed = TRIAL_MODELS_BY_PROVIDER.get(provider, []) if is_grandfathered else []-- return Response(- {"models": [{"id": model, "posthog_available": model in posthog_allowed} for model in available]}- )+ return Response({"models": [{"id": model} for model in available]})diff --git a/products/ai_observability/backend/api/provider_keys.py b/products/ai_observability/backend/api/provider_keys.pyindex cc474980a8c7..01b0e0aef766 100644--- a/products/ai_observability/backend/api/provider_keys.py+++ b/products/ai_observability/backend/api/provider_keys.py@@ -3,7 +3,7 @@ from uuid import UUIDfrom django.core.cache import cachefrom django.db import transaction-from django.db.models import Q, QuerySet+from django.db.models import QuerySetfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import extend_schema@@ -422,117 +422,6 @@ class LLMProviderKeyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, v})- @action(detail=False, methods=["get"])- @llma_track_latency("llma_provider_keys_trial_evaluations")- @monitor(feature=None, endpoint="llma_provider_keys_trial_evaluations", method="GET")- def trial_evaluations(self, request: Request, **_kwargs) -> Response:- """List enabled evaluations currently using trial credits for a given provider."""- provider = request.query_params.get("provider")- if not provider:- return Response({"detail": "provider query parameter is required"}, status=status.HTTP_400_BAD_REQUEST)- if provider not in [choice[0] for choice in LLMProvider.choices]:- return Response({"detail": f"Unsupported provider: {provider}"}, status=status.HTTP_400_BAD_REQUEST)-- # Evaluations on trial: model_configuration has matching provider but no pinned key- trial_filter = Q(- model_configuration__provider=provider,- model_configuration__provider_key__isnull=True,- )- # Legacy evaluations (no model_configuration) default to OpenAI- if provider == "openai":- trial_filter |= Q(model_configuration__isnull=True)-- # The legacy "no model_configuration" clause above would otherwise include Hog/Sentiment evals.- trial_evals = (- Evaluation.objects.filter(trial_filter, team_id=self.team_id, deleted=False)- .using_provider_keys()- .values("id", "name", "enabled")[:50]- )-- return Response({"evaluations": list(trial_evals)})-- @action(detail=True, methods=["post"])- @llma_track_latency("llma_provider_keys_assign")- @monitor(feature=None, endpoint="llma_provider_keys_assign", method="POST")- def assign(self, request: Request, **_kwargs) -> Response:- """Assign this key to evaluations and optionally re-enable them."""- instance = self.get_object()- evaluation_ids = request.data.get("evaluation_ids", [])- enable = request.data.get("enable", False)-- if not evaluation_ids:- return Response({"detail": "evaluation_ids is required"}, status=status.HTTP_400_BAD_REQUEST)-- with transaction.atomic():- # Update model configurations to use this key- model_config_ids = list(- LLMModelConfiguration.objects.filter(- evaluations__id__in=evaluation_ids,- evaluations__team_id=self.team_id,- evaluations__deleted=False,- provider=instance.provider,- )- .distinct()- .values_list("id", flat=True)- )- configs_updated = LLMModelConfiguration.objects.filter(- id__in=model_config_ids,- team_id=self.team_id,- ).update(provider_key=instance)- _reload_model_config_dependents_on_commit(self.team_id, model_config_ids)-- # Handle legacy evaluations (no model_configuration) — these are always- # OpenAI, so only create a config if the key matches. Exclude Hog/Sentiment: minting a- # config for them locks the eval out of all future edits.- if instance.provider == "openai":- legacy_evals = Evaluation.objects.filter(- id__in=evaluation_ids,- team_id=self.team_id,- model_configuration__isnull=True,- deleted=False,- ).using_provider_keys()- for eval_obj in legacy_evals:- mc = LLMModelConfiguration.objects.create(- team_id=self.team_id,- provider="openai",- model="gpt-5-mini",- provider_key=instance,- )- eval_obj.model_configuration = mc- eval_obj.save(update_fields=["model_configuration"])- configs_updated += 1-- # A key assignment resolves any `provider_key_deleted` / `model_not_allowed` error on the- # dependent evals — the cause no longer applies once they're attached to a live key.- for eval_obj in Evaluation.objects.filter(- id__in=evaluation_ids, team_id=self.team_id, deleted=False, status="error"- ).using_provider_keys():- eval_obj.set_status("paused")-- evals_enabled = 0- if enable:- for eval_obj in Evaluation.objects.filter(- id__in=evaluation_ids, team_id=self.team_id, deleted=False, enabled=False- ).using_provider_keys():- eval_obj.set_status("active")- evals_enabled += 1-- report_user_action(- request.user,- "llma provider key assigned to evaluations",- {- "provider_key_id": str(instance.id),- "provider": instance.provider,- "evaluation_ids": [str(eid) for eid in evaluation_ids],- "configs_updated": configs_updated,- "evals_enabled": evals_enabled,- },- team=self.team,- request=self.request,- )-- return Response({"configs_updated": configs_updated, "evals_enabled": evals_enabled})-@llma_track_latency("llma_provider_keys_destroy")@monitor(feature=None, endpoint="llma_provider_keys_destroy", method="DELETE")def destroy(self, request, *args, **kwargs):diff --git a/products/ai_observability/backend/api/proxy.py b/products/ai_observability/backend/api/proxy.pyindex 00d7b8ab597b..58eb545c4105 100644--- a/products/ai_observability/backend/api/proxy.py+++ b/products/ai_observability/backend/api/proxy.py@@ -40,12 +40,12 @@ from posthog.settings import SERVER_GATEWAY_INTERFACEfrom products.ai_observability.backend.api.metrics import LLMA_PROXY_BYOK_REQUESTS, llma_track_latencyfrom products.ai_observability.backend.llm import (+ PLAYGROUND_MODEL_IDS,SUPPORTED_MODELS_WITH_THINKING,- TRIAL_MODEL_IDS,Client,CompletionRequest,ModelInfo,- get_trial_models,+ get_playground_models,)from products.ai_observability.backend.llm.errors import UnsupportedProviderErrorfrom products.ai_observability.backend.models.provider_keys import LLMProvider, LLMProviderKey@@ -106,7 +106,7 @@ class LLMProxyViewSet(viewsets.ViewSet):if self.action == "models":return []- # BYOK requests should not count against shared playground trial limits.+ # BYOK requests should not count against shared playground limits.# Check the provider key directly from request data to avoid running the# full serializer just for throttle selection.if self.action == "completion":@@ -237,11 +237,11 @@ class LLMProxyViewSet(viewsets.ViewSet):except ValueError:return Response({"error": "Invalid provider key configuration"}, status=400)- # Enforce trial model allowlist when using PostHog-funded keys- if provider_key is None and model not in TRIAL_MODEL_IDS:+ # Enforce playground model allowlist when using PostHog-funded keys+ if provider_key is None and model not in PLAYGROUND_MODEL_IDS:return Response({- "error": f"Model '{model}' is not available on the trial plan. Please add your own API key to use this model."+ "error": f"Model '{model}' is not available on the PostHog-funded playground. Please add your own API key to use this model."},status=403,)@@ -390,7 +390,7 @@ class LLMProxyViewSet(viewsets.ViewSet):"""Return a list of available models across providers.If provider_key_id is specified, returns models available for that key.- Otherwise, returns only trial-eligible models (PostHog pays for these).+ Otherwise, returns only playground-eligible models (PostHog pays for these)."""provider_key_id = request.query_params.get("provider_key_id")@@ -428,8 +428,8 @@ class LLMProxyViewSet(viewsets.ViewSet):])- # Default: return only trial-eligible models (PostHog pays for these)- return Response(get_trial_models())+ # Default: return only playground-eligible models (PostHog pays for these)+ return Response(get_playground_models())@action(detail=False, methods=["POST"])@llma_track_latency("llma_proxy_completion")diff --git a/products/ai_observability/backend/api/test/test_evaluation_config.py b/products/ai_observability/backend/api/test/test_evaluation_config.pyindex 7b53866f04bb..89bbdf5600ae 100644--- a/products/ai_observability/backend/api/test/test_evaluation_config.py+++ b/products/ai_observability/backend/api/test/test_evaluation_config.py@@ -42,19 +42,10 @@ class TestEvaluationConfigViewSet(APIBaseTest):response = self.client.get(f"/api/environments/{self.team.id}/llm_analytics/evaluation_config/")self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertIn("trial_eval_limit", response.data)- self.assertIn("trial_evals_used", response.data)- self.assertIn("trial_evals_remaining", response.data)self.assertIn("active_provider_key", response.data)- self.assertEqual(response.data["trial_eval_limit"], 100)- self.assertEqual(response.data["trial_evals_used"], 0)- self.assertEqual(response.data["trial_evals_remaining"], 100)self.assertIsNone(response.data["active_provider_key"])- # The frontend gates the terminal/grandfathered UI on these two fields.- self.assertIn("trial_grandfathered", response.data)- self.assertFalse(response.data["trial_grandfathered"])- self.assertIn("trial_deprecation_date", response.data)- self.assertIsNotNone(response.data["trial_deprecation_date"])+ self.assertIn("created_at", response.data)+ self.assertIn("updated_at", response.data)def test_get_creates_config_if_missing(self):self.assertEqual(EvaluationConfig.objects.filter(team=self.team).count(), 0)@@ -65,22 +56,12 @@ class TestEvaluationConfigViewSet(APIBaseTest):self.assertEqual(EvaluationConfig.objects.filter(team=self.team).count(), 1)def test_get_returns_existing_config(self):- EvaluationConfig.objects.create(team=self.team, trial_evals_used=50)+ existing = EvaluationConfig.objects.create(team=self.team)response = self.client.get(f"/api/environments/{self.team.id}/llm_analytics/evaluation_config/")self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.data["trial_evals_used"], 50)- self.assertEqual(response.data["trial_evals_remaining"], 50)-- def test_trial_grandfathered_field_reflects_is_trial_grandfathered_property(self):- # The field must track the model property; pin the cutoff for wall-clock determinism.- with self.settings(AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE="2999-12-31T00:00:00+00:00"):- EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=50)-- response = self.client.get(f"/api/environments/{self.team.id}/llm_analytics/evaluation_config/")-- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertTrue(response.data["trial_grandfathered"])+ self.assertEqual(EvaluationConfig.objects.filter(team=self.team).count(), 1)+ self.assertEqual(EvaluationConfig.objects.get(team=self.team).pk, existing.pk)def test_can_set_active_key(self):key = LLMProviderKey.objects.create(@@ -170,20 +151,6 @@ class TestEvaluationConfigViewSet(APIBaseTest):self.assertEqual(response.data["attr"], "key_id")self.assertEqual(response.data["code"], "required")- def test_trial_evals_remaining_calculated_correctly(self):- EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=75)-- response = self.client.get(f"/api/environments/{self.team.id}/llm_analytics/evaluation_config/")- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.data["trial_evals_remaining"], 25)-- def test_trial_evals_remaining_never_negative(self):- EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=150)-- response = self.client.get(f"/api/environments/{self.team.id}/llm_analytics/evaluation_config/")- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.data["trial_evals_remaining"], 0)-def test_can_change_active_key(self):key1 = LLMProviderKey.objects.create(team=self.team,diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.pyindex a6dbdc7387b9..3f6ffc5834c7 100644--- a/products/ai_observability/backend/api/test/test_evaluations.py+++ b/products/ai_observability/backend/api/test/test_evaluations.py@@ -85,23 +85,29 @@ class TestEvaluationConfigsApi(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)def test_can_create_evaluation_config(self):- # Creating enabled+keyless only validates for a grandfathered team; pin the cutoff for determinism.- with self.settings(AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE="2999-12-31T00:00:00+00:00"):- EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=50)- response = self.client.post(- f"/api/environments/{self.team.id}/evaluations/",- {- "name": "Test Evaluation",- "description": "Test Description",- "enabled": True,- "evaluation_type": "llm_judge",- "model_configuration": _DEFAULT_MODEL_CONFIGURATION,- "evaluation_config": {"prompt": "Test prompt"},- "output_type": "boolean",- "output_config": {},- "conditions": [{"id": "test-condition", "rollout_percentage": 50, "properties": []}],- },- )+ key = LLMProviderKey.objects.create(+ team=self.team,+ provider="openai",+ name="Active Key",+ state=LLMProviderKey.State.OK,+ encrypted_config={"api_key": "sk-test"},+ created_by=self.user,+ )+ EvaluationConfig.objects.create(team=self.team, active_provider_key=key)+ response = self.client.post(+ f"/api/environments/{self.team.id}/evaluations/",+ {+ "name": "Test Evaluation",+ "description": "Test Description",+ "enabled": True,+ "evaluation_type": "llm_judge",+ "model_configuration": _DEFAULT_MODEL_CONFIGURATION,+ "evaluation_config": {"prompt": "Test prompt"},+ "output_type": "boolean",+ "output_config": {},+ "conditions": [{"id": "test-condition", "rollout_percentage": 50, "properties": []}],+ },+ )self.assertEqual(response.status_code, status.HTTP_201_CREATED)self.assertEqual(Evaluation.objects.count(), 1)@@ -1035,10 +1041,10 @@ class TestTestHogEndpoint(APIBaseTest):class TestEnableBlockingWhenKeyRequired(APIBaseTest):- """Enabling a keyless llm_judge eval must mirror the runtime funded-inference gate: a config- with no pinned key falls back to the team's active key for the same provider, else only- grandfathered (mid-trial, pre-cutoff) teams may run it via funded inference. Anything the- serializer lets through here would just flap back to disabled on the next Temporal run."""+ """Enabling a keyless llm_judge eval must mirror the runtime provider-key gate: a config with+ no pinned key falls back to the team's active key for the same provider, else the eval needs a+ provider key of its own. Anything the serializer lets through here would just flap back to+ disabled on the next Temporal run."""def _create_keyless_eval(self, model_configuration=...):if model_configuration is ...:@@ -1075,13 +1081,11 @@ class TestEnableBlockingWhenKeyRequired(APIBaseTest):@parameterized.expand([- ("trial_exhausted_explicit_config", 100, True),- ("trial_never_started_explicit_config", 0, True),- ("trial_never_started_null_config", 0, False),+ ("explicit_config", True),+ ("null_config", False),])- def test_blocks_enabling_keyless_eval_when_not_grandfathered(self, _name, trial_evals_used, explicit_config):- EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=trial_evals_used)+ def test_blocks_enabling_keyless_eval_without_key(self, _name, explicit_config):eval_obj = (self._create_keyless_eval() if explicit_config else self._create_keyless_eval(model_configuration=None))@@ -1093,24 +1097,11 @@ class TestEnableBlockingWhenKeyRequired(APIBaseTest):eval_obj.refresh_from_db()self.assertFalse(eval_obj.enabled)- def test_allows_enabling_keyless_eval_while_grandfathered(self):- with self.settings(AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE="2999-12-31T00:00:00+00:00"):- EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=50)- eval_obj = self._create_keyless_eval()-- response = self._enable(eval_obj)-- self.assertEqual(response.status_code, status.HTTP_200_OK)- eval_obj.refresh_from_db()- self.assertTrue(eval_obj.enabled)-def test_active_team_key_enables_explicit_keyless_eval(self):# An explicit config with no pinned key falls back to the team's active key for the same- # provider, so it enables even with the trial exhausted (mirrors runtime resolution).+ # provider (mirrors runtime resolution).key = self._create_active_key()- EvaluationConfig.objects.create(- team=self.team, trial_eval_limit=100, trial_evals_used=100, active_provider_key=key- )+ EvaluationConfig.objects.create(team=self.team, active_provider_key=key)eval_obj = self._create_keyless_eval()response = self._enable(eval_obj)@@ -1122,9 +1113,7 @@ class TestEnableBlockingWhenKeyRequired(APIBaseTest):def test_active_team_key_enables_null_config_eval(self):# Null configs resolve via the active key at runtime — the gate must not over-block them.key = self._create_active_key()- EvaluationConfig.objects.create(- team=self.team, trial_eval_limit=100, trial_evals_used=100, active_provider_key=key- )+ EvaluationConfig.objects.create(team=self.team, active_provider_key=key)eval_obj = self._create_keyless_eval(model_configuration=None)response = self._enable(eval_obj)@@ -1133,25 +1122,21 @@ class TestEnableBlockingWhenKeyRequired(APIBaseTest):eval_obj.refresh_from_db()self.assertTrue(eval_obj.enabled)- def test_unhealthy_active_key_blocks_null_config_eval_even_while_grandfathered(self):- # Runtime never falls back to funded inference when an active key exists, even unhealthy.+ def test_unhealthy_active_key_blocks_null_config_eval(self):key = self._create_active_key()key.state = LLMProviderKey.State.INVALIDkey.save()- with self.settings(AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE="2999-12-31T00:00:00+00:00"):- EvaluationConfig.objects.create(- team=self.team, trial_eval_limit=100, trial_evals_used=50, active_provider_key=key- )- eval_obj = self._create_keyless_eval(model_configuration=None)+ EvaluationConfig.objects.create(team=self.team, active_provider_key=key)+ eval_obj = self._create_keyless_eval(model_configuration=None)- response = self._enable(eval_obj)+ response = self._enable(eval_obj)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertIn("working provider API key", str(response.data))eval_obj.refresh_from_db()self.assertFalse(eval_obj.enabled)- def test_blocks_creating_enabled_keyless_eval_when_not_grandfathered(self):+ def test_blocks_creating_enabled_keyless_eval_without_key(self):response = self.client.post(f"/api/environments/{self.team.id}/evaluations/",{@@ -1171,8 +1156,7 @@ class TestEnableBlockingWhenKeyRequired(APIBaseTest):self.assertIn("Add a provider API key", str(response.data))self.assertEqual(Evaluation.objects.filter(name="Doomed Eval").count(), 0)- def test_allows_enabling_hog_eval_when_limit_reached(self):- EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=100)+ def test_allows_enabling_hog_eval_without_key(self):eval_obj = Evaluation.objects.create(team=self.team,name="Hog Eval",@@ -1194,8 +1178,7 @@ class TestEnableBlockingWhenKeyRequired(APIBaseTest):eval_obj.refresh_from_db()self.assertTrue(eval_obj.enabled)- def test_allows_enabling_byok_eval_when_limit_reached(self):- EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=100)+ def test_allows_enabling_byok_eval(self):key = LLMProviderKey.objects.create(team=self.team,provider="openai",@@ -1229,8 +1212,7 @@ class TestEnableBlockingWhenKeyRequired(APIBaseTest):eval_obj.refresh_from_db()self.assertTrue(eval_obj.enabled)- def test_rejects_enabling_trial_eval_with_unusable_byok_key_when_limit_reached(self):- EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=100)+ def test_rejects_enabling_llm_judge_eval_with_unusable_byok_key(self):key = LLMProviderKey.objects.create(team=self.team,provider="openai",@@ -1288,64 +1270,6 @@ class TestReEnableValidatesRootCauseResolved(APIBaseTest):eval_obj.refresh_from_db()return eval_obj- def test_rejects_re_enable_when_model_still_not_allowed(self):- # Only a grandfathered team gets past the funded gate to the model-allowlist message.- with self.settings(AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE="2999-12-31T00:00:00+00:00"):- EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=50)- eval_obj = self._create_errored_eval(status_reason="model_not_allowed", model="gpt-9")-- response = self.client.patch(- f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",- {"enabled": True},- format="json",- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn("not available on the trial plan", str(response.data))-- def test_allows_re_enable_when_byok_key_attached_even_if_model_not_allowed(self):- key = LLMProviderKey.objects.create(- team=self.team,- provider="openai",- name="Key",- state=LLMProviderKey.State.OK,- encrypted_config={"api_key": "sk-test"},- created_by=self.user,- )- eval_obj = self._create_errored_eval(status_reason="model_not_allowed", model="gpt-9", provider_key=key)-- response = self.client.patch(- f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",- {"enabled": True},- format="json",- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- eval_obj.refresh_from_db()- self.assertTrue(eval_obj.enabled)- self.assertEqual(eval_obj.status, "active")- self.assertIsNone(eval_obj.status_reason)-- def test_rejects_re_enable_when_model_not_allowed_with_unusable_byok_key(self):- key = LLMProviderKey.objects.create(- team=self.team,- provider="openai",- name="Key",- state=LLMProviderKey.State.INVALID,- encrypted_config={"api_key": "sk-test"},- created_by=self.user,- )- eval_obj = self._create_errored_eval(status_reason="model_not_allowed", model="gpt-9", provider_key=key)-- response = self.client.patch(- f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",- {"enabled": True},- format="json",- )-- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn("working provider API key", str(response.data))- eval_obj.refresh_from_db()- self.assertFalse(eval_obj.enabled)-def test_rejects_re_enable_when_provider_key_required_and_no_key(self):eval_obj = self._create_errored_eval(status_reason="provider_key_required")@@ -1429,16 +1353,21 @@ class TestReEnableValidatesRootCauseResolved(APIBaseTest):self.assertIn("working provider API key", str(response.data))def test_allows_re_enable_when_model_not_found_with_existing_model_config(self):- # Grandfather the team so the funded gate passes — this test is about the model_not_found rule.- with self.settings(AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE="2999-12-31T00:00:00+00:00"):- EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=50)- eval_obj = self._create_errored_eval(status_reason="model_not_found")-- response = self.client.patch(- f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",- {"enabled": True},- format="json",- )+ key = LLMProviderKey.objects.create(+ team=self.team,+ provider="openai",+ name="Key",+ state=LLMProviderKey.State.OK,+ encrypted_config={"api_key": "sk-test"},+ created_by=self.user,+ )+ eval_obj = self._create_errored_eval(status_reason="model_not_found", provider_key=key)++ response = self.client.patch(+ f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",+ {"enabled": True},+ format="json",+ )self.assertEqual(response.status_code, status.HTTP_200_OK)eval_obj.refresh_from_db()@@ -1446,22 +1375,28 @@ class TestReEnableValidatesRootCauseResolved(APIBaseTest):self.assertIsNone(eval_obj.status_reason)def test_allows_re_enable_when_model_not_found_with_new_model(self):- with self.settings(AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE="2999-12-31T00:00:00+00:00"):- EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=50)- eval_obj = self._create_errored_eval(status_reason="model_not_found", model="missing-model")+ key = LLMProviderKey.objects.create(+ team=self.team,+ provider="openai",+ name="Key",+ state=LLMProviderKey.State.OK,+ encrypted_config={"api_key": "sk-test"},+ created_by=self.user,+ )+ eval_obj = self._create_errored_eval(status_reason="model_not_found", model="missing-model")- response = self.client.patch(- f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",- {- "enabled": True,- "model_configuration": {- "provider": "openai",- "model": "gpt-5-mini",- "provider_key_id": None,- },+ response = self.client.patch(+ f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",+ {+ "enabled": True,+ "model_configuration": {+ "provider": "openai",+ "model": "gpt-5-mini",+ "provider_key_id": str(key.id),},- format="json",- )+ },+ format="json",+ )self.assertEqual(response.status_code, status.HTTP_200_OK)eval_obj.refresh_from_db()diff --git a/products/ai_observability/backend/api/test/test_models.py b/products/ai_observability/backend/api/test/test_models.pyindex 656df510e23c..1becebb4cf3a 100644--- a/products/ai_observability/backend/api/test/test_models.py+++ b/products/ai_observability/backend/api/test/test_models.py@@ -3,24 +3,21 @@ from unittest.mock import patchfrom django.test import SimpleTestCase-from parameterized import parameterizedfrom rest_framework import statusfrom products.ai_observability.backend.api.models import LLMModelInfoSerializer, LLMModelsListResponseSerializer-from products.ai_observability.backend.llm import TRIAL_MODELS_BY_PROVIDER-from products.ai_observability.backend.models.evaluation_config import EvaluationConfigclass TestLLMModelInfoSerializer(SimpleTestCase):def test_serializes_expected_shape(self):- serializer = LLMModelInfoSerializer(data={"id": "gpt-4o-mini", "posthog_available": True})+ serializer = LLMModelInfoSerializer(data={"id": "gpt-4o-mini"})self.assertTrue(serializer.is_valid(), serializer.errors)- self.assertEqual(serializer.validated_data, {"id": "gpt-4o-mini", "posthog_available": True})+ self.assertEqual(serializer.validated_data, {"id": "gpt-4o-mini"})- def test_rejects_missing_fields(self):- serializer = LLMModelInfoSerializer(data={"id": "gpt-4o-mini"})+ def test_rejects_missing_id(self):+ serializer = LLMModelInfoSerializer(data={})self.assertFalse(serializer.is_valid())- self.assertIn("posthog_available", serializer.errors)+ self.assertIn("id", serializer.errors)class TestLLMModelsListResponseSerializer(SimpleTestCase):@@ -28,8 +25,8 @@ class TestLLMModelsListResponseSerializer(SimpleTestCase):serializer = LLMModelsListResponseSerializer(data={"models": [- {"id": "gpt-4o-mini", "posthog_available": True},- {"id": "gpt-4o", "posthog_available": False},+ {"id": "gpt-4o-mini"},+ {"id": "gpt-4o"},]})@@ -61,28 +58,6 @@ class TestLLMModelsViewSet(APIBaseTest):self.assertIn("models", response.data)returned_ids = [m["id"] for m in response.data["models"]]self.assertEqual(returned_ids, ["gpt-4o-mini", "gpt-4o"])- for entry in response.data["models"]:- self.assertIn("posthog_available", entry)-- @parameterized.expand(- [- ("grandfathered", 50, True),- ("terminal", 100, False),- ]- )- @patch("products.ai_observability.backend.api.models.LLMModelConfiguration")- def test_posthog_available_requires_grandfathering(self, _name, trial_evals_used, expected, mock_config_cls):- # This flag feeds the MCP judge-models tool — a regression silently re-offers- # PostHog-funded models to terminal teams via agents.- trial_model = TRIAL_MODELS_BY_PROVIDER["openai"][0]- mock_config_cls.return_value.get_available_models.return_value = [trial_model]- with self.settings(AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE="2999-12-31T00:00:00+00:00"):- EvaluationConfig.objects.create(team=self.team, trial_eval_limit=100, trial_evals_used=trial_evals_used)-- response = self.client.get(f"/api/environments/{self.team.id}/llm_analytics/models/?provider=openai")-- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.data["models"][0]["posthog_available"], expected)def test_unauthenticated_user_cannot_list_models(self):self.client.logout()diff --git a/products/ai_observability/backend/api/test/test_provider_keys.py b/products/ai_observability/backend/api/test/test_provider_keys.pyindex 04d037539cca..e86409c24dc3 100644--- a/products/ai_observability/backend/api/test/test_provider_keys.py+++ b/products/ai_observability/backend/api/test/test_provider_keys.py@@ -712,47 +712,6 @@ class TestLLMProviderKeyViewSet(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertIsNone(cache.get(cache_key))- def test_assign_reloads_model_config_dependents(self):- key = LLMProviderKey.objects.create(- team=self.team,- provider="openai",- name="My Key",- state=LLMProviderKey.State.OK,- encrypted_config={"api_key": "sk-test-key"},- created_by=self.user,- )- model_config = LLMModelConfiguration.objects.create(- team=self.team,- provider="openai",- model="gpt-5-mini",- )- evaluation = Evaluation.objects.create(- team=self.team,- name="Test evaluation",- evaluation_type="llm_judge",- evaluation_config={"prompt": "Is this useful?"},- output_type="boolean",- output_config={},- model_configuration=model_config,- created_by=self.user,- conditions=[{"id": "cond-1", "rollout_percentage": 100, "properties": []}],- )-- with (- patch("products.ai_observability.backend.api.provider_keys.reload_evaluations_on_workers") as mock_evals,- patch("products.ai_observability.backend.api.provider_keys.reload_taggers_on_workers") as mock_taggers,- self.captureOnCommitCallbacks(execute=True),- ):- response = self.client.post(- f"/api/environments/{self.team.id}/llm_analytics/provider_keys/{key.id}/assign/",- {"evaluation_ids": [str(evaluation.id)]},- format="json",- )-- self.assertEqual(response.status_code, status.HTTP_200_OK)- mock_evals.assert_called_once_with(team_id=self.team.id, evaluation_ids=[str(evaluation.id)])- mock_taggers.assert_not_called()-def test_destroy_reloads_tagger_model_config_dependents(self):key = LLMProviderKey.objects.create(team=self.team,@@ -1222,251 +1181,3 @@ class TestLLMProviderKeyDependentConfigs(APIBaseTest):)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(LLMProviderKey.objects.filter(id=key.id).count(), 1)---class TestTrialEvaluationsEndpoint(APIBaseTest):- def _create_trial_eval(self, provider="openai", enabled=True):- mc = LLMModelConfiguration.objects.create(team=self.team, provider=provider, model="test-model")- return Evaluation.objects.create(- team=self.team,- name=f"Trial {provider}",- evaluation_type="llm_judge",- output_type="boolean",- model_configuration=mc,- enabled=enabled,- )-- def test_returns_trial_evals_for_provider(self):- self._create_trial_eval("openai")- self._create_trial_eval("anthropic")-- response = self.client.get(- f"/api/environments/{self.team.id}/llm_analytics/provider_keys/trial_evaluations/?provider=openai"- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(len(response.data["evaluations"]), 1)- self.assertEqual(response.data["evaluations"][0]["name"], "Trial openai")-- def test_excludes_evals_with_pinned_key(self):- key = LLMProviderKey.objects.create(- team=self.team,- provider="openai",- name="Key",- state=LLMProviderKey.State.OK,- encrypted_config={"api_key": "sk-test"},- created_by=self.user,- )- mc = LLMModelConfiguration.objects.create(- team=self.team,- provider="openai",- model="test",- provider_key=key,- )- Evaluation.objects.create(- team=self.team,- name="Pinned",- evaluation_type="llm_judge",- output_type="boolean",- model_configuration=mc,- enabled=True,- )-- response = self.client.get(- f"/api/environments/{self.team.id}/llm_analytics/provider_keys/trial_evaluations/?provider=openai"- )- self.assertEqual(len(response.data["evaluations"]), 0)-- def test_includes_legacy_evals_for_openai(self):- Evaluation.objects.create(- team=self.team,- name="Legacy",- evaluation_type="llm_judge",- output_type="boolean",- model_configuration=None,- enabled=True,- )-- response = self.client.get(- f"/api/environments/{self.team.id}/llm_analytics/provider_keys/trial_evaluations/?provider=openai"- )- self.assertEqual(len(response.data["evaluations"]), 1)- self.assertEqual(response.data["evaluations"][0]["name"], "Legacy")-- def test_excludes_non_llm_judge_evals(self):- # Hog and Sentiment evals have no model_configuration, so the legacy OpenAI clause would- # otherwise sweep them in — but they never use a provider key.- Evaluation.objects.create(- team=self.team,- name="Hog eval",- evaluation_type="hog",- output_type="boolean",- model_configuration=None,- enabled=True,- )- Evaluation.objects.create(- team=self.team,- name="Sentiment eval",- evaluation_type="sentiment",- output_type="sentiment",- model_configuration=None,- enabled=True,- )-- response = self.client.get(- f"/api/environments/{self.team.id}/llm_analytics/provider_keys/trial_evaluations/?provider=openai"- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(len(response.data["evaluations"]), 0)-- def test_rejects_invalid_provider(self):- response = self.client.get(- f"/api/environments/{self.team.id}/llm_analytics/provider_keys/trial_evaluations/?provider=invalid"- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)-- def test_requires_provider_param(self):- response = self.client.get(f"/api/environments/{self.team.id}/llm_analytics/provider_keys/trial_evaluations/")- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)---class TestAssignKeyEndpoint(APIBaseTest):- def setUp(self):- super().setUp()- self.organization_membership.level = OrganizationMembership.Level.ADMIN- self.organization_membership.save()-- def test_assigns_key_to_trial_evaluations(self):- key = LLMProviderKey.objects.create(- team=self.team,- provider="openai",- name="Key",- state=LLMProviderKey.State.OK,- encrypted_config={"api_key": "sk-test"},- created_by=self.user,- )- mc = LLMModelConfiguration.objects.create(team=self.team, provider="openai", model="gpt-5-mini")- eval_obj = Evaluation.objects.create(- team=self.team,- name="Eval",- evaluation_type="llm_judge",- output_type="boolean",- model_configuration=mc,- enabled=True,- )-- response = self.client.post(- f"/api/environments/{self.team.id}/llm_analytics/provider_keys/{key.id}/assign/",- {"evaluation_ids": [str(eval_obj.id)]},- format="json",- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.data["configs_updated"], 1)-- mc.refresh_from_db()- self.assertEqual(mc.provider_key, key)-- def test_assigns_key_and_reenables(self):- key = LLMProviderKey.objects.create(- team=self.team,- provider="openai",- name="Key",- state=LLMProviderKey.State.OK,- encrypted_config={"api_key": "sk-test"},- created_by=self.user,- )- mc = LLMModelConfiguration.objects.create(team=self.team, provider="openai", model="gpt-5-mini")- eval_obj = Evaluation.objects.create(- team=self.team,- name="Eval",- evaluation_type="llm_judge",- output_type="boolean",- model_configuration=mc,- enabled=False,- )-- response = self.client.post(- f"/api/environments/{self.team.id}/llm_analytics/provider_keys/{key.id}/assign/",- {"evaluation_ids": [str(eval_obj.id)], "enable": True},- format="json",- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.data["evals_enabled"], 1)-- eval_obj.refresh_from_db()- self.assertTrue(eval_obj.enabled)-- def test_handles_legacy_evals(self):- key = LLMProviderKey.objects.create(- team=self.team,- provider="openai",- name="Key",- state=LLMProviderKey.State.OK,- encrypted_config={"api_key": "sk-test"},- created_by=self.user,- )- eval_obj = Evaluation.objects.create(- team=self.team,- name="Legacy",- evaluation_type="llm_judge",- output_type="boolean",- model_configuration=None,- )-- response = self.client.post(- f"/api/environments/{self.team.id}/llm_analytics/provider_keys/{key.id}/assign/",- {"evaluation_ids": [str(eval_obj.id)]},- format="json",- )- self.assertEqual(response.status_code, status.HTTP_200_OK)-- eval_obj.refresh_from_db()- assert eval_obj.model_configuration is not None- self.assertEqual(eval_obj.model_configuration.provider_key, key)-- def test_rejects_empty_evaluation_ids(self):- key = LLMProviderKey.objects.create(- team=self.team,- provider="openai",- name="Key",- state=LLMProviderKey.State.OK,- encrypted_config={"api_key": "sk-test"},- created_by=self.user,- )-- response = self.client.post(- f"/api/environments/{self.team.id}/llm_analytics/provider_keys/{key.id}/assign/",- {"evaluation_ids": []},- format="json",- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)-- def test_does_not_create_config_for_hog_eval(self):- key = LLMProviderKey.objects.create(- team=self.team,- provider="openai",- name="Key",- state=LLMProviderKey.State.OK,- encrypted_config={"api_key": "sk-test"},- created_by=self.user,- )- hog_eval = Evaluation.objects.create(- team=self.team,- name="Hog eval",- evaluation_type="hog",- output_type="boolean",- model_configuration=None,- enabled=False,- )-- response = self.client.post(- f"/api/environments/{self.team.id}/llm_analytics/provider_keys/{key.id}/assign/",- {"evaluation_ids": [str(hog_eval.id)], "enable": True},- format="json",- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.data["evals_enabled"], 0)-- hog_eval.refresh_from_db()- self.assertIsNone(hog_eval.model_configuration)- self.assertFalse(hog_eval.enabled)- self.assertEqual(LLMModelConfiguration.objects.filter(team=self.team).count(), 0)diff --git a/products/ai_observability/backend/api/test/test_proxy.py b/products/ai_observability/backend/api/test/test_proxy.pyindex 386db8ddfed5..8fb9af94dc1b 100644--- a/products/ai_observability/backend/api/test/test_proxy.py+++ b/products/ai_observability/backend/api/test/test_proxy.py@@ -19,10 +19,15 @@ from posthog.rate_limit import ()from products.ai_observability.backend.api.proxy import LLMProxyCompletionSerializer, LLMProxyViewSet-from products.ai_observability.backend.llm import PROVIDERS, TRIAL_MODEL_IDS, get_default_models, get_trial_models+from products.ai_observability.backend.llm import (+ PLAYGROUND_MODEL_IDS,+ PROVIDERS,+ get_default_models,+ get_playground_models,+)from products.ai_observability.backend.models.provider_keys import LLMProviderKey-TRIAL_THROTTLES = (LLMProxyBurstRateThrottle, LLMProxySustainedRateThrottle, LLMProxyDailyRateThrottle)+PLAYGROUND_THROTTLES = (LLMProxyBurstRateThrottle, LLMProxySustainedRateThrottle, LLMProxyDailyRateThrottle)BYOK_THROTTLES = (LLMProxyBYOKBurstRateThrottle, LLMProxyBYOKSustainedRateThrottle, LLMProxyBYOKDailyRateThrottle)@@ -50,9 +55,9 @@ class TestLLMProxyThrottles(APIBaseTest):# Params: (provider_key_id, key_provider, encrypted_config, request_provider, has_team, expected_throttles)@parameterized.expand([- ("no_provider_key", None, "openai", None, "openai", True, TRIAL_THROTTLES),- ("invalid_provider_key_id", str(uuid4()), "openai", None, "openai", True, TRIAL_THROTTLES),- ("provider_key_without_api_key", "generated", "openai", {}, "openai", True, TRIAL_THROTTLES),+ ("no_provider_key", None, "openai", None, "openai", True, PLAYGROUND_THROTTLES),+ ("invalid_provider_key_id", str(uuid4()), "openai", None, "openai", True, PLAYGROUND_THROTTLES),+ ("provider_key_without_api_key", "generated", "openai", {}, "openai", True, PLAYGROUND_THROTTLES),("valid_matching_provider_key","generated",@@ -107,7 +112,15 @@ class TestLLMProxyThrottles(APIBaseTest):True,BYOK_THROTTLES,),- ("user_without_team", "generated", "openai", {"api_key": "sk-test-key"}, "openai", False, TRIAL_THROTTLES),+ (+ "user_without_team",+ "generated",+ "openai",+ {"api_key": "sk-test-key"},+ "openai",+ False,+ PLAYGROUND_THROTTLES,+ ),])def test_completion_throttle_behavior(@@ -163,28 +176,28 @@ class TestLLMProxyThrottles(APIBaseTest):assert serializer.validated_data["seed"] == 42-class TestTrialModelAllowlist(TestCase):- def test_trial_models_are_subset_of_supported_models(self) -> None:+class TestPlaygroundModelAllowlist(TestCase):+ def test_playground_models_are_subset_of_supported_models(self) -> None:for _, config in PROVIDERS:- assert set(config.TRIAL_MODELS) <= set(config.SUPPORTED_MODELS), (- f"{config.__name__}.TRIAL_MODELS contains models not in SUPPORTED_MODELS"+ assert set(config.PLAYGROUND_MODELS) <= set(config.SUPPORTED_MODELS), (+ f"{config.__name__}.PLAYGROUND_MODELS contains models not in SUPPORTED_MODELS")def test_model_ids_unique_across_providers(self) -> None:- all_trial: list[str] = []+ all_playground: list[str] = []for _, config in PROVIDERS:- all_trial.extend(config.TRIAL_MODELS)- assert len(all_trial) == len(set(all_trial)), "Duplicate model IDs found across providers"+ all_playground.extend(config.PLAYGROUND_MODELS)+ assert len(all_playground) == len(set(all_playground)), "Duplicate model IDs found across providers"- def test_get_trial_models_returns_only_trial_eligible(self) -> None:- trial_ids = {m["id"] for m in get_trial_models()}- assert trial_ids == TRIAL_MODEL_IDS+ def test_get_playground_models_returns_only_playground_eligible(self) -> None:+ playground_ids = {m["id"] for m in get_playground_models()}+ assert playground_ids == PLAYGROUND_MODEL_IDS- def test_get_trial_models_smaller_than_default(self) -> None:- assert len(get_trial_models()) < len(get_default_models())+ def test_get_playground_models_smaller_than_default(self) -> None:+ assert len(get_playground_models()) < len(get_default_models())-class TestTrialModelEnforcement(APIBaseTest):+class TestPlaygroundModelEnforcement(APIBaseTest):def setUp(self) -> None:super().setUp()self.organization.customer_id = "cus_test"@@ -204,17 +217,17 @@ class TestTrialModelEnforcement(APIBaseTest):("expensive_anthropic", "claude-opus-4-6", "anthropic"),])- def test_completion_rejects_non_trial_model(self, _name: str, model: str, provider: str) -> None:+ def test_completion_rejects_non_playground_model(self, _name: str, model: str, provider: str) -> None:response = self.client.post("/api/llm_proxy/completion/",data=self._completion_payload(model, provider),format="json",)assert response.status_code == 403- assert "not available on the trial plan" in response.json()["error"]+ assert "not available on the PostHog-funded playground" in response.json()["error"]@patch("products.ai_observability.backend.api.proxy.Client")- def test_completion_allows_trial_model(self, mock_client_cls) -> None:+ def test_completion_allows_playground_model(self, mock_client_cls) -> None:mock_client_cls.return_value.stream.return_value = iter([])response = self.client.post("/api/llm_proxy/completion/",@@ -227,7 +240,7 @@ class TestTrialModelEnforcement(APIBaseTest):mock_client_cls.return_value.stream.assert_called_once()@patch("products.ai_observability.backend.api.proxy.Client")- def test_byok_key_bypasses_trial_allowlist(self, mock_client_cls) -> None:+ def test_byok_key_bypasses_playground_allowlist(self, mock_client_cls) -> None:mock_client_cls.return_value.stream.return_value = iter([])byok_key = LLMProviderKey.objects.create(team=self.team,@@ -248,8 +261,8 @@ class TestTrialModelEnforcement(APIBaseTest):b"".join(response.streaming_content) # type: ignore[attr-defined]mock_client_cls.return_value.stream.assert_called_once()- def test_models_endpoint_returns_only_trial_models(self) -> None:+ def test_models_endpoint_returns_only_playground_models(self) -> None:response = self.client.get("/api/llm_proxy/models/")assert response.status_code == 200returned_ids = {m["id"] for m in response.json()}- assert returned_ids == TRIAL_MODEL_IDS+ assert returned_ids == PLAYGROUND_MODEL_IDSdiff --git a/products/ai_observability/backend/constants.py b/products/ai_observability/backend/constants.pydeleted file mode 100644index 119a2d14c3cf..000000000000--- a/products/ai_observability/backend/constants.py+++ /dev/null@@ -1,15 +0,0 @@-from datetime import UTC, datetime--from django.conf import settings--# Cutoff for the trial-eval deprecation: grandfathered teams keep PostHog-funded inference until-# this date. Extendable without a deploy via the env var (see posthog/settings/base_variables.py).-DEFAULT_TRIAL_EVAL_DEPRECATION_DATE = datetime(2026, 7, 17, tzinfo=UTC)---def trial_eval_deprecation_date() -> datetime:- override = settings.AI_OBSERVABILITY_TRIAL_EVAL_DEPRECATION_DATE- if override:- parsed = datetime.fromisoformat(override)- return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)- return DEFAULT_TRIAL_EVAL_DEPRECATION_DATEdiff --git a/products/ai_observability/backend/llm/__init__.py b/products/ai_observability/backend/llm/__init__.pyindex d9eb8b362ae1..45e3df34fc27 100644--- a/products/ai_observability/backend/llm/__init__.py+++ b/products/ai_observability/backend/llm/__init__.py@@ -21,7 +21,7 @@ class ModelInfo(TypedDict):# Single registry of providers. Add new providers here and everything else-# (model lists, trial models, ID sets) derives from it automatically.+# (model lists, playground models, ID sets) derives from it automatically.PROVIDERS: list[tuple[str, Any]] = [("OpenAI", OpenAIConfig),("Anthropic", AnthropicConfig),@@ -41,23 +41,23 @@ def get_default_models() -> list[ModelInfo]:return result-def get_trial_models() -> list[ModelInfo]:- """Returns the models available to trial users (PostHog pays).+def get_playground_models() -> list[ModelInfo]:+ """Returns the models available in the PostHog-funded playground.This is a curated subset excluding expensive models like pro/opus tierswhile including one flagship per provider for quality evaluation."""result: list[ModelInfo] = []for display_name, config in PROVIDERS:- result.extend(_build_model_infos(display_name, config.TRIAL_MODELS))+ result.extend(_build_model_infos(display_name, config.PLAYGROUND_MODELS))return result-TRIAL_MODEL_IDS: frozenset[str] = frozenset(model for _, config in PROVIDERS for model in config.TRIAL_MODELS)+PLAYGROUND_MODEL_IDS: frozenset[str] = frozenset(model for _, config in PROVIDERS for model in config.PLAYGROUND_MODELS)# Provider-keyed lookup (lowercase keys matching DB provider values)-TRIAL_MODELS_BY_PROVIDER: dict[str, list[str]] = {- display_name.lower(): config.TRIAL_MODELS for display_name, config in PROVIDERS+PLAYGROUND_MODELS_BY_PROVIDER: dict[str, list[str]] = {+ display_name.lower(): config.PLAYGROUND_MODELS for display_name, config in PROVIDERS}# Model picked when an eval/tagger has no explicit model_configuration and the provider is@@ -79,11 +79,11 @@ __all__ = ["UnsupportedProviderError","PROVIDERS","SUPPORTED_MODELS_WITH_THINKING",- "TRIAL_MODEL_IDS",- "TRIAL_MODELS_BY_PROVIDER",+ "PLAYGROUND_MODEL_IDS",+ "PLAYGROUND_MODELS_BY_PROVIDER","DEFAULT_MODEL_BY_PROVIDER","get_default_models",- "get_trial_models",+ "get_playground_models","OpenAIConfig","AnthropicConfig","GeminiConfig",diff --git a/products/ai_observability/backend/llm/config.py b/products/ai_observability/backend/llm/config.pyindex f53dc2c8eb5e..a5a4dd3047f0 100644--- a/products/ai_observability/backend/llm/config.py+++ b/products/ai_observability/backend/llm/config.py@@ -5,25 +5,3 @@ from dataclasses import dataclassclass ProviderConfig:api_key: strbase_url: str | None = None---def get_eval_config(provider: str) -> ProviderConfig | None:- """Get eval-specific provider config with fallback to general settings."""- from django.conf import settings-- match provider:- case "openai":- api_key = settings.LLMA_EVAL_OPENAI_API_KEY or settings.OPENAI_API_KEY- base_url = settings.LLMA_EVAL_OPENAI_BASE_URL or settings.OPENAI_BASE_URL- case "anthropic":- api_key = settings.LLMA_EVAL_ANTHROPIC_API_KEY or settings.ANTHROPIC_API_KEY- base_url = None- case "gemini":- api_key = settings.LLMA_EVAL_GEMINI_API_KEY or settings.GEMINI_API_KEY- base_url = None- case _:- return None-- if not api_key:- return None- return ProviderConfig(api_key=api_key, base_url=base_url)diff --git a/products/ai_observability/backend/llm/providers/anthropic.py b/products/ai_observability/backend/llm/providers/anthropic.pyindex c7c97da337c6..49b69c3f63b0 100644--- a/products/ai_observability/backend/llm/providers/anthropic.py+++ b/products/ai_observability/backend/llm/providers/anthropic.py@@ -58,9 +58,9 @@ class AnthropicConfig:"claude-sonnet-4-0",]- # Models available to trial users (PostHog pays). Excludes expensive+ # Models available in the PostHog-funded playground. Excludes expensive# opus tiers and includes one flagship sonnet for quality evaluation.- TRIAL_MODELS: list[str] = [+ PLAYGROUND_MODELS: list[str] = ["claude-sonnet-4-6","claude-haiku-4-5",]diff --git a/products/ai_observability/backend/llm/providers/gemini.py b/products/ai_observability/backend/llm/providers/gemini.pyindex 5f580fff8757..c42f710cb69b 100644--- a/products/ai_observability/backend/llm/providers/gemini.py+++ b/products/ai_observability/backend/llm/providers/gemini.py@@ -52,9 +52,9 @@ class GeminiConfig:"gemini-1.5-pro",]- # Models available to trial users (PostHog pays). Excludes older/preview+ # Models available in the PostHog-funded playground. Excludes older/preview# pro tiers while keeping the current flagship (gemini-2.5-pro).- TRIAL_MODELS: list[str] = [+ PLAYGROUND_MODELS: list[str] = ["gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite",diff --git a/products/ai_observability/backend/llm/providers/openai.py b/products/ai_observability/backend/llm/providers/openai.pyindex 57134ac7e135..6bd61584cd63 100644--- a/products/ai_observability/backend/llm/providers/openai.py+++ b/products/ai_observability/backend/llm/providers/openai.py@@ -72,9 +72,9 @@ class OpenAIConfig:})- # Models available to trial users (PostHog pays). Excludes expensive+ # Models available in the PostHog-funded playground. Excludes expensive# "pro" tiers and includes one flagship model for quality evaluation.- TRIAL_MODELS: list[str] = [+ PLAYGROUND_MODELS: list[str] = ["gpt-4.1","gpt-4.1-mini","gpt-4.1-nano",diff --git a/products/ai_observability/backend/llm/providers/openai_compatible_byok.py b/products/ai_observability/backend/llm/providers/openai_compatible_byok.pyindex 434c0160374e..da55c006a587 100644--- a/products/ai_observability/backend/llm/providers/openai_compatible_byok.py+++ b/products/ai_observability/backend/llm/providers/openai_compatible_byok.py@@ -18,7 +18,7 @@ logger = logging.getLogger(__name__)class OpenAICompatibleByokAdapter(OpenAIAdapter):- """Base for providers with OpenAI-compatible APIs and no PostHog trial key."""+ """Base for providers with OpenAI-compatible APIs and no PostHog-funded key."""BASE_URL: ClassVar[str]PROVIDER_DISPLAY_NAME: ClassVar[str]diff --git a/products/ai_observability/backend/llm/providers/openrouter.py b/products/ai_observability/backend/llm/providers/openrouter.pyindex e47b63810e69..78aaaefc0ffe 100644--- a/products/ai_observability/backend/llm/providers/openrouter.py+++ b/products/ai_observability/backend/llm/providers/openrouter.py@@ -1,7 +1,7 @@"""OpenRouter provider for unified LLM client.OpenRouter is an LLM gateway with an OpenAI-compatible API that exposes models-from many providers. It is BYOKEY-only (no PostHog trial key).+from many providers. It is BYOKEY-only (no PostHog-funded key)."""import loggingdiff --git a/products/ai_observability/backend/llm/test/test_config.py b/products/ai_observability/backend/llm/test/test_config.pyindex 1c49dc9c6177..f838afde8302 100644--- a/products/ai_observability/backend/llm/test/test_config.py+++ b/products/ai_observability/backend/llm/test/test_config.py@@ -1,8 +1,6 @@-from django.test import SimpleTestCase, override_settings+from django.test import SimpleTestCase-from parameterized import parameterized--from products.ai_observability.backend.llm.config import ProviderConfig, get_eval_config+from products.ai_observability.backend.llm.config import ProviderConfigclass TestProviderConfig(SimpleTestCase):@@ -14,105 +12,3 @@ class TestProviderConfig(SimpleTestCase):def test_provider_config_default_base_url(self):config = ProviderConfig(api_key="test-key")assert config.base_url is None---class TestGetEvalConfig(SimpleTestCase):- @parameterized.expand(- [- ("openai", "LLMA_EVAL_OPENAI_API_KEY", "OPENAI_API_KEY", "LLMA_EVAL_OPENAI_BASE_URL", "OPENAI_BASE_URL"),- ("anthropic", "LLMA_EVAL_ANTHROPIC_API_KEY", "ANTHROPIC_API_KEY", None, None),- ("gemini", "LLMA_EVAL_GEMINI_API_KEY", "GEMINI_API_KEY", None, None),- ]- )- def test_eval_specific_key_takes_precedence(- self, provider, eval_key_setting, fallback_key_setting, eval_url_setting, fallback_url_setting- ):- settings_dict = {- eval_key_setting: "eval-specific-key",- fallback_key_setting: "fallback-key",- }- if eval_url_setting:- settings_dict[eval_url_setting] = "https://eval.example.com"- settings_dict[fallback_url_setting] = "https://fallback.example.com"-- with override_settings(**settings_dict):- config = get_eval_config(provider)-- assert config is not None- assert config.api_key == "eval-specific-key"- if eval_url_setting:- assert config.base_url == "https://eval.example.com"-- @parameterized.expand(- [- ("openai", "LLMA_EVAL_OPENAI_API_KEY", "OPENAI_API_KEY"),- ("anthropic", "LLMA_EVAL_ANTHROPIC_API_KEY", "ANTHROPIC_API_KEY"),- ("gemini", "LLMA_EVAL_GEMINI_API_KEY", "GEMINI_API_KEY"),- ]- )- def test_falls_back_to_general_key_when_eval_empty(self, provider, eval_key_setting, fallback_key_setting):- settings_dict = {- eval_key_setting: "",- fallback_key_setting: "fallback-key",- }- if provider == "openai":- settings_dict["LLMA_EVAL_OPENAI_BASE_URL"] = ""- settings_dict["OPENAI_BASE_URL"] = "https://fallback.example.com"-- with override_settings(**settings_dict):- config = get_eval_config(provider)-- assert config is not None- assert config.api_key == "fallback-key"- if provider == "openai":- assert config.base_url == "https://fallback.example.com"-- @parameterized.expand(- [- ("openai", "LLMA_EVAL_OPENAI_API_KEY", "OPENAI_API_KEY"),- ("anthropic", "LLMA_EVAL_ANTHROPIC_API_KEY", "ANTHROPIC_API_KEY"),- ("gemini", "LLMA_EVAL_GEMINI_API_KEY", "GEMINI_API_KEY"),- ]- )- def test_returns_none_when_no_key_available(self, provider, eval_key_setting, fallback_key_setting):- settings_dict = {- eval_key_setting: "",- fallback_key_setting: "",- }- if provider == "openai":- settings_dict["LLMA_EVAL_OPENAI_BASE_URL"] = ""- settings_dict["OPENAI_BASE_URL"] = "https://example.com"-- with override_settings(**settings_dict):- config = get_eval_config(provider)-- assert config is None-- def test_returns_none_for_unsupported_provider(self):- config = get_eval_config("unsupported")- assert config is None-- def test_openai_base_url_fallback(self):- with override_settings(- LLMA_EVAL_OPENAI_API_KEY="eval-key",- LLMA_EVAL_OPENAI_BASE_URL="",- OPENAI_BASE_URL="https://api.openai.com/v1",- ):- config = get_eval_config("openai")-- assert config is not None- assert config.base_url == "https://api.openai.com/v1"-- def test_anthropic_and_gemini_have_no_base_url(self):- with override_settings(- LLMA_EVAL_ANTHROPIC_API_KEY="anthropic-key",- LLMA_EVAL_GEMINI_API_KEY="gemini-key",- ):- anthropic_config = get_eval_config("anthropic")- gemini_config = get_eval_config("gemini")-- assert anthropic_config is not None- assert anthropic_config.base_url is None-- assert gemini_config is not None- assert gemini_config.base_url is Nonediff --git a/products/ai_observability/backend/migrations/0024_relabel_trial_status_reasons.py b/products/ai_observability/backend/migrations/0024_relabel_trial_status_reasons.pynew file mode 100644index 000000000000..7111b7941078--- /dev/null+++ b/products/ai_observability/backend/migrations/0024_relabel_trial_status_reasons.py@@ -0,0 +1,22 @@+from django.db import migrations+++def relabel_trial_status_reasons(apps, schema_editor):+ """Trial evaluations are gone, so any evaluation still carrying a trial-era disable reason is now+ just a keyless eval that needs a provider key. 0017 relabeled terminal teams but left mid-trial+ (grandfathered) teams' labels intact; sweep whatever remains to `provider_key_required`."""+ Evaluation = apps.get_model("ai_observability", "Evaluation")+ Evaluation.objects.filter(status_reason__in=["trial_limit_reached", "model_not_allowed"]).update(+ status_reason="provider_key_required", status_reason_detail=None+ )+++class Migration(migrations.Migration):+ dependencies = [+ ("ai_observability", "0023_llmpromptlabel"),+ ]++ operations = [+ # Lossy relabel; reverse is a no-op.+ migrations.RunPython(relabel_trial_status_reasons, migrations.RunPython.noop),+ ]diff --git a/products/ai_observability/backend/migrations/0025_alter_evaluation_status_reason.py b/products/ai_observability/backend/migrations/0025_alter_evaluation_status_reason.pynew file mode 100644index 000000000000..5282f1a00525--- /dev/null+++ b/products/ai_observability/backend/migrations/0025_alter_evaluation_status_reason.py@@ -0,0 +1,37 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("ai_observability", "0024_relabel_trial_status_reasons"),+ ]++ operations = [+ # Choices-only change; emits no SQL on Postgres.+ migrations.AlterField(+ model_name="evaluation",+ name="status_reason",+ field=models.CharField(+ blank=True,+ choices=[+ ("provider_key_required", "No provider API key configured"),+ ("provider_key_deleted", "Provider API key was deleted"),+ (+ "no_default_model",+ "No default model available for the selected provider",+ ),+ ("provider_key_invalid", "Provider API key is invalid"),+ (+ "provider_key_permission_denied",+ "Provider API key lacks model access",+ ),+ ("provider_key_quota_exceeded", "Provider API key quota exceeded"),+ ("provider_key_rate_limited", "Provider API key is rate limited"),+ ("model_not_found", "Model not found"),+ ("hog_error", "Hog evaluation code failed"),+ ],+ max_length=50,+ null=True,+ ),+ ),+ ]diff --git a/products/ai_observability/backend/migrations/0026_retire_trial_columns.py b/products/ai_observability/backend/migrations/0026_retire_trial_columns.pynew file mode 100644index 000000000000..ed7b126b9675--- /dev/null+++ b/products/ai_observability/backend/migrations/0026_retire_trial_columns.py@@ -0,0 +1,38 @@+from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("ai_observability", "0025_alter_evaluation_status_reason"),+ ]++ operations = [+ # Retire the trial columns from Django's state now, but keep them in the DB so pods still+ # running the previous release keep working through the rollout. Drop NOT NULL and set+ # DB-level defaults (the old model defaults) so inserts from either release stay valid:+ # new code omits the columns and gets the defaults instead of NULL, so old code never+ # reads NULL and the reverse SET NOT NULL cannot fail. A follow-up migration physically+ # drops the columns once the previous release is fully gone.+ migrations.SeparateDatabaseAndState(+ database_operations=[+ migrations.RunSQL(+ sql=[+ "ALTER TABLE llm_analytics_evaluationconfig ALTER COLUMN trial_eval_limit DROP NOT NULL;",+ "ALTER TABLE llm_analytics_evaluationconfig ALTER COLUMN trial_eval_limit SET DEFAULT 100;",+ "ALTER TABLE llm_analytics_evaluationconfig ALTER COLUMN trial_evals_used DROP NOT NULL;",+ "ALTER TABLE llm_analytics_evaluationconfig ALTER COLUMN trial_evals_used SET DEFAULT 0;",+ ],+ reverse_sql=[+ "ALTER TABLE llm_analytics_evaluationconfig ALTER COLUMN trial_evals_used DROP DEFAULT;",+ "ALTER TABLE llm_analytics_evaluationconfig ALTER COLUMN trial_evals_used SET NOT NULL;",+ "ALTER TABLE llm_analytics_evaluationconfig ALTER COLUMN trial_eval_limit DROP DEFAULT;",+ "ALTER TABLE llm_analytics_evaluationconfig ALTER COLUMN trial_eval_limit SET NOT NULL;",+ ],+ ),+ ],+ state_operations=[+ migrations.RemoveField(model_name="evaluationconfig", name="trial_eval_limit"),+ migrations.RemoveField(model_name="evaluationconfig", name="trial_evals_used"),+ ],+ ),+ ]diff --git a/products/ai_observability/backend/migrations/max_migration.txt b/products/ai_observability/backend/migrations/max_migration.txtindex 439eda06d283..5fe7a221056b 100644--- a/products/ai_observability/backend/migrations/max_migration.txt+++ b/products/ai_observability/backend/migrations/max_migration.txt@@ -1 +1 @@-0023_llmpromptlabel+0026_retire_trial_columnsdiff --git a/products/ai_observability/backend/migrations/test/__init__.py b/products/ai_observability/backend/migrations/test/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/ai_observability/backend/migrations/test/test_migration_0026.py b/products/ai_observability/backend/migrations/test/test_migration_0026.pynew file mode 100644index 000000000000..681871c17e34--- /dev/null+++ b/products/ai_observability/backend/migrations/test/test_migration_0026.py@@ -0,0 +1,93 @@+from typing import Any++from posthog.test.base import NonAtomicTestMigrations++from django.db import connection+from django.db.migrations.executor import MigrationExecutor+++# Non-atomic: the ALTER TABLE in 0026 cannot run in the same transaction as the FK-bearing+# fixture inserts (pending trigger events).+class RemoveTrialEvaluationsMigrationTest(NonAtomicTestMigrations):+ migrate_from = "0023_llmpromptlabel"+ migrate_to = "0026_retire_trial_columns"++ CLASS_DATA_LEVEL_SETUP = False++ @property+ def app(self) -> str:+ return "ai_observability"++ def setUpBeforeMigration(self, apps: Any) -> None:+ Organization = apps.get_model("posthog", "Organization")+ Project = apps.get_model("posthog", "Project")+ Team = apps.get_model("posthog", "Team")+ Evaluation = apps.get_model("ai_observability", "Evaluation")+ EvaluationConfig = apps.get_model("ai_observability", "EvaluationConfig")++ org = Organization.objects.create(name="Test Organization")+ project = Project.objects.create(id=999_998, organization=org, name="Test Project")+ team = Team.objects.create(organization=org, project=project, name="Test Team")+ self.team_id = team.id+ self.organization_id = org.id+ self.project_id = project.id++ EvaluationConfig.objects.create(team=team, trial_eval_limit=100, trial_evals_used=50)++ def create_evaluation(name: str, status_reason: str, detail: str) -> Any:+ return Evaluation.objects.create(+ team=team,+ name=name,+ evaluation_type="llm_judge",+ output_type="boolean",+ enabled=False,+ status="error",+ status_reason=status_reason,+ status_reason_detail=detail,+ )++ self.trial_limit_eval_id = create_evaluation(+ "trial limit", "trial_limit_reached", "Trial evaluation limit reached."+ ).id+ self.model_not_allowed_eval_id = create_evaluation(+ "model not allowed", "model_not_allowed", "Model not on the trial plan."+ ).id+ self.control_eval_id = create_evaluation("control", "provider_key_deleted", "Key was deleted.").id++ def test_migration(self) -> None:+ assert self.apps is not None+ Evaluation = self.apps.get_model("ai_observability", "Evaluation")+ EvaluationConfig = self.apps.get_model("ai_observability", "EvaluationConfig")+ Team = self.apps.get_model("posthog", "Team")++ for eval_id in (self.trial_limit_eval_id, self.model_not_allowed_eval_id):+ migrated = Evaluation.objects.get(id=eval_id)+ self.assertEqual(migrated.status_reason, "provider_key_required")+ self.assertIsNone(migrated.status_reason_detail)++ control = Evaluation.objects.get(id=self.control_eval_id)+ self.assertEqual(control.status_reason, "provider_key_deleted")+ self.assertEqual(control.status_reason_detail, "Key was deleted.")++ # New configs no longer know about the retired columns, so the insert must be absorbed by+ # their DB defaults — pods on the previous release read these columns and must never see NULL.+ post_migration_team = Team.objects.create(+ organization_id=self.organization_id, project_id=self.project_id, name="Post-migration team"+ )+ EvaluationConfig.objects.create(team=post_migration_team)+ with connection.cursor() as cursor:+ cursor.execute(+ "SELECT trial_eval_limit, trial_evals_used FROM llm_analytics_evaluationconfig WHERE team_id = %s",+ [post_migration_team.id],+ )+ self.assertEqual(cursor.fetchone(), (100, 0))++ # Reverse (SET NOT NULL) must not trip over rows created after the columns were retired.+ executor = MigrationExecutor(connection)+ executor.loader.build_graph()+ executor.migrate([(self.app, self.migrate_from)])++ old_apps = executor.loader.project_state([(self.app, self.migrate_from)]).apps+ OldEvaluationConfig = old_apps.get_model("ai_observability", "EvaluationConfig")+ self.assertEqual(OldEvaluationConfig.objects.get(team_id=post_migration_team.id).trial_eval_limit, 100)+ self.assertEqual(OldEvaluationConfig.objects.get(team_id=self.team_id).trial_evals_used, 50)diff --git a/products/ai_observability/backend/models/evaluation_config.py b/products/ai_observability/backend/models/evaluation_config.pyindex 4bbade6c7a5a..1a53efe9c4ee 100644--- a/products/ai_observability/backend/models/evaluation_config.py+++ b/products/ai_observability/backend/models/evaluation_config.py@@ -1,11 +1,8 @@from django.db import models-from django.utils import timezone--from products.ai_observability.backend.constants import trial_eval_deprecation_dateclass EvaluationConfig(models.Model):- """Team-level configuration and usage tracking for evaluations"""+ """Team-level configuration for evaluations"""team = models.OneToOneField("posthog.Team",@@ -14,10 +11,6 @@ class EvaluationConfig(models.Model):related_name="evaluation_config",)- # Trial evaluations (permanent limit for alpha)- trial_eval_limit = models.IntegerField(default=100)- trial_evals_used = models.IntegerField(default=0)-# Active BYOK key (single source of truth)active_provider_key = models.ForeignKey("ai_observability.LLMProviderKey",@@ -35,15 +28,3 @@ class EvaluationConfig(models.Model):def __str__(self):return f"EvaluationConfig for team {self.team_id}"-- @property- def trial_evals_remaining(self) -> int:- return max(0, self.trial_eval_limit - self.trial_evals_used)-- @property- def is_trial_grandfathered(self) -> bool:- """Only teams already mid-trial keep PostHog-funded inference, and only until the cutoff.- Teams that never started (used == 0) or exhausted (used >= limit) the trial are terminal- and must bring their own provider key — as are all teams once the deprecation date passes.- """- return 0 < self.trial_evals_used < self.trial_eval_limit and timezone.now() < trial_eval_deprecation_date()diff --git a/products/ai_observability/backend/models/evaluations.py b/products/ai_observability/backend/models/evaluations.pyindex 18615b5a16ee..fa7eace8e5c2 100644--- a/products/ai_observability/backend/models/evaluations.py+++ b/products/ai_observability/backend/models/evaluations.py@@ -32,9 +32,6 @@ class EvaluationStatus(models.TextChoices):class EvaluationStatusReason(models.TextChoices):PROVIDER_KEY_REQUIRED = "provider_key_required", "No provider API key configured"- # Trial reasons — retained while mid-trial teams are grandfathered; removed once the trial is fully deprecated.- 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"PROVIDER_KEY_INVALID = "provider_key_invalid", "Provider API key is invalid"diff --git a/products/ai_observability/backend/models/model_configuration.py b/products/ai_observability/backend/models/model_configuration.pyindex a0dea72e189c..1734d710bc08 100644--- a/products/ai_observability/backend/models/model_configuration.py+++ b/products/ai_observability/backend/models/model_configuration.py@@ -45,16 +45,16 @@ class LLMModelConfiguration(UUIDTModel):def get_available_models(self) -> list[str]:"""Get available models — delegates to the provider API if a BYOK key is- present, otherwise returns the trial model list (PostHog pays)."""+ present, otherwise returns the playground model list (PostHog pays)."""if self.provider_key:from products.ai_observability.backend.llm.client import Clientapi_key = self.provider_key.encrypted_config.get("api_key")return Client.list_models(self.provider, api_key)- from products.ai_observability.backend.llm import TRIAL_MODELS_BY_PROVIDER+ from products.ai_observability.backend.llm import PLAYGROUND_MODELS_BY_PROVIDER- return TRIAL_MODELS_BY_PROVIDER.get(self.provider, [])+ return PLAYGROUND_MODELS_BY_PROVIDER.get(self.provider, [])def save(self, *args, **kwargs) -> None:self.full_clean()diff --git a/products/ai_observability/backend/models/test/test_evaluations.py b/products/ai_observability/backend/models/test/test_evaluations.pyindex a534f40cd2ab..0b7e3bd1ccba 100644--- a/products/ai_observability/backend/models/test/test_evaluations.py+++ b/products/ai_observability/backend/models/test/test_evaluations.py@@ -375,7 +375,7 @@ class TestEvaluationStatusCoercion(BaseTest):def test_flipping_enabled_true_on_errored_row_transitions_to_active_and_clears_reason(self):evaluation = self._create(enabled=False)evaluation.status = EvaluationStatus.ERROR- evaluation.status_reason = EvaluationStatusReason.TRIAL_LIMIT_REACHED+ evaluation.status_reason = EvaluationStatusReason.PROVIDER_KEY_REQUIREDevaluation.save()self.assertEqual(evaluation.status, EvaluationStatus.ERROR)@@ -394,17 +394,17 @@ class TestEvaluationStatusCoercion(BaseTest):def test_setting_status_error_with_reason_forces_enabled_false(self):evaluation = self._create(enabled=True)evaluation.status = EvaluationStatus.ERROR- evaluation.status_reason = EvaluationStatusReason.MODEL_NOT_ALLOWED+ evaluation.status_reason = EvaluationStatusReason.PROVIDER_KEY_REQUIREDevaluation.save()self.assertEqual(evaluation.status, EvaluationStatus.ERROR)self.assertFalse(evaluation.enabled)- self.assertEqual(evaluation.status_reason, EvaluationStatusReason.MODEL_NOT_ALLOWED)+ self.assertEqual(evaluation.status_reason, EvaluationStatusReason.PROVIDER_KEY_REQUIRED)def test_paused_status_clears_any_stale_status_reason(self):evaluation = self._create(enabled=True)evaluation.status = EvaluationStatus.ERROR- evaluation.status_reason = EvaluationStatusReason.TRIAL_LIMIT_REACHED- evaluation.status_reason_detail = "The trial limit was reached."+ evaluation.status_reason = EvaluationStatusReason.PROVIDER_KEY_REQUIRED+ evaluation.status_reason_detail = "No provider API key configured."evaluation.save()evaluation.status = EvaluationStatus.PAUSED@@ -432,7 +432,7 @@ class TestEvaluationStatusCoercion(BaseTest):evaluation = self._create(enabled=True)# Simulate a system transition happening elsewhere (another worker, another request, etc.).Evaluation.objects.filter(id=evaluation.id).update(- enabled=False, status=EvaluationStatus.ERROR, status_reason=EvaluationStatusReason.TRIAL_LIMIT_REACHED+ enabled=False, status=EvaluationStatus.ERROR, status_reason=EvaluationStatusReason.PROVIDER_KEY_REQUIRED)evaluation.refresh_from_db()diff --git a/products/ai_observability/frontend/ModelPicker.tsx b/products/ai_observability/frontend/ModelPicker.tsxindex a6903a42c01b..1252c6681355 100644--- a/products/ai_observability/frontend/ModelPicker.tsx+++ b/products/ai_observability/frontend/ModelPicker.tsx@@ -20,8 +20,8 @@ export function getModelPickerFooterLink(hasByokKeys: boolean): { label: string;}}-export function parseTrialProviderKeyId(providerKeyId: string): LLMProvider | null {- return providerKeyId.startsWith('trial:') ? toLLMProvider(providerKeyId.slice(6)) : null+export function parsePlaygroundProviderKeyId(providerKeyId: string): LLMProvider | null {+ return providerKeyId.startsWith('playground:') ? toLLMProvider(providerKeyId.slice(11)) : null}export interface ModelPickerProps {@@ -46,7 +46,7 @@ export function findSelectedProvider(if (exactMatch) {return exactMatch.provider}- // Fall back to matching by model id alone (e.g., trial mode where providerKeyId is null)+ // Fall back to matching by model id alone (e.g., playground mode where providerKeyId is null)const modelMatch = groups.find((g) => g.models.some((m) => m.id === model))return modelMatch?.provider ?? null}diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsxindex ede37e2b3ea1..5c8f991878b4 100644--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx@@ -628,25 +628,15 @@ export function AIObservabilityEvaluation(): JSX.Element {}function EvaluationModelPicker(): JSX.Element {- const {- hasByokKeys,- byokModels,- trialModels,- providerModelGroups,- trialProviderModelGroups,- byokModelsLoading,- trialModelsLoading,- providerKeysLoading,- } = useValues(modelPickerLogic)- const { selectedModel, selectedPickerProviderKeyId, requiresProviderKey, modelSelectionRequired } =- useValues(llmEvaluationLogic)+ const { hasByokKeys, byokModels, providerModelGroups, byokModelsLoading, providerKeysLoading } =+ useValues(modelPickerLogic)+ const { selectedModel, selectedPickerProviderKeyId, modelSelectionRequired } = useValues(llmEvaluationLogic)const { selectModelFromPicker } = useActions(llmEvaluationLogic)- const showTrialModels = !hasByokKeys && !requiresProviderKey- const allModels = showTrialModels ? trialModels : byokModels- const selectedModelName = allModels.find((m) => m.id === selectedModel)?.name- const groups = showTrialModels ? trialProviderModelGroups : providerModelGroups- const loading = showTrialModels ? trialModelsLoading : byokModelsLoading || providerKeysLoading+ // Evals always run on the team's own provider key, so only BYOK models are offered.+ const selectedModelName = byokModels.find((m) => m.id === selectedModel)?.name+ const groups = providerModelGroups+ const loading = byokModelsLoading || providerKeysLoadingconst footerLink = getModelPickerFooterLink(hasByokKeys)diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsxindex c6dfef934839..0c414acac5e8 100644--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx@@ -43,7 +43,6 @@ import {providerKeyStateLabel,providerLabel,} from '../settings/providerKeyStateUtils'-import { TrialUsageMeter } from '../settings/TrialUsageMeter'import {EvaluationMetrics,PASS_RATE_SUCCESS_THRESHOLD,@@ -411,8 +410,6 @@ function AIObservabilityEvaluationsContent(): JSX.Element {return (<div className="space-y-4">- <TrialUsageMeter showSettingsLink />-{unhealthyProviderKeysUsedByEvaluations.length > 0 && (<LemonBanner type="warning"><div className="space-y-2">diff --git a/products/ai_observability/frontend/evaluations/apiErrors.test.ts b/products/ai_observability/frontend/evaluations/apiErrors.test.tsindex 402a550aa250..7e853caa69d3 100644--- a/products/ai_observability/frontend/evaluations/apiErrors.test.ts+++ b/products/ai_observability/frontend/evaluations/apiErrors.test.ts@@ -7,9 +7,9 @@ describe('evaluationErrorMessage', () => {['extracts a DRF field-level validation error',new ApiError('Non-OK response', 400, undefined, {- enabled: ['Trial evaluation limit reached. Add a provider API key to re-enable.'],+ enabled: ['Add a provider API key to enable this evaluation.'],}),- 'Trial evaluation limit reached. Add a provider API key to re-enable.',+ 'Add a provider API key to enable this evaluation.',],['extracts a nested field error from a model_configuration-style payload',diff --git a/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts b/products/ai_observability/frontend/evaluations/evaluationCapabilities.tsindex 5ec76d45853f..c6f43c2347ec 100644--- a/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts+++ b/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts@@ -1,3 +1,4 @@+import type { LLMProviderKey } from '../settings/llmProviderKeysLogic'import type { EvaluationConfig, EvaluationOutputType, EvaluationType, LLMJudgeEvaluation } from './types'const REPORTABLE_OUTPUT_TYPES: ReadonlySet<EvaluationOutputType> = new Set(['boolean', 'sentiment'])@@ -37,8 +38,9 @@ export function evaluationTypeUsesProviderKey(evaluationType: EvaluationType | nexport function evaluationCanResolveModel(evaluation: Pick<EvaluationConfig, 'evaluation_type' | 'model_configuration'>,- requiresProviderKey: boolean,- isTrialGrandfathered: boolean+ // undefined = the team's evaluation config hasn't loaded yet — stay permissive rather than+ // flashing a disabled state; null = loaded, and there is no active key.+ activeProviderKey: Pick<LLMProviderKey, 'provider' | 'state'> | null | undefined): boolean {if (!evaluationTypeUsesProviderKey(evaluation.evaluation_type)) {return true@@ -46,12 +48,16 @@ export function evaluationCanResolveModel(if (evaluation.model_configuration?.provider_key_id) {return true}- // An explicit keyless config never falls back to the team's active key at runtime —- // it only resolves via PostHog-funded inference while the team is still grandfathered.- if (evaluation.model_configuration) {- return isTrialGrandfathered+ if (activeProviderKey === undefined) {+ return true+ }+ // No pinned key: the eval falls back to the team's active key, which must be healthy and —+ // when the eval has an explicit model configuration — belong to the same provider (mirrors+ // `active_key_fallback` in model_resolution.py).+ if (activeProviderKey === null || activeProviderKey.state !== 'ok') {+ return false}- return !requiresProviderKey+ return !evaluation.model_configuration || evaluation.model_configuration.provider === activeProviderKey.provider}export function evaluationTypeDefaultsToBooleanOutput(evaluationType: EvaluationType | null | undefined): boolean {diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.tsindex d6a9527e27d4..fe6cd8dba51c 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts@@ -231,21 +231,13 @@ describe('llmEvaluationLogic', () => {get: {'/api/environments/:teamId/llm_analytics/provider_keys/': { results: mockProviderKeys },'/api/environments/:teamId/llm_analytics/evaluation_config/': {- trial_eval_limit: 100,- trial_evals_used: 0,- trial_evals_remaining: 100,- trial_grandfathered: false,- trial_deprecation_date: '2026-07-15T00:00:00Z',active_provider_key: null,created_at: '2024-01-01T00:00:00Z',updated_at: '2024-01-01T00:00:00Z',},'/api/projects/:teamId/evaluations/:id/': mockEvaluation,'/api/environments/:teamId/llm_analytics/models/': {- models: [- { id: 'gpt-5-mini', posthog_available: true },- { id: 'gpt-5', posthog_available: false },- ],+ models: [{ id: 'gpt-5-mini' }, { id: 'gpt-5' }],},},})@@ -595,15 +587,10 @@ describe('llmEvaluationLogic', () => {describe('async flows', () => {describe('loadEvaluation', () => {it('initializes new evaluation with default values', async () => {- // Pin the team to a non-terminal state before mounting so the draft's enabled+ // Pin the team to a state with an active key before mounting so the draft's enabled// default doesn't depend on config-fetch timing.keysLogic.actions.loadEvaluationConfigSuccess({- trial_eval_limit: 100,- trial_evals_used: 50,- trial_evals_remaining: 50,- trial_grandfathered: true,- trial_deprecation_date: '2026-07-17T00:00:00Z',- active_provider_key: null,+ active_provider_key: mockProviderKeys[0],created_at: '2024-01-01T00:00:00Z',updated_at: '2024-01-01T00:00:00Z',})@@ -624,13 +611,8 @@ describe('llmEvaluationLogic', () => {})})- it('initializes new evaluation disabled for terminal teams that require a provider key', async () => {+ it('initializes new evaluation disabled for teams that require a provider key', async () => {keysLogic.actions.loadEvaluationConfigSuccess({- trial_eval_limit: 100,- trial_evals_used: 100,- trial_evals_remaining: 0,- trial_grandfathered: false,- trial_deprecation_date: '2026-07-17T00:00:00Z',active_provider_key: null,created_at: '2024-01-01T00:00:00Z',updated_at: '2024-01-01T00:00:00Z',@@ -650,12 +632,7 @@ describe('llmEvaluationLogic', () => {// The draft's enabled default is read before the config fetch resolves — the// listener must correct it when the config arrives late.keysLogic.actions.loadEvaluationConfigSuccess({- trial_eval_limit: 100,- trial_evals_used: 50,- trial_evals_remaining: 50,- trial_grandfathered: true,- trial_deprecation_date: '2026-07-17T00:00:00Z',- active_provider_key: null,+ active_provider_key: mockProviderKeys[0],created_at: '2024-01-01T00:00:00Z',updated_at: '2024-01-01T00:00:00Z',})@@ -668,11 +645,6 @@ describe('llmEvaluationLogic', () => {})keysLogic.actions.loadEvaluationConfigSuccess({- trial_eval_limit: 100,- trial_evals_used: 100,- trial_evals_remaining: 0,- trial_grandfathered: false,- trial_deprecation_date: '2026-07-17T00:00:00Z',active_provider_key: null,created_at: '2024-01-01T00:00:00Z',updated_at: '2024-01-01T00:00:00Z',@@ -1217,10 +1189,10 @@ describe('llmEvaluationLogic', () => {})})- it('sets model configuration from trial provider key', async () => {+ it('sets model configuration from playground provider key', async () => {await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])- logic.actions.selectModelFromPicker('gpt-5', 'trial:openai')+ logic.actions.selectModelFromPicker('gpt-5', 'playground:openai')await expectLogic(logic).toMatchValues({selectedModel: 'gpt-5',@@ -1417,11 +1389,6 @@ describe('llmEvaluationLogic', () => {get: {'/api/environments/:teamId/llm_analytics/provider_keys/': { results: mockProviderKeys },'/api/environments/:teamId/llm_analytics/evaluation_config/': {- trial_eval_limit: 100,- trial_evals_used: 100,- trial_evals_remaining: 0,- trial_grandfathered: false,- trial_deprecation_date: '2026-07-15T00:00:00Z',active_provider_key: null,created_at: '2024-01-01T00:00:00Z',updated_at: '2024-01-01T00:00:00Z',@@ -1432,7 +1399,7 @@ describe('llmEvaluationLogic', () => {'/api/projects/:teamId/evaluations/:id/': () => [400,{- enabled: ['Trial evaluation limit reached. Add a provider API key to re-enable.'],+ enabled: ['Add a provider API key to enable this evaluation.'],},],},diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.tsindex 9b4f098c8cbf..6a16ac123351 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts@@ -17,9 +17,9 @@ import {evaluationsTestHogCreate,llmAnalyticsEvaluationSummaryCreate,} from '../generated/api'-import { parseTrialProviderKeyId } from '../ModelPicker'+import { parsePlaygroundProviderKeyId } from '../ModelPicker'import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'-import type { EvaluationTrialConfig } from '../settings/llmProviderKeysLogic'+import type { EvaluationConfig as TeamEvaluationConfig } from '../settings/llmProviderKeysLogic'import { getUnhealthyProviderKey } from '../settings/providerKeyStateUtils'import { EvaluationRunsStats, queryEvaluationRuns, queryEvaluationRunsStats } from '../utils'import { evaluationErrorMessage } from './apiErrors'@@ -134,7 +134,7 @@ export interface LLMEvaluationLogicProps {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface llmEvaluationLogicValues {- isTrialGrandfathered: boolean // llmProviderKeysLogic+ activeProviderKey: LLMProviderKey | null | undefined // llmProviderKeysLogicproviderKeys: LLMProviderKey[] // llmProviderKeysLogicproviderKeysLoading: boolean // llmProviderKeysLogicrequiresProviderKey: boolean // llmProviderKeysLogic@@ -182,10 +182,10 @@ export interface llmEvaluationLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface llmEvaluationLogicActions {loadEvaluationConfigSuccess: (- evaluationConfig: EvaluationTrialConfig | null,+ evaluationConfig: TeamEvaluationConfig | null,payload?: any) => {- evaluationConfig: EvaluationTrialConfig | null+ evaluationConfig: TeamEvaluationConfig | nullpayload?: any} // llmProviderKeysLogicloadProviderKeys: () => any // llmProviderKeysLogic@@ -353,8 +353,7 @@ export interface llmEvaluationLogicMeta {formValid: (evaluation: EvaluationConfig | null, modelSelectionRequired: boolean) => booleancanEnable: (evaluation: EvaluationConfig | null,- requiresProviderKey: boolean,- isTrialGrandfathered: boolean+ activeProviderKey: LLMProviderKey | null | undefined) => booleancanEnableReason: (canEnable: boolean) => string | nullevaluationProviderKeyIssue: (@@ -403,7 +402,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([connect(() => ({values: [llmProviderKeysLogic,- ['providerKeys', 'providerKeysLoading', 'requiresProviderKey', 'isTrialGrandfathered'],+ ['providerKeys', 'providerKeysLoading', 'requiresProviderKey', 'activeProviderKey'],],actions: [llmProviderKeysLogic, ['loadProviderKeys', 'loadEvaluationConfigSuccess']],})),@@ -764,7 +763,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([if (props.evaluationId === 'new' &&values.evaluation?.enabled &&- !evaluationCanResolveModel(values.evaluation, values.requiresProviderKey, values.isTrialGrandfathered)+ !evaluationCanResolveModel(values.evaluation, values.activeProviderKey)) {actions.setEvaluationEnabled(false)}@@ -1010,10 +1009,10 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([if (!modelId) {return}- const trialProvider = parseTrialProviderKeyId(providerKeyId)- if (trialProvider) {+ const playgroundProvider = parsePlaygroundProviderKeyId(providerKeyId)+ if (playgroundProvider) {actions.setModelConfiguration({- provider: trialProvider,+ provider: playgroundProvider,model: modelId,provider_key_id: null,})@@ -1084,16 +1083,12 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([],canEnable: [- (s) => [s.evaluation, s.requiresProviderKey, s.isTrialGrandfathered],- (- evaluation: EvaluationConfig | null,- requiresProviderKey: boolean,- isTrialGrandfathered: boolean- ): boolean => {+ (s) => [s.evaluation, s.activeProviderKey],+ (evaluation: EvaluationConfig | null, activeProviderKey: LLMProviderKey | null | undefined): boolean => {if (!evaluation) {return true}- return evaluationCanResolveModel(evaluation, requiresProviderKey, isTrialGrandfathered)+ return evaluationCanResolveModel(evaluation, activeProviderKey)},],diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.tsindex a3e3f11c0a82..6eff6f79fc05 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts@@ -101,11 +101,6 @@ describe('llmEvaluationsLogic', () => {get: {'/api/environments/:teamId/llm_analytics/provider_keys/': { results: mockProviderKeys },'/api/environments/:teamId/llm_analytics/evaluation_config/': {- trial_eval_limit: 100,- trial_evals_used: 0,- trial_evals_remaining: 100,- trial_grandfathered: false,- trial_deprecation_date: '2026-07-15T00:00:00Z',active_provider_key: null,created_at: '2024-01-01T00:00:00Z',updated_at: '2024-01-01T00:00:00Z',@@ -136,13 +131,9 @@ describe('llmEvaluationsLogic', () => {})describe('unhealthyProviderKeysUsedByEvaluations', () => {- it('allows Hog and sentiment evaluations when trial limit is reached', async () => {+ it('allows Hog and sentiment evaluations when a provider key is required', async () => {+ // Team with no active key → requiresProviderKey.keysLogic.actions.loadEvaluationConfigSuccess({- trial_eval_limit: 100,- trial_evals_used: 100,- trial_evals_remaining: 0,- trial_grandfathered: false,- trial_deprecation_date: '2026-07-15T00:00:00Z',active_provider_key: null,created_at: '2024-01-01T00:00:00Z',updated_at: '2024-01-01T00:00:00Z',@@ -153,26 +144,45 @@ describe('llmEvaluationsLogic', () => {expect(logic.values.canEnableEvaluation(evaluationWithKey('llm-default', null))).toBe(false)})- it('an active team key only unlocks null-config evaluations, never explicit keyless ones', async () => {- // Runtime resolution uses the active key only for null configs — explicit keyless- // configs never fall back to it, so they stay blocked.+ it('an active team key unlocks keyless llm_judge evaluations', async () => {keysLogic.actions.loadEvaluationConfigSuccess({- trial_eval_limit: 100,- trial_evals_used: 100,- trial_evals_remaining: 0,- trial_grandfathered: false,- trial_deprecation_date: '2026-07-17T00:00:00Z',active_provider_key: mockProviderKeys[0],created_at: '2024-01-01T00:00:00Z',updated_at: '2024-01-01T00:00:00Z',})+ expect(logic.values.canEnableEvaluation(evaluationWithKey('llm-default', null))).toBe(true)+ })++ it('the active key must be healthy and match an explicit keyless config provider', async () => {const explicitKeyless: LLMJudgeEvaluation = {...evaluationWithKey('llm-explicit', null),model_configuration: { provider: 'openai', model: 'gpt-5-mini', provider_key_id: null },}++ // Unhealthy active key resolves nothing.+ keysLogic.actions.loadEvaluationConfigSuccess({+ active_provider_key: mockProviderKeys[1],+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ })+ expect(logic.values.canEnableEvaluation(evaluationWithKey('llm-default', null))).toBe(false)++ // Healthy, but for a different provider than the explicit config.+ keysLogic.actions.loadEvaluationConfigSuccess({+ active_provider_key: { ...mockProviderKeys[1], state: 'ok' },+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ })expect(logic.values.canEnableEvaluation(explicitKeyless)).toBe(false)- expect(logic.values.canEnableEvaluation(evaluationWithKey('llm-default', null))).toBe(true)++ // Healthy and matching.+ keysLogic.actions.loadEvaluationConfigSuccess({+ active_provider_key: mockProviderKeys[0],+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ })+ expect(logic.values.canEnableEvaluation(explicitKeyless)).toBe(true)})it('returns unhealthy keys used by evaluations without duplicates', async () => {@@ -190,7 +200,7 @@ describe('llmEvaluationsLogic', () => {const errored = evaluationWithKey('eval-errored', 'key-ok')errored.enabled = falseerrored.status = 'error'- errored.status_reason = 'trial_limit_reached'+ errored.status_reason = 'provider_key_required'logic.actions.loadEvaluationsSuccess([errored])logic.actions.toggleEvaluationEnabledSuccess('eval-errored')@@ -213,7 +223,7 @@ describe('llmEvaluationsLogic', () => {'/api/environments/:teamId/evaluations/:id/': () => [400,{- enabled: ['Trial evaluation limit reached. Add a provider API key to re-enable.'],+ enabled: ['Add a provider API key to enable this evaluation.'],},],},diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.tsindex d8948f02a494..bcf59a70af5e 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts@@ -40,9 +40,8 @@ function redirectToOnlineEvaluations(searchParams: Record<string, unknown>): voi// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface llmEvaluationsLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogic- isTrialGrandfathered: boolean // llmProviderKeysLogic+ activeProviderKey: LLMProviderKey | null | undefined // llmProviderKeysLogicproviderKeys: LLMProviderKey[] // llmProviderKeysLogic- requiresProviderKey: boolean // llmProviderKeysLogiccanEnableEvaluation: (evaluation: EvaluationConfig) => booleandateFilter: {dateFrom: string | null@@ -129,8 +128,7 @@ export interface llmEvaluationsLogicMeta {showDisabledEvaluations: boolean) => EvaluationConfig[]canEnableEvaluation: (- requiresProviderKey: boolean,- isTrialGrandfathered: boolean+ activeProviderKey: LLMProviderKey | null | undefined) => (evaluation: EvaluationConfig) => booleanunhealthyProviderKeysUsedByEvaluations: (evaluations: EvaluationConfig[],@@ -150,12 +148,7 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([path(['products', 'ai_observability', 'evaluations', 'llmEvaluationsLogic']),props({} as LLMEvaluationsLogicProps),connect(() => ({- values: [- featureFlagLogic,- ['featureFlags'],- llmProviderKeysLogic,- ['providerKeys', 'requiresProviderKey', 'isTrialGrandfathered'],- ],+ values: [featureFlagLogic, ['featureFlags'], llmProviderKeysLogic, ['providerKeys', 'activeProviderKey']],actions: [teamLogic, ['addProductIntent'], llmProviderKeysLogic, ['loadProviderKeys']],})),@@ -349,10 +342,10 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([},],canEnableEvaluation: [- (s) => [s.requiresProviderKey, s.isTrialGrandfathered],- (requiresProviderKey: boolean, isTrialGrandfathered: boolean) => {+ (s) => [s.activeProviderKey],+ (activeProviderKey: LLMProviderKey | null | undefined) => {return (evaluation: EvaluationConfig): boolean =>- evaluationCanResolveModel(evaluation, requiresProviderKey, isTrialGrandfathered)+ evaluationCanResolveModel(evaluation, activeProviderKey)},],diff --git a/products/ai_observability/frontend/evaluations/statusDisplay.test.ts b/products/ai_observability/frontend/evaluations/statusDisplay.test.tsindex fcf3c194907c..b6f93a54ac3e 100644--- a/products/ai_observability/frontend/evaluations/statusDisplay.test.ts+++ b/products/ai_observability/frontend/evaluations/statusDisplay.test.ts@@ -4,8 +4,6 @@ describe('statusDisplay', () => {describe('statusReasonLabel', () => {it.each([['provider_key_required' as const, 'No provider API key configured'],- ['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'],['provider_key_invalid' as const, 'Provider API key is invalid'],@@ -30,14 +28,6 @@ describe('statusDisplay', () => {'provider_key_required' as const,'Add a provider API key in settings, then re-enable the evaluation to resume running.',],- [- 'trial_limit_reached' as const,- 'Add a provider API key in settings, then re-enable the evaluation to resume running.',- ],- [- 'model_not_allowed' as const,- 'Choose a supported model or add a provider API key in settings, then re-enable the evaluation to resume running.',- ],['provider_key_deleted' as const,'Fix or replace the provider API key in settings, then re-enable the evaluation to resume running.',diff --git a/products/ai_observability/frontend/evaluations/statusDisplay.ts b/products/ai_observability/frontend/evaluations/statusDisplay.tsindex 64f8dd863e6b..b57c8cb7e1ee 100644--- a/products/ai_observability/frontend/evaluations/statusDisplay.ts+++ b/products/ai_observability/frontend/evaluations/statusDisplay.ts@@ -2,8 +2,6 @@ import { EvaluationStatusReason } from './types'const REASON_LABELS: Record<EvaluationStatusReason, string> = {provider_key_required: 'No provider API key configured',- 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',provider_key_invalid: 'Provider API key is invalid',@@ -30,12 +28,9 @@ export function statusReasonLabel(reason: EvaluationStatusReason | null | undefi}export function statusReasonRecoveryLabel(reason: EvaluationStatusReason | null | undefined): string {- if (reason === 'provider_key_required' || reason === 'trial_limit_reached') {+ if (reason === 'provider_key_required') {return 'Add a provider API key in settings, then re-enable the evaluation to resume running.'}- if (reason === 'model_not_allowed') {- return 'Choose a supported model or add a provider API key in settings, then re-enable the evaluation to resume running.'- }if (reason === 'no_default_model' || reason === 'model_not_found') {return 'Choose an available model, then re-enable the evaluation to resume running.'}diff --git a/products/ai_observability/frontend/evaluations/types.ts b/products/ai_observability/frontend/evaluations/types.tsindex c7c2d47b97f1..7d9eb2e5555b 100644--- a/products/ai_observability/frontend/evaluations/types.ts+++ b/products/ai_observability/frontend/evaluations/types.ts@@ -15,8 +15,6 @@ export type EvaluationOutputType = 'boolean' | 'sentiment'export type EvaluationStatus = 'active' | 'paused' | 'error'export type EvaluationStatusReason =| 'provider_key_required'- | 'trial_limit_reached'- | 'model_not_allowed'| 'provider_key_deleted'| 'no_default_model'| 'provider_key_invalid'diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.tsindex cb19a263c5cf..ae7bd2899371 100644--- a/products/ai_observability/frontend/generated/api.schemas.ts+++ b/products/ai_observability/frontend/generated/api.schemas.ts@@ -381,8 +381,6 @@ export const EvaluationStatusEnumApi = {/*** * `provider_key_required` - No provider API key configured- * * `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* * `provider_key_invalid` - Provider API key is invalid@@ -396,8 +394,6 @@ export type StatusReasonEnumApi = (typeof StatusReasonEnumApi)[keyof typeof Statexport const StatusReasonEnumApi = {ProviderKeyRequired: 'provider_key_required',- TrialLimitReached: 'trial_limit_reached',- ModelNotAllowed: 'model_not_allowed',ProviderKeyDeleted: 'provider_key_deleted',NoDefaultModel: 'no_default_model',ProviderKeyInvalid: 'provider_key_invalid',@@ -1001,16 +997,6 @@ export interface LLMProviderKeyApi {}export interface EvaluationConfigApi {- /** Cap on trial runs — a getting-started affordance only, not for ongoing evals (use the team's own key). */- readonly trial_eval_limit: number- /** Trial runs consumed (getting-started affordance only). */- readonly trial_evals_used: number- /** Trial runs remaining — a getting-started affordance only; evals should use the team's own provider key. */- readonly trial_evals_remaining: number- /** True while this team keeps PostHog-funded trial inference during the deprecation window (i.e. it is mid-trial and the cutoff has not passed). False means the team must use its own provider key. */- readonly trial_grandfathered: boolean- /** Timestamp after which trial evaluations are fully removed and every team must use its own provider key. */- readonly trial_deprecation_date: string/** Provider key used to run llm_judge evals; null if none configured yet. */readonly active_provider_key: LLMProviderKeyApi | null/** Timestamp when the evaluation config row was created. */@@ -1435,8 +1421,6 @@ export interface EvaluationSummaryResponseApi {export interface LLMModelInfoApi {/** Provider-specific model identifier (e.g. 'gpt-4o-mini', 'claude-3-5-sonnet-20241022'). */id: string- /** True if the model can run without a provider key on PostHog-funded trial credits. Only true for teams still grandfathered into the deprecating trial; every other team must use its own key. */- posthog_available: boolean}export interface LLMModelsListResponseApi {diff --git a/products/ai_observability/frontend/generated/api.ts b/products/ai_observability/frontend/generated/api.tsindex 9bbf4e96fcd0..eacf8c3e55ac 100644--- a/products/ai_observability/frontend/generated/api.ts+++ b/products/ai_observability/frontend/generated/api.ts@@ -1243,27 +1243,6 @@ export const llmAnalyticsProviderKeysDestroy = async (})}-export const getLlmAnalyticsProviderKeysAssignCreateUrl = (projectId: string, id: string) => {- return `/api/projects/${projectId}/llm_analytics/provider_keys/${id}/assign/`-}--/**- * Assign this key to evaluations and optionally re-enable them.- */-export const llmAnalyticsProviderKeysAssignCreate = async (- projectId: string,- id: string,- lLMProviderKeyApi: NonReadonly<LLMProviderKeyApi>,- options?: RequestInit-): Promise<LLMProviderKeyApi> => {- return apiMutator<LLMProviderKeyApi>(getLlmAnalyticsProviderKeysAssignCreateUrl(projectId, id), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(lLMProviderKeyApi),- })-}-export const getLlmAnalyticsProviderKeysDependentConfigsRetrieveUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/llm_analytics/provider_keys/${id}/dependent_configs/`}@@ -1300,23 +1279,6 @@ export const llmAnalyticsProviderKeysValidateCreate = async (})}-export const getLlmAnalyticsProviderKeysTrialEvaluationsRetrieveUrl = (projectId: string) => {- return `/api/projects/${projectId}/llm_analytics/provider_keys/trial_evaluations/`-}--/**- * List enabled evaluations currently using trial credits for a given provider.- */-export const llmAnalyticsProviderKeysTrialEvaluationsRetrieve = async (- projectId: string,- options?: RequestInit-): Promise<LLMProviderKeyApi> => {- return apiMutator<LLMProviderKeyApi>(getLlmAnalyticsProviderKeysTrialEvaluationsRetrieveUrl(projectId), {- ...options,- method: 'GET',- })-}-export const getLlmAnalyticsReviewQueueItemsListUrl = (projectId: string,params?: LlmAnalyticsReviewQueueItemsListParamsdiff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.tsindex 7c801e994fe7..c7705b1b53cd 100644--- a/products/ai_observability/frontend/generated/api.zod.ts+++ b/products/ai_observability/frontend/generated/api.zod.ts@@ -1208,42 +1208,6 @@ export const LlmAnalyticsProviderKeysPartialUpdateBody = /* @__PURE__ */ zod.objset_as_active: zod.boolean().default(llmAnalyticsProviderKeysPartialUpdateBodySetAsActiveDefault),})-/**- * Assign this key to evaluations and optionally re-enable them.- */-export const llmAnalyticsProviderKeysAssignCreateBodyNameMax = 255--export const llmAnalyticsProviderKeysAssignCreateBodyApiVersionMax = 20--export const llmAnalyticsProviderKeysAssignCreateBodySetAsActiveDefault = false--export const LlmAnalyticsProviderKeysAssignCreateBody = /* @__PURE__ */ zod.object({- provider: zod- .enum([- 'openai',- 'anthropic',- 'gemini',- 'openrouter',- 'fireworks',- 'azure_openai',- 'together_ai',- 'minimax',- 'zeabur',- ])- .describe(- '\* `openai` - Openai\n\* `anthropic` - Anthropic\n\* `gemini` - Gemini\n\* `openrouter` - Openrouter\n\* `fireworks` - Fireworks\n\* `azure_openai` - Azure OpenAI\n\* `together_ai` - Together AI\n\* `minimax` - MiniMax\n\* `zeabur` - Zeabur AI Hub'- ),- name: zod.string().max(llmAnalyticsProviderKeysAssignCreateBodyNameMax),- api_key: zod.string().optional(),- azure_endpoint: zod.url().optional().describe('Azure OpenAI endpoint URL'),- api_version: zod- .string()- .max(llmAnalyticsProviderKeysAssignCreateBodyApiVersionMax)- .optional()- .describe('Azure OpenAI API version'),- set_as_active: zod.boolean().default(llmAnalyticsProviderKeysAssignCreateBodySetAsActiveDefault),-})-export const llmAnalyticsProviderKeysValidateCreateBodyNameMax = 255export const llmAnalyticsProviderKeysValidateCreateBodyApiVersionMax = 20diff --git a/products/ai_observability/frontend/modelPickerLogic.test.ts b/products/ai_observability/frontend/modelPickerLogic.test.tsindex 960fae83a987..317a696e60f7 100644--- a/products/ai_observability/frontend/modelPickerLogic.test.ts+++ b/products/ai_observability/frontend/modelPickerLogic.test.ts@@ -3,9 +3,9 @@ import { expectLogic } from 'kea-test-utils'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { filterGroups, findSelectedProvider, parseTrialProviderKeyId } from './ModelPicker'+import { filterGroups, findSelectedProvider, parsePlaygroundProviderKeyId } from './ModelPicker'import {- buildTrialProviderModelGroups,+ buildPlaygroundProviderModelGroups,modelPickerLogic,type ModelOption,type ProviderModelGroup,@@ -368,8 +368,8 @@ const GROUPS: ProviderModelGroup[] = [{ provider: 'anthropic', providerKeyId: 'key-2', label: 'Anthropic', models: [MODEL_B] },]-describe('parseTrialProviderKeyId', () => {- // The 'trial:' case exercises the unknown-provider path, which logs a console.error by design.+describe('parsePlaygroundProviderKeyId', () => {+ // The 'playground:' case exercises the unknown-provider path, which logs a console.error by design.let consoleErrorSpy: jest.SpyInstancebeforeEach(() => {@@ -381,14 +381,14 @@ describe('parseTrialProviderKeyId', () => {})it.each([- ['trial:openai', 'openai'],- ['trial:anthropic', 'anthropic'],+ ['playground:openai', 'openai'],+ ['playground:anthropic', 'anthropic'],['key-123', null],['', null],- ['trial:', null],- ])('parseTrialProviderKeyId(%s) => %s', (input, expected) => {- expect(parseTrialProviderKeyId(input)).toBe(expected)- if (input === 'trial:') {+ ['playground:', null],+ ])('parsePlaygroundProviderKeyId(%s) => %s', (input, expected) => {+ expect(parsePlaygroundProviderKeyId(input)).toBe(expected)+ if (input === 'playground:') {expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining('Unknown LLM provider'))}})@@ -429,22 +429,22 @@ describe('filterGroups', () => {})})-describe('buildTrialProviderModelGroups', () => {- it('groups models by provider with trial: prefix keys', () => {+describe('buildPlaygroundProviderModelGroups', () => {+ it('groups models by provider with playground: prefix keys', () => {const models: ModelOption[] = [MODEL_A, MODEL_C, MODEL_B]- const groups = buildTrialProviderModelGroups(models)+ const groups = buildPlaygroundProviderModelGroups(models)expect(groups).toHaveLength(2)expect(groups[0].provider).toBe('openai')- expect(groups[0].providerKeyId).toBe('trial:openai')+ expect(groups[0].providerKeyId).toBe('playground:openai')expect(groups[0].models).toHaveLength(2)expect(groups[1].provider).toBe('anthropic')- expect(groups[1].providerKeyId).toBe('trial:anthropic')+ expect(groups[1].providerKeyId).toBe('playground:anthropic')expect(groups[1].models).toHaveLength(1)})it('returns empty array for empty input', () => {- expect(buildTrialProviderModelGroups([])).toEqual([])+ expect(buildPlaygroundProviderModelGroups([])).toEqual([])})it('sorts groups by provider order', () => {@@ -452,7 +452,7 @@ describe('buildTrialProviderModelGroups', () => {{ ...MODEL_B, provider: 'Anthropic' },{ ...MODEL_A, provider: 'OpenAI' },]- const groups = buildTrialProviderModelGroups(models)+ const groups = buildPlaygroundProviderModelGroups(models)expect(groups.map((g) => g.provider)).toEqual(['openai', 'anthropic'])})})diff --git a/products/ai_observability/frontend/modelPickerLogic.ts b/products/ai_observability/frontend/modelPickerLogic.tsindex af4a61253a56..cd68b61d0474 100644--- a/products/ai_observability/frontend/modelPickerLogic.ts+++ b/products/ai_observability/frontend/modelPickerLogic.ts@@ -31,7 +31,7 @@ export interface ProviderModelGroup {disabled?: boolean}-export function buildTrialProviderModelGroups(models: ModelOption[]): ProviderModelGroup[] {+export function buildPlaygroundProviderModelGroups(models: ModelOption[]): ProviderModelGroup[] {const byProvider: Record<string, ModelOption[]> = {}for (const model of models) {const provider = model.provider || 'Unknown'@@ -50,7 +50,7 @@ export function buildTrialProviderModelGroups(models: ModelOption[]): ProviderMoreturn [{provider: llmProvider,- providerKeyId: `trial:${llmProvider}`,+ providerKeyId: `playground:${llmProvider}`,label: LLM_PROVIDER_LABELS[llmProvider] ?? provider,models: providerModels,},@@ -65,10 +65,10 @@ export interface modelPickerLogicValues {byokModels: ModelOption[]byokModelsLoading: booleanhasByokKeys: boolean+ playgroundModels: ModelOption[]+ playgroundModelsLoading: boolean+ playgroundProviderModelGroups: ProviderModelGroup[]providerModelGroups: ProviderModelGroup[]- trialModels: ModelOption[]- trialModelsLoading: boolean- trialProviderModelGroups: ProviderModelGroup[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -123,19 +123,19 @@ export interface modelPickerLogicActions {byokModels: ModelOption[]payload?: any}- loadTrialModels: () => any- loadTrialModelsFailure: (+ loadPlaygroundModels: () => any+ loadPlaygroundModelsFailure: (error: string,errorObject?: any) => {error: stringerrorObject?: any}- loadTrialModelsSuccess: (- trialModels: ModelOption[],+ loadPlaygroundModelsSuccess: (+ playgroundModels: ModelOption[],payload?: any) => {- trialModels: ModelOption[]+ playgroundModels: ModelOption[]payload?: any}}@@ -144,7 +144,7 @@ export interface modelPickerLogicActions {export interface modelPickerLogicMeta {__keaTypeGenInternalSelectorTypes: {hasByokKeys: (providerKeys: LLMProviderKey[]) => boolean- trialProviderModelGroups: (trialModels: ModelOption[]) => ProviderModelGroup[]+ playgroundProviderModelGroups: (playgroundModels: ModelOption[]) => ProviderModelGroup[]providerModelGroups: (byokModels: ModelOption[], providerKeys: LLMProviderKey[]) => ProviderModelGroup[]}}@@ -209,9 +209,9 @@ export const modelPickerLogic = kea<modelPickerLogicType>([return Array.from(dedupedModels.values())},},- trialModels: {+ playgroundModels: {__default: [] as ModelOption[],- loadTrialModels: async (): Promise<ModelOption[]> => {+ loadPlaygroundModels: async (): Promise<ModelOption[]> => {// nosemgrep: prefer-codegen-apiconst rawModels = (await api.get('/api/llm_proxy/models/')) as (Omit<ModelOption, 'isRecommended'> & {is_recommended?: boolean@@ -242,7 +242,7 @@ export const modelPickerLogic = kea<modelPickerLogicType>([})),afterMount(({ actions, values }) => {- actions.loadTrialModels()+ actions.loadPlaygroundModels()if (values.providerKeys.length > 0) {actions.loadByokModels()}@@ -253,10 +253,10 @@ export const modelPickerLogic = kea<modelPickerLogicType>([(s) => [s.providerKeys],(providerKeys: LLMProviderKey[]): boolean => providerKeys.some((k) => k.state === 'ok'),],- trialProviderModelGroups: [- (s) => [s.trialModels],- (trialModels: ModelOption[]): ProviderModelGroup[] =>- buildTrialProviderModelGroups(Array.isArray(trialModels) ? trialModels : []),+ playgroundProviderModelGroups: [+ (s) => [s.playgroundModels],+ (playgroundModels: ModelOption[]): ProviderModelGroup[] =>+ buildPlaygroundProviderModelGroups(Array.isArray(playgroundModels) ? playgroundModels : []),],providerModelGroups: [(s) => [s.byokModels, s.providerKeys],diff --git a/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx b/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsxindex 904f60b3e229..b94f55ac4d6f 100644--- a/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx+++ b/products/ai_observability/frontend/playground/AIObservabilityPlaygroundScene.tsx@@ -46,7 +46,7 @@ import { ProductKey } from '~/queries/schema/schema-general'import { JSONEditor } from '../components/JSONEditor'import { MetadataHeader } from '../ConversationDisplay/MetadataHeader'-import { getModelPickerFooterLink, ModelPicker, parseTrialProviderKeyId } from '../ModelPicker'+import { getModelPickerFooterLink, ModelPicker, parsePlaygroundProviderKeyId } from '../ModelPicker'import { modelPickerLogic } from '../modelPickerLogic'import { llmPlaygroundModelLogic } from './llmPlaygroundModelLogic'import {@@ -455,7 +455,7 @@ function PromptResultCard({ item }: { item?: ComparisonItem }): JSX.Element {)}-function getTrialModelsErrorMessage(errorStatus: number | null): string | null {+function getPlaygroundModelsErrorMessage(errorStatus: number | null): string | null {if (errorStatus === null) {return null}@@ -467,16 +467,16 @@ function getTrialModelsErrorMessage(errorStatus: number | null): string | null {function PlaygroundModelPicker({ promptId }: { promptId: string }): JSX.Element {const prompt = usePromptConfig(promptId)- const { effectiveModelOptions, trialModelsErrorStatus } = useValues(llmPlaygroundModelLogic)+ const { effectiveModelOptions, playgroundModelsErrorStatus } = useValues(llmPlaygroundModelLogic)const {hasByokKeys,providerModelGroups,- trialProviderModelGroups,+ playgroundProviderModelGroups,byokModelsLoading,- trialModelsLoading,+ playgroundModelsLoading,providerKeysLoading,} = useValues(modelPickerLogic)- const { loadTrialModels } = useActions(modelPickerLogic)+ const { loadPlaygroundModels } = useActions(modelPickerLogic)const { setModel } = useActions(llmPlaygroundPromptsLogic)if (!prompt) {@@ -484,10 +484,10 @@ function PlaygroundModelPicker({ promptId }: { promptId: string }): JSX.Element}const selectedModel = effectiveModelOptions.find((m) => m.id === prompt.model)- const groups = hasByokKeys ? providerModelGroups : trialProviderModelGroups- const loading = hasByokKeys ? byokModelsLoading || providerKeysLoading : trialModelsLoading- const errorMessage = !hasByokKeys ? getTrialModelsErrorMessage(trialModelsErrorStatus) : null- const showError = !hasByokKeys && effectiveModelOptions.length === 0 && !trialModelsLoading+ const groups = hasByokKeys ? providerModelGroups : playgroundProviderModelGroups+ const loading = hasByokKeys ? byokModelsLoading || providerKeysLoading : playgroundModelsLoading+ const errorMessage = !hasByokKeys ? getPlaygroundModelsErrorMessage(playgroundModelsErrorStatus) : null+ const showError = !hasByokKeys && effectiveModelOptions.length === 0 && !playgroundModelsLoadingreturn (<>@@ -495,12 +495,12 @@ function PlaygroundModelPicker({ promptId }: { promptId: string }): JSX.Elementmodel={prompt.model}selectedProviderKeyId={prompt.selectedProviderKeyId}onSelect={(modelId, providerKeyId) => {- const trialProvider = parseTrialProviderKeyId(providerKeyId)+ const playgroundProvider = parsePlaygroundProviderKeyId(providerKeyId)posthog.capture('llma playground model changed', {model: modelId,- is_byok: !trialProvider,+ is_byok: !playgroundProvider,})- setModel(modelId, trialProvider ? undefined : providerKeyId, promptId)+ setModel(modelId, playgroundProvider ? undefined : providerKeyId, promptId)}}groups={groups}loading={loading}@@ -514,7 +514,7 @@ function PlaygroundModelPicker({ promptId }: { promptId: string }): JSX.Element<buttontype="button"className="text-xs text-link mt-1 underline"- onClick={() => loadTrialModels()}+ onClick={() => loadPlaygroundModels()}>Retry</button>diff --git a/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts b/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.tsindex 85ffd3fe58ab..2f6843f3ef93 100644--- a/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts+++ b/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts@@ -106,8 +106,8 @@ describe('llmPlaygroundLogic', () => {},})- // Reload trial models so the empty mock takes effect- modelPickerLogic.actions.loadTrialModels()+ // Reload playground models so the empty mock takes effect+ modelPickerLogic.actions.loadPlaygroundModels()const emptyRunLogic = llmPlaygroundRunLogic()emptyRunLogic.mount()@@ -196,8 +196,8 @@ describe('llmPlaygroundLogic', () => {},})- // Reload trial models with the extended mock data- modelPickerLogic.actions.loadTrialModels()+ // Reload playground models with the extended mock data+ modelPickerLogic.actions.loadPlaygroundModels()const testRunLogic = llmPlaygroundRunLogic()testRunLogic.mount()@@ -404,7 +404,7 @@ describe('llmPlaygroundLogic', () => {testRunLogic.unmount()})- it('should keep trial model selection even when BYOK models are available', async () => {+ it('should keep playground model selection even when BYOK models are available', async () => {const byokModels: ModelOption[] = [{id: 'anthropic/claude-sonnet-4.5',@@ -450,14 +450,14 @@ describe('llmPlaygroundLogic', () => {})})- describe('loadTrialModels auto-correction', () => {- it('should auto-correct invalid model after loading trial models', async () => {+ describe('loadPlaygroundModels auto-correction', () => {+ it('should auto-correct invalid model after loading playground models', async () => {const testRunLogic = llmPlaygroundRunLogic()testRunLogic.mount()llmPlaygroundPromptsLogic.actions.setModel('gpt-5-2025-08-07')- modelPickerLogic.actions.loadTrialModels()+ modelPickerLogic.actions.loadPlaygroundModels()await expectLogic(testRunLogic).toFinishAllListeners()@@ -479,12 +479,12 @@ describe('llmPlaygroundLogic', () => {testRunLogic.unmount()})- it('should preserve trial models when reload fails', async () => {- // The reload deliberately fails the loadTrialModels loader.+ it('should preserve playground models when reload fails', async () => {+ // The reload deliberately fails the loadPlaygroundModels loader.silenceKeaLoadersErrors()try {await expectLogic(runLogic).toFinishAllListeners()- expect(modelPickerLogic.values.trialModels).toEqual(MOCK_MODEL_OPTIONS)+ expect(modelPickerLogic.values.playgroundModels).toEqual(MOCK_MODEL_OPTIONS)useMocks({get: {@@ -497,10 +497,10 @@ describe('llmPlaygroundLogic', () => {},})- modelPickerLogic.actions.loadTrialModels()+ modelPickerLogic.actions.loadPlaygroundModels()await expectLogic(runLogic).toFinishAllListeners()- expect(modelPickerLogic.values.trialModels).toEqual(MOCK_MODEL_OPTIONS)+ expect(modelPickerLogic.values.playgroundModels).toEqual(MOCK_MODEL_OPTIONS)} finally {resumeKeaLoadersErrors()}@@ -665,13 +665,13 @@ describe('llmPlaygroundLogic', () => {})describe('effectiveModelOptions', () => {- it('should return trial models when no BYOK keys exist', async () => {+ it('should return playground models when no BYOK keys exist', async () => {await expectLogic(runLogic).toFinishAllListeners()expect(llmPlaygroundModelLogic.values.effectiveModelOptions).toEqual(MOCK_MODEL_OPTIONS)})- it('should return trial models when all keys are invalid', async () => {+ it('should return playground models when all keys are invalid', async () => {useMocks({get: {'/api/environments/:team_id/llm_analytics/evaluation_config/': {@@ -694,7 +694,7 @@ describe('llmPlaygroundLogic', () => {testRunLogic.unmount()})- it('should return trial models when provider keys API fails', async () => {+ it('should return playground models when provider keys API fails', async () => {// The provider keys loader deliberately fails here.silenceKeaLoadersErrors()try {diff --git a/products/ai_observability/frontend/playground/llmPlaygroundModelLogic.ts b/products/ai_observability/frontend/playground/llmPlaygroundModelLogic.tsindex 4dec11ab4e66..3453adc24a56 100644--- a/products/ai_observability/frontend/playground/llmPlaygroundModelLogic.ts+++ b/products/ai_observability/frontend/playground/llmPlaygroundModelLogic.ts@@ -52,9 +52,9 @@ export interface llmPlaygroundModelLogicValues {byokModels: ModelOption[] // modelPickerLogicbyokModelsLoading: boolean // modelPickerLogichasByokKeys: boolean // modelPickerLogic- trialModels: ModelOption[] // modelPickerLogic- trialModelsLoading: boolean // modelPickerLogic- trialProviderModelGroups: ProviderModelGroup[] // modelPickerLogic+ playgroundModels: ModelOption[] // modelPickerLogic+ playgroundModelsLoading: boolean // modelPickerLogic+ playgroundProviderModelGroups: ProviderModelGroup[] // modelPickerLogicactiveProviderKeyId: string | nullallModelOptions: ModelOption[]byokModelsSettled: boolean@@ -66,10 +66,10 @@ export interface llmPlaygroundModelLogicValues {} | nullevaluationConfigLoading: booleanhasProviderKey: boolean+ playgroundModelsErrorStatus: number | null+ playgroundModelsSettled: booleanproviderKeyForCurrentModel: LLMProviderKey | nullproviderKeysSettled: boolean- trialModelsErrorStatus: number | null- trialModelsSettled: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -121,19 +121,19 @@ export interface llmPlaygroundModelLogicActions {byokModels: ModelOption[]payload?: any} // modelPickerLogic- loadTrialModelsFailure: (+ loadPlaygroundModelsFailure: (error: string,errorObject?: any) => {error: stringerrorObject?: any} // modelPickerLogic- loadTrialModelsSuccess: (- trialModels: ModelOption[],+ loadPlaygroundModelsSuccess: (+ playgroundModels: ModelOption[],payload?: any) => {payload?: any- trialModels: ModelOption[]+ playgroundModels: ModelOption[]} // modelPickerLogicloadEvaluationConfig: () => anyloadEvaluationConfigFailure: (@@ -169,9 +169,9 @@ export interface llmPlaygroundModelLogicMeta {effectiveModelOptions: (hasByokKeys: boolean,byokModels: ModelOption[],- trialModels: ModelOption[]+ playgroundModels: ModelOption[]) => ModelOption[]- allModelOptions: (trialModels: ModelOption[], byokModels: ModelOption[]) => ModelOption[]+ allModelOptions: (playgroundModels: ModelOption[], byokModels: ModelOption[]) => ModelOption[]providerKeyForCurrentModel: (activePromptConfig: PromptConfig,effectiveModelOptions: ModelOption[],@@ -206,10 +206,10 @@ export const llmPlaygroundModelLogic = kea<llmPlaygroundModelLogicType>([['byokModels','byokModelsLoading',- 'trialModels',- 'trialModelsLoading',+ 'playgroundModels',+ 'playgroundModelsLoading','hasByokKeys',- 'trialProviderModelGroups',+ 'playgroundProviderModelGroups',],llmProviderKeysLogic,['providerKeys', 'providerKeysLoading'],@@ -218,7 +218,12 @@ export const llmPlaygroundModelLogic = kea<llmPlaygroundModelLogicType>([llmPlaygroundPromptsLogic,['setupPlaygroundFromEvent', 'setModel', 'setPromptConfigs', 'clearPendingTargetModel'],modelPickerLogic,- ['loadByokModelsSuccess', 'loadByokModelsFailure', 'loadTrialModelsSuccess', 'loadTrialModelsFailure'],+ [+ 'loadByokModelsSuccess',+ 'loadByokModelsFailure',+ 'loadPlaygroundModelsSuccess',+ 'loadPlaygroundModelsFailure',+ ],llmProviderKeysLogic,['loadProviderKeys', 'loadProviderKeysSuccess', 'loadProviderKeysFailure'],],@@ -229,11 +234,11 @@ export const llmPlaygroundModelLogic = kea<llmPlaygroundModelLogicType>([}),reducers({- trialModelsErrorStatus: [+ playgroundModelsErrorStatus: [null as number | null,{- loadTrialModelsSuccess: () => null,- loadTrialModelsFailure: (_: number | null, { error }: { error: unknown }) => {+ loadPlaygroundModelsSuccess: () => null,+ loadPlaygroundModelsFailure: (_: number | null, { error }: { error: unknown }) => {if (error instanceof ApiError) {return error.status ?? null}@@ -265,11 +270,11 @@ export const llmPlaygroundModelLogic = kea<llmPlaygroundModelLogicType>([loadByokModelsFailure: () => true,},],- trialModelsSettled: [+ playgroundModelsSettled: [false as boolean,{- loadTrialModelsSuccess: () => true,- loadTrialModelsFailure: () => true,+ loadPlaygroundModelsSuccess: () => true,+ loadPlaygroundModelsFailure: () => true,},],}),@@ -297,13 +302,16 @@ export const llmPlaygroundModelLogic = kea<llmPlaygroundModelLogicType>([selectors({effectiveModelOptions: [- (s) => [s.hasByokKeys, s.byokModels, s.trialModels],- (hasByokKeys: boolean, byokModels: ModelOption[], trialModels: ModelOption[]): ModelOption[] =>- hasByokKeys && byokModels.length > 0 ? byokModels : trialModels,+ (s) => [s.hasByokKeys, s.byokModels, s.playgroundModels],+ (hasByokKeys: boolean, byokModels: ModelOption[], playgroundModels: ModelOption[]): ModelOption[] =>+ hasByokKeys && byokModels.length > 0 ? byokModels : playgroundModels,],allModelOptions: [- (s) => [s.trialModels, s.byokModels],- (trialModels: ModelOption[], byokModels: ModelOption[]): ModelOption[] => [...trialModels, ...byokModels],+ (s) => [s.playgroundModels, s.byokModels],+ (playgroundModels: ModelOption[], byokModels: ModelOption[]): ModelOption[] => [+ ...playgroundModels,+ ...byokModels,+ ],],providerKeyForCurrentModel: [(s) => [s.activePromptConfig, s.effectiveModelOptions, s.providerKeys],@@ -337,17 +345,17 @@ export const llmPlaygroundModelLogic = kea<llmPlaygroundModelLogicType>([actions.clearPendingTargetModel()}- // Resolve a pending target model once provider keys, BYOK models, and trial models have+ // Resolve a pending target model once provider keys, BYOK models, and playground models have// all settled — whichever of those loads last drives the resolution. Previously this only- // ran from the trial/BYOK success handlers, so a pending model was silently dropped when- // trial models loaded before provider keys settled and there were no BYOK keys to fire+ // ran from the playground/BYOK success handlers, so a pending model was silently dropped when+ // playground models loaded before provider keys settled and there were no BYOK keys to fire// loadByokModelsSuccess (the resolution would bail on the settled-gate and never retry).const resolvePendingTarget = (): void => {const pendingTargetModel = values.pendingTargetModelif (!pendingTargetModel) {return}- if (!values.providerKeysSettled || !values.byokModelsSettled || !values.trialModelsSettled) {+ if (!values.providerKeysSettled || !values.byokModelsSettled || !values.playgroundModelsSettled) {return}if (values.pendingTargetIsTrace) {@@ -372,12 +380,12 @@ export const llmPlaygroundModelLogic = kea<llmPlaygroundModelLogicType>([}) => {actions.setActiveProviderKeyId(evaluationConfig?.active_provider_key?.id ?? null)},- loadTrialModelsSuccess: ({ trialModels }: { trialModels: ModelOption[] }) => {- if (trialModels.length === 0) {+ loadPlaygroundModelsSuccess: ({ playgroundModels }: { playgroundModels: ModelOption[] }) => {+ if (playgroundModels.length === 0) {return}- // Normalize prompts to available trial models+ // Normalize prompts to available playground modelsconst pendingTargetModel = values.pendingTargetModelconst normalizedPrompts = values.promptConfigs.map((prompt, index) => {@@ -388,7 +396,7 @@ export const llmPlaygroundModelLogic = kea<llmPlaygroundModelLogicType>([return prompt}- const closestMatch = matchClosestModel(prompt.model, trialModels)+ const closestMatch = matchClosestModel(prompt.model, playgroundModels)if (prompt.model === closestMatch) {return prompt}@@ -407,12 +415,12 @@ export const llmPlaygroundModelLogic = kea<llmPlaygroundModelLogicType>([resolvePendingTarget()},loadProviderKeysSuccess: () => {- // If trial models loaded before provider keys settled, the trial handler couldn't+ // If playground models loaded before provider keys settled, the playground handler couldn't// resolve the pending target yet. Retry now that keys (and the BYOK-settled flag) are in.resolvePendingTarget()},loadProviderKeysFailure: () => resolvePendingTarget(),- loadTrialModelsFailure: () => resolvePendingTarget(),+ loadPlaygroundModelsFailure: () => resolvePendingTarget(),loadByokModelsFailure: () => resolvePendingTarget(),loadByokModelsSuccess: ({ byokModels }: { byokModels: ModelOption[] }) => {if (byokModels.length === 0) {diff --git a/products/ai_observability/frontend/playground/playgroundModelMatching.test.ts b/products/ai_observability/frontend/playground/playgroundModelMatching.test.tsindex d1c46fc23a60..15826629628b 100644--- a/products/ai_observability/frontend/playground/playgroundModelMatching.test.ts+++ b/products/ai_observability/frontend/playground/playgroundModelMatching.test.ts@@ -85,25 +85,25 @@ describe('playgroundModelMatching', () => {})describe('resolveTraceModelSelection', () => {- const trialModels = [model('gpt-5'), model('gpt-5-mini'), model('claude-sonnet-4')]+ const playgroundModels = [model('gpt-5'), model('gpt-5-mini'), model('claude-sonnet-4')]it('resolves exact match from available models', () => {- const result = resolveTraceModelSelection('claude-sonnet-4', 'anthropic', trialModels, [])+ const result = resolveTraceModelSelection('claude-sonnet-4', 'anthropic', playgroundModels, [])expect(result.resolvedModelId).toBe('claude-sonnet-4')})it('resolves gateway-style model by stripping namespace', () => {- const result = resolveTraceModelSelection('anthropic/claude-sonnet-4', 'anthropic', trialModels, [])+ const result = resolveTraceModelSelection('anthropic/claude-sonnet-4', 'anthropic', playgroundModels, [])expect(result.resolvedModelId).toBe('claude-sonnet-4')})it('resolves snapshot model ID via prefix matching', () => {- const result = resolveTraceModelSelection('gpt-5-2025-08-07', 'openai', trialModels, [])+ const result = resolveTraceModelSelection('gpt-5-2025-08-07', 'openai', playgroundModels, [])expect(result.resolvedModelId).toBe('gpt-5')})it('falls back to raw model ID when no match found', () => {- const result = resolveTraceModelSelection('llama-3-70b', 'meta', trialModels, [])+ const result = resolveTraceModelSelection('llama-3-70b', 'meta', playgroundModels, [])expect(result.resolvedModelId).toBe('llama-3-70b')})diff --git a/products/ai_observability/frontend/settings/LLMProviderKeysSettings.tsx b/products/ai_observability/frontend/settings/LLMProviderKeysSettings.tsxindex 9400c04d549f..972d6a5a7967 100644--- a/products/ai_observability/frontend/settings/LLMProviderKeysSettings.tsx+++ b/products/ai_observability/frontend/settings/LLMProviderKeysSettings.tsx@@ -17,7 +17,6 @@ import {import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'import { TeamMembershipLevel } from 'lib/constants'import { IconKey } from 'lib/lemon-ui/icons'-import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { LLMProviderIcon, LLM_PROVIDER_SELECT_OPTIONS } from '../LLMProviderIcon'@@ -31,12 +30,10 @@ import {LLMProviderKey,LLMProviderKeyState,LLM_PROVIDER_LABELS,- TrialEvaluation,UpdateLLMProviderKeyPayload,llmProviderKeysLogic,sortProviderKeys,} from './llmProviderKeysLogic'-import { TrialUsageMeter } from './TrialUsageMeter'function StateTag({ state, errorMessage }: { state: LLMProviderKeyState; errorMessage: string | null }): JSX.Element {const tagProps: { type: 'success' | 'danger' | 'warning' | 'default'; children: string } = {@@ -218,6 +215,7 @@ function AddKeyModal({ restrictionReason }: { restrictionReason: string | null }isAzure,azureEndpoint,apiVersion,+ evaluationConfig?.active_provider_key,]) // oxlint-disable-line react-hooks/exhaustive-depsconst handleClose = (): void => {@@ -650,106 +648,6 @@ function DeleteKeyModal({)}-function AssignKeyModal(): JSX.Element | null {- const { newlyCreatedKey, trialEvaluations, trialEvaluationsLoading } = useValues(llmProviderKeysLogic)- const { confirmAssignKey, dismissAssignKey } = useActions(llmProviderKeysLogic)-- const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())- const [enableAfterAssign, setEnableAfterAssign] = useState(true)-- const hasDisabledEvals = trialEvaluations.some((e: TrialEvaluation) => !e.enabled)- const isOpen = newlyCreatedKey !== null && !trialEvaluationsLoading && trialEvaluations.length > 0-- // Select all by default when modal opens- useEffect(() => {- if (isOpen) {- setSelectedIds(new Set(trialEvaluations.map((e: TrialEvaluation) => e.id)))- setEnableAfterAssign(true)- }- }, [isOpen]) // oxlint-disable-line react-hooks/exhaustive-deps-- if (!newlyCreatedKey) {- return null- }-- // If no trial evals found after loading, auto-dismiss- if (!trialEvaluationsLoading && trialEvaluations.length === 0) {- return null- }-- const toggleEval = (id: string): void => {- setSelectedIds((prev) => {- const next = new Set(prev)- if (next.has(id)) {- next.delete(id)- } else {- next.add(id)- }- return next- })- }-- const providerLabel = LLM_PROVIDER_LABELS[newlyCreatedKey.provider] || newlyCreatedKey.provider-- return (- <LemonModal- isOpen={isOpen}- onClose={dismissAssignKey}- title={`Apply "${newlyCreatedKey.name}" to existing evaluations?`}- width={520}- footer={- <>- <LemonButton type="secondary" onClick={dismissAssignKey}>- Skip- </LemonButton>- <LemonButton- type="primary"- disabled={selectedIds.size === 0}- onClick={() => confirmAssignKey(Array.from(selectedIds), enableAfterAssign && hasDisabledEvals)}- >- Apply key- {selectedIds.size > 0- ? ` to ${selectedIds.size} evaluation${selectedIds.size !== 1 ? 's' : ''}`- : ''}- </LemonButton>- </>- }- >- <div className="space-y-3">- <p className="text-sm text-muted">- The following evaluations are using {providerLabel} trial credits. Select which ones should use your- new key instead.- </p>- <div className="border rounded divide-y">- {trialEvaluations.map((evaluation: TrialEvaluation) => (- <label- key={evaluation.id}- className="flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-bg-light"- >- <LemonCheckbox- checked={selectedIds.has(evaluation.id)}- onChange={() => toggleEval(evaluation.id)}- />- <span className="flex-1 text-sm">{evaluation.name}</span>- {!evaluation.enabled && (- <LemonTag type="default" size="small">- Disabled- </LemonTag>- )}- </label>- ))}- </div>- {hasDisabledEvals && (- <label className="flex items-center gap-2 cursor-pointer">- <LemonCheckbox checked={enableAfterAssign} onChange={setEnableAfterAssign} />- <span className="text-sm">Also re-enable disabled evaluations</span>- </label>- )}- </div>- </LemonModal>- )-}-export function LLMProviderKeysSettings(): JSX.Element {const {providerKeys,@@ -883,8 +781,6 @@ export function LLMProviderKeysSettings(): JSX.Element {</LemonButton></div>- <TrialUsageMeter showSettingsLink={false} />-{providerKeys.length === 0 ? (<div className="border rounded-lg p-8 flex flex-col items-center"><IconKey className="text-muted text-4xl mb-4" />@@ -926,7 +822,6 @@ export function LLMProviderKeysSettings(): JSX.Element {)}</div><AddKeyModal restrictionReason={restrictionReason} />- <AssignKeyModal />{editingKey && <EditKeyModal keyToEdit={editingKey} restrictionReason={restrictionReason} />}{keyToDelete && (<DeleteKeyModaldiff --git a/products/ai_observability/frontend/settings/TrialUsageMeter.tsx b/products/ai_observability/frontend/settings/TrialUsageMeter.tsxdeleted file mode 100644index 2b1250be6a70..000000000000--- a/products/ai_observability/frontend/settings/TrialUsageMeter.tsx+++ /dev/null@@ -1,104 +0,0 @@-import { useValues } from 'kea'--import { LemonBanner, Link } from '@posthog/lemon-ui'--import { dayjs } from 'lib/dayjs'-import { urls } from 'scenes/urls'--import { EvaluationTrialConfig, llmProviderKeysLogic } from './llmProviderKeysLogic'--function TrialDeprecationBanner({- deprecationDate,- showSettingsLink,- noun,-}: {- deprecationDate: string- showSettingsLink: boolean- noun: string-}): JSX.Element {- const endDate = dayjs.utc(deprecationDate).format('MMMM D, YYYY')-- return (- <LemonBanner type="warning">- Trial {noun} are being phased out and will be removed on {endDate}.{' '}- {showSettingsLink ? (- <Link to={urls.settings('project-ai-observability', 'ai-observability-byok')}>Add a provider key</Link>- ) : (- 'Add a provider key'- )}{' '}- to keep {noun} working without interruption.- </LemonBanner>- )-}--export function TrialUsageMeter({- showSettingsLink = false,- noun = 'evaluations',-}: {- showSettingsLink?: boolean- noun?: string-}): JSX.Element | null {- const { evaluationConfig } = useValues(llmProviderKeysLogic)-- // Terminal teams get no trial UI at all — post-deprecation the trial should look like it never existed.- if (!evaluationConfig || !evaluationConfig.trial_grandfathered || evaluationConfig.active_provider_key) {- return null- }-- return (- <div className="space-y-3">- <TrialDeprecationBanner- deprecationDate={evaluationConfig.trial_deprecation_date}- showSettingsLink={showSettingsLink}- noun={noun}- />- <TrialUsageMeterDisplay- evaluationConfig={evaluationConfig}- showSettingsLink={showSettingsLink}- noun={noun}- />- </div>- )-}--function TrialUsageMeterDisplay({- evaluationConfig,- showSettingsLink = false,- noun = 'evaluations',-}: {- evaluationConfig: EvaluationTrialConfig- showSettingsLink?: boolean- noun?: string-}): JSX.Element {- const { trial_eval_limit, trial_evals_remaining } = evaluationConfig- const percentUsed = Math.min(((trial_eval_limit - trial_evals_remaining) / trial_eval_limit) * 100, 100)-- return (- <div className="rounded-lg p-4 space-y-3 border">- <div className="flex justify-between items-center">- <span className="font-medium">Trial {noun}</span>- <span className="text-sm text-muted">- {trial_evals_remaining} of {trial_eval_limit} remaining- </span>- </div>- <div className="h-2 bg-border rounded-full overflow-hidden">- <div- className="h-full transition-all bg-success"- // eslint-disable-next-line react/forbid-dom-props- style={{ width: `${percentUsed}%` }}- />- </div>- <p className="text-sm text-muted">- You have {trial_evals_remaining} {noun} to try things out before{' '}- {showSettingsLink ? (- <Link to={urls.settings('project-ai-observability', 'ai-observability-byok')}>- adding your own key- </Link>- ) : (- 'adding your own key'- )}- .- </p>- </div>- )-}diff --git a/products/ai_observability/frontend/settings/llmProviderKeysLogic.ts b/products/ai_observability/frontend/settings/llmProviderKeysLogic.tsindex 54215f1c6f5e..299adb970721 100644--- a/products/ai_observability/frontend/settings/llmProviderKeysLogic.ts+++ b/products/ai_observability/frontend/settings/llmProviderKeysLogic.ts@@ -138,12 +138,7 @@ export function firstUsableProviderKeyIdForProvider(return sortProviderKeys(keys).find((key) => key.state === 'ok' && key.provider === normalizedProvider)?.id ?? null}-export interface EvaluationTrialConfig {- trial_eval_limit: number- trial_evals_used: number- trial_evals_remaining: number- trial_grandfathered: boolean- trial_deprecation_date: string+export interface EvaluationConfig {active_provider_key: LLMProviderKey | nullcreated_at: stringupdated_at: string@@ -173,12 +168,6 @@ export interface KeyValidationResult {error_field?: string | null}-export interface TrialEvaluation {- id: string- name: string- enabled: boolean-}-export interface DependentEvaluation {id: stringname: string@@ -198,25 +187,19 @@ export interface DependentConfigsResponse {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface llmProviderKeysLogicValues {+ activeProviderKey: LLMProviderKey | null | undefineddependentConfigs: DependentConfigsResponse | nulldependentConfigsLoading: booleaneditingKey: LLMProviderKey | null- evaluationConfig: EvaluationTrialConfig | null+ evaluationConfig: EvaluationConfig | nullevaluationConfigLoading: boolean- isTrialGrandfathered: booleankeyToDelete: LLMProviderKey | nullnewKeyModalOpen: boolean- newlyCreatedKey: LLMProviderKey | nullpreValidationResult: KeyValidationResult | nullpreValidationResultLoading: booleanproviderKeys: LLMProviderKey[]providerKeysLoading: booleanrequiresProviderKey: boolean- trialEvalLimit: number- trialEvalsRemaining: number- trialEvalsUsed: number- trialEvaluations: TrialEvaluation[]- trialEvaluationsLoading: booleanvalidatingKeyId: string | null}@@ -225,13 +208,6 @@ export interface llmProviderKeysLogicActions {clearPreValidation: () => {value: true}- confirmAssignKey: (- evaluationIds: string[],- enable: boolean- ) => {- enable: boolean- evaluationIds: string[]- }confirmDelete: (replacementKeyId?: string) => {replacementKeyId: string | undefined}@@ -280,9 +256,6 @@ export interface llmProviderKeysLogicActions {replacementKeyId?: string}}- dismissAssignKey: () => {- value: true- }loadDependentConfigs: ({ keyId }: { keyId: string }) => {keyId: string}@@ -313,10 +286,10 @@ export interface llmProviderKeysLogicActions {errorObject?: any}loadEvaluationConfigSuccess: (- evaluationConfig: EvaluationTrialConfig | null,+ evaluationConfig: EvaluationConfig | null,payload?: any) => {- evaluationConfig: EvaluationTrialConfig | null+ evaluationConfig: EvaluationConfig | nullpayload?: any}loadProviderKeys: () => any@@ -334,27 +307,6 @@ export interface llmProviderKeysLogicActions {providerKeys: LLMProviderKey[]payload?: any}- loadTrialEvaluations: ({ provider }: { provider: LLMProvider }) => {- provider: LLMProvider- }- loadTrialEvaluationsFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadTrialEvaluationsSuccess: (- trialEvaluations: TrialEvaluation[],- payload?: {- provider: LLMProvider- }- ) => {- trialEvaluations: TrialEvaluation[]- payload?: {- provider: LLMProvider- }- }preValidateKey: ({apiKey,provider,@@ -404,9 +356,6 @@ export interface llmProviderKeysLogicActions {setNewKeyModalOpen: (open: boolean) => {open: boolean}- setNewlyCreatedKey: (key: LLMProviderKey | null) => {- key: LLMProviderKey | null- }updateProviderKey: ({ id, payload }: { id: string; payload: UpdateLLMProviderKeyPayload }) => {id: stringpayload: UpdateLLMProviderKeyPayload@@ -457,11 +406,8 @@ export interface llmProviderKeysLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface llmProviderKeysLogicMeta {__keaTypeGenInternalSelectorTypes: {- trialEvalsUsed: (evaluationConfig: EvaluationTrialConfig | null) => number- trialEvalLimit: (evaluationConfig: EvaluationTrialConfig | null) => number- trialEvalsRemaining: (evaluationConfig: EvaluationTrialConfig | null) => number- isTrialGrandfathered: (evaluationConfig: EvaluationTrialConfig | null) => boolean- requiresProviderKey: (evaluationConfig: EvaluationTrialConfig | null) => boolean+ requiresProviderKey: (evaluationConfig: EvaluationConfig | null) => boolean+ activeProviderKey: (evaluationConfig: EvaluationConfig | null) => LLMProviderKey | null | undefined}}@@ -481,9 +427,6 @@ export const llmProviderKeysLogic = kea<llmProviderKeysLogicType>([setEditingKey: (key: LLMProviderKey | null) => ({ key }),setKeyToDelete: (key: LLMProviderKey | null) => ({ key }),confirmDelete: (replacementKeyId?: string) => ({ replacementKeyId }),- setNewlyCreatedKey: (key: LLMProviderKey | null) => ({ key }),- confirmAssignKey: (evaluationIds: string[], enable: boolean) => ({ evaluationIds, enable }),- dismissAssignKey: true,}),reducers({@@ -523,32 +466,9 @@ export const llmProviderKeysLogic = kea<llmProviderKeysLogicType>([deleteProviderKeySuccess: () => null,},],- newlyCreatedKey: [- null as LLMProviderKey | null,- {- setNewlyCreatedKey: (_, { key }) => key,- dismissAssignKey: () => null,- },- ],}),loaders(({ values, actions }) => ({- trialEvaluations: [- [] as TrialEvaluation[],- {- loadTrialEvaluations: async ({ provider }: { provider: LLMProvider }): Promise<TrialEvaluation[]> => {- const teamId = teamLogic.values.currentTeamId- if (!teamId) {- return []- }- // nosemgrep: prefer-codegen-api- const response = await api.get(- `/api/environments/${teamId}/llm_analytics/provider_keys/trial_evaluations/?provider=${encodeURIComponent(provider)}`- )- return response.evaluations- },- },- ],dependentConfigs: [null as DependentConfigsResponse | null,{@@ -616,9 +536,9 @@ export const llmProviderKeysLogic = kea<llmProviderKeysLogicType>([},],evaluationConfig: [- null as EvaluationTrialConfig | null,+ null as EvaluationConfig | null,{- loadEvaluationConfig: async (): Promise<EvaluationTrialConfig | null> => {+ loadEvaluationConfig: async (): Promise<EvaluationConfig | null> => {const teamId = teamLogic.values.currentTeamIdif (!teamId) {return null@@ -656,9 +576,6 @@ export const llmProviderKeysLogic = kea<llmProviderKeysLogicType>([)actions.setNewKeyModalOpen(false)actions.loadEvaluationConfig()- // Check if there are trial evaluations that could use this key- actions.setNewlyCreatedKey(response)- actions.loadTrialEvaluations({ provider: response.provider })return [...values.providerKeys, response]},updateProviderKey: async ({@@ -724,29 +641,17 @@ export const llmProviderKeysLogic = kea<llmProviderKeysLogicType>([})),selectors({- trialEvalsUsed: [- (s) => [s.evaluationConfig],- (evaluationConfig: EvaluationTrialConfig | null) => evaluationConfig?.trial_evals_used ?? 0,- ],- trialEvalLimit: [- (s) => [s.evaluationConfig],- (evaluationConfig: EvaluationTrialConfig | null) => evaluationConfig?.trial_eval_limit ?? 100,- ],- trialEvalsRemaining: [- (s) => [s.evaluationConfig],- (evaluationConfig: EvaluationTrialConfig | null) => evaluationConfig?.trial_evals_remaining ?? 0,- ],- isTrialGrandfathered: [+ // The team has no active key, so it must bring its own provider key to run llm_judge evals and taggers.+ requiresProviderKey: [(s) => [s.evaluationConfig],- (evaluationConfig: EvaluationTrialConfig | null) => evaluationConfig?.trial_grandfathered ?? false,+ (evaluationConfig: EvaluationConfig | null) =>+ evaluationConfig !== null && evaluationConfig.active_provider_key === null,],- // Terminal state: no active key and not grandfathered — the team must bring its own provider key.- requiresProviderKey: [+ // The key keyless evals resolve through. undefined = config not loaded yet; null = no active key.+ activeProviderKey: [(s) => [s.evaluationConfig],- (evaluationConfig: EvaluationTrialConfig | null) =>- evaluationConfig !== null &&- evaluationConfig.active_provider_key === null &&- !evaluationConfig.trial_grandfathered,+ (evaluationConfig: EvaluationConfig | null): LLMProviderKey | null | undefined =>+ evaluationConfig === null ? undefined : evaluationConfig.active_provider_key,],}),@@ -771,44 +676,11 @@ export const llmProviderKeysLogic = kea<llmProviderKeysLogicType>([actions.loadDependentConfigs({ keyId: key.id })}},- loadTrialEvaluationsSuccess: ({ trialEvaluations }) => {- // If no trial evaluations found, auto-dismiss the assign key modal- if (trialEvaluations.length === 0 && values.newlyCreatedKey) {- actions.setNewlyCreatedKey(null)- }- },confirmDelete: ({ replacementKeyId }) => {if (values.keyToDelete) {actions.deleteProviderKey({ id: values.keyToDelete.id, replacementKeyId })}},- confirmAssignKey: async ({ evaluationIds, enable }) => {- const key = values.newlyCreatedKey- if (!key || evaluationIds.length === 0) {- actions.setNewlyCreatedKey(null)- return- }- const teamId = teamLogic.values.currentTeamId- if (!teamId) {- return- }- try {- // nosemgrep: prefer-codegen-api- await api.create(`/api/environments/${teamId}/llm_analytics/provider_keys/${key.id}/assign/`, {- evaluation_ids: evaluationIds,- enable,- })- const count = evaluationIds.length- lemonToast.success(- enable- ? `Assigned key and re-enabled ${count} evaluation${count !== 1 ? 's' : ''}`- : `Assigned key to ${count} evaluation${count !== 1 ? 's' : ''}`- )- } catch {- lemonToast.error('Failed to assign key to evaluations')- }- actions.setNewlyCreatedKey(null)- },})),afterMount(({ actions }) => {diff --git a/products/ai_observability/frontend/tags/AIObservabilityTag.tsx b/products/ai_observability/frontend/tags/AIObservabilityTag.tsxindex d6b62fc02958..34ce2657bea6 100644--- a/products/ai_observability/frontend/tags/AIObservabilityTag.tsx+++ b/products/ai_observability/frontend/tags/AIObservabilityTag.tsx@@ -33,7 +33,7 @@ import { InsightVizNode, NodeKind, ProductKey } from '~/queries/schema/schema-geimport { getModelPickerFooterLink, ModelPicker } from '../ModelPicker'import { modelPickerLogic } from '../modelPickerLogic'-import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'+import { LLMProviderKey } from '../settings/llmProviderKeysLogic'import {getUnhealthyProviderKey,providerKeyStateIssueDescription,@@ -109,25 +109,15 @@ function TagDefinitionsEditor({ id }: { id: string }): JSX.Element {}function TaggerModelPicker({ id }: { id: string }): JSX.Element {- const {- hasByokKeys,- byokModels,- trialModels,- providerModelGroups,- trialProviderModelGroups,- byokModelsLoading,- trialModelsLoading,- providerKeysLoading,- } = useValues(modelPickerLogic)+ const { hasByokKeys, byokModels, providerModelGroups, byokModelsLoading, providerKeysLoading } =+ useValues(modelPickerLogic)const { selectedModel, selectedPickerProviderKeyId } = useValues(llmTaggerLogic({ id }))const { selectModelFromPicker } = useActions(llmTaggerLogic({ id }))- const { requiresProviderKey } = useValues(llmProviderKeysLogic)- const showTrialModels = !hasByokKeys && !requiresProviderKey- const allModels = showTrialModels ? trialModels : byokModels- const selectedModelName = allModels.find((m) => m.id === selectedModel)?.name- const groups = showTrialModels ? trialProviderModelGroups : providerModelGroups- const loading = showTrialModels ? trialModelsLoading : byokModelsLoading || providerKeysLoading+ // Taggers always run on the team's own provider key, so only BYOK models are offered.+ const selectedModelName = byokModels.find((m) => m.id === selectedModel)?.name+ const groups = providerModelGroups+ const loading = byokModelsLoading || providerKeysLoadingconst footerLink = getModelPickerFooterLink(hasByokKeys)diff --git a/products/ai_observability/frontend/tags/AIObservabilityTagsScene.tsx b/products/ai_observability/frontend/tags/AIObservabilityTagsScene.tsxindex e2cc7cbfde4d..d2f62dd7023e 100644--- a/products/ai_observability/frontend/tags/AIObservabilityTagsScene.tsx+++ b/products/ai_observability/frontend/tags/AIObservabilityTagsScene.tsx@@ -29,7 +29,6 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'import { getUnhealthyProviderKey, providerKeyStateIssueDescription } from '../settings/providerKeyStateUtils'-import { TrialUsageMeter } from '../settings/TrialUsageMeter'import { llmTaggersLogic } from './llmTaggersLogic'import { Tagger } from './types'@@ -277,8 +276,6 @@ function AIObservabilityTagsContent(): JSX.Element {return (<div className="space-y-4">- <TrialUsageMeter showSettingsLink noun="runs" />-<DateFilter dateFrom={dateFilter.dateFrom} dateTo={dateFilter.dateTo} onChange={setDates} /><TaggerMetrics />diff --git a/products/ai_observability/frontend/tags/llmTaggerLogic.test.ts b/products/ai_observability/frontend/tags/llmTaggerLogic.test.tsindex 2048d9c34adb..41850353bf82 100644--- a/products/ai_observability/frontend/tags/llmTaggerLogic.test.ts+++ b/products/ai_observability/frontend/tags/llmTaggerLogic.test.ts@@ -461,8 +461,8 @@ describe('llmTaggerLogic', () => {})})- it('sets model configuration from trial provider key', async () => {- logic.actions.selectModelFromPicker('gpt-5', 'trial:openai')+ it('sets model configuration from playground provider key', async () => {+ logic.actions.selectModelFromPicker('gpt-5', 'playground:openai')await expectLogic(logic).toMatchValues({selectedModel: 'gpt-5',diff --git a/products/ai_observability/frontend/tags/llmTaggerLogic.ts b/products/ai_observability/frontend/tags/llmTaggerLogic.tsindex eb59eb2c778b..33ae7f672b69 100644--- a/products/ai_observability/frontend/tags/llmTaggerLogic.ts+++ b/products/ai_observability/frontend/tags/llmTaggerLogic.ts@@ -13,7 +13,7 @@ import { escapeHogQLString } from '~/queries/utils'import { ChartDisplayType, PropertyFilterType, PropertyOperator } from '~/types'import { aiObservabilitySharedLogic } from '../aiObservabilitySharedLogic'-import { parseTrialProviderKeyId } from '../ModelPicker'+import { parsePlaygroundProviderKeyId } from '../ModelPicker'import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'import { llmTaggersLogic } from './llmTaggersLogic'import {@@ -603,11 +603,11 @@ export const llmTaggerLogic = kea<llmTaggerLogicType>([if (!modelId) {return}- const trialProvider = parseTrialProviderKeyId(providerKeyId)- if (trialProvider) {+ const playgroundProvider = parsePlaygroundProviderKeyId(providerKeyId)+ if (playgroundProvider) {actions.setTaggerFormValues({model_configuration: {- provider: trialProvider,+ provider: playgroundProvider,model: modelId,provider_key_id: null,},diff --git a/products/ai_observability/frontend/tags/llmTaggersLogic.test.ts b/products/ai_observability/frontend/tags/llmTaggersLogic.test.tsindex fb20dcc84c7e..36c96845aab7 100644--- a/products/ai_observability/frontend/tags/llmTaggersLogic.test.ts+++ b/products/ai_observability/frontend/tags/llmTaggersLogic.test.ts@@ -53,11 +53,9 @@ const mockTaggers: Tagger[] = [const providerKeyMocks = {'/api/environments/:team_id/llm_analytics/provider_keys/': { results: [] },'/api/environments/:team_id/llm_analytics/evaluation_config/': {- trial_eval_limit: 100,- trial_evals_used: 0,- trial_evals_remaining: 100,- trial_grandfathered: false,- trial_deprecation_date: '2026-07-15T00:00:00Z',+ active_provider_key: null,+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',},}diff --git a/products/ai_observability/mcp/tools.yaml b/products/ai_observability/mcp/tools.yamlindex 670f92e801bd..1d7e938d9741 100644--- a/products/ai_observability/mcp/tools.yaml+++ b/products/ai_observability/mcp/tools.yaml@@ -597,9 +597,6 @@ tools:- edits- base_version- version_description- llma-provider-key-assign:- operation: llm_analytics_provider_keys_assign_create- enabled: falsellma-provider-key-create:operation: llm_analytics_provider_keys_createenabled: false@@ -638,9 +635,6 @@ tools:name, validation state, and a masked preview — never the secret itself. Call this before creating anllm_judge evaluation to discover which providers have a usable ('ok' state) key available. Creating,updating, and deleting keys are intentionally UI-only.- llma-provider-key-trial-evaluations-get:- operation: llm_analytics_provider_keys_trial_evaluations_retrieve- enabled: falsellma-provider-key-update:operation: llm_analytics_provider_keys_partial_updateenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex db971ddc5b16..b23e7543a861 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -23589,8 +23589,6 @@ export namespace Schemas {/*** * `provider_key_required` - No provider API key configured- * * `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* * `provider_key_invalid` - Provider API key is invalid@@ -23605,8 +23603,6 @@ export namespace Schemas {export const StatusReasonEnum = {ProviderKeyRequired: 'provider_key_required',- TrialLimitReached: 'trial_limit_reached',- ModelNotAllowed: 'model_not_allowed',ProviderKeyDeleted: 'provider_key_deleted',NoDefaultModel: 'no_default_model',ProviderKeyInvalid: 'provider_key_invalid',@@ -23820,16 +23816,6 @@ export namespace Schemas {}export interface EvaluationConfig {- /** Cap on trial runs — a getting-started affordance only, not for ongoing evals (use the team's own key). */- readonly trial_eval_limit: number;- /** Trial runs consumed (getting-started affordance only). */- readonly trial_evals_used: number;- /** Trial runs remaining — a getting-started affordance only; evals should use the team's own provider key. */- readonly trial_evals_remaining: number;- /** True while this team keeps PostHog-funded trial inference during the deprecation window (i.e. it is mid-trial and the cutoff has not passed). False means the team must use its own provider key. */- readonly trial_grandfathered: boolean;- /** Timestamp after which trial evaluations are fully removed and every team must use its own provider key. */- readonly trial_deprecation_date: string;/** Provider key used to run llm_judge evals; null if none configured yet. */readonly active_provider_key: LLMProviderKey | null;/** Timestamp when the evaluation config row was created. */@@ -33461,8 +33447,6 @@ export namespace Schemas {export interface LLMModelInfo {/** Provider-specific model identifier (e.g. 'gpt-4o-mini', 'claude-3-5-sonnet-20241022'). */id: string;- /** True if the model can run without a provider key on PostHog-funded trial credits. Only true for teams still grandfathered into the deprecating trial; every other team must use its own key. */- posthog_available: boolean;}export interface LLMModelsListResponse {