Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(aio): validate evaluation configuration (#70113)

Radu Raicea4a3274caf36c
diff --git a/posthog/test/activity_logging/test_evaluation_activity_logging.py b/posthog/test/activity_logging/test_evaluation_activity_logging.py
index e5a50489cb4e..c63af4979c8e 100644
--- a/posthog/test/activity_logging/test_evaluation_activity_logging.py
+++ b/posthog/test/activity_logging/test_evaluation_activity_logging.py
@@ -18,6 +18,11 @@ def _create_evaluation_payload(**overrides: Any) -> dict[str, Any]:
"description": "Initial",
"enabled": True,
"evaluation_type": "llm_judge",
+ "model_configuration": {
+ "provider": "openai",
+ "model": "gpt-5-mini",
+ "provider_key_id": None,
+ },
"evaluation_config": {"prompt": "Test prompt"},
"output_type": "boolean",
"output_config": {},
diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.py
index bf39c9099031..96e17b64b19e 100644
--- a/products/ai_observability/backend/api/evaluations.py
+++ b/products/ai_observability/backend/api/evaluations.py
@@ -145,10 +145,19 @@ class ModelConfigurationSerializer(serializers.Serializer):
provider_key_id = serializers.UUIDField(
required=False,
allow_null=True,
- help_text="Team provider key to run this eval with (same provider as `provider`). Leave null only for brief pre-key testing; real evals should set it.",
+ help_text=(
+ "Optional team provider key to run this evaluation with; it must use the same provider. "
+ "May be null when no key is pinned or after the selected key is removed."
+ ),
)
provider_key_name = serializers.SerializerMethodField(read_only=True)
+ def validate(self, data: dict[str, Any]) -> dict[str, Any]:
+ errors = {field: "This field is required." for field in ("provider", "model") if field not in data}
+ if errors:
+ raise serializers.ValidationError(errors, code="required")
+ return data
+
def get_provider_key_name(self, obj: LLMModelConfiguration) -> str | None:
if obj.provider_key:
return obj.provider_key.name
@@ -182,7 +191,17 @@ class EvaluationConditionSerializer(serializers.Serializer):
class EvaluationSerializer(serializers.ModelSerializer):
created_by = UserBasicSerializer(read_only=True)
- model_configuration = ModelConfigurationSerializer(required=False, allow_null=True)
+ model_configuration = ModelConfigurationSerializer(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. "
+ "To add or replace a model, provide both provider and model. On an existing configured llm_judge, "
+ "omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or "
+ "sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable "
+ "without adding one. The nested provider_key_id may be null."
+ ),
+ )
status_reason_detail = serializers.CharField(
read_only=True,
allow_null=True,
@@ -290,6 +309,19 @@ class EvaluationSerializer(serializers.ModelSerializer):
{"model_configuration": "This evaluation type does not use model configuration."}
)
+ if evaluation_uses_model_configuration(evaluation_type) and model_configuration is None:
+ existing_uses_model_configuration = bool(
+ self.instance and evaluation_uses_model_configuration(self.instance.evaluation_type)
+ )
+ newly_requires_model_configuration = self.instance is None or not existing_uses_model_configuration
+ clears_existing_model_configuration = bool(
+ self.instance and self.instance.model_configuration_id and "model_configuration" in data
+ )
+ if newly_requires_model_configuration or clears_existing_model_configuration:
+ raise serializers.ValidationError(
+ {"model_configuration": "Select a provider and model for this LLM judge evaluation."}
+ )
+
should_validate_configs = (
self.instance is None
or "evaluation_type" in data
@@ -438,9 +470,9 @@ class EvaluationSerializer(serializers.ModelSerializer):
def _effective_model_configuration(self, data: dict) -> dict[str, Any] | None:
"""The explicit model configuration the evaluation will have after this update, or None
- when it defers to the team default (null config). An explicit `model_configuration: null`
- detaches the stored config (see update()), so payload presence wins — membership, not
- truthiness."""
+ when it defers to the team default (null config). Payload presence wins because an explicit
+ null is still accepted for legacy null-config evaluations and when switching to a type that
+ does not use a model."""
if "model_configuration" in data:
return data["model_configuration"]
if self.instance is not None and self.instance.model_configuration is not None:
@@ -512,8 +544,8 @@ class EvaluationSerializer(serializers.ModelSerializer):
return super().create(validated_data)
def update(self, instance, validated_data):
- # An explicit `model_configuration: null` detaches the config; a PATCH that omits the field must
- # leave it untouched. pop()'s default can't tell the two apart, so check membership explicitly.
+ # Switching away from an LLM judge uses an explicit null to detach its config; omission leaves it untouched.
+ # pop()'s default can't tell the two apart, so check membership explicitly.
model_config_provided = "model_configuration" in validated_data
model_config_data = validated_data.pop("model_configuration", None)
old_config = None
diff --git a/products/ai_observability/backend/api/test/test_ai_observability_access_control.py b/products/ai_observability/backend/api/test/test_ai_observability_access_control.py
index 2f9186dc2720..e9fc9eefe41d 100644
--- a/products/ai_observability/backend/api/test/test_ai_observability_access_control.py
+++ b/products/ai_observability/backend/api/test/test_ai_observability_access_control.py
@@ -21,6 +21,13 @@ except ImportError:
pass
+_DEFAULT_MODEL_CONFIGURATION = {
+ "provider": "openai",
+ "model": "gpt-5-mini",
+ "provider_key_id": None,
+}
+
+
@pytest.mark.ee
class TestAIObservabilityAccessControl(APIBaseTest):
def setUp(self):
@@ -241,6 +248,7 @@ class TestAIObservabilityAccessControl(APIBaseTest):
{
"name": "New Evaluation",
"evaluation_type": "llm_judge",
+ "model_configuration": _DEFAULT_MODEL_CONFIGURATION,
"evaluation_config": {"prompt": "prompt"},
"output_type": "boolean",
"output_config": {},
@@ -400,6 +408,7 @@ class TestAIObservabilityAccessControl(APIBaseTest):
{
"name": "Editor Evaluation",
"evaluation_type": "llm_judge",
+ "model_configuration": _DEFAULT_MODEL_CONFIGURATION,
"evaluation_config": {"prompt": "prompt"},
"output_type": "boolean",
"output_config": {},
@@ -635,6 +644,7 @@ class TestAIObservabilityAccessControl(APIBaseTest):
{
"name": "Admin Evaluation",
"evaluation_type": "llm_judge",
+ "model_configuration": _DEFAULT_MODEL_CONFIGURATION,
"evaluation_config": {"prompt": "prompt"},
"output_type": "boolean",
"output_config": {},
diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.py
index 782ae5e1b049..e11391c6a1b2 100644
--- a/products/ai_observability/backend/api/test/test_evaluations.py
+++ b/products/ai_observability/backend/api/test/test_evaluations.py
@@ -4,18 +4,26 @@ from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.db import IntegrityError, transaction
+from django.test import SimpleTestCase
from parameterized import parameterized
from rest_framework import status
from posthog.models import Organization, Project, Team, User
+from products.ai_observability.backend.api.evaluations import ModelConfigurationSerializer
from products.ai_observability.backend.models.evaluation_config import EvaluationConfig
from products.ai_observability.backend.models.evaluation_reports import EvaluationReport
from products.ai_observability.backend.models.evaluations import Evaluation
from products.ai_observability.backend.models.model_configuration import LLMModelConfiguration
from products.ai_observability.backend.models.provider_keys import LLMProviderKey
+_DEFAULT_MODEL_CONFIGURATION = {
+ "provider": "openai",
+ "model": "gpt-5-mini",
+ "provider_key_id": None,
+}
+
def _setup_team():
org = Organization.objects.create(name="test")
@@ -39,7 +47,38 @@ def _setup_team():
return team
+class TestModelConfigurationSerializer(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("missing_provider", {"model": "gpt-5-mini"}, "provider"),
+ ("missing_model", {"provider": "openai"}, "model"),
+ ]
+ )
+ def test_partial_update_requires_complete_configuration(
+ self, _name: str, data: dict[str, str], missing_field: str
+ ) -> None:
+ serializer = ModelConfigurationSerializer(data=data, partial=True)
+
+ self.assertFalse(serializer.is_valid())
+ self.assertEqual(serializer.errors[missing_field][0].code, "required")
+
+
class TestEvaluationConfigsApi(APIBaseTest):
+ def _create_configured_llm_judge(self) -> tuple[Evaluation, LLMModelConfiguration]:
+ model_configuration = LLMModelConfiguration.objects.create(
+ team=self.team, provider="openai", model="gpt-5-mini"
+ )
+ evaluation = Evaluation.objects.create(
+ team=self.team,
+ name="Judge",
+ evaluation_type="llm_judge",
+ evaluation_config={"prompt": "Test"},
+ output_type="boolean",
+ model_configuration=model_configuration,
+ created_by=self.user,
+ )
+ return evaluation, model_configuration
+
def test_unauthenticated_user_cannot_access_evaluation_configs(self):
self.client.logout()
response = self.client.get(f"/api/environments/{self.team.id}/evaluations/")
@@ -56,6 +95,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
"description": "Test Description",
"enabled": True,
"evaluation_type": "llm_judge",
+ "model_configuration": _DEFAULT_MODEL_CONFIGURATION,
"evaluation_config": {"prompt": "Test prompt"},
"output_type": "boolean",
"output_config": {},
@@ -98,6 +138,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
{
"name": "Default target",
"evaluation_type": "llm_judge",
+ "model_configuration": _DEFAULT_MODEL_CONFIGURATION,
"evaluation_config": {"prompt": "Test prompt"},
"output_type": "boolean",
"output_config": {},
@@ -114,6 +155,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
{
"name": "Trace target",
"evaluation_type": "llm_judge",
+ "model_configuration": _DEFAULT_MODEL_CONFIGURATION,
"evaluation_config": {"prompt": "Test prompt"},
"output_type": "boolean",
"output_config": {},
@@ -136,6 +178,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
{
"name": "Trace custom window",
"evaluation_type": "llm_judge",
+ "model_configuration": _DEFAULT_MODEL_CONFIGURATION,
"evaluation_config": {"prompt": "Test prompt"},
"output_type": "boolean",
"output_config": {},
@@ -154,6 +197,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
{
"name": "Trace tiny window",
"evaluation_type": "llm_judge",
+ "model_configuration": _DEFAULT_MODEL_CONFIGURATION,
"evaluation_config": {"prompt": "Test prompt"},
"output_type": "boolean",
"output_config": {},
@@ -172,6 +216,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
{
"name": "Generation with stray config",
"evaluation_type": "llm_judge",
+ "model_configuration": _DEFAULT_MODEL_CONFIGURATION,
"evaluation_config": {"prompt": "Test prompt"},
"output_type": "boolean",
"output_config": {},
@@ -190,6 +235,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
{
"name": "Trace unknown key",
"evaluation_type": "llm_judge",
+ "model_configuration": _DEFAULT_MODEL_CONFIGURATION,
"evaluation_config": {"prompt": "Test prompt"},
"output_type": "boolean",
"output_config": {},
@@ -208,6 +254,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
{
"name": "Bad target",
"evaluation_type": "llm_judge",
+ "model_configuration": _DEFAULT_MODEL_CONFIGURATION,
"evaluation_config": {"prompt": "Test prompt"},
"output_type": "boolean",
"output_config": {},
@@ -232,6 +279,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
{
"name": "Will Rollback",
"evaluation_type": "llm_judge",
+ "model_configuration": _DEFAULT_MODEL_CONFIGURATION,
"evaluation_config": {"prompt": "Test prompt"},
"output_type": "boolean",
"output_config": {},
@@ -306,18 +354,30 @@ class TestEvaluationConfigsApi(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data["attr"], "model_configuration")
- def test_clearing_model_configuration_with_explicit_null(self):
- mc = LLMModelConfiguration.objects.create(team=self.team, provider="openai", model="gpt-5-mini")
- eval_obj = Evaluation.objects.create(
- team=self.team,
- name="Judge",
- evaluation_type="llm_judge",
- evaluation_config={"prompt": "Test"},
- output_type="boolean",
- model_configuration=mc,
- created_by=self.user,
+ @parameterized.expand([("omitted", False), ("null", True)])
+ def test_llm_judge_creation_requires_model_configuration(self, _name, include_null_configuration):
+ payload: dict[str, object] = {
+ "name": "Judge without model",
+ "evaluation_type": "llm_judge",
+ "evaluation_config": {"prompt": "Test"},
+ "output_type": "boolean",
+ }
+ if include_null_configuration:
+ payload["model_configuration"] = None
+
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/evaluations/",
+ payload,
+ format="json",
)
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.data["attr"], "model_configuration")
+ self.assertEqual(Evaluation.objects.count(), 0)
+
+ def test_configured_llm_judge_rejects_clearing_model_configuration(self) -> None:
+ eval_obj, mc = self._create_configured_llm_judge()
+
response = self.client.patch(
f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",
{"name": "Renamed"},
@@ -332,9 +392,82 @@ class TestEvaluationConfigsApi(APIBaseTest):
{"model_configuration": None},
format="json",
)
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.data["attr"], "model_configuration")
+ eval_obj.refresh_from_db()
+ self.assertEqual(eval_obj.model_configuration_id, mc.id)
+ self.assertTrue(LLMModelConfiguration.objects.filter(id=mc.id).exists())
+
+ @parameterized.expand(
+ [
+ ("omitted", {}, "model_configuration"),
+ (
+ "incomplete",
+ {"model_configuration": {"provider": "openai"}},
+ "model_configuration__model",
+ ),
+ ]
+ )
+ def test_switching_existing_evaluation_to_llm_judge_requires_model_configuration(
+ self, _name: str, extra_payload: dict[str, object], expected_attr: str
+ ) -> None:
+ eval_obj = Evaluation.objects.create(
+ team=self.team,
+ name="Hog evaluation",
+ evaluation_type="hog",
+ evaluation_config={"source": "return true"},
+ output_type="boolean",
+ created_by=self.user,
+ )
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",
+ {
+ "evaluation_type": "llm_judge",
+ "evaluation_config": {"prompt": "Test"},
+ **extra_payload,
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.data["attr"], expected_attr)
+ eval_obj.refresh_from_db()
+ self.assertEqual(eval_obj.evaluation_type, "hog")
+
+ @parameterized.expand(
+ [
+ ("hog", "hog", "boolean", {"source": "return true"}),
+ ("sentiment", "sentiment", "sentiment", {"source": "user_messages"}),
+ ]
+ )
+ def test_switching_llm_judge_type_clears_model_configuration(
+ self,
+ _name: str,
+ evaluation_type: str,
+ output_type: str,
+ evaluation_config: dict[str, str],
+ ) -> None:
+ eval_obj, mc = self._create_configured_llm_judge()
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",
+ {
+ "evaluation_type": evaluation_type,
+ "evaluation_config": evaluation_config,
+ "output_type": output_type,
+ "output_config": {},
+ "model_configuration": None,
+ },
+ format="json",
+ )
+
self.assertEqual(response.status_code, status.HTTP_200_OK)
eval_obj.refresh_from_db()
- self.assertIsNone(eval_obj.model_configuration)
+ self.assertEqual(eval_obj.evaluation_type, evaluation_type)
+ self.assertEqual(eval_obj.output_type, output_type)
+ self.assertEqual(eval_obj.evaluation_config["source"], evaluation_config["source"])
+ self.assertIsNone(eval_obj.model_configuration_id)
self.assertFalse(LLMModelConfiguration.objects.filter(id=mc.id).exists())
def test_db_constraint_blocks_model_config_on_non_judge_eval(self):
@@ -360,17 +493,21 @@ class TestEvaluationConfigsApi(APIBaseTest):
def test_rejects_unsupported_evaluation_output_type_combinations(
self, _name, evaluation_type, output_type, evaluation_config, output_config
):
+ payload = {
+ "name": "Unsupported Evaluation",
+ "enabled": True,
+ "evaluation_type": evaluation_type,
+ "evaluation_config": evaluation_config,
+ "output_type": output_type,
+ "output_config": output_config,
+ "conditions": [{"id": "test-condition", "rollout_percentage": 50, "properties": []}],
+ }
+ if evaluation_type == "llm_judge":
+ payload["model_configuration"] = _DEFAULT_MODEL_CONFIGURATION
+
response = self.client.post(
f"/api/environments/{self.team.id}/evaluations/",
- {
- "name": "Unsupported Evaluation",
- "enabled": True,
- "evaluation_type": evaluation_type,
- "evaluation_config": evaluation_config,
- "output_type": output_type,
- "output_config": output_config,
- "conditions": [{"id": "test-condition", "rollout_percentage": 50, "properties": []}],
- },
+ payload,
format="json",
)
@@ -632,6 +769,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
f"/api/environments/{self.team.id}/evaluations/",
{
"evaluation_type": "llm_judge",
+ "model_configuration": _DEFAULT_MODEL_CONFIGURATION,
"evaluation_config": {"prompt": "Test prompt"},
"output_type": "boolean",
"output_config": {},
@@ -659,6 +797,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
{
"name": "Test Evaluation",
"evaluation_type": "llm_judge",
+ "model_configuration": _DEFAULT_MODEL_CONFIGURATION,
"evaluation_config": {},
"output_type": "boolean",
"output_config": {},
@@ -712,6 +851,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
{
"name": "Test with Properties",
"evaluation_type": "llm_judge",
+ "model_configuration": _DEFAULT_MODEL_CONFIGURATION,
"evaluation_config": {"prompt": "Evaluate this"},
"output_type": "boolean",
"output_config": {},
@@ -749,6 +889,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
{
"name": "Typo eval",
"evaluation_type": "llm_judge",
+ "model_configuration": _DEFAULT_MODEL_CONFIGURATION,
"evaluation_config": {"prompt": "Evaluate"},
"output_type": "boolean",
"output_config": {},
@@ -776,6 +917,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
{
"name": "Out of range",
"evaluation_type": "llm_judge",
+ "model_configuration": _DEFAULT_MODEL_CONFIGURATION,
"evaluation_config": {"prompt": "Evaluate"},
"output_type": "boolean",
"output_config": {},
@@ -791,6 +933,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
{
"name": "Boundary",
"evaluation_type": "llm_judge",
+ "model_configuration": _DEFAULT_MODEL_CONFIGURATION,
"evaluation_config": {"prompt": "Evaluate"},
"output_type": "boolean",
"output_config": {},
@@ -1009,25 +1152,6 @@ class TestEnableBlockingWhenKeyRequired(APIBaseTest):
eval_obj.refresh_from_db()
self.assertFalse(eval_obj.enabled)
- def test_detaching_model_configuration_enables_via_active_key(self):
- # The gate must validate the post-detach state, not the stored config.
- key = self._create_active_key()
- EvaluationConfig.objects.create(
- team=self.team, trial_eval_limit=100, trial_evals_used=100, active_provider_key=key
- )
- eval_obj = self._create_keyless_eval()
-
- response = self.client.patch(
- f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",
- {"enabled": True, "model_configuration": None},
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- eval_obj.refresh_from_db()
- self.assertTrue(eval_obj.enabled)
- self.assertIsNone(eval_obj.model_configuration)
-
def test_blocks_creating_enabled_keyless_eval_when_not_grandfathered(self):
response = self.client.post(
f"/api/environments/{self.team.id}/evaluations/",
@@ -1035,6 +1159,7 @@ class TestEnableBlockingWhenKeyRequired(APIBaseTest):
"name": "Doomed Eval",
"enabled": True,
"evaluation_type": "llm_judge",
+ "model_configuration": _DEFAULT_MODEL_CONFIGURATION,
"evaluation_config": {"prompt": "test"},
"output_type": "boolean",
"output_config": {},
diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
index caf15958c39f..ccd55ddb9108 100644
--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
@@ -23,7 +23,6 @@ import { DurationPicker } from 'lib/components/DurationPicker/DurationPicker'
import { NotFound } from 'lib/components/NotFound'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { SceneExport } from 'scenes/sceneTypes'
-import { userLogic } from 'scenes/userLogic'
import { SceneBreadcrumbBackButton } from '~/layout/scenes/components/SceneBreadcrumbs'
import { InsightVizNode, NodeKind } from '~/queries/schema/schema-general'
@@ -42,9 +41,9 @@ import { EvaluationTriggers } from './components/EvaluationTriggers'
import {
evaluationSupportsReports,
evaluationTypeHasEditableCriteria,
- evaluationTypeSupportsSignalEmission,
evaluationTypeUsesModelConfiguration,
} from './evaluationCapabilities'
+import { evaluationReportLogic } from './evaluationReportLogic'
import { DEFAULT_TRACE_WINDOW_SECONDS, LLMEvaluationLogicProps, llmEvaluationLogic } from './llmEvaluationLogic'
import { statusReasonLabel, statusReasonRecoveryLabel } from './statusDisplay'
import { EvaluationTarget, EvaluationType } from './types'
@@ -59,12 +58,11 @@ export function AIObservabilityEvaluation(): JSX.Element {
isNewEvaluation,
runsSummary,
evaluationProviderKeyIssue,
- signalEmissionEnabled,
activeTab,
canEnable,
canEnableReason,
+ modelSelectionRequired,
} = useValues(llmEvaluationLogic)
- const { user } = useValues(userLogic)
const { searchParams } = useValues(router)
const {
setEvaluationName,
@@ -76,7 +74,6 @@ export function AIObservabilityEvaluation(): JSX.Element {
setEvaluationType,
setEvaluationTarget,
setTraceWindowSeconds,
- setSignalEmission,
setActiveTab,
} = useActions(llmEvaluationLogic)
const { push } = useActions(router)
@@ -160,6 +157,7 @@ export function AIObservabilityEvaluation(): JSX.Element {
: isSentiment
? true
: evaluation.evaluation_config.prompt.trim().length > 0
+ const hasSelectedJudgeModel = !modelSelectionRequired || Boolean(evaluation.model_configuration?.model.trim())
const hasName = evaluation.name.length > 0
const basicFieldsValid = hasName && configValid
const percentageUnset = evaluation.conditions.some((c) => (c.rollout_percentage ?? 0) === 0)
@@ -173,7 +171,9 @@ export function AIObservabilityEvaluation(): JSX.Element {
? isHog
? 'Add evaluation code before saving'
: 'Add an evaluation prompt before saving'
- : undefined
+ : !hasSelectedJudgeModel
+ ? 'Select a judge model before saving'
+ : undefined
const focusTriggers = (): void => {
setActiveTab('configuration')
@@ -201,6 +201,12 @@ export function AIObservabilityEvaluation(): JSX.Element {
return
}
+ const reportLogic = evaluationReportLogic({ evaluationId: isNewEvaluation ? 'new' : evaluation.id })
+ if (isReportableEvaluation && reportLogic.isMounted() && reportLogic.values.configError) {
+ lemonToast.error(reportLogic.values.configError)
+ return
+ }
+
saveEvaluation()
}
@@ -556,20 +562,6 @@ export function AIObservabilityEvaluation(): JSX.Element {
</div>
</Field>
)}
- {!isNewEvaluation &&
- user?.is_staff &&
- evaluationTypeSupportsSignalEmission(evaluation.evaluation_type) && (
- <div className="flex items-center gap-2">
- <LemonSwitch
- checked={signalEmissionEnabled}
- onChange={setSignalEmission}
- />
- <span>Emit signals</span>
- <Tooltip title="When enabled, true verdicts from this evaluation will be emitted as signals for clustering and investigation.">
- <IconInfo className="text-muted text-base" />
- </Tooltip>
- </div>
- )}
</div>
</div>
@@ -629,7 +621,8 @@ function EvaluationModelPicker(): JSX.Element {
trialModelsLoading,
providerKeysLoading,
} = useValues(modelPickerLogic)
- const { selectedModel, selectedPickerProviderKeyId, requiresProviderKey } = useValues(llmEvaluationLogic)
+ const { selectedModel, selectedPickerProviderKeyId, requiresProviderKey, modelSelectionRequired } =
+ useValues(llmEvaluationLogic)
const { selectModelFromPicker } = useActions(llmEvaluationLogic)
const showTrialModels = !hasByokKeys && !requiresProviderKey
@@ -649,16 +642,21 @@ function EvaluationModelPicker(): JSX.Element {
<div className="space-y-4">
<Field name="model" label="Model">
- <ModelPicker
- model={selectedModel}
- selectedProviderKeyId={selectedPickerProviderKeyId}
- onSelect={selectModelFromPicker}
- groups={groups}
- loading={loading}
- footerLink={footerLink}
- selectedModelName={selectedModelName}
- data-attr="evaluation-model-selector"
- />
+ <div>
+ <ModelPicker
+ model={selectedModel}
+ selectedProviderKeyId={selectedPickerProviderKeyId}
+ onSelect={selectModelFromPicker}
+ groups={groups}
+ loading={loading}
+ footerLink={footerLink}
+ selectedModelName={selectedModelName}
+ data-attr="evaluation-model-selector"
+ />
+ {modelSelectionRequired && !selectedModel && (
+ <p className="text-sm text-danger mt-1">Select a judge model.</p>
+ )}
+ </div>
</Field>
</div>
</div>
diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx
index f93ebcfcaae7..89632feb908c 100644
--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx
+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluationsScene.tsx
@@ -1,7 +1,7 @@
import { BindLogic, useActions, useMountedLogic, useValues } from 'kea'
import { combineUrl, router } from 'kea-router'
-import { IconCopy, IconPencil, IconPlus, IconSearch, IconTrash, IconWarning } from '@posthog/icons'
+import { IconPencil, IconPlus, IconSearch, IconTrash, IconWarning } from '@posthog/icons'
import {
LemonBanner,
LemonButton,
@@ -130,8 +130,7 @@ function AIObservabilityEvaluationsContent(): JSX.Element {
unhealthyProviderKeysUsedByEvaluations,
canEnableEvaluation,
} = useValues(evaluationsLogic)
- const { setEvaluationsFilter, toggleEvaluationEnabled, duplicateEvaluation, loadEvaluations, setDates } =
- useActions(evaluationsLogic)
+ const { setEvaluationsFilter, toggleEvaluationEnabled, loadEvaluations, setDates } = useActions(evaluationsLogic)
const { evaluationsWithMetrics } = useValues(metricsLogic)
const { currentTeamId } = useValues(teamLogic)
const { push } = useActions(router)
@@ -319,17 +318,6 @@ function AIObservabilityEvaluationsContent(): JSX.Element {
onClick={() => push(evaluationUrl(evaluation.id))}
/>
</AccessControlAction>
- <AccessControlAction
- resourceType={AccessControlResourceType.LlmAnalytics}
- minAccessLevel={AccessControlLevel.Editor}
- >
- <LemonButton
- size="small"
- type="secondary"
- icon={<IconCopy />}
- onClick={() => duplicateEvaluation(evaluation.id)}
- />
- </AccessControlAction>
<AccessControlAction
resourceType={AccessControlResourceType.LlmAnalytics}
minAccessLevel={AccessControlLevel.Editor}
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationReportConfig.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationReportConfig.tsx
index 466c3aee263b..276a77414f3b 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationReportConfig.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationReportConfig.tsx
@@ -81,7 +81,15 @@ export function ScheduleConfig({
}
/** Threshold config shown when frequency is 'every_n' */
-function ThresholdConfig({ value, onChange }: { value: number; onChange: (value: number) => void }): JSX.Element {
+function ThresholdConfig({
+ value,
+ error,
+ onChange,
+}: {
+ value: number
+ error?: string
+ onChange: (value: number) => void
+}): JSX.Element {
return (
<div>
<label className="font-semibold text-sm">Evaluation count threshold</label>
@@ -91,8 +99,10 @@ function ThresholdConfig({ value, onChange }: { value: number; onChange: (value:
max={TRIGGER_THRESHOLD_MAX}
value={value}
onChange={(val) => onChange(Number(val))}
+ status={error ? 'danger' : undefined}
fullWidth
/>
+ {error && <p className="text-xs text-danger mt-1">{error}</p>}
<p className="text-xs text-muted mt-1">
A report will be generated after this many new evaluation results arrive. Checked every 5 minutes. Min{' '}
{TRIGGER_THRESHOLD_MIN}, max {TRIGGER_THRESHOLD_MAX.toLocaleString()}.
@@ -102,7 +112,15 @@ function ThresholdConfig({ value, onChange }: { value: number; onChange: (value:
}
/** Cooldown config shown when frequency is 'every_n' */
-function CooldownConfig({ value, onChange }: { value: number; onChange: (value: number) => void }): JSX.Element {
+function CooldownConfig({
+ value,
+ error,
+ onChange,
+}: {
+ value: number
+ error?: string
+ onChange: (value: number) => void
+}): JSX.Element {
return (
<div>
<label className="font-semibold text-sm">Minimum hours between reports</label>
@@ -112,8 +130,10 @@ function CooldownConfig({ value, onChange }: { value: number; onChange: (value:
max={COOLDOWN_HOURS_MAX}
value={value}
onChange={(val) => onChange(Number(val))}
+ status={error ? 'danger' : undefined}
fullWidth
/>
+ {error && <p className="text-xs text-danger mt-1">{error}</p>}
<p className="text-xs text-muted mt-1">
After a report is generated, wait this many hours before generating another — even if the threshold is
crossed again. Min {COOLDOWN_HOURS_MIN}, max {COOLDOWN_HOURS_MAX}.
@@ -187,7 +207,7 @@ function DeliveryTargetsConfig({
/** Shared form body used by both the create-evaluation and edit-existing-evaluation paths.
* All state is backed by `evaluationReportLogic.configDraft` keyed by evaluationId. */
function ReportFormFields({ evaluationId }: { evaluationId: string }): JSX.Element {
- const { configDraft } = useValues(evaluationReportLogic({ evaluationId }))
+ const { configDraft, configErrors } = useValues(evaluationReportLogic({ evaluationId }))
const {
setDraftFrequency,
setDraftScheduleCadence,
@@ -213,8 +233,16 @@ function ReportFormFields({ evaluationId }: { evaluationId: string }): JSX.Eleme
</div>
{configDraft.frequency === 'every_n' && (
<>
- <ThresholdConfig value={configDraft.triggerThreshold} onChange={setDraftTriggerThreshold} />
- <CooldownConfig value={configDraft.cooldownHours} onChange={setDraftCooldownHours} />
+ <ThresholdConfig
+ value={configDraft.triggerThreshold}
+ error={configErrors.triggerThreshold}
+ onChange={setDraftTriggerThreshold}
+ />
+ <CooldownConfig
+ value={configDraft.cooldownHours}
+ error={configErrors.cooldownHours}
+ onChange={setDraftCooldownHours}
+ />
</>
)}
{configDraft.frequency === 'scheduled' && (
diff --git a/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts b/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts
index 334d80ed36a2..86a702013c3a 100644
--- a/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts
@@ -52,7 +52,3 @@ export function evaluationTypeDefaultsToBooleanOutput(evaluationType: Evaluation
export function evaluationTypeHasEditableCriteria(evaluationType: EvaluationType | null | undefined): boolean {
return evaluationTypeDefaultsToBooleanOutput(evaluationType)
}
-
-export function evaluationTypeSupportsSignalEmission(evaluationType: EvaluationType | null | undefined): boolean {
- return evaluationType === 'llm_judge'
-}
diff --git a/products/ai_observability/frontend/evaluations/evaluationReportLogic.ts b/products/ai_observability/frontend/evaluations/evaluationReportLogic.ts
index 0c3f2d7aa52c..02dc9d889860 100644
--- a/products/ai_observability/frontend/evaluations/evaluationReportLogic.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationReportLogic.ts
@@ -44,6 +44,11 @@ export interface ReportConfigDraft {
cooldownHours: number
}
+export interface ReportConfigErrors {
+ triggerThreshold?: string
+ cooldownHours?: string
+}
+
export const TRIGGER_THRESHOLD_MIN = 100
export const TRIGGER_THRESHOLD_DEFAULT = 100
export const TRIGGER_THRESHOLD_MAX = 10_000
@@ -78,6 +83,32 @@ const DEFAULT_CONFIG_DRAFT: ReportConfigDraft = {
cooldownHours: COOLDOWN_HOURS_DEFAULT,
}
+export function getReportConfigErrors(draft: ReportConfigDraft): ReportConfigErrors {
+ if (draft.frequency !== 'every_n') {
+ return {}
+ }
+
+ return {
+ triggerThreshold:
+ Number.isInteger(draft.triggerThreshold) &&
+ draft.triggerThreshold >= TRIGGER_THRESHOLD_MIN &&
+ draft.triggerThreshold <= TRIGGER_THRESHOLD_MAX
+ ? undefined
+ : `Evaluation count threshold must be a whole number between ${TRIGGER_THRESHOLD_MIN} and ${TRIGGER_THRESHOLD_MAX.toLocaleString()}.`,
+ cooldownHours:
+ Number.isInteger(draft.cooldownHours) &&
+ draft.cooldownHours >= COOLDOWN_HOURS_MIN &&
+ draft.cooldownHours <= COOLDOWN_HOURS_MAX
+ ? undefined
+ : `Minimum hours between reports must be a whole number between ${COOLDOWN_HOURS_MIN} and ${COOLDOWN_HOURS_MAX}.`,
+ }
+}
+
+export function getReportConfigError(draft: ReportConfigDraft): string | null {
+ const errors = getReportConfigErrors(draft)
+ return errors.triggerThreshold ?? errors.cooldownHours ?? null
+}
+
function normalizeScheduleWeekdays(weekdays: ReportScheduleWeekday[]): ReportScheduleWeekday[] {
const selected = new Set(weekdays)
const normalized = WEEKDAY_ORDER.filter((weekday) => selected.has(weekday))
@@ -220,6 +251,11 @@ export async function persistReportDraft(
draft: ReportConfigDraft,
activeReport: EvaluationReport | null
): Promise<boolean> {
+ const configError = getReportConfigError(draft)
+ if (configError) {
+ throw new Error(configError)
+ }
+
const targets = buildDeliveryTargets(draft)
if (activeReport) {
await llmAnalyticsEvaluationReportsPartialUpdate(
@@ -409,6 +445,14 @@ export const evaluationReportLogic = kea<evaluationReportLogicType>([
selectors({
isNewEvaluation: [(_, p) => [p.evaluationId], (evaluationId: string) => evaluationId === 'new'],
+ configErrors: [
+ (s) => [s.configDraft],
+ (configDraft: ReportConfigDraft): ReportConfigErrors => getReportConfigErrors(configDraft),
+ ],
+ configError: [
+ (s) => [s.configDraft],
+ (configDraft: ReportConfigDraft): string | null => getReportConfigError(configDraft),
+ ],
activeReport: [
(s) => [s.reports],
(reports): EvaluationReport | null => {
@@ -474,6 +518,11 @@ export const evaluationReportLogic = kea<evaluationReportLogicType>([
},
saveDraft: () => {
const { configDraft, activeReport } = values
+ if (values.configError) {
+ lemonToast.error(values.configError)
+ return
+ }
+
const targets = buildDeliveryTargets(configDraft)
if (activeReport) {
actions.updateReport({
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
index 1560659a414d..42d4a673e1a5 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
@@ -240,7 +240,7 @@ describe('llmEvaluationLogic', () => {
created_at: '2024-01-01T00:00:00Z',
updated_at: '2024-01-01T00:00:00Z',
},
- '/api/environments/:teamId/evaluations/:id/': mockEvaluation,
+ '/api/projects/:teamId/evaluations/:id/': mockEvaluation,
'/api/environments/:teamId/llm_analytics/models/': {
models: [
{ id: 'gpt-5-mini', posthog_available: true },
@@ -411,6 +411,15 @@ describe('llmEvaluationLogic', () => {
await expectLogic(logic).toMatchValues({ formValid: false })
})
+ it('returns false when an LLM judge has no selected model', async () => {
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
+ logic.actions.setEvaluationName('Valid Name')
+ logic.actions.setEvaluationPrompt('Valid prompt')
+ logic.actions.setTriggerConditions([{ id: 'c1', rollout_percentage: 50, properties: [] }])
+
+ await expectLogic(logic).toMatchValues({ formValid: false })
+ })
+
it('returns false when no conditions have rollout > 0', async () => {
await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
logic.actions.setEvaluationName('Valid Name')
@@ -446,6 +455,11 @@ describe('llmEvaluationLogic', () => {
logic.actions.setEvaluationName('Valid Name')
logic.actions.setEvaluationPrompt('Valid prompt')
logic.actions.setTriggerConditions([{ id: 'c1', rollout_percentage: 50, properties: [] }])
+ logic.actions.setModelConfiguration({
+ provider: 'openai',
+ model: 'gpt-5-mini',
+ provider_key_id: 'key-1',
+ })
await expectLogic(logic).toMatchValues({ formValid: true })
})
@@ -465,6 +479,43 @@ describe('llmEvaluationLogic', () => {
})
})
+ describe('modelSelectionRequired', () => {
+ beforeEach(() => {
+ logic = llmEvaluationLogic({ evaluationId: 'eval-123' })
+ logic.mount()
+ })
+
+ it('allows existing legacy evaluations without a model configuration to remain editable', async () => {
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
+
+ logic.actions.loadEvaluationSuccess({ ...mockEvaluation, model_configuration: null })
+
+ await expectLogic(logic).toMatchValues({ modelSelectionRequired: false, formValid: true })
+ })
+
+ it('requires an existing configured evaluation to keep a selected model', async () => {
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
+
+ logic.actions.setModelConfiguration(null)
+
+ await expectLogic(logic).toMatchValues({ modelSelectionRequired: true, formValid: false })
+ })
+
+ it('requires a model when converting an existing Hog evaluation to an LLM judge', async () => {
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
+ logic.actions.loadEvaluationSuccess({
+ ...mockEvaluation,
+ evaluation_type: 'hog',
+ evaluation_config: { source: DEFAULT_HOG_SOURCE },
+ model_configuration: null,
+ })
+
+ logic.actions.setEvaluationType('llm_judge')
+
+ await expectLogic(logic).toMatchValues({ modelSelectionRequired: true, formValid: false })
+ })
+ })
+
describe('evaluationProviderKeyIssue', () => {
beforeEach(() => {
logic = llmEvaluationLogic({ evaluationId: 'eval-123' })
@@ -1197,6 +1248,48 @@ describe('llmEvaluationLogic', () => {
})
describe('saveEvaluation report persistence', () => {
+ it('does not create an evaluation when the report threshold is invalid', async () => {
+ let evaluationCreateCount = 0
+ useMocks({
+ post: {
+ '/api/projects/:teamId/evaluations/': () => {
+ evaluationCreateCount += 1
+ return mockEvaluation
+ },
+ },
+ })
+
+ logic = llmEvaluationLogic({ evaluationId: 'new' })
+ const reportLogic = evaluationReportLogic({ evaluationId: 'new' })
+ logic.mount()
+ reportLogic.mount()
+
+ try {
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
+ logic.actions.setEvaluationName('Valid Name')
+ logic.actions.setEvaluationPrompt('Valid prompt')
+ logic.actions.setModelConfiguration({
+ provider: 'openai',
+ model: 'gpt-5-mini',
+ provider_key_id: 'key-1',
+ })
+ reportLogic.actions.setDraftTriggerThreshold(67)
+
+ expect(reportLogic.values.configErrors.triggerThreshold).toBe(
+ 'Evaluation count threshold must be a whole number between 100 and 10,000.'
+ )
+
+ logic.actions.saveEvaluation()
+
+ await expectLogic(logic)
+ .toDispatchActions(['saveEvaluationFailure'])
+ .toMatchValues({ evaluationFormSubmitting: false })
+ expect(evaluationCreateCount).toBe(0)
+ } finally {
+ reportLogic.unmount()
+ }
+ })
+
it('does not overwrite a saved report with defaults before the report load finishes', async () => {
let reportWriteCount = 0
let reportListRequestCount = 0
@@ -1222,7 +1315,7 @@ describe('llmEvaluationLogic', () => {
},
},
patch: {
- '/api/environments/:teamId/evaluations/:id/': () => mockEvaluation,
+ '/api/projects/:teamId/evaluations/:id/': () => mockEvaluation,
'/api/projects/:teamId/llm_analytics/evaluation_reports/:id/': () => {
reportWriteCount += 1
return mockEvaluationReport
@@ -1277,10 +1370,10 @@ describe('llmEvaluationLogic', () => {
created_at: '2024-01-01T00:00:00Z',
updated_at: '2024-01-01T00:00:00Z',
},
- '/api/environments/:teamId/evaluations/:id/': mockEvaluation,
+ '/api/projects/:teamId/evaluations/:id/': mockEvaluation,
},
patch: {
- '/api/environments/:teamId/evaluations/:id/': () => [
+ '/api/projects/:teamId/evaluations/:id/': () => [
400,
{
enabled: ['Trial evaluation limit reached. Add a provider API key to re-enable.'],
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
index 388616466e07..00a0b5878b4d 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
@@ -3,16 +3,20 @@ import { loaders } from 'kea-loaders'
import { combineUrl, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
-import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
-import { signalSourcesLogic } from 'scenes/inbox/signalSourcesLogic'
-import { SignalSourceConfig, SignalSourceProduct, SignalSourceType } from 'scenes/inbox/types'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { MaxContextInput, createMaxContextHelpers } from '~/scenes/max/maxTypes'
import { Breadcrumb } from '~/types'
+import {
+ evaluationsCreate,
+ evaluationsPartialUpdate,
+ evaluationsRetrieve,
+ evaluationsTestHogCreate,
+ llmAnalyticsEvaluationSummaryCreate,
+} from '../generated/api'
import { parseTrialProviderKeyId } from '../ModelPicker'
import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'
import { getUnhealthyProviderKey } from '../settings/providerKeyStateUtils'
@@ -142,21 +146,8 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
values: [
llmProviderKeysLogic,
['providerKeys', 'providerKeysLoading', 'requiresProviderKey', 'isTrialGrandfathered'],
- signalSourcesLogic,
- ['sourceConfigs', 'sourceConfigsLoading'],
- ],
- actions: [
- llmProviderKeysLogic,
- ['loadProviderKeys', 'loadEvaluationConfigSuccess'],
- signalSourcesLogic,
- [
- 'loadSourceConfigs',
- 'loadSourceConfigsSuccess',
- 'toggleSignalSource',
- 'toggleSignalSourceSuccess',
- 'toggleSignalSourceFailure',
- ],
],
+ actions: [llmProviderKeysLogic, ['loadProviderKeys', 'loadEvaluationConfigSuccess']],
})),
actions({
@@ -173,9 +164,6 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
setTraceWindowSeconds: (windowSeconds: number) => ({ windowSeconds }),
setHogSource: (source: string) => ({ source }),
- // Signal emission
- setSignalEmission: (enabled: boolean) => ({ enabled }),
-
// Tab navigation
setActiveTab: (tab: string) => ({ tab }),
@@ -223,14 +211,16 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
const conditions = evaluation.conditions
.filter((c) => c.properties && c.properties.length > 0)
.map((c) => ({ properties: c.properties }))
- // nosemgrep: prefer-codegen-api
- const response = await api.create(`/api/environments/${teamId}/evaluations/test_hog/`, {
+ const response = await evaluationsTestHogCreate(teamId.toString(), {
source: evaluation.evaluation_config.source,
sample_count: 5,
allows_na: evaluation.output_config?.allows_na ?? false,
conditions,
})
- return response.results
+ return response.results.map((result) => ({
+ ...result,
+ reasoning: result.reasoning ?? '',
+ }))
} catch (e: unknown) {
const message = e instanceof Error ? e.message : typeof e === 'string' ? e : 'Unknown error'
return [
@@ -276,10 +266,17 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
}
const requestFilter = values.evaluationSummaryFilter
+ if (
+ requestFilter !== 'all' &&
+ requestFilter !== 'pass' &&
+ requestFilter !== 'fail' &&
+ requestFilter !== 'na'
+ ) {
+ return null
+ }
// Backend fetches data server-side by ID - we just pass the filter
- // nosemgrep: prefer-codegen-api
- const response = await api.create(`/api/environments/${teamId}/llm_analytics/evaluation_summary/`, {
+ const response = await llmAnalyticsEvaluationSummaryCreate(teamId.toString(), {
evaluation_id: props.evaluationId,
filter: requestFilter,
force_refresh: shouldRefresh,
@@ -430,14 +427,6 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
saveEvaluationFailure: () => false,
},
],
- signalEmissionOptimistic: [
- null as boolean | null,
- {
- setSignalEmission: (_, { enabled }) => enabled,
- loadSourceConfigsSuccess: () => null,
- toggleSignalSourceFailure: () => null,
- },
- ],
hasUnsavedChanges: [
false,
{
@@ -516,9 +505,8 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
return
}
- // nosemgrep: prefer-codegen-api
- const evaluation = await api.get(`/api/environments/${teamId}/evaluations/${props.evaluationId}/`)
- actions.loadEvaluationSuccess(evaluation)
+ const evaluation = await evaluationsRetrieve(teamId.toString(), props.evaluationId)
+ actions.loadEvaluationSuccess(evaluation as unknown as EvaluationConfig)
} catch (error) {
console.error('Failed to load evaluation:', error)
actions.loadEvaluationSuccess(null)
@@ -662,27 +650,6 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
}
},
- setSignalEmission: ({ enabled }) => {
- const configs: SignalSourceConfig[] = values.sourceConfigs ?? []
- const existing = configs.find(
- (c) =>
- c.source_product === SignalSourceProduct.LlmAnalytics &&
- c.source_type === SignalSourceType.Evaluation
- )
-
- const currentIds: string[] = existing?.config?.evaluation_ids ?? []
- const newIds = enabled
- ? [...new Set([...currentIds, props.evaluationId])]
- : currentIds.filter((id: string) => id !== props.evaluationId)
-
- actions.toggleSignalSource({
- sourceProduct: SignalSourceProduct.LlmAnalytics,
- sourceType: SignalSourceType.Evaluation,
- enabled: true,
- config: { ...existing?.config, evaluation_ids: newIds },
- })
- },
-
saveEvaluation: async () => {
try {
const teamId = teamLogic.values.currentTeamId
@@ -690,15 +657,40 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
return
}
+ if (!values.formValid || !values.evaluation) {
+ const message =
+ values.evaluation?.evaluation_type === 'llm_judge' &&
+ !values.evaluation.model_configuration?.model.trim()
+ ? 'Select a judge model before saving.'
+ : 'Some required fields are missing. Please review the configuration.'
+ lemonToast.error(message)
+ actions.saveEvaluationFailure(message)
+ return
+ }
+
const isNew = props.evaluationId === 'new'
- const response = isNew
- ? // nosemgrep: prefer-codegen-api
- await api.create(`/api/environments/${teamId}/evaluations/`, values.evaluation!)
- : // nosemgrep: prefer-codegen-api
- await api.update(
- `/api/environments/${teamId}/evaluations/${props.evaluationId}/`,
- values.evaluation!
+ const reportLogicKey = isNew ? 'new' : props.evaluationId
+ const reportLogic = evaluationReportLogic({ evaluationId: reportLogicKey })
+ if (
+ evaluationSupportsReports(values.evaluation) &&
+ reportLogic.isMounted() &&
+ reportLogic.values.configError
+ ) {
+ lemonToast.error(reportLogic.values.configError)
+ actions.saveEvaluationFailure(reportLogic.values.configError)
+ return
+ }
+
+ const response = (isNew
+ ? await evaluationsCreate(
+ teamId.toString(),
+ values.evaluation as Parameters<typeof evaluationsCreate>[1]
)
+ : await evaluationsPartialUpdate(
+ teamId.toString(),
+ props.evaluationId,
+ values.evaluation as Parameters<typeof evaluationsPartialUpdate>[2]
+ )) as unknown as EvaluationConfig
actions.saveEvaluationSuccess(response)
// Piggyback the scheduled-report draft onto the main save so the single
@@ -706,8 +698,6 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
// evaluationReportLogic is only mounted when EvaluationReportConfig is
// rendered (gated on the reports feature flag), so skip when it isn't —
// reading .values on an unmounted keyed logic would throw.
- const reportLogicKey = isNew ? 'new' : props.evaluationId
- const reportLogic = evaluationReportLogic({ evaluationId: reportLogicKey })
if (response?.id && evaluationSupportsReports(response) && reportLogic.isMounted()) {
const reportConfigStillLoading =
!isNew && reportLogic.values.reportsLoading && !reportLogic.values.activeReport
@@ -771,28 +761,26 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
selectors({
isNewEvaluation: [(_, props) => [props.evaluationId], (evaluationId: string) => evaluationId === 'new'],
- signalEmissionEnabled: [
- (s, props) => [s.signalEmissionOptimistic, s.sourceConfigs, props.evaluationId],
- (optimistic: boolean | null, sourceConfigs: SignalSourceConfig[] | null, evaluationId: string): boolean => {
- if (optimistic !== null) {
- return optimistic
- }
- if (!sourceConfigs) {
+ modelSelectionRequired: [
+ (s, props) => [s.evaluation, s.originalEvaluation, props.evaluationId],
+ (
+ evaluation: EvaluationConfig | null,
+ originalEvaluation: EvaluationConfig | null,
+ evaluationId: string
+ ): boolean => {
+ if (!isLLMJudgeEvaluation(evaluation)) {
return false
}
- const llmEvalConfig = sourceConfigs.find(
- (c) =>
- c.source_product === SignalSourceProduct.LlmAnalytics &&
- c.source_type === SignalSourceType.Evaluation
- )
- const ids: string[] = llmEvalConfig?.config?.evaluation_ids ?? []
- return !!llmEvalConfig?.enabled && ids.includes(evaluationId)
+ if (evaluationId === 'new' || originalEvaluation?.evaluation_type !== 'llm_judge') {
+ return true
+ }
+ return originalEvaluation.model_configuration != null
},
],
formValid: [
- (s) => [s.evaluation],
- (evaluation) => {
+ (s) => [s.evaluation, s.modelSelectionRequired],
+ (evaluation, modelSelectionRequired: boolean) => {
if (!evaluation) {
return false
}
@@ -809,7 +797,9 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
} else if (evaluation.evaluation_type === 'sentiment') {
hasValidConfig = true
} else if (isLLMJudgeEvaluation(evaluation)) {
- hasValidConfig = (evaluation.evaluation_config?.prompt?.length ?? 0) > 0
+ hasValidConfig =
+ (evaluation.evaluation_config?.prompt?.length ?? 0) > 0 &&
+ (!modelSelectionRequired || (evaluation.model_configuration?.model.trim().length ?? 0) > 0)
}
return hasValidName && hasValidConfig && hasValidConditions
@@ -952,7 +942,6 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
afterMount(({ actions, props }) => {
actions.loadProviderKeys()
- actions.loadSourceConfigs()
actions.loadEvaluation()
if (props.evaluationId !== 'new') {
actions.loadEvaluationRuns()
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts
index a3e52c3d369f..95df95c8f324 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts
@@ -59,8 +59,6 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([
updateEvaluationSuccess: (id: string, evaluation: Partial<EvaluationConfig>) => ({ id, evaluation }),
deleteEvaluation: (id: string) => ({ id }),
deleteEvaluationSuccess: (id: string) => ({ id }),
- duplicateEvaluation: (id: string) => ({ id }),
- duplicateEvaluationSuccess: (evaluation: EvaluationConfig) => ({ evaluation }),
toggleEvaluationEnabled: (id: string) => ({ id }),
toggleEvaluationEnabledSuccess: (id: string) => ({ id }),
toggleEvaluationEnabledFailure: (id: string, error: string) => ({ id, error }),
@@ -88,7 +86,6 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([
e.id === id ? ({ ...e, ...evaluation } as EvaluationConfig) : e
),
deleteEvaluationSuccess: (state, { id }) => state.filter((e: EvaluationConfig) => e.id !== id),
- duplicateEvaluationSuccess: (state, { evaluation }) => [...state, evaluation],
toggleEvaluationEnabledSuccess: (state, { id }) =>
state.map((e: EvaluationConfig) =>
e.id === id
@@ -187,37 +184,6 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([
}
},
- duplicateEvaluation: async ({ id }) => {
- try {
- const original = values.evaluations.find((e: EvaluationConfig) => e.id === id)
- if (!original) {
- return
- }
-
- const duplicate = {
- name: `${original.name} (Copy)`,
- description: original.description,
- enabled: original.enabled,
- evaluation_type: original.evaluation_type,
- evaluation_config: original.evaluation_config,
- output_type: original.output_type,
- output_config: original.output_config,
- conditions: original.conditions,
- }
-
- const teamId = teamLogic.values.currentTeamId
- if (!teamId) {
- return
- }
-
- // nosemgrep: prefer-codegen-api
- const response = await api.create(`/api/environments/${teamId}/evaluations/`, duplicate)
- actions.duplicateEvaluationSuccess(response)
- } catch (error) {
- console.error('Failed to duplicate evaluation:', error)
- }
- },
-
toggleEvaluationEnabled: async ({ id }) => {
const evaluation = values.evaluations.find((e: EvaluationConfig) => e.id === id)
if (!evaluation) {
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index d6a4d3ed4c98..ac29920bace3 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -461,7 +461,7 @@ export interface ModelConfigurationApi {
/** @maxLength 100 */
model: string
/**
- * Team provider key to run this eval with (same provider as `provider`). Leave null only for brief pre-key testing; real evals should set it.
+ * Optional team provider key to run this evaluation with; it must use the same provider. May be null when no key is pinned or after the selected key is removed.
* @nullable
*/
provider_key_id?: string | null
@@ -554,6 +554,7 @@ export interface EvaluationApi {
target?: EvaluationTargetEnumApi
/** Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'. */
target_config?: EvaluationApiTargetConfig
+ /** Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null. */
model_configuration?: ModelConfigurationApi | null
readonly created_at: string
readonly updated_at: string
@@ -656,6 +657,7 @@ export interface PatchedEvaluationApi {
target?: EvaluationTargetEnumApi
/** Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'. */
target_config?: PatchedEvaluationApiTargetConfig
+ /** Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null. */
model_configuration?: ModelConfigurationApi | null
readonly created_at?: string
readonly updated_at?: string
diff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.ts
index fb972db4fe3f..6783a47e2ba5 100644
--- a/products/ai_observability/frontend/generated/api.zod.ts
+++ b/products/ai_observability/frontend/generated/api.zod.ts
@@ -244,14 +244,17 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod.object({
.uuid()
.nullish()
.describe(
- 'Team provider key to run this eval with (same provider as `provider`). Leave null only for brief pre-key testing; real evals should set it.'
+ 'Optional team provider key to run this evaluation with; it must use the same provider. May be null when no key is pinned or after the selected key is removed.'
),
provider_key_name: zod.string().nullable(),
})
.describe('Nested serializer for model configuration.'),
zod.null(),
])
- .optional(),
+ .optional()
+ .describe(
+ 'Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null.'
+ ),
deleted: zod.boolean().optional().describe('Set to true to soft-delete the evaluation.'),
})
@@ -397,14 +400,17 @@ export const EvaluationsUpdateBody = /* @__PURE__ */ zod.object({
.uuid()
.nullish()
.describe(
- 'Team provider key to run this eval with (same provider as `provider`). Leave null only for brief pre-key testing; real evals should set it.'
+ 'Optional team provider key to run this evaluation with; it must use the same provider. May be null when no key is pinned or after the selected key is removed.'
),
provider_key_name: zod.string().nullable(),
})
.describe('Nested serializer for model configuration.'),
zod.null(),
])
- .optional(),
+ .optional()
+ .describe(
+ 'Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null.'
+ ),
deleted: zod.boolean().optional().describe('Set to true to soft-delete the evaluation.'),
})
@@ -552,14 +558,17 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod.object({
.uuid()
.nullish()
.describe(
- 'Team provider key to run this eval with (same provider as `provider`). Leave null only for brief pre-key testing; real evals should set it.'
+ 'Optional team provider key to run this evaluation with; it must use the same provider. May be null when no key is pinned or after the selected key is removed.'
),
provider_key_name: zod.string().nullable(),
})
.describe('Nested serializer for model configuration.'),
zod.null(),
])
- .optional(),
+ .optional()
+ .describe(
+ 'Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null.'
+ ),
deleted: zod.boolean().optional().describe('Set to true to soft-delete the evaluation.'),
})
diff --git a/products/ai_observability/mcp/tools.yaml b/products/ai_observability/mcp/tools.yaml
index fad00832e8d4..3fc2452a5443 100644
--- a/products/ai_observability/mcp/tools.yaml
+++ b/products/ai_observability/mcp/tools.yaml
@@ -211,11 +211,11 @@ tools:
idempotent: false
title: Create evaluation
description: >
- Create an evaluation. 'llm_judge': set evaluation_config.prompt and model_configuration (provider + model +
- provider_key_id from llma-provider-key-list, preferring a provider the team already has a key for). 'hog':
- evaluation_config.source (Hog returning a boolean). 'sentiment': output_type='sentiment', omit
- model_configuration, optional evaluation_config.source='user_messages'. When enabled, runs on new
- $ai_generation events; results are '$ai_evaluation' events.
+ Create an evaluation. 'llm_judge': set evaluation_config.prompt and model_configuration with provider and
+ model; provider_key_id may be null when no key is pinned. 'hog': evaluation_config.source (Hog returning a
+ boolean). 'sentiment': output_type='sentiment', omit model_configuration, optional
+ evaluation_config.source='user_messages'. When enabled, runs on new $ai_generation events; results are
+ '$ai_evaluation' events.
llma-evaluation-delete:
operation: evaluations_destroy
enabled: true
@@ -447,9 +447,12 @@ tools:
idempotent: true
title: Update evaluation
description: >
- Update an existing AI observability evaluation (partial update). Toggle enabled/disabled, update the
- evaluation config (prompt, Hog source, or sentiment source), or change the model configuration for llm_judge
- evaluations.
+ Partially update an AI observability evaluation. Toggle enabled, change its type or evaluation config, or
+ change the model for an llm_judge. When switching to llm_judge, include model_configuration with provider
+ and model. When an llm_judge remains an llm_judge, omit model_configuration to keep its current model or
+ provide both fields to replace it; null is rejected for configured judges. When switching an llm_judge to
+ hog or sentiment, set model_configuration to null. Legacy llm_judge evaluations without a model remain
+ editable. provider_key_id may be null when no key is pinned.
llma-evaluation-update-full:
operation: evaluations_update
enabled: false
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 1748218c9814..c455d5e71008 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -4738,7 +4738,7 @@
}
},
"llma-evaluation-create": {
- "description": "Create an evaluation. 'llm_judge': set evaluation_config.prompt and model_configuration (provider + model + provider_key_id from llma-provider-key-list, preferring a provider the team already has a key for). 'hog': evaluation_config.source (Hog returning a boolean). 'sentiment': output_type='sentiment', omit model_configuration, optional evaluation_config.source='user_messages'. When enabled, runs on new $ai_generation events; results are '$ai_evaluation' events.",
+ "description": "Create an evaluation. 'llm_judge': set evaluation_config.prompt and model_configuration with provider and model; provider_key_id may be null when no key is pinned. 'hog': evaluation_config.source (Hog returning a boolean). 'sentiment': output_type='sentiment', omit model_configuration, optional evaluation_config.source='user_messages'. When enabled, runs on new $ai_generation events; results are '$ai_evaluation' events.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Create evaluation",
@@ -4935,7 +4935,7 @@
}
},
"llma-evaluation-update": {
- "description": "Update an existing AI observability evaluation (partial update). Toggle enabled/disabled, update the evaluation config (prompt, Hog source, or sentiment source), or change the model configuration for llm_judge evaluations.",
+ "description": "Partially update an AI observability evaluation. Toggle enabled, change its type or evaluation config, or change the model for an llm_judge. When switching to llm_judge, include model_configuration with provider and model. When an llm_judge remains an llm_judge, omit model_configuration to keep its current model or provide both fields to replace it; null is rejected for configured judges. When switching an llm_judge to hog or sentiment, set model_configuration to null. Legacy llm_judge evaluations without a model remain editable. provider_key_id may be null when no key is pinned.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Update evaluation",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 48156d5346d3..6a321ee6f8f1 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -5034,7 +5034,7 @@
}
},
"llma-evaluation-create": {
- "description": "Create an evaluation. 'llm_judge': set evaluation_config.prompt and model_configuration (provider + model + provider_key_id from llma-provider-key-list, preferring a provider the team already has a key for). 'hog': evaluation_config.source (Hog returning a boolean). 'sentiment': output_type='sentiment', omit model_configuration, optional evaluation_config.source='user_messages'. When enabled, runs on new $ai_generation events; results are '$ai_evaluation' events.",
+ "description": "Create an evaluation. 'llm_judge': set evaluation_config.prompt and model_configuration with provider and model; provider_key_id may be null when no key is pinned. 'hog': evaluation_config.source (Hog returning a boolean). 'sentiment': output_type='sentiment', omit model_configuration, optional evaluation_config.source='user_messages'. When enabled, runs on new $ai_generation events; results are '$ai_evaluation' events.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Create evaluation",
@@ -5231,7 +5231,7 @@
}
},
"llma-evaluation-update": {
- "description": "Update an existing AI observability evaluation (partial update). Toggle enabled/disabled, update the evaluation config (prompt, Hog source, or sentiment source), or change the model configuration for llm_judge evaluations.",
+ "description": "Partially update an AI observability evaluation. Toggle enabled, change its type or evaluation config, or change the model for an llm_judge. When switching to llm_judge, include model_configuration with provider and model. When an llm_judge remains an llm_judge, omit model_configuration to keep its current model or provide both fields to replace it; null is rejected for configured judges. When switching an llm_judge to hog or sentiment, set model_configuration to null. Legacy llm_judge evaluations without a model remain editable. provider_key_id may be null when no key is pinned.",
"category": "AI observability",
"feature": "llm_analytics",
"summary": "Update evaluation",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6afa13c2c38c..c45a0d32770b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -21945,7 +21945,7 @@ export namespace Schemas {
/** @maxLength 100 */
model: string;
/**
- * Team provider key to run this eval with (same provider as `provider`). Leave null only for brief pre-key testing; real evals should set it.
+ * Optional team provider key to run this evaluation with; it must use the same provider. May be null when no key is pinned or after the selected key is removed.
* @nullable
*/
provider_key_id?: string | null;
@@ -21995,6 +21995,7 @@ export namespace Schemas {
target?: EvaluationTargetEnum;
/** Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'. */
target_config?: EvaluationTargetConfig;
+ /** Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null. */
model_configuration?: ModelConfiguration | null;
readonly created_at: string;
readonly updated_at: string;
@@ -40325,6 +40326,7 @@ export namespace Schemas {
target?: EvaluationTargetEnum;
/** Target-specific config. For 'trace' target: {window_seconds}. Empty for 'generation'. */
target_config?: PatchedEvaluationTargetConfig;
+ /** Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null. */
model_configuration?: ModelConfiguration | null;
readonly created_at?: string;
readonly updated_at?: string;
diff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.ts
index 54386c70ff4f..defd2ed24240 100644
--- a/services/mcp/src/generated/ai_observability/api.ts
+++ b/services/mcp/src/generated/ai_observability/api.ts
@@ -265,14 +265,17 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod.object({
.string()
.nullish()
.describe(
- 'Team provider key to run this eval with (same provider as `provider`). Leave null only for brief pre-key testing; real evals should set it.'
+ 'Optional team provider key to run this evaluation with; it must use the same provider. May be null when no key is pinned or after the selected key is removed.'
),
provider_key_name: zod.string().nullish(),
})
.describe('Nested serializer for model configuration.'),
zod.null(),
])
- .optional(),
+ .optional()
+ .describe(
+ 'Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null.'
+ ),
deleted: zod.boolean().optional().describe('Set to true to soft-delete the evaluation.'),
})
@@ -438,14 +441,17 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod.object({
.string()
.nullish()
.describe(
- 'Team provider key to run this eval with (same provider as `provider`). Leave null only for brief pre-key testing; real evals should set it.'
+ 'Optional team provider key to run this evaluation with; it must use the same provider. May be null when no key is pinned or after the selected key is removed.'
),
provider_key_name: zod.string().nullish(),
})
.describe('Nested serializer for model configuration.'),
zod.null(),
])
- .optional(),
+ .optional()
+ .describe(
+ 'Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null.'
+ ),
deleted: zod.boolean().optional().describe('Set to true to soft-delete the evaluation.'),
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.json
index 5d017cccd00f..3bc620de2e54 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.json
@@ -123,7 +123,7 @@
"type": "null"
}
],
- "description": "Team provider key to run this eval with (same provider as `provider`). Leave null only for brief pre-key testing; real evals should set it."
+ "description": "Optional team provider key to run this evaluation with; it must use the same provider. May be null when no key is pinned or after the selected key is removed."
},
"provider_key_name": {
"anyOf": [
@@ -142,7 +142,8 @@
{
"type": "null"
}
- ]
+ ],
+ "description": "Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null."
},
"name": {
"description": "Name of the evaluation.",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.json
index 6a201d0724eb..5d88eb3062cd 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.json
@@ -127,7 +127,7 @@
"type": "null"
}
],
- "description": "Team provider key to run this eval with (same provider as `provider`). Leave null only for brief pre-key testing; real evals should set it."
+ "description": "Optional team provider key to run this evaluation with; it must use the same provider. May be null when no key is pinned or after the selected key is removed."
},
"provider_key_name": {
"anyOf": [
@@ -146,7 +146,8 @@
{
"type": "null"
}
- ]
+ ],
+ "description": "Provider and model for an llm_judge evaluation. Required when creating or switching to llm_judge. To add or replace a model, provide both provider and model. On an existing configured llm_judge, omit this field to keep the current model; null is rejected. When switching an llm_judge to hog or sentiment, set this field to null. Legacy llm_judge evaluations without a model remain editable without adding one. The nested provider_key_id may be null."
},
"name": {
"description": "Name of the evaluation.",