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.

feat(aio): support OpenRouter decision models in evaluations (#110762)

Bernat Torresd73aee069d6f
diff --git a/docs/internal/ai-observability-judge-inputs.md b/docs/internal/ai-observability-judge-inputs.md
index 89adc2cb6752..54bf6e394ab8 100644
--- a/docs/internal/ai-observability-judge-inputs.md
+++ b/docs/internal/ai-observability-judge-inputs.md
@@ -57,9 +57,9 @@ These connection and response limits also apply when using the same provider in
Disconnecting from the playground releases the server's stream slot without waiting for an in-flight provider read.
The worker closes the connection when that read finishes or reaches the provider's deadline.
-## System One judges
+## Decision model judges
-System One-compatible models are available under the existing LLM judge option.
+Decision models are available under the existing LLM judge option. They return typed answers without written reasoning.
The `llm-analytics-system-one-evaluations` project-group feature flag controls access in the browser and background workers.
Both use the project's UUID as its group key; the numeric project ID is a group property.
Deploy the ingestion and evaluation worker changes before enabling the flag.
@@ -69,7 +69,23 @@ The configured endpoint authorizes the supplied credential, including connection
Connection validation and every evaluation check these gates; an absent flag or failed flag lookup blocks the call.
Turning the flag off stops subsequent runs, including queued work, without disabling the saved evaluation.
Keep the experimental flag limited to staff projects during rollout.
-Add a connection under **System One** in provider key settings.
+OpenRouter decision models, including Jev, appear under an existing OpenRouter key in the evaluation model picker when this flag is enabled.
+They use OpenRouter's alpha `/api/alpha/decisions` endpoint with that key; no custom endpoint or System One connection is needed.
+These requests send the same PostHog attribution headers as OpenRouter chat requests.
+The picker discovers models through the catalogue's `decisions` output modality, so new models and versions appear without a code change.
+The picker does not exclude individual decision models. Listed models may not support every evaluation output type.
+The catalogue does not expose supported question types. If a model rejects a request, the run is skipped without retrying, with a reason to check output-type and criteria compatibility.
+Support added by a provider works on subsequent runs without a PostHog code change.
+Chat models such as Jev Router keep using chat completions.
+Decision models are excluded from the playground and tagger model pickers.
+The catalogue refreshes hourly and keeps its last successful response when a refresh fails, retrying refreshes after one minute.
+For projects with this flag enabled, an unavailable catalogue makes OpenRouter runs retry only when no successful response is cached.
+These projects also need the catalogue when changing a model or output configuration, changing the evaluation type, or enabling an evaluation.
+Renaming or disabling an evaluation does not require the catalogue.
+With the flag off or unavailable, cached decision models skip their runs without calling either API or disabling the evaluation.
+Other OpenRouter models keep the existing chat path without a catalogue refresh. If a failed chat call identifies a decision model, that run also skips without disabling the evaluation.
+An out-of-credits response disables the evaluation and marks its provider key as failing, as on the chat path.
+For other compatible services, add a connection under **System One** in provider key settings.
Enter the public HTTPS base URL and model ID of a compatible service; neither has a default.
TypeSafe's hosted endpoint is not supported by this integration.
The client appends `/systemone` to the base URL and sends the API key as a bearer token.
@@ -77,9 +93,9 @@ An empty key selects no authentication.
Changing the endpoint requires entering its credential again, or explicitly choosing no authentication, so an existing key is not forwarded to a new host.
Private network destinations and redirects are blocked by the shared DNS-pinned HTTP transport.
Saving a connection validates it with a short synthetic input and a Noul question, without sending evaluation data, using a 10-second request timeout.
-System One connections opt into the shared HTTPX client's bounded transport.
+Decision model connections opt into the shared HTTPX client's bounded transport.
Each HTTP request has a total deadline covering connection setup, response headers, and the body; expiry cancels the network operation and closes the connection.
-Validation uses 10 seconds and System One evaluations use 60 seconds.
+Validation uses 10 seconds and decision model evaluations use 60 seconds.
The transport rejects response bodies above 1 MiB, including errors.
It requests uncompressed responses and rejects compressed responses to prevent decompression from bypassing the size limit.
Responses stream incrementally, with a separate connection per request; connections are not pooled across requests.
@@ -116,16 +132,17 @@ A custom deployment reporting a recognized model name can inherit that model's c
Evaluations that allow N/A send a separate Noul question about whether the criteria apply, using the 0.5 threshold.
Uncertainty alone does not produce N/A.
-System One answers contain no written reasoning, so reports inspect the original source when explaining outcomes.
+Decision model answers contain no written reasoning, so reports inspect the original source when explaining outcomes.
Endpoint rate limits and overload responses are retried through Temporal, honoring `Retry-After` up to one minute.
Evaluation events retain model, usage, latency, and error telemetry.
If retries fail, the run fails and the evaluation stays enabled.
-Blocked endpoints and redirects disable the evaluation and mark the connection for revalidation, without recording model usage.
+Blocked System One endpoints and redirects disable the evaluation and mark the connection for revalidation, without recording model usage.
+DNS failures and redirects at OpenRouter's fixed decision endpoint retry without disabling the evaluation or marking its key as failing. Redirects are never followed.
Requests rejected because of an individual input skip that run without changing the shared connection.
Invalid probabilities, missing answers, and mismatched answer types skip the item as an unparsable response.
Inputs rejected for exceeding the model's context window are skipped.
-See TypeSafe's [API reference](https://docs.typesafe.ai/api) for the System One protocol.
+See OpenRouter's [Decisions API reference](https://openrouter.ai/docs/api/api-reference/alphadecisions/submit-a-decisions-request) and TypeSafe's [API reference](https://docs.typesafe.ai/api) for their compatible question and answer formats.
## Model output limits
@@ -143,7 +160,7 @@ Boolean online evaluations write their raw verdict to `$ai_evaluation_result`.
Numeric evaluations write their score to `$ai_evaluation_numeric_result`, with optional `$ai_evaluation_numeric_result_min` and `$ai_evaluation_numeric_result_max` bounds.
Result badges and mean scores display up to two decimal places, with two significant digits for values below one to keep small nonzero scores visible. Badges in the runs table expose the exact score on hover; storage, sorting, and passing rules use the original value.
If rounding would change whether the displayed score meets the passing rule, the badge shows the exact score instead.
-For online LLM judges, including System One, `step` is a suggested score increment in the prompt; results are not rounded or restricted to its multiples.
+For online LLM judges, including decision models, `step` is a suggested score increment in the prompt; results are not rounded or restricted to its multiples.
Hog evaluations use the numeric value returned by the code and do not apply `step`.
`$ai_evaluation_result_type` identifies the output type; events without it are legacy boolean results.
Categorical evaluations write a list of category keys to `$ai_evaluation_categorical_result`, including for single selection.
diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.py
index 962c450bc321..a5a9dbb059c7 100644
--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py
+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py
@@ -48,6 +48,12 @@ from posthog.temporal.common.errors import NonReportableApplicationError, NonRep
from posthog.temporal.common.utils import close_db_connections
from products.ai_observability.backend.llm import DEFAULT_MODEL_BY_PROVIDER, Client, CompletionRequest, Usage
+from products.ai_observability.backend.llm.decisions import (
+ DecisionClient,
+ DecisionEndpointBlockedError,
+ decision_evaluations_enabled,
+ is_decision_model,
+)
from products.ai_observability.backend.llm.errors import (
AuthenticationError,
ContentFilteredError,
@@ -66,11 +72,7 @@ from products.ai_observability.backend.llm.errors import (
UnsupportedModelError,
provider_error_detail,
)
-from products.ai_observability.backend.llm.system_one import (
- SystemOneClient,
- SystemOneEndpointBlockedError,
- system_one_evaluations_enabled,
-)
+from products.ai_observability.backend.llm.providers.openrouter import OPENROUTER_DECISIONS_BASE_URL, decision_model_ids
from products.ai_observability.backend.llm.types import CompletionResponse
from products.ai_observability.backend.models.evaluation_configs import (
CategoricalOutputConfig,
@@ -533,7 +535,7 @@ def _execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> EvaluationActi
)
-def _system_one_numeric_score(minimum: float, maximum: float, index: float) -> float:
+def _decision_numeric_score(minimum: float, maximum: float, index: float) -> float:
last_index = MAX_SCORE_LEVELS - 1
if index == 0:
return minimum
@@ -580,23 +582,6 @@ def call_llm_judge(
is_byok = resolved.is_byok
key_id = str(provider_key.id) if provider_key else None
- if provider == "system_one":
- if output_type not in ("boolean", "categorical", "numeric"):
- return build_skipped_evaluation_result(
- output_type=output_type,
- allows_na=allows_na,
- reasoning="System One supports boolean, categorical, and numeric evaluations.",
- skip_reason="unsupported_output_type",
- )
- base_url = provider_key.encrypted_config.get("base_url", "") if provider_key else ""
- if not system_one_evaluations_enabled(team_id, base_url=base_url):
- return build_skipped_evaluation_result(
- output_type=output_type,
- allows_na=allows_na,
- reasoning="System One evaluations are not available for this project.",
- skip_reason="system_one_unavailable",
- )
-
type_config = get_output_type_config(allows_na, output_type=output_type, output_config=output_config)
response_format = type_config.response_format
@@ -609,9 +594,38 @@ def call_llm_judge(
)
probability: float | None = None
- system_one_result = None
+ decision_result = None
try:
- if provider == "system_one":
+ openrouter_enabled = provider == "openrouter" and decision_evaluations_enabled(
+ team_id, base_url=OPENROUTER_DECISIONS_BASE_URL
+ )
+ uses_decisions = is_decision_model(provider, model, openrouter_enabled=openrouter_enabled)
+ if provider == "openrouter" and not openrouter_enabled:
+ uses_decisions = model in (decision_model_ids(refresh=False) or ())
+ if uses_decisions:
+ if output_type not in ("boolean", "categorical", "numeric"):
+ return build_skipped_evaluation_result(
+ output_type=output_type,
+ allows_na=allows_na,
+ reasoning="Decision models support boolean, categorical, and numeric evaluations.",
+ skip_reason="unsupported_output_type",
+ )
+ base_url = (
+ OPENROUTER_DECISIONS_BASE_URL
+ if provider == "openrouter"
+ else provider_key.encrypted_config.get("base_url", "")
+ if provider_key
+ else ""
+ )
+ if (provider == "openrouter" and not openrouter_enabled) or (
+ provider == "system_one" and not decision_evaluations_enabled(team_id, base_url=base_url)
+ ):
+ return build_skipped_evaluation_result(
+ output_type=output_type,
+ allows_na=allows_na,
+ reasoning="Decision model evaluations are not available for this project.",
+ skip_reason="system_one_unavailable",
+ )
prompt = evaluation["evaluation_config"]["prompt"]
categorical_config = (
CategoricalOutputConfig.model_validate(output_config) if output_type == "categorical" else None
@@ -624,11 +638,11 @@ def call_llm_judge(
return build_skipped_evaluation_result(
output_type=output_type,
allows_na=allows_na,
- reasoning="System One numeric evaluations require a minimum score below the maximum score.",
+ reasoning="Numeric evaluations with decision models require a minimum score below the maximum score.",
skip_reason="request_rejected",
)
numeric_levels = [
- _system_one_numeric_score(numeric_config.min, numeric_config.max, index)
+ _decision_numeric_score(numeric_config.min, numeric_config.max, index)
for index in range(MAX_SCORE_LEVELS)
]
if numeric_config.step is not None:
@@ -669,16 +683,17 @@ def call_llm_judge(
+ prompt
)
)
- system_one_result = SystemOneClient.evaluate(
+ decision_result = DecisionClient.evaluate(
api_key=provider_key.encrypted_config.get("api_key", "") if provider_key else "",
base_url=base_url,
+ path="decisions" if provider == "openrouter" else "systemone",
model=model,
state=user_prompt,
questions=questions,
)
applicable = True
if allows_na:
- applicability_answer = system_one_result.answers["applicable"]
+ applicability_answer = decision_result.answers["applicable"]
if not isinstance(applicability_answer, NoulAnswer):
raise StructuredOutputParseError("The endpoint returned an invalid applicability answer.")
applicable = applicability_answer.probability >= 0.5
@@ -691,10 +706,10 @@ def call_llm_judge(
| NumericWithNAEvalResult
)
if numeric_levels is not None:
- score_answer = system_one_result.answers["score"]
+ score_answer = decision_result.answers["score"]
if not isinstance(score_answer, ScoreAnswer):
raise StructuredOutputParseError("The endpoint returned an invalid score answer.")
- score = _system_one_numeric_score(numeric_levels[0], numeric_levels[-1], score_answer.score)
+ score = _decision_numeric_score(numeric_levels[0], numeric_levels[-1], score_answer.score)
parsed = (
NumericWithNAEvalResult(reasoning="", score=score if applicable else None)
if allows_na
@@ -703,13 +718,13 @@ def call_llm_judge(
elif categorical_config is not None:
categories: list[str] = []
if categorical_config.selection_mode == "single":
- category_answer = system_one_result.answers["category"]
+ category_answer = decision_result.answers["category"]
if not isinstance(category_answer, ChoiceAnswer):
raise StructuredOutputParseError("The endpoint returned an invalid category answer.")
categories = [category_answer.choice]
else:
for index, option in enumerate(categorical_config.options):
- category_match = system_one_result.answers[f"category_{index}"]
+ category_match = decision_result.answers[f"category_{index}"]
if not isinstance(category_match, NoulAnswer):
raise StructuredOutputParseError("The endpoint returned an invalid category answer.")
if category_match.probability >= 0.5:
@@ -720,7 +735,7 @@ def call_llm_judge(
else CategoricalEvalResult(reasoning="", categories=categories)
)
else:
- verdict_answer = system_one_result.answers["verdict"]
+ verdict_answer = decision_result.answers["verdict"]
if not isinstance(verdict_answer, NoulAnswer):
raise StructuredOutputParseError("The endpoint returned an invalid verdict answer.")
probability = verdict_answer.probability
@@ -737,9 +752,9 @@ def call_llm_judge(
model=model,
parsed=parsed,
usage=Usage(
- input_tokens=(system_one_result.input_tokens or 0),
- output_tokens=(system_one_result.output_tokens or 0),
- total_tokens=(system_one_result.input_tokens or 0) + (system_one_result.output_tokens or 0),
+ input_tokens=(decision_result.input_tokens or 0),
+ output_tokens=(decision_result.output_tokens or 0),
+ total_tokens=(decision_result.input_tokens or 0) + (decision_result.output_tokens or 0),
),
)
else:
@@ -752,7 +767,7 @@ def call_llm_judge(
response_format=response_format,
)
)
- except (SystemOneEndpointBlockedError, ProviderConfigurationError) as e:
+ except (DecisionEndpointBlockedError, ProviderConfigurationError) as e:
increment_user_errors("endpoint_blocked", provider=provider)
return terminal_user_error_result(
spec=require_user_error_spec("endpoint_blocked", is_byok=is_byok),
@@ -859,6 +874,14 @@ def call_llm_judge(
non_retryable=True,
)
except UnsupportedModelError:
+ # A failed chat call can populate a cold catalogue; a disabled flag must not disable the evaluation.
+ if provider == "openrouter" and not openrouter_enabled and model in (decision_model_ids(refresh=False) or ()):
+ return build_skipped_evaluation_result(
+ output_type=output_type,
+ allows_na=allows_na,
+ reasoning="Decision model evaluations are not available for this project.",
+ skip_reason="system_one_unavailable",
+ )
increment_user_errors("model_not_supported", provider=provider)
return terminal_user_error_result(
spec=require_user_error_spec("model_not_supported", is_byok=is_byok),
@@ -1040,9 +1063,9 @@ def call_llm_judge(
"model": model,
"provider": provider,
}
- if system_one_result is not None:
- result_dict["input_tokens"] = system_one_result.input_tokens
- result_dict["output_tokens"] = system_one_result.output_tokens
+ if decision_result is not None:
+ result_dict["input_tokens"] = decision_result.input_tokens
+ result_dict["output_tokens"] = decision_result.output_tokens
if isinstance(parsed_result, CategoricalEvalResult | CategoricalWithNAEvalResult):
result_dict["result_type"] = "categorical"
diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.py
index a82dc0f9ec6b..ee2f4615045c 100644
--- a/posthog/temporal/ai_observability/test_run_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_evaluation.py
@@ -1,6 +1,7 @@
import json
import uuid
import dataclasses
+from contextlib import nullcontext
from datetime import UTC, datetime, timedelta
from ipaddress import IPv4Address, IPv6Address, ip_address
from typing import Any, cast
@@ -8,6 +9,7 @@ from typing import Any, cast
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
+from django.core.cache import cache
from django.test import override_settings
import httpx
@@ -44,6 +46,11 @@ from products.ai_observability.backend.llm.errors import (
StructuredOutputParseError,
UnsupportedModelError,
)
+from products.ai_observability.backend.llm.providers.openai import OpenAIAdapter
+from products.ai_observability.backend.llm.providers.openrouter import (
+ NON_CHAT_MODELS_CACHE_KEY,
+ NON_CHAT_MODELS_LAST_GOOD_CACHE_KEY,
+)
from products.ai_observability.backend.models.evaluation_config import EvaluationConfig
from products.ai_observability.backend.models.evaluation_directories import EvaluationDirectory
from products.ai_observability.backend.models.evaluations import Evaluation
@@ -301,27 +308,109 @@ def _mock_config_with_active_key(provider: str = "openai") -> MagicMock:
return MagicMock(active_provider_key=key)
[email protected]("flag", [True, False, None])
+def test_openrouter_catalogue_outage_only_affects_projects_with_decisions_enabled(flag: bool | None) -> None:
+ key = MagicMock(provider="openrouter", encrypted_config={"api_key": "example-token"})
+ with (
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,
+ patch(
+ "products.ai_observability.backend.llm.providers.openrouter._non_chat_models", return_value=None
+ ) as catalogue,
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.decision_evaluations_enabled", return_value=flag),
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client.complete") as complete,
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.DecisionClient.evaluate") as decide,
+ ):
+ spec.return_value.resolve.return_value = MagicMock(
+ provider="openrouter", model="openai/gpt-4o", provider_key=key, is_byok=True
+ )
+ complete.return_value = MagicMock(parsed=BooleanEvalResult(verdict=True, reasoning="Polite"), usage=None)
+ with pytest.raises(TransientJudgeError, match="OpenRouter model capabilities") if flag else nullcontext():
+ result = call_llm_judge(
+ evaluation={"team_id": 1, "evaluation_config": {"prompt": "Is the response polite?"}},
+ system_prompt="",
+ user_prompt="Hello!",
+ allows_na=False,
+ )
+ if flag:
+ complete.assert_not_called()
+ else:
+ assert result["verdict"] is True
+ catalogue.assert_called_once_with(refresh=False)
+ decide.assert_not_called()
+
+
[email protected]("flag", [False, None])
[email protected]("cached", [True, False])
+def test_openrouter_decision_model_with_disabled_flag_skips_without_disabling(flag: bool | None, cached: bool) -> None:
+ cache.delete_many([NON_CHAT_MODELS_CACHE_KEY, NON_CHAT_MODELS_LAST_GOOD_CACHE_KEY])
+ model = "example/decision"
+ if cached:
+ cache.set(NON_CHAT_MODELS_LAST_GOOD_CACHE_KEY, {model: ["decisions"]}, timeout=None)
+ key = MagicMock(provider="openrouter", encrypted_config={"api_key": "example-token"})
+ try:
+ with (
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,
+ patch(
+ "posthog.temporal.ai_observability.evaluation_llm_judge.decision_evaluations_enabled", return_value=flag
+ ),
+ patch.object(OpenAIAdapter, "complete", side_effect=ModelNotFoundError(model)) as complete,
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.DecisionClient.evaluate") as decide,
+ patch("products.ai_observability.backend.llm.providers.openrouter.httpx.get") as catalogue,
+ ):
+ spec.return_value.resolve.return_value = MagicMock(
+ provider="openrouter", model=model, provider_key=key, is_byok=True
+ )
+ catalogue.return_value.json.return_value = {
+ "data": [{"id": model, "architecture": {"output_modalities": ["decisions"]}}]
+ }
+ result = call_llm_judge(
+ evaluation={"team_id": 1, "evaluation_config": {"prompt": "Is the response polite?"}},
+ system_prompt="",
+ user_prompt="Hello!",
+ allows_na=False,
+ )
+ assert result["skipped"] is True
+ assert result["skip_reason"] == "system_one_unavailable"
+ assert "terminal_user_error" not in result
+ assert "provider_key_state" not in result
+ assert complete.call_count == (0 if cached else 1)
+ assert catalogue.call_count == (0 if cached else 1)
+ decide.assert_not_called()
+ finally:
+ cache.delete_many([NON_CHAT_MODELS_CACHE_KEY, NON_CHAT_MODELS_LAST_GOOD_CACHE_KEY])
+
+
@pytest.mark.parametrize(
- "connection_config,base_url,model,usage",
+ "provider,connection_config,base_url,model,usage",
[
(
+ "system_one",
{"api_key": "example-token", "base_url": "https://decisions.example.com/v1"},
"https://decisions.example.com/v1",
"example-judge-v1",
{"input_tokens": 120, "output_tokens": 10},
),
(
+ "system_one",
{"api_key": "", "base_url": "https://decisions.example.com/v1"},
"https://decisions.example.com/v1",
"custom-model",
{"input_tokens": 120},
),
(
+ "system_one",
{"api_key": "example-token", "base_url": "https://ai-gateway.us.posthog.com/v1"},
"https://ai-gateway.us.posthog.com/v1",
"example-judge-v1",
{},
),
+ (
+ "openrouter",
+ {"api_key": "example-openrouter-token"},
+ "https://openrouter.ai/api/alpha",
+ "typesafe/jev-1.13",
+ {"input_tokens": 120, "output_tokens": 10},
+ ),
],
)
@pytest.mark.parametrize(
@@ -333,13 +422,14 @@ def test_system_one_judge_emits_boolean_probability_without_reasoning(
applicability: float,
allows_na: bool,
verdict: bool | None,
+ provider: str,
connection_config: dict[str, str],
base_url: str,
model: str,
usage: dict[str, int],
) -> None:
- key = MagicMock(provider="system_one", encrypted_config=connection_config)
- resolved = MagicMock(provider="system_one", model=model, provider_key=key, is_byok=True)
+ key = MagicMock(provider=provider, encrypted_config=connection_config)
+ resolved = MagicMock(provider=provider, model=model, provider_key=key, is_byok=True)
response_body = {
"model": "endpoint-controlled-model",
"answers": {
@@ -357,10 +447,14 @@ def test_system_one_judge_emits_boolean_probability_without_reasoning(
}
with (
override_settings(POSTHOG_INTERNAL_ORG_IDS=[]),
+ patch(
+ "products.ai_observability.backend.llm.providers.openrouter._non_chat_models",
+ return_value={"typesafe/jev-1.13": ["decisions"]},
+ ),
patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")}),
patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,
- patch("products.ai_observability.backend.llm.system_one.Team.objects.only") as teams,
- patch("products.ai_observability.backend.llm.system_one.get_feature_flag_or_none", return_value=True),
+ patch("products.ai_observability.backend.llm.decisions.Team.objects.only") as teams,
+ patch("products.ai_observability.backend.llm.decisions.get_feature_flag_or_none", return_value=True),
patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response) as request,
):
teams.return_value.get.return_value = Team(id=1, organization_id=uuid.uuid4(), uuid=uuid.uuid4())
@@ -372,7 +466,8 @@ def test_system_one_judge_emits_boolean_probability_without_reasoning(
allows_na=allows_na,
)
- assert str(request.call_args.args[0].url) == f"{base_url}/systemone"
+ endpoint = "decisions" if provider == "openrouter" else "systemone"
+ assert str(request.call_args.args[0].url) == f"{base_url}/{endpoint}"
assert request.call_args.args[0].headers.get("Authorization") == (
f"Bearer {connection_config['api_key']}" if connection_config["api_key"] else None
)
@@ -389,6 +484,7 @@ def test_system_one_judge_emits_boolean_probability_without_reasoning(
assert properties["$ai_output_tokens"] == usage.get("output_tokens")
assert properties.get("$ai_evaluation_probability") == (probability if verdict is not None else None)
assert properties["$ai_model"] == model
+ assert properties["$ai_provider"] == provider
assert properties["$ai_evaluation_key_type"] == "byok"
@@ -403,7 +499,9 @@ def test_system_one_judge_emits_boolean_probability_without_reasoning(
("multiple", [0.9, 0.9], True, False, None),
],
)
[email protected]("provider", ["system_one", "openrouter"])
def test_system_one_categorical_results_use_category_keys_without_boolean_probability(
+ provider: str,
selection_mode: str,
probabilities: list[float],
allows_na: bool,
@@ -428,22 +526,24 @@ def test_system_one_categorical_results_use_category_keys_without_boolean_probab
if allows_na:
answers["applicable"] = {"noul": 0.9 if applicable else 0.1}
key = MagicMock(
- provider="system_one",
+ provider=provider,
encrypted_config={"api_key": "example-token", "base_url": "https://decisions.example.com/v1"},
)
with (
- patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")}),
- patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,
patch(
- "posthog.temporal.ai_observability.evaluation_llm_judge.system_one_evaluations_enabled", return_value=True
+ "products.ai_observability.backend.llm.providers.openrouter._non_chat_models",
+ return_value={"typesafe/jev-1.13": ["decisions"]},
),
+ patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")}),
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.decision_evaluations_enabled", return_value=True),
patch("httpx.AsyncHTTPTransport.handle_async_request") as request,
):
spec.return_value.resolve.return_value = MagicMock(
- provider="system_one", model="custom-model", provider_key=key, is_byok=True
+ provider=provider, model="typesafe/jev-1.13", provider_key=key, is_byok=True
)
request.return_value = httpx.Response(
- 200, stream=httpx.ByteStream(json.dumps({"model": "custom-model", "answers": answers}).encode())
+ 200, stream=httpx.ByteStream(json.dumps({"model": "typesafe/jev-1.13", "answers": answers}).encode())
)
result = call_llm_judge(evaluation=evaluation, system_prompt="", user_prompt="Hello!", allows_na=allows_na)
@@ -483,8 +583,15 @@ def test_system_one_categorical_results_use_category_keys_without_boolean_probab
(0, 10, 6.75, True, False, None),
],
)
-def test_system_one_numeric_scores_use_configured_bounds(
- minimum: float, maximum: float, index: float, allows_na: bool, applicable: bool, expected: float | None
[email protected]("provider", ["system_one", "openrouter"])
+def test_decision_numeric_scores_use_configured_bounds(
+ provider: str,
+ minimum: float,
+ maximum: float,
+ index: float,
+ allows_na: bool,
+ applicable: bool,
+ expected: float | None,
) -> None:
prompt = "Score how well the response answers the question."
evaluation = {
@@ -501,24 +608,24 @@ def test_system_one_numeric_scores_use_configured_bounds(
}
if allows_na:
answers["applicable"] = {"noul": 0.9 if applicable else 0.1}
- key = MagicMock(
- provider="system_one", encrypted_config={"api_key": "", "base_url": "https://decisions.example.com/v1"}
- )
+ key = MagicMock(provider=provider, encrypted_config={"api_key": "", "base_url": "https://decisions.example.com/v1"})
with (
- patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")}),
- patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,
patch(
- "posthog.temporal.ai_observability.evaluation_llm_judge.system_one_evaluations_enabled", return_value=True
+ "products.ai_observability.backend.llm.providers.openrouter._non_chat_models",
+ return_value={"typesafe/jev-1.13": ["decisions"]},
),
+ patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")}),
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.decision_evaluations_enabled", return_value=True),
patch(
"httpx.AsyncHTTPTransport.handle_async_request",
return_value=httpx.Response(
- 200, stream=httpx.ByteStream(json.dumps({"model": "custom-model", "answers": answers}).encode())
+ 200, stream=httpx.ByteStream(json.dumps({"model": "typesafe/jev-1.13", "answers": answers}).encode())
),
) as request,
):
spec.return_value.resolve.return_value = MagicMock(
- provider="system_one", model="custom-model", provider_key=key, is_byok=True
+ provider=provider, model="typesafe/jev-1.13", provider_key=key, is_byok=True
)
result = call_llm_judge(evaluation=evaluation, system_prompt="", user_prompt="Hello!", allows_na=allows_na)
@@ -555,9 +662,7 @@ def test_system_one_numeric_requires_a_score_range(output_config: dict[str, floa
with (
patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")}),
patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,
- patch(
- "posthog.temporal.ai_observability.evaluation_llm_judge.system_one_evaluations_enabled", return_value=True
- ),
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.decision_evaluations_enabled", return_value=True),
patch("httpx.AsyncHTTPTransport.handle_async_request") as request,
):
spec.return_value.resolve.return_value = MagicMock(
@@ -580,27 +685,29 @@ def test_system_one_numeric_requires_a_score_range(output_config: dict[str, floa
@pytest.mark.parametrize(
- "base_url,flag",
+ "provider,base_url,flag",
[
- ("https://decisions.example.com/v1", False),
- ("https://ai-gateway.us.posthog.com/v1", False),
- ("https://api.typesafe.ai/v1", True),
+ ("system_one", "https://decisions.example.com/v1", False),
+ ("system_one", "https://ai-gateway.us.posthog.com/v1", False),
+ ("system_one", "https://api.typesafe.ai/v1", True),
],
)
-def test_system_one_restricted_connection_does_not_send_evaluation_data(base_url: str, flag: bool) -> None:
+def test_system_one_restricted_connection_does_not_send_evaluation_data(
+ provider: str, base_url: str, flag: bool
+) -> None:
with (
override_settings(POSTHOG_INTERNAL_ORG_IDS=[]),
patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,
- patch("products.ai_observability.backend.llm.system_one.Team.objects.only") as teams,
- patch("products.ai_observability.backend.llm.system_one.get_feature_flag_or_none", return_value=flag),
+ patch("products.ai_observability.backend.llm.decisions.Team.objects.only") as teams,
+ patch("products.ai_observability.backend.llm.decisions.get_feature_flag_or_none", return_value=flag),
patch("httpx.AsyncHTTPTransport.handle_async_request") as request,
):
teams.return_value.get.return_value = Team(id=1, organization_id=uuid.uuid4(), uuid=uuid.uuid4())
spec.return_value.resolve.return_value = MagicMock(
- provider="system_one",
+ provider=provider,
model="custom-model",
provider_key=MagicMock(
- provider="system_one", encrypted_config={"base_url": base_url, "api_key": "example-token"}
+ provider=provider, encrypted_config={"base_url": base_url, "api_key": "example-token"}
),
is_byok=True,
)
@@ -619,13 +726,19 @@ def test_system_one_restricted_connection_does_not_send_evaluation_data(base_url
[
("system_one", 301, "identity", "endpoint_blocked"),
("system_one", 400, "identity", "request_rejected"),
+ ("system_one", 402, "identity", "quota_error"),
("system_one", 422, "identity", "request_rejected"),
("system_one", 200, "gzip", "request_rejected"),
+ ("openrouter", 301, "identity", None),
+ ("openrouter", 400, "identity", "request_rejected"),
+ ("openrouter", 402, "identity", "quota_error"),
+ ("openrouter", 422, "identity", "request_rejected"),
+ ("openrouter", 200, "gzip", "request_rejected"),
("openai_compatible", 200, "gzip", "request_rejected"),
],
)
def test_provider_rejections_distinguish_blocked_endpoints_from_bad_inputs(
- provider: str, status: int, encoding: str, expected_skip_reason: str
+ provider: str, status: int, encoding: str, expected_skip_reason: str | None
) -> None:
key = MagicMock(
provider=provider,
@@ -635,32 +748,45 @@ def test_provider_rejections_distinguish_blocked_endpoints_from_bad_inputs(
status, stream=httpx.ByteStream(b"Invalid request"), headers={"Content-Encoding": encoding}
)
with (
- patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")}),
- patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,
patch(
- "posthog.temporal.ai_observability.evaluation_llm_judge.system_one_evaluations_enabled", return_value=True
+ "products.ai_observability.backend.llm.providers.openrouter._non_chat_models",
+ return_value={"example-judge-v1": ["decisions"]},
),
- patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response),
+ patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")}),
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.decision_evaluations_enabled", return_value=True),
+ patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response) as request,
):
spec.return_value.resolve.return_value = MagicMock(
provider=provider, model="example-judge-v1", provider_key=key, is_byok=True
)
- result = call_llm_judge(
- evaluation={"id": "test-evaluation", "team_id": 1, "evaluation_config": {"prompt": "Polite?"}},
- system_prompt="",
- user_prompt="Hello!",
- allows_na=False,
- )
+ with pytest.raises(TransientJudgeError) if expected_skip_reason is None else nullcontext():
+ result = call_llm_judge(
+ evaluation={"id": "test-evaluation", "team_id": 1, "evaluation_config": {"prompt": "Polite?"}},
+ system_prompt="",
+ user_prompt="Hello!",
+ allows_na=False,
+ )
+ request.assert_called_once()
+ if expected_skip_reason is None:
+ return
assert result["skip_reason"] == expected_skip_reason
- if status == 301:
+ if status in (301, 402):
assert result["terminal_user_error"] is True
assert result["provider_key_state"] == "error"
else:
assert result["skipped"] is True
+ if encoding == "identity":
+ assert "supports this evaluation's output type" in result["reasoning"]
assert "terminal_user_error" not in result
assert "provider_key_state" not in result
- assert "model" not in result
- assert "provider" not in result
+ if status == 402:
+ assert result["status_reason"] == "provider_key_quota_exceeded"
+ assert result["key_id"] == str(key.id)
+ assert result["provider"] == provider
+ else:
+ assert "model" not in result
+ assert "provider" not in result
if encoding == "gzip":
assert "uncompressed responses no larger than 1 MiB" in result["reasoning"]
@@ -767,9 +893,7 @@ def test_custom_provider_rate_limit_retries_without_disabling_the_evaluation(
with (
patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")}),
patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,
- patch(
- "posthog.temporal.ai_observability.evaluation_llm_judge.system_one_evaluations_enabled", return_value=True
- ),
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.decision_evaluations_enabled", return_value=True),
patch(
"httpx.AsyncHTTPTransport.handle_async_request",
side_effect=[
diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.py
index 2fdaed62c6bf..0c50c60e1985 100644
--- a/products/ai_observability/backend/api/evaluations.py
+++ b/products/ai_observability/backend/api/evaluations.py
@@ -46,7 +46,9 @@ from products.access_control.backend.presentation.access_control import (
from ..evaluation_conditions import build_condition_filter
from ..hog import compile_ai_observability_hog
from ..llm import DEFAULT_MODEL_BY_PROVIDER
-from ..llm.providers.openrouter import is_non_chat_model
+from ..llm.decisions import decision_evaluations_enabled, is_decision_model
+from ..llm.errors import ProviderConnectionError
+from ..llm.providers.openrouter import OPENROUTER_BASE_URL, is_non_chat_model
from ..models.evaluation_config import EvaluationConfig
from ..models.evaluation_configs import (
EVALUATION_TEST_LOOKBACK_DAYS,
@@ -184,12 +186,12 @@ class _EvaluationConfigField(serializers.JSONField):
"min": {
"type": "number",
"nullable": True,
- "description": "Inclusive minimum numeric score. Omit for no lower bound. Required for System One numeric judges.",
+ "description": "Inclusive minimum numeric score. Omit for no lower bound. Required for numeric decision models.",
},
"max": {
"type": "number",
"nullable": True,
- "description": "Inclusive maximum numeric score. Omit for no upper bound. Required for System One numeric judges and must exceed min.",
+ "description": "Inclusive maximum numeric score. Omit for no upper bound. Required for numeric decision models and must exceed min.",
},
"step": {
"type": "number",
@@ -541,6 +543,27 @@ class EvaluationSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
"deleted": {"help_text": "Set to true to soft-delete the evaluation."},
}
+ def _uses_decision_model(self, data: dict[str, object]) -> bool:
+ should_validate_model = (
+ self.instance is None
+ or bool({"model_configuration", "evaluation_type", "output_type", "output_config"} & data.keys())
+ or data.get("enabled", False)
+ )
+ if not should_validate_model:
+ return False
+
+ model_configuration = self._effective_model_configuration(data) or {}
+ model_provider = model_configuration.get("provider")
+ try:
+ return is_decision_model(
+ model_provider,
+ model_configuration.get("model"),
+ openrouter_enabled=model_provider == "openrouter"
+ and decision_evaluations_enabled(self.context["get_team"]().id, base_url=OPENROUTER_BASE_URL),
+ )
+ except ProviderConnectionError as e:
+ raise serializers.ValidationError({"model_configuration": str(e)}) from e
+
def validate(self, data):
evaluation_type = data.get("evaluation_type") or getattr(self.instance, "evaluation_type", None)
output_type = data.get("output_type") or getattr(self.instance, "output_type", None)
@@ -566,12 +589,8 @@ class EvaluationSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
"model_configuration",
getattr(self.instance, "model_configuration", None) if self.instance else None,
)
- model_provider = (
- model_configuration.get("provider")
- if isinstance(model_configuration, dict)
- else getattr(model_configuration, "provider", None)
- )
- if model_provider == LLMProvider.SYSTEM_ONE and output_type not in ("boolean", "categorical", "numeric"):
+ uses_decision_model = self._uses_decision_model(data)
+ if uses_decision_model and output_type not in ("boolean", "categorical", "numeric"):
raise serializers.ValidationError(
{"model_configuration": "Select a model that supports this evaluation output type."}
)
@@ -595,7 +614,7 @@ class EvaluationSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
)
if data.get("model_configuration") or data.get("enabled"):
- self._validate_chat_model(data)
+ self._validate_chat_model(data, uses_decision_model=uses_decision_model)
should_validate_configs = (
self.instance is None
@@ -622,11 +641,13 @@ class EvaluationSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
except ValueError as e:
raise serializers.ValidationError({"config": str(e)})
- if model_provider == LLMProvider.SYSTEM_ONE and output_type == "numeric":
+ if uses_decision_model and output_type == "numeric":
config = data.get("output_config", getattr(self.instance, "output_config", {}))
if config.get("min") is None or config.get("max") is None or config["min"] >= config["max"]:
raise serializers.ValidationError(
- {"output_config": "System One numeric evaluations require a minimum score below the maximum score."}
+ {
+ "output_config": "Numeric evaluations with decision models require a minimum score below the maximum score."
+ }
)
# Sentiment is addressed per-message within one generation event ($ai_target_event_id +
@@ -667,19 +688,22 @@ class EvaluationSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
return data
- def _validate_chat_model(self, data: dict) -> None:
- """The judge calls chat completions, so a model without text output fails on every run."""
+ def _validate_chat_model(self, data: dict, *, uses_decision_model: bool) -> None:
+ """OpenRouter judges use either chat completions or typed decisions."""
model_config = self._effective_model_configuration(data)
if not model_config or model_config.get("provider") != LLMProvider.OPENROUTER:
return
model = model_config.get("model")
+ if uses_decision_model:
+ return
if model and is_non_chat_model(model):
+ guidance = (
+ "Choose a chat model or a supported decision model."
+ if decision_evaluations_enabled(self.context["get_team"]().id, base_url=OPENROUTER_BASE_URL)
+ else "Choose a chat model."
+ )
raise serializers.ValidationError(
- {
- "model_configuration": (
- f"'{model}' does not support chat completions, so it cannot be an LLM judge. Choose a chat model."
- )
- }
+ {"model_configuration": f"'{model}' is not supported as an evaluation judge. {guidance}"}
)
def _validate_can_run(self, data: dict) -> None:
diff --git a/products/ai_observability/backend/api/provider_keys.py b/products/ai_observability/backend/api/provider_keys.py
index dfe8ea490c1e..14b7019c3787 100644
--- a/products/ai_observability/backend/api/provider_keys.py
+++ b/products/ai_observability/backend/api/provider_keys.py
@@ -25,6 +25,7 @@ from posthog.security.url_validation import strip_userinfo
from products.access_control.backend.presentation.access_control import AccessControlViewSetMixin
from ..llm.client import Client
+from ..llm.decisions import DecisionClient, decision_evaluations_enabled
from ..llm.providers.azure_openai import (
DEFAULT_API_VERSION,
DISALLOWED_ENDPOINT_MESSAGE,
@@ -36,7 +37,6 @@ from ..llm.providers.openai_compatible import (
error_field_for_validation_message as openai_compatible_error_field,
is_allowed_custom_base_url,
)
-from ..llm.system_one import SystemOneClient, system_one_evaluations_enabled
from ..models.evaluation_config import EvaluationConfig
from ..models.evaluations import Evaluation
from ..models.model_configuration import LLMModelConfiguration
@@ -77,7 +77,7 @@ def _reload_model_config_dependents_on_commit(team_id: int, model_config_ids: li
def validate_provider_key(provider: str, api_key: str, *, team_id: int, **kwargs: str) -> tuple[str, str | None]:
"""Validate an API key for any supported provider using the unified client."""
- if provider == LLMProvider.SYSTEM_ONE and not system_one_evaluations_enabled(
+ if provider == LLMProvider.SYSTEM_ONE and not decision_evaluations_enabled(
team_id, base_url=kwargs.get("base_url", "")
):
raise exceptions.PermissionDenied("System One evaluations are not available for this project.")
@@ -192,7 +192,7 @@ class LLMProviderKeySerializer(serializers.ModelSerializer):
provider = self.initial_data.get("provider", self.instance.provider if self.instance else None)
if provider == LLMProvider.SYSTEM_ONE:
try:
- return SystemOneClient.normalize_base_url(value)
+ return DecisionClient.normalize_base_url(value)
except ValueError as error:
raise serializers.ValidationError(str(error)) from error
# `base_url_display` is readable by any project member while the API key is masked, and the
diff --git a/products/ai_observability/backend/api/proxy.py b/products/ai_observability/backend/api/proxy.py
index 3f2e3b355c25..3ce45ad0a986 100644
--- a/products/ai_observability/backend/api/proxy.py
+++ b/products/ai_observability/backend/api/proxy.py
@@ -18,6 +18,7 @@ from django.http.response import HttpResponseBase
from django.utils import timezone
import structlog
+from drf_spectacular.utils import OpenApiParameter, extend_schema
from rest_framework import serializers, viewsets
from rest_framework.decorators import action
from rest_framework.permissions import BasePermission, IsAuthenticated
@@ -49,11 +50,13 @@ from products.ai_observability.backend.llm import (
ModelInfo,
get_playground_models,
)
+from products.ai_observability.backend.llm.decisions import decision_evaluations_enabled
from products.ai_observability.backend.llm.errors import (
ProviderConfigurationError,
ProviderHostUnresolvedError,
UnsupportedProviderError,
)
+from products.ai_observability.backend.llm.providers.openrouter import OPENROUTER_BASE_URL, decision_model_ids
from products.ai_observability.backend.models.provider_keys import (
LLMProvider,
LLMProviderKey,
@@ -102,6 +105,17 @@ class LLMProxyCompletionSerializer(serializers.Serializer):
provider_key_id = serializers.UUIDField(required=False, allow_null=True)
+class LLMProxyModelInfoSerializer(serializers.Serializer):
+ id = serializers.CharField(help_text="Provider-specific model identifier.")
+ name = serializers.CharField(help_text="Model display name.")
+ provider = serializers.CharField(help_text="Provider display name.")
+ description = serializers.CharField(allow_blank=True, help_text="Description of the model.")
+ is_recommended = serializers.BooleanField(help_text="Whether the provider recommends this model.")
+ supports_decisions = serializers.BooleanField(
+ default=False, help_text="Whether this model supports decision questions instead of chat completions."
+ )
+
+
class PlaygroundAccessPermission(BasePermission):
"""Resource-level RBAC for the playground.
@@ -445,6 +459,14 @@ class LLMProxyViewSet(viewsets.ViewSet):
return properties
+ @extend_schema(
+ parameters=[
+ OpenApiParameter(
+ "provider_key_id", type=uuid.UUID, description="Team provider key whose models should be listed."
+ )
+ ],
+ responses=LLMProxyModelInfoSerializer(many=True),
+ )
@action(detail=False, methods=["GET"])
@llma_track_latency("llma_proxy_models")
@monitor(feature=None, endpoint="llma_proxy_models", method="GET")
@@ -477,6 +499,12 @@ class LLMProxyViewSet(viewsets.ViewSet):
cache.set(cache_key, models, timeout=MODELS_CACHE_TIMEOUT_SECONDS)
recommended = Client.recommended_models(provider_key.provider)
provider_display = PROVIDER_DISPLAY_NAMES.get(provider_key.provider, provider_key.provider.title())
+ decision_models: frozenset[str] = frozenset()
+ if provider_key.provider == LLMProvider.OPENROUTER and decision_evaluations_enabled(
+ provider_key.team_id, base_url=OPENROUTER_BASE_URL
+ ):
+ decision_models = decision_model_ids() or frozenset()
+ models = list(dict.fromkeys([*models, *sorted(decision_models)]))
return Response(
[
ModelInfo(
@@ -485,6 +513,7 @@ class LLMProxyViewSet(viewsets.ViewSet):
provider=provider_display,
description="",
is_recommended=m in recommended,
+ supports_decisions=provider_key.provider == LLMProvider.SYSTEM_ONE or m in decision_models,
)
for m in models
]
diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.py
index fe9cac71d2bc..c329b1400ffe 100644
--- a/products/ai_observability/backend/api/test/test_evaluations.py
+++ b/products/ai_observability/backend/api/test/test_evaluations.py
@@ -131,7 +131,7 @@ class TestModelConfigurationSerializer(SimpleTestCase):
output_config=output_config,
)
serializer = EvaluationSerializer(instance=evaluation, partial=True)
- data = {"model_configuration": {"provider": "system_one", "model": "custom-model"}}
+ data = {"model_configuration": {"provider": "system_one", "model": "typesafe/jev-1.13"}}
with patch.object(serializer, "_validate_chat_model"):
self.assertEqual(serializer.validate(data), data)
@@ -150,22 +150,74 @@ class TestModelConfigurationSerializer(SimpleTestCase):
):
serializer.validate({"model_configuration": {"provider": "system_one", "model": "custom-model"}})
- @parameterized.expand([("system_one", False), ("openai", True)])
+ @parameterized.expand([("system_one", False), ("openrouter", False), ("openai", True)])
def test_clearing_numeric_bounds_depends_on_provider(self, provider: str, valid: bool) -> None:
evaluation = Evaluation(
evaluation_type="llm_judge",
evaluation_config={"prompt": "Score quality"},
output_type="numeric",
output_config={"min": 0, "max": 10},
- model_configuration=LLMModelConfiguration(provider=provider, model="custom-model"),
+ model_configuration=LLMModelConfiguration(provider=provider, model="typesafe/jev-1.13"),
)
- serializer = EvaluationSerializer(instance=evaluation, data={"output_config": {"max": None}}, partial=True)
- self.assertEqual(serializer.is_valid(), valid, serializer.errors)
+ serializer = EvaluationSerializer(
+ instance=evaluation,
+ data={"output_config": {"max": None}},
+ partial=True,
+ context={"get_team": lambda: Mock(id=1)},
+ )
+ with (
+ patch(
+ "products.ai_observability.backend.llm.providers.openrouter._non_chat_models",
+ return_value={"typesafe/jev-1.13": ["decisions"]},
+ ),
+ patch("products.ai_observability.backend.api.evaluations.decision_evaluations_enabled", return_value=True),
+ ):
+ self.assertEqual(serializer.is_valid(), valid, serializer.errors)
if valid:
self.assertEqual(serializer.validated_data["output_config"]["min"], 0)
else:
self.assertIn("output_config", serializer.errors)
+ @parameterized.expand(
+ [
+ (True, {"name": "Updated judge"}, True),
+ (True, {"enabled": False}, True),
+ (True, {"output_config": {"max": None}}, False),
+ (False, {"output_config": {"max": None}}, True),
+ (True, {"model_configuration": {"provider": "openrouter", "model": "openai/gpt-4o"}}, False),
+ (False, {"model_configuration": {"provider": "openrouter", "model": "openai/gpt-4o"}}, True),
+ (True, {"enabled": True}, False),
+ ]
+ )
+ def test_openrouter_catalogue_outage_only_blocks_model_validation(
+ self, flag: bool, data: dict[str, object], valid: bool
+ ) -> None:
+ evaluation = Evaluation(
+ evaluation_type="llm_judge",
+ evaluation_config={"prompt": "Score quality"},
+ enabled=True,
+ output_type="numeric",
+ output_config={"min": 0, "max": 10},
+ model_configuration=LLMModelConfiguration(provider="openrouter", model="typesafe/jev-1.13"),
+ )
+ serializer = EvaluationSerializer(
+ instance=evaluation, data=data, partial=True, context={"get_team": lambda: Mock(id=1)}
+ )
+ with (
+ patch(
+ "products.ai_observability.backend.llm.providers.openrouter._non_chat_models", return_value=None
+ ) as catalogue,
+ patch("products.ai_observability.backend.api.evaluations.decision_evaluations_enabled", return_value=flag),
+ ):
+ self.assertEqual(serializer.is_valid(), valid, serializer.errors)
+ if valid:
+ for field, value in data.items():
+ if field in ("name", "enabled"):
+ self.assertEqual(serializer.validated_data[field], value)
+ catalogue.assert_not_called()
+ else:
+ self.assertIn("Try again", str(serializer.errors["model_configuration"]))
+
@parameterized.expand(
[
("missing_key", "example-judge-v1", None, False),
@@ -874,11 +926,26 @@ class TestEvaluationConfigsApi(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data["attr"], "model_configuration")
- @parameterized.expand([("decision_model", "typesafe/jev-1.13", 400), ("chat_model", "openai/gpt-4o", 201)])
- def test_llm_judge_creation_rejects_openrouter_non_chat_model(self, _name, model, expected_status):
- with patch(
- "products.ai_observability.backend.llm.providers.openrouter._non_chat_model_ids",
- return_value=frozenset({"typesafe/jev-1.13"}),
+ @parameterized.expand(
+ [
+ ("decision_model_enabled", "typesafe/jev-1.13", True, 201),
+ ("decision_model_disabled", "typesafe/jev-1.13", False, 400),
+ ("decision_model_alias", "~typesafe/jev-latest", True, 201),
+ ("chat_model", "openai/gpt-4o", False, 201),
+ ("other_non_chat_model", "example/embedding", True, 400),
+ ]
+ )
+ def test_llm_judge_creation_checks_openrouter_model_capabilities(self, _name, model, flag, expected_status):
+ with (
+ patch(
+ "products.ai_observability.backend.llm.providers.openrouter._non_chat_models",
+ return_value={
+ "typesafe/jev-1.13": ["decisions"],
+ "~typesafe/jev-latest": ["decisions"],
+ "example/embedding": ["embeddings"],
+ },
+ ),
+ patch("products.ai_observability.backend.api.evaluations.decision_evaluations_enabled", return_value=flag),
):
response = self.client.post(
f"/api/environments/{self.team.id}/evaluations/",
@@ -896,6 +963,10 @@ class TestEvaluationConfigsApi(APIBaseTest):
self.assertEqual(response.status_code, expected_status, response.json())
if expected_status == 400:
self.assertEqual(response.data["attr"], "model_configuration")
+ if flag:
+ self.assertIn("Choose a chat model or a supported decision model.", response.data["detail"])
+ else:
+ self.assertIn("Choose a chat model.", response.data["detail"])
@parameterized.expand([("omitted", False), ("null", True)])
def test_llm_judge_creation_requires_model_configuration(self, _name, include_null_configuration):
@@ -2138,7 +2209,8 @@ class TestReEnableValidatesRootCauseResolved(APIBaseTest):
self.assertTrue(eval_obj.enabled)
self.assertIsNone(eval_obj.status_reason)
- def test_rejects_re_enable_when_model_still_not_supported(self):
+ @parameterized.expand([(False, 400), (True, 200)])
+ def test_re_enable_openrouter_decision_model_depends_on_rollout(self, flag, expected_status):
key = LLMProviderKey.objects.create(
team=self.team,
provider="openrouter",
@@ -2151,9 +2223,12 @@ class TestReEnableValidatesRootCauseResolved(APIBaseTest):
status_reason="model_not_supported", model="typesafe/jev-1.13", provider_key=key, provider="openrouter"
)
- with patch(
- "products.ai_observability.backend.llm.providers.openrouter._non_chat_model_ids",
- return_value=frozenset({"typesafe/jev-1.13"}),
+ with (
+ patch(
+ "products.ai_observability.backend.llm.providers.openrouter._non_chat_models",
+ return_value={"typesafe/jev-1.13": ["decisions"]},
+ ),
+ patch("products.ai_observability.backend.api.evaluations.decision_evaluations_enabled", return_value=flag),
):
response = self.client.patch(
f"/api/environments/{self.team.id}/evaluations/{eval_obj.id}/",
@@ -2161,10 +2236,9 @@ class TestReEnableValidatesRootCauseResolved(APIBaseTest):
format="json",
)
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertEqual(response.data["attr"], "model_configuration")
+ self.assertEqual(response.status_code, expected_status, response.json())
eval_obj.refresh_from_db()
- self.assertFalse(eval_obj.enabled)
+ self.assertEqual(eval_obj.enabled, flag)
def test_allows_re_enable_when_model_not_found_with_new_model(self):
key = LLMProviderKey.objects.create(
diff --git a/products/ai_observability/backend/api/test/test_provider_keys.py b/products/ai_observability/backend/api/test/test_provider_keys.py
index 2d43772a203a..a45e07adcf55 100644
--- a/products/ai_observability/backend/api/test/test_provider_keys.py
+++ b/products/ai_observability/backend/api/test/test_provider_keys.py
@@ -187,7 +187,7 @@ class TestLLMProviderKeyViewSet(APIBaseTest):
with (
self.settings(POSTHOG_INTERNAL_ORG_IDS=[]),
patch(
- "products.ai_observability.backend.llm.system_one.get_feature_flag_or_none",
+ "products.ai_observability.backend.llm.decisions.get_feature_flag_or_none",
return_value=False,
),
patch("httpx.AsyncHTTPTransport.handle_async_request") as request,
@@ -262,7 +262,7 @@ class TestLLMProviderKeyViewSet(APIBaseTest):
@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")})
@patch("httpx.AsyncHTTPTransport.handle_async_request")
- @patch("products.ai_observability.backend.llm.system_one.get_feature_flag_or_none", return_value=True)
+ @patch("products.ai_observability.backend.llm.decisions.get_feature_flag_or_none", return_value=True)
def test_custom_system_one_connection_round_trip(self, _flag: Mock, request: Mock, _dns: Mock) -> None:
body = json.dumps(
{
diff --git a/products/ai_observability/backend/api/test/test_proxy.py b/products/ai_observability/backend/api/test/test_proxy.py
index 90f12e448419..80461f565654 100644
--- a/products/ai_observability/backend/api/test/test_proxy.py
+++ b/products/ai_observability/backend/api/test/test_proxy.py
@@ -323,3 +323,32 @@ class TestPlaygroundModelEnforcement(APIBaseTest):
assert response.status_code == 200
returned_ids = {m["id"] for m in response.json()}
assert returned_ids == PLAYGROUND_MODEL_IDS
+
+ @parameterized.expand([(True,), (False,)])
+ def test_openrouter_decision_models_use_the_existing_key(self, flag: bool) -> None:
+ key = LLMProviderKey.objects.create(
+ team=self.team,
+ provider="openrouter",
+ name="OpenRouter",
+ encrypted_config={"api_key": "example-openrouter-token"},
+ created_by=self.user,
+ )
+ with (
+ patch(
+ "products.ai_observability.backend.api.proxy.Client.list_models", return_value=["typesafe/jev-router"]
+ ),
+ patch("products.ai_observability.backend.api.proxy.decision_evaluations_enabled", return_value=flag),
+ patch(
+ "products.ai_observability.backend.api.proxy.decision_model_ids",
+ return_value=frozenset({"typesafe/jev-1.13"}),
+ ),
+ ):
+ response = self.client.get("/api/llm_proxy/models/", {"provider_key_id": str(key.id)})
+
+ assert response.status_code == 200
+ models = {model["id"]: model for model in response.json()}
+ assert models["typesafe/jev-router"]["supports_decisions"] is False
+ assert ("typesafe/jev-1.13" in models) is flag
+ if flag:
+ assert models["typesafe/jev-1.13"]["provider"] == "OpenRouter"
+ assert models["typesafe/jev-1.13"]["supports_decisions"] is True
diff --git a/products/ai_observability/backend/llm/__init__.py b/products/ai_observability/backend/llm/__init__.py
index 45e3df34fc27..b8195d39ea52 100644
--- a/products/ai_observability/backend/llm/__init__.py
+++ b/products/ai_observability/backend/llm/__init__.py
@@ -1,4 +1,4 @@
-from typing import Any, TypedDict
+from typing import Any, NotRequired, TypedDict
from products.ai_observability.backend.llm.client import Client
from products.ai_observability.backend.llm.errors import LLMError, ProviderMismatchError, UnsupportedProviderError
@@ -18,6 +18,7 @@ class ModelInfo(TypedDict):
provider: str
description: str
is_recommended: bool
+ supports_decisions: NotRequired[bool]
# Single registry of providers. Add new providers here and everything else
diff --git a/products/ai_observability/backend/llm/client.py b/products/ai_observability/backend/llm/client.py
index eee4b8b3fc56..ec5bd231adf9 100644
--- a/products/ai_observability/backend/llm/client.py
+++ b/products/ai_observability/backend/llm/client.py
@@ -8,8 +8,8 @@ import uuid
from collections.abc import Generator
from typing import TYPE_CHECKING, Any
+from products.ai_observability.backend.llm.decisions import DecisionClient
from products.ai_observability.backend.llm.errors import ProviderMismatchError, UnsupportedProviderError
-from products.ai_observability.backend.llm.system_one import SystemOneClient
from products.ai_observability.backend.llm.types import (
AnalyticsContext,
CompletionRequest,
@@ -83,7 +83,7 @@ class Client:
def validate_key(cls, provider: str, api_key: str, **kwargs: Any) -> tuple[str, str | None]:
"""Validate an API key for a provider. Returns (state, error_message)."""
if provider == "system_one":
- return SystemOneClient.validate_key(api_key, **kwargs)
+ return DecisionClient.validate_key(api_key, **kwargs)
return _get_provider(provider).validate_key(api_key, **kwargs)
@classmethod
diff --git a/products/ai_observability/backend/llm/system_one.py b/products/ai_observability/backend/llm/decisions.py
similarity index 61%
rename from products/ai_observability/backend/llm/system_one.py
rename to products/ai_observability/backend/llm/decisions.py
index 36ed0b117ac5..ce90126bb5cd 100644
--- a/products/ai_observability/backend/llm/system_one.py
+++ b/products/ai_observability/backend/llm/decisions.py
@@ -1,4 +1,5 @@
from collections.abc import Mapping
+from typing import Literal
from urllib.parse import urlsplit
import httpx
@@ -15,7 +16,7 @@ from posthog.llm.system_one import (
from posthog.models import Team
from posthog.ph_client import get_feature_flag_or_none
from posthog.security.pinned_requests import SSRFBlockedError
-from posthog.security.url_validation import has_authority_bypass_chars, validate_url_and_pin_ips
+from posthog.security.url_validation import UNRESOLVED_HOST_REASON, has_authority_bypass_chars, validate_url_and_pin_ips
from products.ai_observability.backend.llm.errors import (
RESPONSE_LIMIT_MESSAGE,
@@ -25,16 +26,31 @@ from products.ai_observability.backend.llm.errors import (
ModelNotFoundError,
ModelPermissionError,
ProviderConnectionError,
+ ProviderHostUnresolvedError,
ProviderRequestRejectedError,
+ QuotaExceededError,
RateLimitError,
RetryableRateLimitError,
StructuredOutputParseError,
is_context_window_error_message,
)
from products.ai_observability.backend.llm.providers._diagnostics import tagged_http_client
+from products.ai_observability.backend.llm.providers.openrouter import OPENROUTER_HEADERS, decision_model_ids
-def system_one_evaluations_enabled(team_id: int, *, base_url: str) -> bool:
+def is_decision_model(provider: str | None, model: str | None, *, openrouter_enabled: bool) -> bool:
+ if provider == "system_one":
+ return True
+ # Disabled projects keep the chat path independent of catalogue availability.
+ if provider != "openrouter" or not model or not openrouter_enabled:
+ return False
+ models = decision_model_ids()
+ if models is None:
+ raise ProviderConnectionError("Could not load OpenRouter model capabilities. Try again.")
+ return model in models
+
+
+def decision_evaluations_enabled(team_id: int, *, base_url: str) -> bool:
try:
host = (urlsplit(base_url).hostname or "").encode("idna").decode("ascii").lower().rstrip(".")
except (ValueError, UnicodeError):
@@ -53,20 +69,20 @@ def system_one_evaluations_enabled(team_id: int, *, base_url: str) -> bool:
)
-class SystemOneRequestRejectedError(ProviderRequestRejectedError):
+class DecisionRequestRejectedError(ProviderRequestRejectedError):
pass
-class SystemOneEndpointBlockedError(LLMError):
+class DecisionEndpointBlockedError(LLMError):
pass
-class SystemOneRateLimitError(RetryableRateLimitError):
+class DecisionRateLimitError(RetryableRateLimitError):
def __init__(self, retry_after: str | None) -> None:
- super().__init__("The System One endpoint is temporarily unavailable. Try again later.", retry_after)
+ super().__init__("The decision endpoint is temporarily unavailable. Try again later.", retry_after)
-class SystemOneClient:
+class DecisionClient:
@staticmethod
def normalize_base_url(base_url: str) -> str:
parsed = urlsplit(base_url)
@@ -97,15 +113,21 @@ class SystemOneClient:
questions: Mapping[str, Question],
base_url: str,
timeout: float = 60,
+ path: Literal["systemone", "decisions"] = "systemone",
) -> SystemOneResult:
try:
- base_url = SystemOneClient.normalize_base_url(base_url)
+ base_url = DecisionClient.normalize_base_url(base_url)
except ValueError as error:
- raise SystemOneEndpointBlockedError(str(error)) from error
+ raise DecisionEndpointBlockedError(str(error)) from error
try:
verdict = validate_url_and_pin_ips(base_url)
if not verdict.allowed:
+ if path == "decisions" and verdict.reason == UNRESOLVED_HOST_REASON:
+ raise ProviderHostUnresolvedError()
raise SSRFBlockedError(verdict.reason)
+ headers = dict(OPENROUTER_HEADERS) if path == "decisions" else {}
+ if api_key:
+ headers["Authorization"] = f"Bearer {api_key}"
with tagged_http_client(
pin=(base_url, verdict.pinned_ips),
timeout=timeout,
@@ -113,16 +135,16 @@ class SystemOneClient:
follow_redirects=False,
) as client:
response = client.post(
- f"{base_url}/systemone",
- headers={"Authorization": f"Bearer {api_key}"} if api_key else {},
+ f"{base_url}/{path}",
+ headers=headers,
json=build_system_one_body(state=state, questions=questions, model=model),
)
except SSRFBlockedError as error:
- raise SystemOneEndpointBlockedError("This endpoint is not allowed. Use a public HTTPS endpoint.") from error
+ raise DecisionEndpointBlockedError("This endpoint is not allowed. Use a public HTTPS endpoint.") from error
except httpx.DecodingError as error:
- raise SystemOneRequestRejectedError(RESPONSE_LIMIT_MESSAGE) from error
+ raise DecisionRequestRejectedError(RESPONSE_LIMIT_MESSAGE) from error
except httpx.RequestError as error:
- raise ProviderConnectionError("Could not reach the System One endpoint. Try again.") from error
+ raise ProviderConnectionError("Could not reach the decision endpoint. Try again.") from error
status = response.status_code
if status == 200:
@@ -130,30 +152,36 @@ class SystemOneClient:
return parse_system_one_response(response.json(), questions)
except (ValueError, SystemOneRequestFailed) as error:
raise StructuredOutputParseError(
- "The endpoint returned an invalid System One response. Check compatibility."
+ "The endpoint returned an invalid decision response. Check compatibility."
) from error
if status == 401:
raise AuthenticationError("The endpoint rejected this credential. Check the bearer token.")
+ if status == 402:
+ raise QuotaExceededError("The endpoint account has insufficient credits. Check its billing settings.")
if status == 403:
raise ModelPermissionError(model)
if status == 404:
raise ModelNotFoundError(model)
if status in (408, 429, 503, 529):
- raise SystemOneRateLimitError(response.headers.get("Retry-After"))
+ raise DecisionRateLimitError(response.headers.get("Retry-After"))
if status >= 500:
- raise ProviderConnectionError("The System One endpoint is temporarily unavailable. Try again.")
+ raise ProviderConnectionError("The decision endpoint is temporarily unavailable. Try again.")
if 300 <= status < 400:
- raise SystemOneEndpointBlockedError("The endpoint redirected the request. Use its final HTTPS URL.")
+ # OpenRouter owns this fixed endpoint; redirects must not invalidate its shared key.
+ if path == "decisions":
+ raise ProviderConnectionError("The OpenRouter decision endpoint redirected the request. Try again.")
+ raise DecisionEndpointBlockedError("The endpoint redirected the request. Use its final HTTPS URL.")
if status == 413 or (status == 422 and is_context_window_error_message(response.text)):
raise ContextWindowExceededError("This input exceeds the endpoint's size limit. Reduce the input.")
- raise SystemOneRequestRejectedError(
- "The endpoint rejected the evaluation request. Check the model and criteria."
+ raise DecisionRequestRejectedError(
+ "The endpoint rejected the evaluation request. "
+ "Check that the model supports this evaluation's output type and criteria."
)
@staticmethod
def validate_key(api_key: str, *, base_url: str, model: str) -> tuple[str, str | None]:
try:
- SystemOneClient.evaluate(
+ DecisionClient.evaluate(
api_key=api_key,
base_url=base_url,
model=model,
@@ -167,10 +195,11 @@ class SystemOneClient:
ValueError,
ModelNotFoundError,
ProviderConnectionError,
+ QuotaExceededError,
RateLimitError,
StructuredOutputParseError,
- SystemOneEndpointBlockedError,
- SystemOneRequestRejectedError,
+ DecisionEndpointBlockedError,
+ DecisionRequestRejectedError,
ContextWindowExceededError,
) as error:
return "error", str(error)
diff --git a/products/ai_observability/backend/llm/providers/openrouter.py b/products/ai_observability/backend/llm/providers/openrouter.py
index d6477bf5bd66..c22a5f286d5e 100644
--- a/products/ai_observability/backend/llm/providers/openrouter.py
+++ b/products/ai_observability/backend/llm/providers/openrouter.py
@@ -25,6 +25,7 @@ from products.ai_observability.backend.llm.types import (
logger = logging.getLogger(__name__)
OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"
+OPENROUTER_DECISIONS_BASE_URL = "https://openrouter.ai/api/alpha"
# For App Attribution
OPENROUTER_HEADERS = {
@@ -34,7 +35,8 @@ OPENROUTER_HEADERS = {
# The default model list only has text-output models, so ask for every output modality.
OPENROUTER_ALL_MODELS_URL = f"{OPENROUTER_BASE_URL}/models?output_modalities=all"
-NON_CHAT_MODELS_CACHE_KEY = "ai_observability:openrouter:non_chat_models"
+NON_CHAT_MODELS_CACHE_KEY = "ai_observability:openrouter:non_chat_models:v2"
+NON_CHAT_MODELS_LAST_GOOD_CACHE_KEY = f"{NON_CHAT_MODELS_CACHE_KEY}:last_good"
NON_CHAT_MODELS_CACHE_TTL_SECONDS = 60 * 60
NON_CHAT_MODELS_FETCH_TIMEOUT_SECONDS = 5.0
# Short, so a catalogue outage adds the fetch timeout at most once a minute.
@@ -42,31 +44,49 @@ NON_CHAT_MODELS_UNAVAILABLE_TTL_SECONDS = 60
_CATALOGUE_UNAVAILABLE = "unavailable"
-def _non_chat_model_ids() -> frozenset[str] | None:
- """IDs of OpenRouter models that cannot produce text, such as decision models.
+def _non_chat_models(*, refresh: bool = True) -> dict[str, list[str]] | None:
+ """Output modalities of OpenRouter models that cannot produce text.
- Returns None when the catalogue is unavailable, so callers fail open.
+ Returns the last successful catalogue during outages, or None before the first success.
"""
cached = cache.get(NON_CHAT_MODELS_CACHE_KEY)
if cached == _CATALOGUE_UNAVAILABLE:
- return None
+ return cache.get(NON_CHAT_MODELS_LAST_GOOD_CACHE_KEY)
if cached is not None:
- return frozenset(cached)
+ return cached
+ if not refresh:
+ return cache.get(NON_CHAT_MODELS_LAST_GOOD_CACHE_KEY)
try:
response = httpx.get(OPENROUTER_ALL_MODELS_URL, timeout=NON_CHAT_MODELS_FETCH_TIMEOUT_SECONDS)
response.raise_for_status()
models = response.json()["data"]
- ids = sorted(
- model["id"]
+ modalities = {
+ model["id"]: model["architecture"]["output_modalities"]
for model in models
- if "text" not in (model.get("architecture") or {}).get("output_modalities", ["text"])
- )
+ if "text" not in ((model.get("architecture") or {}).get("output_modalities") or ["text"])
+ }
except Exception:
logger.warning("Could not fetch the OpenRouter model catalogue", exc_info=True)
cache.set(NON_CHAT_MODELS_CACHE_KEY, _CATALOGUE_UNAVAILABLE, NON_CHAT_MODELS_UNAVAILABLE_TTL_SECONDS)
- return None
- cache.set(NON_CHAT_MODELS_CACHE_KEY, ids, NON_CHAT_MODELS_CACHE_TTL_SECONDS)
- return frozenset(ids)
+ return cache.get(NON_CHAT_MODELS_LAST_GOOD_CACHE_KEY)
+ # An outage must not discard the last successful catalogue.
+ cache.set(NON_CHAT_MODELS_LAST_GOOD_CACHE_KEY, modalities, timeout=None)
+ cache.set(NON_CHAT_MODELS_CACHE_KEY, modalities, NON_CHAT_MODELS_CACHE_TTL_SECONDS)
+ return modalities
+
+
+def _non_chat_model_ids() -> frozenset[str] | None:
+ models = _non_chat_models()
+ return frozenset(models) if models is not None else None
+
+
+def decision_model_ids(*, refresh: bool = True) -> frozenset[str] | None:
+ models = _non_chat_models(refresh=refresh)
+ return (
+ frozenset(model for model, modalities in models.items() if "decisions" in modalities)
+ if models is not None
+ else None
+ )
def is_non_chat_model(model: str) -> bool:
diff --git a/products/ai_observability/backend/llm/providers/test/test_openrouter.py b/products/ai_observability/backend/llm/providers/test/test_openrouter.py
index 211630011f19..6fa06ea6f40e 100644
--- a/products/ai_observability/backend/llm/providers/test/test_openrouter.py
+++ b/products/ai_observability/backend/llm/providers/test/test_openrouter.py
@@ -14,9 +14,11 @@ from products.ai_observability.backend.llm.errors import (
from products.ai_observability.backend.llm.providers.openai import OpenAIAdapter
from products.ai_observability.backend.llm.providers.openrouter import (
NON_CHAT_MODELS_CACHE_KEY,
+ NON_CHAT_MODELS_LAST_GOOD_CACHE_KEY,
OPENROUTER_HEADERS,
OpenRouterAdapter,
_non_chat_model_ids,
+ decision_model_ids,
)
@@ -181,7 +183,16 @@ class TestOpenRouterNonChatModels:
{"id": "openai/gpt-4o", "architecture": {"output_modalities": ["text"]}},
{"id": "google/image-model", "architecture": {"output_modalities": ["image", "text"]}},
{"id": "typesafe/jev-1.13", "architecture": {"output_modalities": ["decisions"]}},
+ {"id": "~typesafe/jev-latest", "architecture": {"output_modalities": ["decisions"]}},
+ {"id": "typesafe/jev-router", "architecture": {"output_modalities": ["text"]}},
+ {"id": "respan/span-01", "architecture": {"output_modalities": ["decisions"]}},
+ {"id": "respan/span-01-lite", "architecture": {"output_modalities": ["decisions"]}},
+ {"id": "respan/span-01-lite:free", "architecture": {"output_modalities": ["decisions"]}},
+ {"id": "respan/example-future-model", "architecture": {"output_modalities": ["decisions"]}},
+ {"id": "example/new-decision-model", "architecture": {"output_modalities": ["decisions"]}},
+ {"id": "example/embedding", "architecture": {"output_modalities": ["embeddings"]}},
{"id": "no-architecture/model"},
+ {"id": "null-modalities/model", "architecture": {"output_modalities": None}},
]
}
with (
@@ -189,17 +200,64 @@ class TestOpenRouterNonChatModels:
patch("products.ai_observability.backend.llm.providers.openrouter.cache.set"),
patch("products.ai_observability.backend.llm.providers.openrouter.httpx.get", return_value=mock_response),
):
- assert _non_chat_model_ids() == frozenset({"typesafe/jev-1.13"})
-
- def test_catalogue_failure_is_cached_briefly(self) -> None:
+ assert _non_chat_model_ids() == frozenset(
+ {
+ "typesafe/jev-1.13",
+ "~typesafe/jev-latest",
+ "example/embedding",
+ "respan/span-01",
+ "respan/span-01-lite",
+ "respan/span-01-lite:free",
+ "respan/example-future-model",
+ "example/new-decision-model",
+ }
+ )
+ assert decision_model_ids() == frozenset(
+ {
+ "typesafe/jev-1.13",
+ "~typesafe/jev-latest",
+ "respan/span-01",
+ "respan/span-01-lite",
+ "respan/span-01-lite:free",
+ "example/new-decision-model",
+ "respan/example-future-model",
+ }
+ )
+
+ @pytest.mark.parametrize("cached_decisions", [None, False, True])
+ def test_catalogue_failure_keeps_last_success_and_recovers(self, cached_decisions: bool | None) -> None:
cache.delete(NON_CHAT_MODELS_CACHE_KEY)
+ cache.delete(NON_CHAT_MODELS_LAST_GOOD_CACHE_KEY)
try:
with patch(
"products.ai_observability.backend.llm.providers.openrouter.httpx.get",
- side_effect=httpx.ConnectError("down"),
) as mock_get:
- assert _non_chat_model_ids() is None
- assert _non_chat_model_ids() is None
- assert mock_get.call_count == 1
+ expected: frozenset[str] | None = None
+ if cached_decisions is not None:
+ mock_get.return_value.json.return_value = {
+ "data": [{"id": "example/decision", "architecture": {"output_modalities": ["decisions"]}}]
+ if cached_decisions
+ else []
+ }
+ expected = frozenset({"example/decision"}) if cached_decisions else frozenset()
+ assert decision_model_ids() == expected
+ cache.delete(NON_CHAT_MODELS_CACHE_KEY)
+ mock_get.reset_mock()
+
+ mock_get.side_effect = httpx.ConnectError("down")
+ assert decision_model_ids() == expected
+ assert decision_model_ids() == expected
+ mock_get.assert_called_once()
+
+ cache.delete(NON_CHAT_MODELS_CACHE_KEY)
+ mock_get.side_effect = None
+ mock_get.return_value.json.return_value = {
+ "data": [{"id": "example/replacement", "architecture": {"output_modalities": ["decisions"]}}]
+ }
+ assert decision_model_ids() == frozenset({"example/replacement"})
+ cache.delete(NON_CHAT_MODELS_CACHE_KEY)
+ mock_get.side_effect = httpx.ConnectError("down")
+ assert decision_model_ids() == frozenset({"example/replacement"})
finally:
cache.delete(NON_CHAT_MODELS_CACHE_KEY)
+ cache.delete(NON_CHAT_MODELS_LAST_GOOD_CACHE_KEY)
diff --git a/products/ai_observability/backend/llm/test/test_system_one.py b/products/ai_observability/backend/llm/test/test_decisions.py
similarity index 75%
rename from products/ai_observability/backend/llm/test/test_system_one.py
rename to products/ai_observability/backend/llm/test/test_decisions.py
index 5d4989439c1d..31f13feab313 100644
--- a/products/ai_observability/backend/llm/test/test_system_one.py
+++ b/products/ai_observability/backend/llm/test/test_decisions.py
@@ -2,6 +2,7 @@ import json
from collections.abc import Iterator
from contextlib import nullcontext
from ipaddress import ip_address
+from typing import Literal
from uuid import uuid4
import pytest
@@ -15,20 +16,23 @@ from posthog.llm.system_one import NoulAnswer, NoulQuestion, ScoreAnswer, ScoreQ
from posthog.models import Team
from products.ai_observability.backend.llm.client import Client
+from products.ai_observability.backend.llm.decisions import (
+ DecisionClient,
+ DecisionEndpointBlockedError,
+ DecisionRateLimitError,
+ DecisionRequestRejectedError,
+ decision_evaluations_enabled,
+)
from products.ai_observability.backend.llm.errors import (
AuthenticationError,
ContextWindowExceededError,
ModelPermissionError,
ProviderConnectionError,
+ ProviderHostUnresolvedError,
+ QuotaExceededError,
StructuredOutputParseError,
)
-from products.ai_observability.backend.llm.system_one import (
- SystemOneClient,
- SystemOneEndpointBlockedError,
- SystemOneRateLimitError,
- SystemOneRequestRejectedError,
- system_one_evaluations_enabled,
-)
+from products.ai_observability.backend.llm.providers.openrouter import OPENROUTER_DECISIONS_BASE_URL, OPENROUTER_HEADERS
def _response(status: int, body: dict[str, object] | str = "") -> httpx.Response:
@@ -67,17 +71,19 @@ def test_system_one_connections_require_flag_and_supported_endpoint(
team = Team(id=1, organization_id=uuid4(), uuid=uuid4())
with (
override_settings(POSTHOG_INTERNAL_ORG_IDS=[]),
- patch("products.ai_observability.backend.llm.system_one.Team.objects.only") as teams,
+ patch("products.ai_observability.backend.llm.decisions.Team.objects.only") as teams,
patch(
- "products.ai_observability.backend.llm.system_one.get_feature_flag_or_none",
+ "products.ai_observability.backend.llm.decisions.get_feature_flag_or_none",
side_effect=lambda *args, groups, **kwargs: flag if groups["project"] == str(team.uuid) else False,
),
):
teams.return_value.get.return_value = team
- assert system_one_evaluations_enabled(team.id, base_url=base_url) is enabled
+ assert decision_evaluations_enabled(team.id, base_url=base_url) is enabled
[email protected]("status, expected_state", [(200, "ok"), (401, "invalid"), (403, "invalid"), (500, "error")])
+ "status, expected_state", [(200, "ok"), (401, "invalid"), (402, "error"), (403, "invalid"), (500, "error")]
+)
def test_system_one_key_validation(status: int, expected_state: str) -> None:
response = _response(
status,
@@ -110,8 +116,8 @@ def test_system_one_key_validation(status: int, expected_state: str) -> None:
[
(httpx.ConnectError("Connection refused"), ProviderConnectionError),
(httpx.ReadTimeout("Timed out"), ProviderConnectionError),
- (httpx.DecodingError("The endpoint must return an uncompressed response."), SystemOneRequestRejectedError),
- (httpx.DecodingError("The endpoint response exceeds the size limit."), SystemOneRequestRejectedError),
+ (httpx.DecodingError("The endpoint must return an uncompressed response."), DecisionRequestRejectedError),
+ (httpx.DecodingError("The endpoint response exceeds the size limit."), DecisionRequestRejectedError),
],
)
def test_transport_failures_map_to_provider_errors(error: Exception, expected_error: type[Exception]) -> None:
@@ -119,7 +125,7 @@ def test_transport_failures_map_to_provider_errors(error: Exception, expected_er
patch("httpx.AsyncHTTPTransport.handle_async_request", side_effect=error),
pytest.raises(expected_error),
):
- SystemOneClient.evaluate(
+ DecisionClient.evaluate(
api_key="example-token",
base_url="https://decisions.example.com/v1",
model="custom-model",
@@ -142,7 +148,7 @@ def test_system_one_rejects_invalid_probabilities(probability: object) -> None:
patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response),
pytest.raises(StructuredOutputParseError),
):
- SystemOneClient.evaluate(
+ DecisionClient.evaluate(
api_key="example-token",
base_url="https://decisions.example.com/v1",
model="example-judge-v1",
@@ -179,7 +185,7 @@ def test_system_one_score_response(patch_answer: dict[str, object], valid: bool)
) as request,
nullcontext() if valid else pytest.raises(StructuredOutputParseError),
):
- result = SystemOneClient.evaluate(
+ result = DecisionClient.evaluate(
api_key="",
base_url="https://decisions.example.com/v1",
model="custom-model",
@@ -212,9 +218,9 @@ def test_system_one_rate_limits_are_retryable(status: int) -> None:
response.headers["Retry-After"] = "15"
with (
patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response),
- pytest.raises(SystemOneRateLimitError) as error,
+ pytest.raises(DecisionRateLimitError) as error,
):
- SystemOneClient.evaluate(
+ DecisionClient.evaluate(
api_key="example-token",
base_url="https://decisions.example.com/v1",
model="example-judge-v1",
@@ -244,7 +250,7 @@ def test_unavailable_usage_does_not_discard_a_valid_answer(
},
)
with patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response):
- result = SystemOneClient.evaluate(
+ result = DecisionClient.evaluate(
api_key="example-token",
base_url="https://decisions.example.com/v1",
model="example-judge-v1",
@@ -263,9 +269,9 @@ def test_unavailable_usage_does_not_discard_a_valid_answer(
def test_official_endpoint_is_blocked(base_url: str) -> None:
with (
patch("httpx.AsyncHTTPTransport.handle_async_request") as request,
- pytest.raises(SystemOneEndpointBlockedError, match="hosted endpoint is not available"),
+ pytest.raises(DecisionEndpointBlockedError, match="hosted endpoint is not available"),
):
- SystemOneClient.evaluate(
+ DecisionClient.evaluate(
api_key="example-token",
base_url=base_url,
model="example-judge-v1",
@@ -289,7 +295,7 @@ def test_system_one_requires_every_requested_answer(answers: dict[str, object])
patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response),
pytest.raises(StructuredOutputParseError),
):
- SystemOneClient.evaluate(
+ DecisionClient.evaluate(
api_key="example-token",
base_url="https://decisions.example.com/v1",
model="example-judge-v1",
@@ -302,32 +308,68 @@ def test_system_one_requires_every_requested_answer(answers: dict[str, object])
@pytest.mark.parametrize(
- "status,message,error_type",
+ "status,message,error_type,path",
[
- (200, "<html>Bad gateway</html>", StructuredOutputParseError),
- (302, "Redirect", SystemOneEndpointBlockedError),
- (401, "Invalid key", AuthenticationError),
- (403, "Access denied", ModelPermissionError),
- (500, "Unavailable", ProviderConnectionError),
- (413, "Request too large", ContextWindowExceededError),
- (422, "Input exceeds the context window", ContextWindowExceededError),
- (422, "Invalid question", SystemOneRequestRejectedError),
+ (200, "<html>Bad gateway</html>", StructuredOutputParseError, "systemone"),
+ (302, "Redirect", DecisionEndpointBlockedError, "systemone"),
+ (302, "Redirect", ProviderConnectionError, "decisions"),
+ (401, "Invalid key", AuthenticationError, "systemone"),
+ (402, "Insufficient credits", QuotaExceededError, "systemone"),
+ (403, "Access denied", ModelPermissionError, "systemone"),
+ (500, "Unavailable", ProviderConnectionError, "systemone"),
+ (413, "Request too large", ContextWindowExceededError, "systemone"),
+ (422, "Input exceeds the context window", ContextWindowExceededError, "systemone"),
+ (422, "Invalid question", DecisionRequestRejectedError, "systemone"),
],
)
-def test_system_one_preserves_error_categories(status: int, message: str, error_type: type[Exception]) -> None:
+def test_decision_requests_preserve_error_categories(
+ status: int, message: str, error_type: type[Exception], path: Literal["systemone", "decisions"]
+) -> None:
response = _response(status, message)
response.headers["Location"] = "https://other.example.com/systemone"
with (
- patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response),
+ patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response) as request,
pytest.raises(error_type),
):
- SystemOneClient.evaluate(
+ DecisionClient.evaluate(
api_key="example-token",
- base_url="https://decisions.example.com/v1",
+ base_url=OPENROUTER_DECISIONS_BASE_URL if path == "decisions" else "https://decisions.example.com/v1",
+ path=path,
model="example-judge-v1",
state="Hello!",
questions={"verdict": NoulQuestion(instructions="Polite?")},
)
+ request.assert_called_once()
+
+
+ "path,address,error_type",
+ [
+ ("decisions", None, ProviderHostUnresolvedError),
+ ("systemone", None, DecisionEndpointBlockedError),
+ ("decisions", "127.0.0.1", DecisionEndpointBlockedError),
+ ],
+)
+def test_endpoint_resolution_errors(
+ path: Literal["systemone", "decisions"], address: str | None, error_type: type[Exception]
+) -> None:
+ with (
+ override_settings(DEBUG=False, TEST=False),
+ patch(
+ "posthog.security.url_validation.resolve_host_ips", return_value={ip_address(address)} if address else set()
+ ),
+ patch("httpx.AsyncHTTPTransport.handle_async_request") as request,
+ pytest.raises(error_type),
+ ):
+ DecisionClient.evaluate(
+ api_key="example-token",
+ base_url=OPENROUTER_DECISIONS_BASE_URL if path == "decisions" else "https://decisions.example.com/v1",
+ path=path,
+ model="example-judge-v1",
+ state="Hello!",
+ questions={"verdict": NoulQuestion(instructions="Polite?")},
+ )
+ request.assert_not_called()
@override_settings(
@@ -338,7 +380,10 @@ def test_system_one_preserves_error_categories(status: int, message: str, error_
TYPESAFE_API_KEY="example-instance-key",
)
@pytest.mark.parametrize("api_key", ["example-token", ""])
-def test_custom_endpoint_and_model(api_key: str) -> None:
[email protected]("path", ["systemone", "decisions"])
+def test_custom_endpoint_and_model(api_key: str, path: Literal["systemone", "decisions"]) -> None:
+ base_url = OPENROUTER_DECISIONS_BASE_URL if path == "decisions" else "https://decisions.example.com/v1"
+ host = "openrouter.ai" if path == "decisions" else "decisions.example.com"
response = _response(
200,
{
@@ -351,8 +396,8 @@ def test_custom_endpoint_and_model(api_key: str) -> None:
def respond(request: httpx.Request) -> httpx.Response:
assert request.url.host == "8.8.8.8"
- assert request.headers["Host"] == "decisions.example.com"
- assert request.extensions["sni_hostname"] == "decisions.example.com"
+ assert request.headers["Host"] == host
+ assert request.extensions["sni_hostname"] == host
return response
with (
@@ -360,9 +405,10 @@ def test_custom_endpoint_and_model(api_key: str) -> None:
patch("posthog.egress.typesafe.transport.consume_typesafe_sync") as budget,
patch("posthog.egress.typesafe.observability.typesafe_egress.record_response") as telemetry,
):
- result = SystemOneClient.evaluate(
+ result = DecisionClient.evaluate(
api_key=api_key,
- base_url="https://decisions.example.com/v1/",
+ base_url=f"{base_url}/",
+ path=path,
model="custom-model",
state="Hello!",
questions={
@@ -370,8 +416,10 @@ def test_custom_endpoint_and_model(api_key: str) -> None:
"applicable": NoulQuestion(instructions="Relevant?"),
},
)
- assert str(request.call_args.args[0].url) == "https://decisions.example.com/v1/systemone"
+ assert str(request.call_args.args[0].url) == f"{base_url}/{path}"
assert request.call_args.args[0].headers.get("Authorization") == (f"Bearer {api_key}" if api_key else None)
+ for name, value in OPENROUTER_HEADERS.items():
+ assert request.call_args.args[0].headers.get(name) == (value if path == "decisions" else None)
assert json.loads(request.call_args.args[0].content)["model"] == "custom-model"
budget.assert_not_called()
telemetry.assert_not_called()
@@ -393,7 +441,7 @@ def test_custom_endpoint_and_model(api_key: str) -> None:
)
def test_invalid_endpoint_is_rejected_before_sending_credentials(base_url: str) -> None:
with patch("httpx.AsyncHTTPTransport.handle_async_request") as request:
- state, _ = SystemOneClient.validate_key("example-token", base_url=base_url, model="custom-model")
+ state, _ = DecisionClient.validate_key("example-token", base_url=base_url, model="custom-model")
assert state == "error"
request.assert_not_called()
@@ -405,6 +453,6 @@ def test_private_endpoint_is_blocked(base_url: str) -> None:
patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("127.0.0.1")}),
patch("httpx.AsyncHTTPTransport.handle_async_request") as request,
):
- state, _ = SystemOneClient.validate_key("example-token", base_url=base_url, model="custom-model")
+ state, _ = DecisionClient.validate_key("example-token", base_url=base_url, model="custom-model")
assert state == "error"
request.assert_not_called()
diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
index 0d414ffe995e..4104a908d978 100644
--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
@@ -103,6 +103,7 @@ export function AIObservabilityEvaluation(): JSX.Element {
canEnableReason,
modelSelectionRequired,
numericBoundsRequired,
+ usesDecisionModel,
} = useValues(llmEvaluationLogic)
const { searchParams } = useValues(router)
const { featureFlags } = useValues(featureFlagLogic)
@@ -141,9 +142,7 @@ export function AIObservabilityEvaluation(): JSX.Element {
return <NotFound object="evaluation" />
}
const openInPlaygroundUrl =
- evaluationTypeUsesModelConfiguration(evaluation.evaluation_type) &&
- evaluation.id &&
- evaluation.model_configuration?.provider !== 'system_one'
+ evaluationTypeUsesModelConfiguration(evaluation.evaluation_type) && evaluation.id && !usesDecisionModel
? combineUrl(urls.aiObservabilityPlayground(), { source_evaluation_id: evaluation.id }).url
: null
@@ -950,7 +949,7 @@ export function AIObservabilityEvaluation(): JSX.Element {
function EvaluationModelPicker(): JSX.Element {
const { byokModels, evaluationProviderModelGroups, byokModelsLoading, providerKeysLoading } =
useValues(modelPickerLogic)
- const { selectedModel, selectedPickerProviderKeyId, modelSelectionRequired, evaluation } =
+ const { selectedModel, selectedPickerProviderKeyId, modelSelectionRequired, evaluation, usesDecisionModel } =
useValues(llmEvaluationLogic)
const { selectModelFromPicker } = useActions(llmEvaluationLogic)
@@ -988,13 +987,13 @@ function EvaluationModelPicker(): JSX.Element {
data-attr="evaluation-model-selector"
/>
<ByokModelPickerNotice forEvaluation />
- {evaluation?.model_configuration?.provider === 'system_one' && (
+ {evaluation && usesDecisionModel && (
<p className="text-sm text-muted mt-2">
{evaluation.output_type === 'categorical'
- ? 'This judge selects categories without written reasoning. For multiple selections, each category is included when its probability is 50% or higher.'
+ ? 'This decision model selects categories without written reasoning. For multiple selections, each category is included when its probability is 50% or higher.'
: evaluation.output_type === 'numeric'
- ? 'This judge estimates a score between your minimum and maximum without written reasoning. Define what low and high scores mean in your evaluation prompt. Scores can be fractional.'
- : 'This judge returns a probability without written reasoning. A probability of 50% or higher produces a true result.'}
+ ? 'This decision model estimates a score between your minimum and maximum without written reasoning. Define what low and high scores mean in your evaluation prompt. Scores can be fractional.'
+ : 'This decision model returns a probability without written reasoning. A probability of 50% or higher produces a true result.'}
</p>
)}
{modelSelectionRequired && !selectedModel && (
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.test.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.test.tsx
index 1a6f9c7f0383..c4e1b606c33c 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.test.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.test.tsx
@@ -76,6 +76,7 @@ describe('EvaluationCodeEditor', () => {
beforeEach(() => {
useMocks({
get: {
+ '/api/llm_proxy/models/': [],
'/api/environments/:teamId/llm_analytics/provider_keys/': { results: [] },
'/api/environments/:teamId/llm_analytics/evaluation_config/': {
active_provider_key: null,
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.test.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.test.tsx
index ca0dd4d9a056..6c5bf1f5b6fd 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.test.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.test.tsx
@@ -58,6 +58,7 @@ describe('EvaluationRunsTable', () => {
beforeEach(() => {
useMocks({
get: {
+ '/api/llm_proxy/models/': [],
'/api/environments/:teamId/llm_analytics/provider_keys/': { results: [] },
'/api/environments/:teamId/llm_analytics/evaluation_config/': {
active_provider_key: null,
diff --git a/products/ai_observability/frontend/evaluations/components/NumericEvaluationConfig.test.tsx b/products/ai_observability/frontend/evaluations/components/NumericEvaluationConfig.test.tsx
index e846acb144ec..959f7dfcbfe5 100644
--- a/products/ai_observability/frontend/evaluations/components/NumericEvaluationConfig.test.tsx
+++ b/products/ai_observability/frontend/evaluations/components/NumericEvaluationConfig.test.tsx
@@ -15,7 +15,7 @@ describe('NumericEvaluationConfig', () => {
)
getByLabelText('Minimum')
getByLabelText('Maximum')
- getByText('System One numeric evaluations require a minimum score below the maximum score.')
+ getByText('Numeric evaluations with decision models require a minimum score below the maximum score.')
expect(numericOutputConfigError(config)).toBeNull()
expect(numericOutputConfigError({ min: -2, max: 4 }, true)).toBeNull()
}
diff --git a/products/ai_observability/frontend/evaluations/components/NumericEvaluationConfig.tsx b/products/ai_observability/frontend/evaluations/components/NumericEvaluationConfig.tsx
index f688cbbee6e3..f38b27131ecd 100644
--- a/products/ai_observability/frontend/evaluations/components/NumericEvaluationConfig.tsx
+++ b/products/ai_observability/frontend/evaluations/components/NumericEvaluationConfig.tsx
@@ -29,7 +29,7 @@ export function NumericEvaluationConfig({
htmlFor={`${id}-${field}`}
info={
field === 'step'
- ? 'Suggests a score increment to LLM judges, including System One. Scores are not rounded or restricted to this increment. Hog evaluations use the score returned by your code.'
+ ? 'Suggests a score increment to LLM judges, including decision models. Scores are not rounded or restricted to this increment. Hog evaluations use the score returned by your code.'
: undefined
}
label={
diff --git a/products/ai_observability/frontend/evaluations/constants.ts b/products/ai_observability/frontend/evaluations/constants.ts
index 4e653cbdb50c..ce665c88d0aa 100644
--- a/products/ai_observability/frontend/evaluations/constants.ts
+++ b/products/ai_observability/frontend/evaluations/constants.ts
@@ -28,7 +28,7 @@ export function numericOutputConfigError(config: EvaluationOutputConfig, require
return 'Enter finite numbers for the score bounds, step, and threshold.'
}
if (requiresBounds && (min == null || max == null || min >= max)) {
- return 'System One numeric evaluations require a minimum score below the maximum score.'
+ return 'Numeric evaluations with decision models require a minimum score below the maximum score.'
}
if (min != null && max != null && min > max) {
return 'Minimum must be less than or equal to maximum.'
diff --git a/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.test.ts b/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.test.ts
index 493504bd5f81..dd8f3b88ef60 100644
--- a/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationBackfillsLogic.test.ts
@@ -111,6 +111,7 @@ describe('evaluationBackfillsLogic', () => {
toastError = jest.spyOn(lemonToast, 'error').mockImplementation(() => 'toast-id')
useMocks({
get: {
+ '/api/llm_proxy/models/': [],
'/api/environments/:teamId/llm_analytics/provider_keys/': { results: [] },
'/api/environments/:teamId/llm_analytics/evaluation_config/': {
active_provider_key: null,
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
index 7d0b6397e4c3..d73aecefe83b 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
@@ -10,6 +10,7 @@ import { initKeaTests } from '~/test/init'
import { ActivityScope } from '~/types'
import type { TestHogResponseApi } from '../generated/api.schemas'
+import { modelPickerLogic } from '../modelPickerLogic'
import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'
import { numericScorePasses } from './constants'
import { evaluationReportLogic } from './evaluationReportLogic'
@@ -240,6 +241,7 @@ describe('llmEvaluationLogic', () => {
beforeEach(() => {
useMocks({
get: {
+ '/api/llm_proxy/models/': [],
'/api/environments/:teamId/llm_analytics/provider_keys/': { results: mockProviderKeys },
'/api/environments/:teamId/llm_analytics/evaluation_config/': {
active_provider_key: null,
@@ -722,28 +724,46 @@ return result`,
await expectLogic(logic).toMatchValues({ formValid: true })
})
- it('requires numeric bounds only while a System One judge is selected', async () => {
- await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
- logic.actions.loadEvaluationSuccess({
- ...mockEvaluation,
- output_type: 'numeric',
- output_config: {},
- model_configuration: { provider: 'system_one', model: 'custom-model', provider_key_id: 'key-1' },
- })
- expect(logic.values.formValid).toBe(false)
+ it.each([
+ ['system_one', false, true],
+ ['openrouter', true, true],
+ ['openrouter', false, false],
+ ] as const)(
+ 'requires numeric bounds for %s with supportsDecisions=%s: %s',
+ async (provider, supportsDecisions, boundsRequired) => {
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
+ await expectLogic(logic).toFinishAllListeners()
+ modelPickerLogic.actions.loadByokModelsSuccess([
+ {
+ id: 'custom-model',
+ name: 'Decision model',
+ provider: 'OpenRouter',
+ description: '',
+ providerKeyId: 'key-1',
+ supportsDecisions,
+ },
+ ])
+ logic.actions.loadEvaluationSuccess({
+ ...mockEvaluation,
+ output_type: 'numeric',
+ output_config: {},
+ model_configuration: { provider, model: 'custom-model', provider_key_id: 'key-1' },
+ })
+ expect(logic.values.formValid).toBe(!boundsRequired)
- logic.actions.patchOutputConfig({ min: 1, max: 10 })
- expect(logic.values.formValid).toBe(true)
- logic.actions.patchOutputConfig({ max: null })
- expect(logic.values.formValid).toBe(false)
+ logic.actions.patchOutputConfig({ min: 1, max: 10 })
+ expect(logic.values.formValid).toBe(true)
+ logic.actions.patchOutputConfig({ max: null })
+ expect(logic.values.formValid).toBe(!boundsRequired)
- logic.actions.setModelConfiguration({
- provider: 'openai',
- model: 'gpt-5-mini',
- provider_key_id: 'key-1',
- })
- expect(logic.values.formValid).toBe(true)
- })
+ logic.actions.setModelConfiguration({
+ provider: 'openai',
+ model: 'gpt-5-mini',
+ provider_key_id: 'key-1',
+ })
+ expect(logic.values.formValid).toBe(true)
+ }
+ )
// A loaded evaluation whose stored shape doesn't match its type (e.g. an llm_judge
// record with no prompt) used to crash formValid with a TypeError on render.
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
index 2dd5722f0a52..4d953666befa 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
@@ -23,7 +23,8 @@ import {
import type { EvaluationBackfillApi, TestHogRequestApi, TestHogResultItemApi } from '../generated/api.schemas'
import type { EvaluationApiOutputConfig } from '../generated/api.schemas'
import { parsePlaygroundProviderKeyId } from '../ModelPicker'
-import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'
+import { modelPickerLogic, type ModelOption } from '../modelPickerLogic'
+import { LLMProviderKey, llmProviderKeysLogic, toLLMProvider } from '../settings/llmProviderKeysLogic'
import type { EvaluationConfig as TeamEvaluationConfig } from '../settings/llmProviderKeysLogic'
import { getUnhealthyProviderKey } from '../settings/providerKeyStateUtils'
import { EvaluationRunsStats, queryEvaluationRuns, queryEvaluationRunsStats } from '../utils'
@@ -301,6 +302,7 @@ export interface llmEvaluationLogicValues {
providerKeys: LLMProviderKey[] // llmProviderKeysLogic
providerKeysLoading: boolean // llmProviderKeysLogic
requiresProviderKey: boolean // llmProviderKeysLogic
+ byokModels: ModelOption[] // modelPickerLogic
activeTab: string
breadcrumbs: Breadcrumb[]
canEnable: boolean
@@ -347,6 +349,7 @@ export interface llmEvaluationLogicValues {
selectedPickerProviderKeyId: string | null
sidePanelContext: SidePanelSceneContext | null
trendInsightUrl: string | null
+ usesDecisionModel: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -540,7 +543,8 @@ export interface llmEvaluationLogicMeta {
originalEvaluation: EvaluationConfig | null,
evaluationId: string
) => boolean
- numericBoundsRequired: (evaluation: EvaluationConfig | null) => boolean
+ usesDecisionModel: (evaluation: EvaluationConfig | null, byokModels: ModelOption[]) => boolean
+ numericBoundsRequired: (evaluation: EvaluationConfig | null, usesDecisionModel: boolean) => boolean
formValid: (
evaluation: EvaluationConfig | null,
modelSelectionRequired: boolean,
@@ -607,6 +611,8 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
values: [
llmProviderKeysLogic,
['providerKeys', 'providerKeysLoading', 'requiresProviderKey', 'activeProviderKey'],
+ modelPickerLogic,
+ ['byokModels'],
],
actions: [llmProviderKeysLogic, ['loadProviderKeys', 'loadEvaluationConfigSuccess']],
})),
@@ -1499,12 +1505,27 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
},
],
+ usesDecisionModel: [
+ (s) => [s.evaluation, s.byokModels],
+ (evaluation: EvaluationConfig | null, models: ModelOption[]): boolean => {
+ const config = evaluation?.model_configuration
+ return (
+ config?.provider === 'system_one' ||
+ (config?.provider === 'openrouter' &&
+ models.some(
+ (model) =>
+ model.id === config.model &&
+ toLLMProvider(model.provider) === 'openrouter' &&
+ (!config.provider_key_id || model.providerKeyId === config.provider_key_id) &&
+ model.supportsDecisions
+ ))
+ )
+ },
+ ],
numericBoundsRequired: [
- (s) => [s.evaluation],
- (evaluation: EvaluationConfig | null): boolean =>
- isLLMJudgeEvaluation(evaluation) &&
- evaluation.output_type === 'numeric' &&
- evaluation.model_configuration?.provider === 'system_one',
+ (s) => [s.evaluation, s.usesDecisionModel],
+ (evaluation: EvaluationConfig | null, usesDecisionModel: boolean): boolean =>
+ isLLMJudgeEvaluation(evaluation) && evaluation.output_type === 'numeric' && usesDecisionModel,
],
formValid: [
(s) => [s.evaluation, s.modelSelectionRequired, s.numericBoundsRequired],
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts
index 5b4a82cff52d..d4fd0465c09f 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts
@@ -140,6 +140,7 @@ describe('llmEvaluationsLogic', () => {
beforeEach(() => {
useMocks({
get: {
+ '/api/llm_proxy/models/': [],
'/api/environments/:teamId/llm_analytics/provider_keys/': { results: mockProviderKeys },
'/api/environments/:teamId/llm_analytics/evaluation_config/': {
active_provider_key: null,
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index d43f7072d6fa..c574323b0205 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -2021,12 +2021,12 @@ export type EvaluationApiOutputConfig = {
/** Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
true_is_failure?: boolean
/**
- * Inclusive minimum numeric score. Omit for no lower bound. Required for System One numeric judges.
+ * Inclusive minimum numeric score. Omit for no lower bound. Required for numeric decision models.
* @nullable
*/
min?: number | null
/**
- * Inclusive maximum numeric score. Omit for no upper bound. Required for System One numeric judges and must exceed min.
+ * Inclusive maximum numeric score. Omit for no upper bound. Required for numeric decision models and must exceed min.
* @nullable
*/
max?: number | null
@@ -2342,12 +2342,12 @@ export type PatchedEvaluationApiOutputConfig = {
/** Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
true_is_failure?: boolean
/**
- * Inclusive minimum numeric score. Omit for no lower bound. Required for System One numeric judges.
+ * Inclusive minimum numeric score. Omit for no lower bound. Required for numeric decision models.
* @nullable
*/
min?: number | null
/**
- * Inclusive maximum numeric score. Omit for no upper bound. Required for System One numeric judges and must exceed min.
+ * Inclusive maximum numeric score. Omit for no upper bound. Required for numeric decision models and must exceed min.
* @nullable
*/
max?: number | null
@@ -2521,12 +2521,12 @@ export type TestHogRequestApiOutputConfig = {
/** Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
true_is_failure?: boolean
/**
- * Inclusive minimum numeric score. Omit for no lower bound. Required for System One numeric judges.
+ * Inclusive minimum numeric score. Omit for no lower bound. Required for numeric decision models.
* @nullable
*/
min?: number | null
/**
- * Inclusive maximum numeric score. Omit for no upper bound. Required for System One numeric judges and must exceed min.
+ * Inclusive maximum numeric score. Omit for no upper bound. Required for numeric decision models and must exceed min.
* @nullable
*/
max?: number | null
@@ -3253,12 +3253,12 @@ export type EvaluationReportMetricsApiOutputConfig = {
/** Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
true_is_failure?: boolean
/**
- * Inclusive minimum numeric score. Omit for no lower bound. Required for System One numeric judges.
+ * Inclusive minimum numeric score. Omit for no lower bound. Required for numeric decision models.
* @nullable
*/
min?: number | null
/**
- * Inclusive maximum numeric score. Omit for no upper bound. Required for System One numeric judges and must exceed min.
+ * Inclusive maximum numeric score. Omit for no upper bound. Required for numeric decision models and must exceed min.
* @nullable
*/
max?: number | null
diff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.ts
index 03cf9a96f274..35919a91757b 100644
--- a/products/ai_observability/frontend/generated/api.zod.ts
+++ b/products/ai_observability/frontend/generated/api.zod.ts
@@ -610,13 +610,13 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod
.number()
.nullish()
.describe(
- 'Inclusive minimum numeric score. Omit for no lower bound. Required for System One numeric judges.'
+ 'Inclusive minimum numeric score. Omit for no lower bound. Required for numeric decision models.'
),
max: zod
.number()
.nullish()
.describe(
- 'Inclusive maximum numeric score. Omit for no upper bound. Required for System One numeric judges and must exceed min.'
+ 'Inclusive maximum numeric score. Omit for no upper bound. Required for numeric decision models and must exceed min.'
),
step: zod
.number()
@@ -995,13 +995,13 @@ export const EvaluationsUpdateBody = /* @__PURE__ */ zod
.number()
.nullish()
.describe(
- 'Inclusive minimum numeric score. Omit for no lower bound. Required for System One numeric judges.'
+ 'Inclusive minimum numeric score. Omit for no lower bound. Required for numeric decision models.'
),
max: zod
.number()
.nullish()
.describe(
- 'Inclusive maximum numeric score. Omit for no upper bound. Required for System One numeric judges and must exceed min.'
+ 'Inclusive maximum numeric score. Omit for no upper bound. Required for numeric decision models and must exceed min.'
),
step: zod
.number()
@@ -1284,13 +1284,13 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod
.number()
.nullish()
.describe(
- 'Inclusive minimum numeric score. Omit for no lower bound. Required for System One numeric judges.'
+ 'Inclusive minimum numeric score. Omit for no lower bound. Required for numeric decision models.'
),
max: zod
.number()
.nullish()
.describe(
- 'Inclusive maximum numeric score. Omit for no upper bound. Required for System One numeric judges and must exceed min.'
+ 'Inclusive maximum numeric score. Omit for no upper bound. Required for numeric decision models and must exceed min.'
),
step: zod
.number()
@@ -1521,13 +1521,13 @@ export const EvaluationsTestHogCreateBody = /* @__PURE__ */ zod.object({
.number()
.nullish()
.describe(
- 'Inclusive minimum numeric score. Omit for no lower bound. Required for System One numeric judges.'
+ 'Inclusive minimum numeric score. Omit for no lower bound. Required for numeric decision models.'
),
max: zod
.number()
.nullish()
.describe(
- 'Inclusive maximum numeric score. Omit for no upper bound. Required for System One numeric judges and must exceed min.'
+ 'Inclusive maximum numeric score. Omit for no upper bound. Required for numeric decision models and must exceed min.'
),
step: zod
.number()
diff --git a/products/ai_observability/frontend/modelPickerLogic.test.ts b/products/ai_observability/frontend/modelPickerLogic.test.ts
index 75dc526f2c2f..b4503e0f2d7c 100644
--- a/products/ai_observability/frontend/modelPickerLogic.test.ts
+++ b/products/ai_observability/frontend/modelPickerLogic.test.ts
@@ -113,11 +113,42 @@ describe('modelPickerLogic', () => {
provider: m.provider,
description: m.description,
isRecommended: true,
+ supportsDecisions: false,
providerKeyId: 'key-1',
}))
)
})
+ it('offers OpenRouter decisions to evaluations alongside chat models, but not to generative pickers', async () => {
+ useMocks({
+ get: {
+ '/api/environments/:team_id/llm_analytics/provider_keys/': {
+ results: [{ id: 'key-openrouter', provider: 'openrouter', name: 'OpenRouter', state: 'ok' }],
+ },
+ '/api/environments/:team_id/llm_analytics/evaluation_config/': { active_provider_key: null },
+ '/api/llm_proxy/models/': ({ request }) => [
+ 200,
+ new URL(request.url).searchParams.get('provider_key_id')
+ ? [
+ { id: 'typesafe/jev-1.13', provider: 'OpenRouter', supports_decisions: true },
+ { id: 'typesafe/jev-router', provider: 'OpenRouter', supports_decisions: false },
+ ]
+ : [],
+ ],
+ },
+ })
+ logic = modelPickerLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.evaluationProviderModelGroups[0].models.map((model) => model.id)).toEqual([
+ 'typesafe/jev-1.13',
+ 'typesafe/jev-router',
+ ])
+ expect(logic.values.providerModelGroups[0].models.map((model) => model.id)).toEqual(['typesafe/jev-router'])
+ expect(logic.values.generativeByokModels.map((model) => model.id)).toEqual(['typesafe/jev-router'])
+ })
+
it('should map is_recommended correctly for both true and false values', async () => {
useMocks({
get: {
@@ -244,6 +275,7 @@ describe('modelPickerLogic', () => {
description: m.description,
isRecommended: true,
providerKeyId: 'key-2',
+ supportsDecisions: false,
}))
)
expect(logic.values.providerModelGroups.find((g) => g.providerKeyId === 'key-1')).toEqual({
diff --git a/products/ai_observability/frontend/modelPickerLogic.ts b/products/ai_observability/frontend/modelPickerLogic.ts
index 870fdf3bb9d2..f4fc218953fc 100644
--- a/products/ai_observability/frontend/modelPickerLogic.ts
+++ b/products/ai_observability/frontend/modelPickerLogic.ts
@@ -20,6 +20,7 @@ export interface ModelOption {
description: string
providerKeyId?: string
isRecommended?: boolean
+ supportsDecisions?: boolean
}
export interface ProviderModelGroup {
@@ -265,6 +266,7 @@ export const modelPickerLogic = kea<modelPickerLogicType>([
`/api/llm_proxy/models/?provider_key_id=${encodeURIComponent(key.id)}`
)) as (Omit<ModelOption, 'providerKeyId' | 'isRecommended'> & {
is_recommended?: boolean
+ supports_decisions?: boolean
})[]
return rawModels.map((m) => ({
id: m.id,
@@ -272,6 +274,7 @@ export const modelPickerLogic = kea<modelPickerLogicType>([
provider: m.provider,
description: m.description,
isRecommended: m.is_recommended ?? false,
+ supportsDecisions: m.supports_decisions ?? false,
providerKeyId: key.id,
}))
} catch {
@@ -353,7 +356,9 @@ export const modelPickerLogic = kea<modelPickerLogicType>([
(s) => [s.byokModels, s.providerKeys],
(models: ModelOption[], keys: LLMProviderKey[]): ModelOption[] =>
models.filter(
- (model) => !keys.some((key) => key.id === model.providerKeyId && key.provider === 'system_one')
+ (model) =>
+ !model.supportsDecisions &&
+ !keys.some((key) => key.id === model.providerKeyId && key.provider === 'system_one')
),
],
playgroundProviderModelGroups: [
@@ -421,7 +426,10 @@ export const modelPickerLogic = kea<modelPickerLogicType>([
providerModelGroups: [
(s) => [s.evaluationProviderModelGroups],
(groups: ProviderModelGroup[]): ProviderModelGroup[] =>
- groups.filter((group) => group.provider !== 'system_one'),
+ groups
+ .filter((group) => group.provider !== 'system_one')
+ .map((group) => ({ ...group, models: group.models.filter((model) => !model.supportsDecisions) }))
+ .filter((group) => group.models.length > 0 || group.disabledReason),
],
evaluationModelNotice: [
(s) => [
diff --git a/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts b/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts
index 8bfbff847e6d..5facefe13fe7 100644
--- a/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts
+++ b/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts
@@ -771,7 +771,12 @@ describe('llmPlaygroundLogic', () => {
expect(llmPlaygroundModelLogic.values.hasByokKeys).toBe(true)
expect(llmPlaygroundModelLogic.values.effectiveModelOptions).toEqual(
- byokModels.map((m) => ({ ...m, isRecommended: false, providerKeyId: 'key-1' }))
+ byokModels.map((m) => ({
+ ...m,
+ isRecommended: false,
+ providerKeyId: 'key-1',
+ supportsDecisions: false,
+ }))
)
})
})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 98a4eb34c900..4bbc73fe412e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -40958,12 +40958,12 @@ export namespace Schemas {
/** Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
true_is_failure?: boolean;
/**
- * Inclusive minimum numeric score. Omit for no lower bound. Required for System One numeric judges.
+ * Inclusive minimum numeric score. Omit for no lower bound. Required for numeric decision models.
* @nullable
*/
min?: number | null;
/**
- * Inclusive maximum numeric score. Omit for no upper bound. Required for System One numeric judges and must exceed min.
+ * Inclusive maximum numeric score. Omit for no upper bound. Required for numeric decision models and must exceed min.
* @nullable
*/
max?: number | null;
@@ -41590,12 +41590,12 @@ export namespace Schemas {
/** Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
true_is_failure?: boolean;
/**
- * Inclusive minimum numeric score. Omit for no lower bound. Required for System One numeric judges.
+ * Inclusive minimum numeric score. Omit for no lower bound. Required for numeric decision models.
* @nullable
*/
min?: number | null;
/**
- * Inclusive maximum numeric score. Omit for no upper bound. Required for System One numeric judges and must exceed min.
+ * Inclusive maximum numeric score. Omit for no upper bound. Required for numeric decision models and must exceed min.
* @nullable
*/
max?: number | null;
@@ -77533,12 +77533,12 @@ export namespace Schemas {
/** Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
true_is_failure?: boolean;
/**
- * Inclusive minimum numeric score. Omit for no lower bound. Required for System One numeric judges.
+ * Inclusive minimum numeric score. Omit for no lower bound. Required for numeric decision models.
* @nullable
*/
min?: number | null;
/**
- * Inclusive maximum numeric score. Omit for no upper bound. Required for System One numeric judges and must exceed min.
+ * Inclusive maximum numeric score. Omit for no upper bound. Required for numeric decision models and must exceed min.
* @nullable
*/
max?: number | null;
@@ -107513,12 +107513,12 @@ export namespace Schemas {
/** Boolean output only. Omit for numeric, categorical, and sentiment output. Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
true_is_failure?: boolean;
/**
- * Inclusive minimum numeric score. Omit for no lower bound. Required for System One numeric judges.
+ * Inclusive minimum numeric score. Omit for no lower bound. Required for numeric decision models.
* @nullable
*/
min?: number | null;
/**
- * Inclusive maximum numeric score. Omit for no upper bound. Required for System One numeric judges and must exceed min.
+ * Inclusive maximum numeric score. Omit for no upper bound. Required for numeric decision models and must exceed min.
* @nullable
*/
max?: number | null;
diff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.ts
index 5e09f8eca892..fccb1c6bcdb0 100644
--- a/services/mcp/src/generated/ai_observability/api.ts
+++ b/services/mcp/src/generated/ai_observability/api.ts
@@ -1380,13 +1380,13 @@ export const EvaluationsCreateBody = () => zod
.number()
.nullish()
.describe(
- 'Inclusive minimum numeric score. Omit for no lower bound. Required for System One numeric judges.'
+ 'Inclusive minimum numeric score. Omit for no lower bound. Required for numeric decision models.'
),
max: zod
.number()
.nullish()
.describe(
- 'Inclusive maximum numeric score. Omit for no upper bound. Required for System One numeric judges and must exceed min.'
+ 'Inclusive maximum numeric score. Omit for no upper bound. Required for numeric decision models and must exceed min.'
),
step: zod
.number()
@@ -1846,13 +1846,13 @@ export const EvaluationsPartialUpdateBody = () => zod
.number()
.nullish()
.describe(
- 'Inclusive minimum numeric score. Omit for no lower bound. Required for System One numeric judges.'
+ 'Inclusive minimum numeric score. Omit for no lower bound. Required for numeric decision models.'
),
max: zod
.number()
.nullish()
.describe(
- 'Inclusive maximum numeric score. Omit for no upper bound. Required for System One numeric judges and must exceed min.'
+ 'Inclusive maximum numeric score. Omit for no upper bound. Required for numeric decision models and must exceed min.'
),
step: zod
.number()
@@ -2103,13 +2103,13 @@ export const EvaluationsTestHogCreateBody = () => zod.object({
.number()
.nullish()
.describe(
- 'Inclusive minimum numeric score. Omit for no lower bound. Required for System One numeric judges.'
+ 'Inclusive minimum numeric score. Omit for no lower bound. Required for numeric decision models.'
),
max: zod
.number()
.nullish()
.describe(
- 'Inclusive maximum numeric score. Omit for no upper bound. Required for System One numeric judges and must exceed min.'
+ 'Inclusive maximum numeric score. Omit for no upper bound. Required for numeric decision models and must exceed min.'
),
step: zod
.number()
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 121f11f37e6e..dce2c99f2ac2 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
@@ -180,7 +180,7 @@
"type": "null"
}
],
- "description": "Inclusive maximum numeric score. Omit for no upper bound. Required for System One numeric judges and must exceed min."
+ "description": "Inclusive maximum numeric score. Omit for no upper bound. Required for numeric decision models and must exceed min."
},
"min": {
"anyOf": [
@@ -191,7 +191,7 @@
"type": "null"
}
],
- "description": "Inclusive minimum numeric score. Omit for no lower bound. Required for System One numeric judges."
+ "description": "Inclusive minimum numeric score. Omit for no lower bound. Required for numeric decision models."
},
"options": {
"description": "Categorical output options. Keys identify stored results; labels are displayed to users.",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-test-hog.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-test-hog.json
index 09560ef5b1d7..655cbd92d645 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-test-hog.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-test-hog.json
@@ -33,7 +33,7 @@
"type": "null"
}
],
- "description": "Inclusive maximum numeric score. Omit for no upper bound. Required for System One numeric judges and must exceed min."
+ "description": "Inclusive maximum numeric score. Omit for no upper bound. Required for numeric decision models and must exceed min."
},
"min": {
"anyOf": [
@@ -44,7 +44,7 @@
"type": "null"
}
],
- "description": "Inclusive minimum numeric score. Omit for no lower bound. Required for System One numeric judges."
+ "description": "Inclusive minimum numeric score. Omit for no lower bound. Required for numeric decision models."
},
"options": {
"description": "Categorical output options. Keys identify stored results; labels are displayed to users.",
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 1796d3d8a920..ee35a0a9a838 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
@@ -183,7 +183,7 @@
"type": "null"
}
],
- "description": "Inclusive maximum numeric score. Omit for no upper bound. Required for System One numeric judges and must exceed min."
+ "description": "Inclusive maximum numeric score. Omit for no upper bound. Required for numeric decision models and must exceed min."
},
"min": {
"anyOf": [
@@ -194,7 +194,7 @@
"type": "null"
}
],
- "description": "Inclusive minimum numeric score. Omit for no lower bound. Required for System One numeric judges."
+ "description": "Inclusive minimum numeric score. Omit for no lower bound. Required for numeric decision models."
},
"options": {
"description": "Categorical output options. Keys identify stored results; labels are displayed to users.",