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 native openai decision evaluations (#115148)

Bernat Torresa018a7dcd9bc
diff --git a/docs/internal/ai-observability-judge-inputs.md b/docs/internal/ai-observability-judge-inputs.md
index 2f749de8b10f..bb29483fb61d 100644
--- a/docs/internal/ai-observability-judge-inputs.md
+++ b/docs/internal/ai-observability-judge-inputs.md
@@ -67,11 +67,12 @@ Changing the judge method marks the evaluation as edited, including when the sel
The selection is stored as `evaluation_config.judge_method` (`llm` or `decision`). Evaluations without this field keep automatic routing until a method or model is explicitly selected.
Automatic OpenRouter routing selects decisions only for models without text output. Models supporting both methods keep chat routing unless decisions are explicitly selected.
Prompt-only `evaluation_config` PATCH requests preserve the saved method; an explicit `judge_method: null` restores automatic routing.
+The detail editor PATCHes only changed fields on existing evaluations, so renaming or disabling a saved decision evaluation still works after its feature flag is turned off. Re-enabling it or changing its model or output configuration still validates decision access.
Explicit method selection requires a selected model, including for legacy evaluations that use the project's default connection.
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.
-Projects configure a System One-compatible deployment and its authentication.
+Projects use their saved provider keys or configure a System One-compatible deployment and its authentication.
Evaluation connections never fall back to an instance credential or gateway configuration.
The configured endpoint authorizes the supplied credential, including connections to PostHog's regional AI gateway endpoints.
Connection validation and every evaluation check these gates; an absent flag or failed flag lookup blocks the call.
@@ -94,6 +95,19 @@ Renaming or disabling an evaluation does not require the catalogue.
With the flag off or unavailable, cached decision-only 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.
+Native OpenAI decisions appear under an existing **OpenAI** key when this flag is enabled.
+Select **Decision model** and `gpt-6-luna` to call OpenAI's fixed `https://api.openai.com/v1/decisions` endpoint.
+OpenAI currently documents this model for Decisions; endpoint support is declared separately from the curated chat-model list.
+Existing OpenAI evaluations without an explicit judge method continue using chat, including models supporting both APIs.
+No custom endpoint or additional connection is required. OpenAI-compatible and Azure connections do not use this native endpoint.
+The adapter translates the shared evaluation questions into OpenAI's `predicate`, `choice`, and `score` formats and validates answers by question name.
+Single-selection categorical evaluations need at least two options; multiple selection still uses one predicate per option.
+Numeric scores use the same ten-level rubric and full-precision mapping to configured bounds described below.
+OpenAI refusals skip the run. Temporary rate limits and overload responses honor `Retry-After`, and transport failures, redirects, and server errors retry without invalidating the key.
+Invalid credentials, missing model access, and exhausted quota use the existing terminal-error handling.
+Native OpenAI requests use the shared DNS-pinned transport with a 60-second total deadline covering connection setup, response headers, and the body. Expired requests close their connections.
+Responses are limited to 1 MiB and must be uncompressed. Redirects and SDK retries are disabled; Temporal owns retries.
+
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.
@@ -153,7 +167,7 @@ DNS failures and redirects at OpenRouter's fixed decision endpoint retry without
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 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.
+See OpenAI's [Decisions guide](https://developers.openai.com/api/docs/guides/decisions), 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 question and answer formats.
## Model output limits
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 6e5a30cb60fb..71ddfc294305 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -12382,6 +12382,14 @@ snapshots:
hash: v1.k794b7964.d7689fdc9f71084879154b5bc9e3e886539ed9f69e6f9c0334901a54fae4f72d.a-jcIwlvssNrK79TxURjANuh9k4xS4T5SGtvdqrYo5Q
scenes-app-llm-observability-evaluationmodelpicker--llm--light:
hash: v1.k794b7964.a65534589a6af5d20189fd7890fdca4f3466df3f32f3b408015e69fd557679a5.ABRZcOSSqQCoyQq6c_hOJQTzNnYewJrQ4BzAa0Si7DA
+ scenes-app-llm-observability-evaluationmodelpicker--native-open-ai--dark:
+ hash: v1.k794b7964.5562145a41dea72f27ce564064efbeaa4908e281809a9b54a1571f7da7f3e2f9.mS00sJJtvwHyWRggu2TsH61MK34knaI6lUEWHyZdvm8
+ scenes-app-llm-observability-evaluationmodelpicker--native-open-ai--light:
+ hash: v1.k794b7964.feb7b7a68b8621977f2095616077fbda6eaacf384f1bbd30195a81edf92521df.OJiBHpBc7NvSGrVpFsw0bM9mKGRh2hY-J5z9zQjXsJw
+ scenes-app-llm-observability-evaluationmodelpicker--native-open-ai-narrow--dark:
+ hash: v1.k794b7964.2cc5a685b95d9b77556df85b606bdff8ccc0943a0294f12eef3ab1715dc862b1.dfPKd8pDCzIffD9PtlmtJ91keZFbiMV-Jw0eSpjKo1U
+ scenes-app-llm-observability-evaluationmodelpicker--native-open-ai-narrow--light:
+ hash: v1.k794b7964.d82135caba2d77824e328d0d7145e62ca92b14e0fada7be2055ae91552400d81.Igj-vFsvnOnzz6SU2A15uZGUXlb8lZoYWnVOQF-kj7Y
scenes-app-llm-observability-evaluationmodelpicker--no-decision-models--dark:
hash: v1.k794b7964.ad9ea73d0bf9e87acd8bb321aea9f56ffc55508c18e8810349c60ef2102451a0.o954YssNcVBqGXNxkT01pYc9Pu0RworI3n76Bd5FBn8
scenes-app-llm-observability-evaluationmodelpicker--no-decision-models--light:
diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.py
index c07e592d123b..57e1bf35c176 100644
--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py
+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py
@@ -72,6 +72,8 @@ from products.ai_observability.backend.llm.errors import (
UnsupportedModelError,
provider_error_detail,
)
+from products.ai_observability.backend.llm.providers.openai import OPENAI_DECISIONS_BASE_URL
+from products.ai_observability.backend.llm.providers.openai_decisions import OpenAIDecisionAdapter
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 (
@@ -612,12 +614,14 @@ def call_llm_judge(
base_url = (
OPENROUTER_DECISIONS_BASE_URL
if provider == "openrouter"
+ else OPENAI_DECISIONS_BASE_URL
+ if provider == "openai"
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)
+ provider in ("system_one", "openai") and not decision_evaluations_enabled(team_id, base_url=base_url)
):
return build_skipped_evaluation_result(
output_type=output_type,
@@ -683,14 +687,20 @@ def call_llm_judge(
"evaluate them, even if the result would be a fail. Do not invent missing facts.\n\n" + prompt
)
)
- 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,
- )
+ api_key = provider_key.encrypted_config.get("api_key", "") if provider_key else ""
+ if provider == "openai":
+ decision_result = OpenAIDecisionAdapter().evaluate(
+ api_key=api_key, model=model, state=user_prompt, questions=questions
+ )
+ else:
+ decision_result = DecisionClient.evaluate(
+ api_key=api_key,
+ 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 = decision_result.answers["applicable"]
diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.py
index 952faab24a22..4675903ee581 100644
--- a/posthog/temporal/ai_observability/test_run_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_evaluation.py
@@ -355,12 +355,13 @@ def test_openrouter_catalogue_outage_only_affects_projects_with_decisions_enable
decide.assert_not_called()
[email protected]("provider,model", [("openrouter", "example/dual-model"), ("openai", "gpt-6-luna")])
@pytest.mark.parametrize("flag", [True, False, None])
@pytest.mark.parametrize("judge_method", [None, "llm"])
def test_legacy_and_explicit_llm_methods_use_chat_for_a_dual_capability_model(
- flag: bool | None, judge_method: str | None
+ provider: str, model: str, flag: bool | None, judge_method: str | None
) -> None:
- key = MagicMock(provider="openrouter", encrypted_config={"api_key": "example-token"})
+ key = MagicMock(provider=provider, encrypted_config={"api_key": "example-token"})
with (
patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,
patch(
@@ -370,9 +371,10 @@ def test_legacy_and_explicit_llm_methods_use_chat_for_a_dual_capability_model(
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,
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.OpenAIDecisionAdapter.evaluate") as native_decide,
):
spec.return_value.resolve.return_value = MagicMock(
- provider="openrouter", model="example/dual-model", provider_key=key, is_byok=True
+ provider=provider, model=model, provider_key=key, is_byok=True
)
complete.return_value = MagicMock(
parsed=BooleanEvalResult(verdict=True, reasoning="Meets the criteria."), usage=None
@@ -391,10 +393,160 @@ def test_legacy_and_explicit_llm_methods_use_chat_for_a_dual_capability_model(
)
complete.assert_called_once()
decide.assert_not_called()
+ native_decide.assert_not_called()
assert result["verdict"] is True
assert result["reasoning"] == "Meets the criteria."
[email protected]("applicable", [True, False])
+ "output_type,output_config,answers,expected",
+ [
+ (
+ "boolean",
+ {},
+ [{"name": "verdict", "type": "predicate", "probability": 0.5}],
+ {"verdict": True, "probability": 0.5},
+ ),
+ (
+ "categorical",
+ {
+ "selection_mode": "single",
+ "options": [{"key": "resolved", "label": "Resolved"}, {"key": "other", "label": "Other"}],
+ },
+ [
+ {
+ "name": "category",
+ "type": "choice",
+ "choice": "resolved",
+ "confidence": 0.8,
+ "probabilities": [
+ {"value": "resolved", "probability": 0.8},
+ {"value": "other", "probability": 0.2},
+ ],
+ }
+ ],
+ {"categories": ["resolved"]},
+ ),
+ (
+ "categorical",
+ {
+ "selection_mode": "multiple",
+ "options": [{"key": "resolved", "label": "Resolved"}, {"key": "other", "label": "Other"}],
+ },
+ [
+ {"name": "category_0", "type": "predicate", "probability": 0.7},
+ {"name": "category_1", "type": "predicate", "probability": 0.2},
+ ],
+ {"categories": ["resolved"]},
+ ),
+ (
+ "numeric",
+ {"min": 0, "max": 10, "step": 5, "passing_rule": {"operator": "gte", "threshold": 4.9}},
+ [
+ {
+ "name": "score",
+ "type": "score",
+ "score": 4.4099991,
+ "confidence": 1,
+ "probabilities": [{"value": index, "label": str(index), "probability": 0.1} for index in range(10)],
+ }
+ ],
+ {"score": 4.899999},
+ ),
+ ],
+)
+def test_openai_native_decisions_use_shared_result_semantics(
+ applicable: bool, output_type: str, output_config: dict, answers: list[dict], expected: dict
+) -> None:
+ team = Team(id=1, organization_id=uuid.uuid4(), uuid=uuid.uuid4())
+ evaluation = {
+ "id": "example-evaluation",
+ "name": "Response quality",
+ "team_id": 1,
+ "evaluation_config": {"prompt": "Evaluate the response quality.", "judge_method": "decision"},
+ "output_type": output_type,
+ "output_config": {**output_config, "allows_na": True},
+ }
+ payload = {
+ "model": "gpt-6-luna",
+ "answers": [
+ *answers,
+ {"name": "applicable", "type": "predicate", "probability": 0.9 if applicable else 0.1},
+ ],
+ "usage": {"input_tokens": 120, "output_tokens": 0},
+ }
+ response = httpx.Response(
+ 200,
+ headers={"Content-Type": "application/json"},
+ stream=httpx.ByteStream(json.dumps(payload).encode()),
+ )
+ 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("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 transport,
+ ):
+ teams.return_value.get.return_value = team
+ spec.return_value.resolve.return_value = MagicMock(
+ provider="openai",
+ model="gpt-6-luna",
+ is_byok=True,
+ provider_key=MagicMock(encrypted_config={"api_key": "example-token"}),
+ )
+ result = call_llm_judge(
+ evaluation=evaluation,
+ system_prompt="Unused chat instructions",
+ user_prompt="Example reply.",
+ allows_na=True,
+ )
+ sent = json.loads(transport.call_args.args[0].content)
+ assert sent["input"] == "Example reply."
+ assert result["applicable"] is applicable
+ assert result["reasoning"] == ""
+ assert result["input_tokens"] == 120
+ assert result["output_tokens"] == 0
+ for field, value in expected.items():
+ if not applicable and field in ("verdict", "score", "categories", "probability"):
+ assert result.get(field) is None
+ elif field == "score":
+ assert result["score"] == pytest.approx(value)
+ else:
+ assert result.get(field) == value
+ if output_type == "numeric":
+ assert len(sent["questions"][0]["levels"]) == 10
+ if applicable:
+ assert result["score"] < 4.9
+ if output_type != "boolean":
+ assert "probability" not in result
+
+
[email protected]("flag", [False, None])
+def test_openai_decisions_disabled_flag_skips_without_invalidating_key(flag: bool | None) -> None:
+ 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("httpx.AsyncHTTPTransport.handle_async_request") as transport,
+ ):
+ spec.return_value.resolve.return_value = MagicMock(
+ provider="openai",
+ model="gpt-6-luna",
+ is_byok=True,
+ provider_key=MagicMock(encrypted_config={"api_key": "example-token"}),
+ )
+ result = call_llm_judge(
+ evaluation={"team_id": 1, "evaluation_config": {"prompt": "Check the reply.", "judge_method": "decision"}},
+ system_prompt="",
+ user_prompt="Example reply.",
+ allows_na=False,
+ )
+ assert result["skip_reason"] == "system_one_unavailable"
+ assert "terminal_user_error" not in result
+ assert "provider_key_state" not in result
+ transport.assert_not_called()
+
+
@pytest.mark.parametrize("flag", [False, None])
@pytest.mark.parametrize("cached", [True, False])
def test_openrouter_decision_model_with_disabled_flag_skips_without_disabling(flag: bool | None, cached: bool) -> None:
@@ -923,8 +1075,18 @@ def test_endpoint_host_that_never_resolves_skips_the_run_with_the_reason() -> No
@pytest.mark.parametrize(
- "provider, success_payload",
+ "provider, success_payload, status, retry_after",
[
+ (
+ "openai",
+ {
+ "model": "gpt-6-luna",
+ "answers": [{"name": "verdict", "type": "predicate", "probability": 0.9}],
+ "usage": {"input_tokens": 12, "output_tokens": 0},
+ },
+ 503,
+ 60,
+ ),
(
"system_one",
{
@@ -932,6 +1094,8 @@ def test_endpoint_host_that_never_resolves_skips_the_run_with_the_reason() -> No
"answers": {"verdict": {"type": "noul", "noul": 0.9}},
"usage": {"input_tokens": 12, "output_tokens": 0},
},
+ 429,
+ 15,
),
(
"openai_compatible",
@@ -951,6 +1115,8 @@ def test_endpoint_host_that_never_resolves_skips_the_run_with_the_reason() -> No
}
],
},
+ 429,
+ 15,
),
],
)
@@ -962,10 +1128,14 @@ def test_endpoint_host_that_never_resolves_skips_the_run_with_the_reason() -> No
],
)
def test_custom_provider_rate_limit_retries_without_disabling_the_evaluation(
- provider: str, success_payload: dict[str, Any], attempt: int, reportable: bool
+ provider: str, success_payload: dict[str, Any], status: int, retry_after: int, attempt: int, reportable: bool
) -> None:
env = ActivityEnvironment()
env.info = dataclasses.replace(env.info, attempt=attempt)
+ evaluation = {
+ "team_id": 1,
+ "evaluation_config": {"prompt": "Polite?", **({"judge_method": "decision"} if provider == "openai" else {})},
+ }
key = MagicMock(
provider=provider,
encrypted_config={"api_key": "example-token", "base_url": "https://decisions.example.com/v1"},
@@ -977,7 +1147,7 @@ def test_custom_provider_rate_limit_retries_without_disabling_the_evaluation(
patch(
"httpx.AsyncHTTPTransport.handle_async_request",
side_effect=[
- httpx.Response(429, headers={"Retry-After": "15"}, stream=httpx.ByteStream(b"")),
+ httpx.Response(status, headers={"Retry-After": str(retry_after)}, stream=httpx.ByteStream(b"")),
httpx.Response(
200,
headers={"Content-Type": "application/json"},
@@ -987,12 +1157,15 @@ def test_custom_provider_rate_limit_retries_without_disabling_the_evaluation(
) as transport,
):
spec.return_value.resolve.return_value = MagicMock(
- provider=provider, model="example-judge-v1", provider_key=key, is_byok=True
+ provider=provider,
+ model="gpt-6-luna" if provider == "openai" else "example-judge-v1",
+ provider_key=key,
+ is_byok=True,
)
with pytest.raises(ApplicationError) as error:
env.run(
lambda: call_llm_judge(
- evaluation={"team_id": 1, "evaluation_config": {"prompt": "Polite?"}},
+ evaluation=evaluation,
system_prompt="",
user_prompt="Hello!",
allows_na=False,
@@ -1000,12 +1173,12 @@ def test_custom_provider_rate_limit_retries_without_disabling_the_evaluation(
)
assert not error.value.non_retryable
assert isinstance(error.value, NonReportableError) is not reportable
- assert error.value.next_retry_delay == timedelta(seconds=15)
+ assert error.value.next_retry_delay == timedelta(seconds=retry_after)
assert terminal_user_error_result_from_application_error(error.value, allows_na=False) is None
assert transport.call_count == 1
result = call_llm_judge(
- evaluation={"team_id": 1, "evaluation_config": {"prompt": "Polite?"}},
+ evaluation=evaluation,
system_prompt="",
user_prompt="Hello!",
allows_na=False,
diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.py
index 239a58d0c8f7..b37a5f47ed90 100644
--- a/products/ai_observability/backend/api/evaluations.py
+++ b/products/ai_observability/backend/api/evaluations.py
@@ -48,6 +48,7 @@ from ..hog import compile_ai_observability_hog
from ..llm import DEFAULT_MODEL_BY_PROVIDER
from ..llm.decisions import decision_evaluations_enabled, is_decision_model
from ..llm.errors import ProviderConnectionError
+from ..llm.providers.openai import OPENAI_DECISIONS_BASE_URL, OpenAIConfig
from ..llm.providers.openrouter import OPENROUTER_BASE_URL, is_non_chat_model
from ..models.evaluation_config import EvaluationConfig
from ..models.evaluation_configs import (
@@ -549,6 +550,10 @@ class EvaluationSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
decision_only=judge_method is None,
openrouter_enabled=model_provider == "openrouter"
and decision_evaluations_enabled(self.context["get_team"]().id, base_url=OPENROUTER_BASE_URL),
+ openai_enabled=judge_method == "decision"
+ and model_provider == LLMProvider.OPENAI
+ and model_configuration.get("model") in OpenAIConfig.DECISION_MODELS
+ and decision_evaluations_enabled(self.context["get_team"]().id, base_url=OPENAI_DECISIONS_BASE_URL),
)
except ProviderConnectionError as e:
raise serializers.ValidationError({"model_configuration": str(e)}) from e
@@ -648,6 +653,20 @@ class EvaluationSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
}
)
+ if uses_decision_model and output_type == "categorical":
+ model_configuration = self._effective_model_configuration(data) or {}
+ config = data.get("output_config", getattr(self.instance, "output_config", {}))
+ if (
+ model_configuration.get("provider") == LLMProvider.OPENAI
+ and config.get("selection_mode", "single") == "single"
+ and len(config.get("options", [])) < 2
+ ):
+ raise serializers.ValidationError(
+ {
+ "output_config": "OpenAI decision models require at least two options for single-selection categories."
+ }
+ )
+
# Sentiment is addressed per-message within one generation event ($ai_target_event_id +
# message index). An aggregate target emits a single evaluation event for the whole unit,
# where the message index is ambiguous and that per-generation linkage is absent.
diff --git a/products/ai_observability/backend/api/proxy.py b/products/ai_observability/backend/api/proxy.py
index 738dc319d578..041dddb94acc 100644
--- a/products/ai_observability/backend/api/proxy.py
+++ b/products/ai_observability/backend/api/proxy.py
@@ -63,6 +63,7 @@ from products.ai_observability.backend.llm.errors import (
ProviderHostUnresolvedError,
UnsupportedProviderError,
)
+from products.ai_observability.backend.llm.providers.openai import OPENAI_DECISIONS_BASE_URL, OpenAIConfig
from products.ai_observability.backend.llm.providers.openrouter import (
OPENROUTER_BASE_URL,
decision_model_ids,
@@ -562,6 +563,11 @@ class LLMProxyViewSet(viewsets.ViewSet):
decision_models = decision_model_ids() or frozenset()
non_chat_models = non_chat_model_ids() or frozenset()
models = list(dict.fromkeys([*models, *sorted(decision_models)]))
+ elif provider_key.provider == LLMProvider.OPENAI and decision_evaluations_enabled(
+ provider_key.team_id, base_url=OPENAI_DECISIONS_BASE_URL
+ ):
+ decision_models = OpenAIConfig.DECISION_MODELS
+ models = list(dict.fromkeys([*models, *sorted(decision_models)]))
return Response(
[
ModelInfo(
diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.py
index d196324b347c..31c47cd06933 100644
--- a/products/ai_observability/backend/api/test/test_evaluations.py
+++ b/products/ai_observability/backend/api/test/test_evaluations.py
@@ -216,10 +216,21 @@ class TestModelConfigurationSerializer(SimpleTestCase):
("unsupported_decision", "decision", "openai", ["text"], None),
("custom_chat", "llm", "system_one", ["decisions"], None),
("decision_only_chat", "llm", "openrouter", ["decisions"], None),
+ ("openai_decision", "decision", "openai", ["text"], True, "gpt-6-luna", True),
+ ("openai_legacy", None, "openai", ["text"], False, "gpt-6-luna", True),
+ ("openai_chat", "llm", "openai", ["text"], False, "gpt-6-luna", True),
+ ("openai_disabled", "decision", "openai", ["text"], None, "gpt-6-luna", False),
]
)
def test_judge_method_matches_model_capabilities(
- self, _name: str, method: str | None, provider: str, modalities: list[str], expected: bool | None
+ self,
+ _name: str,
+ method: str | None,
+ provider: str,
+ modalities: list[str],
+ expected: bool | None,
+ model: str = "example/model",
+ flag: bool = True,
) -> None:
config = {"prompt": "Check the response."}
if method:
@@ -229,11 +240,11 @@ class TestModelConfigurationSerializer(SimpleTestCase):
evaluation_config=config,
output_type="boolean",
output_config={},
- model_configuration=LLMModelConfiguration(provider=provider, model="example/model"),
+ model_configuration=LLMModelConfiguration(provider=provider, model=model),
)
serializer = EvaluationSerializer(instance=evaluation, partial=True, context={"get_team": lambda: Mock(id=1)})
with (
- patch("products.ai_observability.backend.api.evaluations.decision_evaluations_enabled", return_value=True),
+ patch("products.ai_observability.backend.api.evaluations.decision_evaluations_enabled", return_value=flag),
patch(
"products.ai_observability.backend.llm.providers.openrouter._model_output_modalities",
return_value={"example/model": modalities},
@@ -250,6 +261,36 @@ class TestModelConfigurationSerializer(SimpleTestCase):
validated = serializer.validate(data)
self.assertEqual(validated["evaluation_config"], config)
+ @parameterized.expand(
+ [
+ ({"name": "Renamed decision evaluation"}, True),
+ ({"enabled": False}, True),
+ ({"enabled": True}, False),
+ ({"output_config": {"allows_na": True}}, False),
+ ]
+ )
+ def test_native_decision_flag_off_allows_rename_and_disable(self, data: dict[str, object], valid: bool) -> None:
+ evaluation = Evaluation(
+ evaluation_type="llm_judge",
+ evaluation_config={"prompt": "Check the response.", "judge_method": "decision"},
+ enabled=data.get("enabled") is not True,
+ output_type="boolean",
+ output_config={},
+ model_configuration=LLMModelConfiguration(provider="openai", model="gpt-6-luna"),
+ )
+ serializer = EvaluationSerializer(
+ instance=evaluation, data=data, partial=True, context={"get_team": lambda: Mock(id=1)}
+ )
+ with patch(
+ "products.ai_observability.backend.api.evaluations.decision_evaluations_enabled", return_value=False
+ ):
+ self.assertEqual(serializer.is_valid(), valid, serializer.errors)
+ if valid:
+ for field, value in data.items():
+ self.assertEqual(serializer.validated_data[field], value)
+ else:
+ self.assertIn("model_configuration", serializer.errors)
+
def test_judge_method_change_validates_the_stored_model(self) -> None:
evaluation = Evaluation(
evaluation_type="llm_judge",
@@ -262,6 +303,30 @@ class TestModelConfigurationSerializer(SimpleTestCase):
with self.assertRaises(ValidationError):
serializer.validate({"evaluation_config": {"prompt": "Check the response.", "judge_method": "decision"}})
+ @parameterized.expand([("single", 1, False), ("single", 2, True), ("multiple", 1, True)])
+ def test_openai_category_question_matches_the_native_option_limits(
+ self, mode: str, count: int, valid: bool
+ ) -> None:
+ evaluation = Evaluation(
+ evaluation_type="llm_judge",
+ evaluation_config={"prompt": "Classify the reply.", "judge_method": "decision"},
+ output_type="categorical",
+ output_config={},
+ model_configuration=LLMModelConfiguration(provider="openai", model="gpt-6-luna"),
+ )
+ serializer = EvaluationSerializer(instance=evaluation, partial=True, context={"get_team": lambda: Mock(id=1)})
+ config = {
+ "selection_mode": mode,
+ "options": [{"key": f"option_{i}", "label": f"Option {i}"} for i in range(count)],
+ }
+ with patch("products.ai_observability.backend.api.evaluations.decision_evaluations_enabled", return_value=True):
+ if valid:
+ assert serializer.validate({"output_config": config})["output_config"]["selection_mode"] == mode
+ else:
+ with self.assertRaises(ValidationError) as error:
+ serializer.validate({"output_config": config})
+ assert "at least two options" in str(error.exception)
+
@parameterized.expand([("boolean", {}), ("categorical", {}), ("numeric", {"min": 0, "max": 10})])
def test_system_one_supports_evaluation_output_types(
self, output_type: str, output_config: dict[str, float]
diff --git a/products/ai_observability/backend/api/test/test_proxy.py b/products/ai_observability/backend/api/test/test_proxy.py
index 5d4fbd9aa9b2..6549a769e914 100644
--- a/products/ai_observability/backend/api/test/test_proxy.py
+++ b/products/ai_observability/backend/api/test/test_proxy.py
@@ -365,6 +365,31 @@ class TestPlaygroundModelEnforcement(APIBaseTest):
returned_ids = {m["id"] for m in response.json()}
assert returned_ids == PLAYGROUND_MODEL_IDS
+ @parameterized.expand([(True,), (False,)])
+ def test_openai_decision_models_use_the_existing_key(self, flag: bool) -> None:
+ key = LLMProviderKey.objects.create(
+ team=self.team,
+ provider="openai",
+ name="OpenAI",
+ state=LLMProviderKey.State.OK,
+ encrypted_config={"api_key": "example-token"},
+ created_by=self.user,
+ )
+ with (
+ patch("products.ai_observability.backend.api.proxy.Client.list_models", return_value=["gpt-5-mini"]),
+ patch("products.ai_observability.backend.api.proxy.decision_evaluations_enabled", return_value=flag),
+ ):
+ 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["gpt-5-mini"]["supports_decisions"] is False
+ assert models["gpt-5-mini"]["supports_chat"] is True
+ assert ("gpt-6-luna" in models) is flag
+ if flag:
+ assert models["gpt-6-luna"]["supports_decisions"] is True
+ assert models["gpt-6-luna"]["supports_chat"] is True
+ assert models["gpt-6-luna"]["provider"] == "OpenAI"
+
@parameterized.expand([(True,), (False,)])
def test_openrouter_decision_models_use_the_existing_key(self, flag: bool) -> None:
key = LLMProviderKey.objects.create(
diff --git a/products/ai_observability/backend/llm/decisions.py b/products/ai_observability/backend/llm/decisions.py
index b3c6aae4c015..7f2a720655e9 100644
--- a/products/ai_observability/backend/llm/decisions.py
+++ b/products/ai_observability/backend/llm/decisions.py
@@ -35,14 +35,22 @@ from products.ai_observability.backend.llm.errors import (
is_context_window_error_message,
)
from products.ai_observability.backend.llm.providers._diagnostics import tagged_http_client
+from products.ai_observability.backend.llm.providers.openai import OpenAIConfig
from products.ai_observability.backend.llm.providers.openrouter import OPENROUTER_HEADERS, decision_model_ids
def is_decision_model(
- provider: str | None, model: str | None, *, openrouter_enabled: bool, decision_only: bool = False
+ provider: str | None,
+ model: str | None,
+ *,
+ openrouter_enabled: bool,
+ decision_only: bool = False,
+ openai_enabled: bool = False,
) -> bool:
if provider == "system_one":
return True
+ if provider == "openai":
+ return openai_enabled and model in OpenAIConfig.DECISION_MODELS
# Disabled projects keep the chat path independent of catalogue availability.
if provider != "openrouter" or not model or not openrouter_enabled:
return False
diff --git a/products/ai_observability/backend/llm/providers/openai.py b/products/ai_observability/backend/llm/providers/openai.py
index 2fed3093e5fc..898e2b853f88 100644
--- a/products/ai_observability/backend/llm/providers/openai.py
+++ b/products/ai_observability/backend/llm/providers/openai.py
@@ -47,12 +47,16 @@ from products.ai_observability.backend.providers.formatters.tools_handler import
logger = logging.getLogger(__name__)
+OPENAI_DECISIONS_BASE_URL = "https://api.openai.com/v1"
+
class OpenAIConfig:
REASONING_EFFORT: ReasoningEffort = "medium"
TEMPERATURE: float = 0
TIMEOUT: float = 300.0
+ DECISION_MODELS: frozenset[str] = frozenset({"gpt-6-luna"})
+
SUPPORTED_MODELS: list[str] = [
"gpt-5.4",
"gpt-5.2",
diff --git a/products/ai_observability/backend/llm/providers/openai_decisions.py b/products/ai_observability/backend/llm/providers/openai_decisions.py
new file mode 100644
index 000000000000..6484bfc62078
--- /dev/null
+++ b/products/ai_observability/backend/llm/providers/openai_decisions.py
@@ -0,0 +1,174 @@
+from collections.abc import Mapping
+from typing import cast
+
+import openai
+
+from posthog.llm.system_one import (
+ ChoiceQuestion,
+ JsonValue,
+ NoulQuestion,
+ Question,
+ ScoreQuestion,
+ SystemOneRequestFailed,
+ SystemOneResult,
+ parse_system_one_response,
+)
+from posthog.security.url_validation import validate_url_and_pin_ips
+
+from products.ai_observability.backend.llm.decisions import DecisionRateLimitError
+from products.ai_observability.backend.llm.errors import (
+ AuthenticationError,
+ ProviderConnectionError,
+ ProviderRequestRejectedError,
+ QuotaExceededError,
+ StructuredOutputParseError,
+)
+from products.ai_observability.backend.llm.providers._diagnostics import tagged_http_client
+from products.ai_observability.backend.llm.providers.openai import OPENAI_DECISIONS_BASE_URL, OpenAIAdapter
+
+
+class OpenAIDecisionAdapter(OpenAIAdapter):
+ @staticmethod
+ def _text(value: JsonValue) -> str:
+ if not isinstance(value, str):
+ raise ValueError("OpenAI decision criteria must be text.")
+ return value
+
+ @classmethod
+ def _question(cls, name: str, question: Question) -> dict[str, JsonValue]:
+ instructions = cls._text(question.instructions)
+ body: dict[str, JsonValue] = {"name": name, "instructions": instructions}
+ if isinstance(question, NoulQuestion):
+ body["type"] = "predicate"
+ for label, criteria in (("True", question.criteria_true), ("False", question.criteria_false)):
+ if criteria is not None:
+ instructions += f"\n{label}: {cls._text(criteria)}"
+ body["instructions"] = instructions
+ elif isinstance(question, ChoiceQuestion):
+ if len(question.criteria) < 2:
+ raise ValueError("OpenAI decision choices require at least two options.")
+ body["type"] = "choice"
+ body["choices"] = [
+ {"value": value, **({"description": cls._text(description)} if description is not None else {})}
+ for value, description in question.criteria.items()
+ ]
+ else:
+ body["type"] = "score"
+ body["levels"] = [
+ {"label": str(index), "description": cls._text(criteria)}
+ for index, criteria in enumerate(question.criteria)
+ ]
+ return body
+
+ @staticmethod
+ def _probabilities(raw: object, question: ChoiceQuestion | ScoreQuestion) -> dict[str, JsonValue]:
+ if not isinstance(raw, list):
+ raise ValueError("The OpenAI decision response contains invalid probabilities.")
+ options = (
+ set(question.criteria)
+ if isinstance(question, ChoiceQuestion)
+ else {str(index) for index in range(len(question.criteria))}
+ )
+ probabilities: dict[str, JsonValue] = {}
+ for item in raw:
+ if not isinstance(item, dict):
+ raise ValueError("The OpenAI decision response contains an invalid probability.")
+ value = item.get("value")
+ if isinstance(question, ScoreQuestion):
+ if isinstance(value, bool) or not isinstance(value, int):
+ raise ValueError("The OpenAI decision response contains an invalid score level.")
+ value = str(value)
+ if not isinstance(value, str) or value not in options or value in probabilities:
+ raise ValueError("The OpenAI decision response contains an unexpected or duplicate option.")
+ probabilities[value] = item.get("probability")
+ return probabilities
+
+ @classmethod
+ def _parse(cls, payload: object, questions: Mapping[str, Question]) -> SystemOneResult:
+ if not isinstance(payload, dict) or not isinstance(payload.get("answers"), list):
+ raise ValueError("The OpenAI decision response contains no answers.")
+ answers: dict[str, JsonValue] = {}
+ for raw in payload["answers"]:
+ if not isinstance(raw, dict):
+ raise ValueError("The OpenAI decision response contains an invalid answer.")
+ name = raw.get("name")
+ if not isinstance(name, str) or name not in questions or name in answers:
+ raise ValueError("The OpenAI decision response contains an unexpected or duplicate answer.")
+ answer = dict(raw)
+ question = questions[name]
+ expected_type = (
+ "predicate"
+ if isinstance(question, NoulQuestion)
+ else "choice"
+ if isinstance(question, ChoiceQuestion)
+ else "score"
+ )
+ if answer.get("type") not in (expected_type, "refusal"):
+ raise ValueError("The OpenAI decision response contains an unexpected answer type.")
+ if answer.get("type") == "predicate":
+ answer["type"] = "noul"
+ answer["noul"] = answer.pop("probability", None)
+ elif answer.get("type") in ("choice", "score"):
+ assert isinstance(question, ChoiceQuestion | ScoreQuestion)
+ answer["probabilities"] = cls._probabilities(answer.get("probabilities"), question)
+ answers[name] = cast(JsonValue, answer)
+ # The shared parser validates answer types, finite scores, and every requested option.
+ return parse_system_one_response({**payload, "answers": answers}, questions)
+
+ def evaluate(
+ self,
+ *,
+ api_key: str,
+ model: str,
+ state: str,
+ questions: Mapping[str, Question],
+ ) -> SystemOneResult:
+ if not api_key:
+ raise AuthenticationError("Add an OpenAI API key to run decision evaluations.")
+ try:
+ body = {
+ "model": model,
+ "input": state,
+ "questions": [self._question(name, q) for name, q in questions.items()],
+ }
+ except ValueError as error:
+ raise ProviderRequestRejectedError(str(error)) from error
+ try:
+ verdict = validate_url_and_pin_ips(OPENAI_DECISIONS_BASE_URL)
+ if not verdict.allowed:
+ raise ProviderConnectionError("Could not reach the OpenAI decision endpoint. Try again.")
+ with openai.OpenAI(
+ api_key=api_key,
+ base_url=OPENAI_DECISIONS_BASE_URL,
+ max_retries=0,
+ timeout=60,
+ http_client=tagged_http_client(
+ pin=(OPENAI_DECISIONS_BASE_URL, verdict.pinned_ips),
+ timeout=60,
+ total_timeout=60,
+ follow_redirects=False,
+ ),
+ ) as client:
+ # The installed SDK's generic POST supports this endpoint without a repo-wide SDK upgrade.
+ payload = client.post("/decisions", body=body, cast_to=object)
+ return self._parse(payload, questions)
+ except openai.APIError as error:
+ mapped = self._mapped_error(error, model)
+ if (
+ isinstance(error, openai.APIStatusError)
+ and error.status_code in (429, 503, 529)
+ and not isinstance(mapped, QuotaExceededError)
+ ):
+ raise DecisionRateLimitError(error.response.headers.get("Retry-After")) from error
+ if mapped is not None:
+ raise mapped from error
+ if isinstance(error, openai.APIStatusError):
+ if error.status_code >= 500 or error.status_code in (408, 409) or 300 <= error.status_code < 400:
+ raise ProviderConnectionError(
+ "The OpenAI decision endpoint is temporarily unavailable. Try again."
+ ) from error
+ raise ProviderRequestRejectedError(
+ "OpenAI rejected the decision request. Check the model and criteria."
+ ) from error
+ except (ValueError, SystemOneRequestFailed) as error:
+ raise StructuredOutputParseError("OpenAI returned an invalid decision response.") from error
diff --git a/products/ai_observability/backend/llm/providers/test/test_openai_decisions.py b/products/ai_observability/backend/llm/providers/test/test_openai_decisions.py
new file mode 100644
index 000000000000..c24031317a5a
--- /dev/null
+++ b/products/ai_observability/backend/llm/providers/test/test_openai_decisions.py
@@ -0,0 +1,301 @@
+import json
+import asyncio
+from collections.abc import Iterator
+from contextlib import nullcontext
+from ipaddress import ip_address
+
+import pytest
+from unittest.mock import patch
+
+import httpx
+import httpcore
+
+from posthog.llm.system_one import (
+ ChoiceAnswer,
+ ChoiceQuestion,
+ NoulAnswer,
+ NoulQuestion,
+ Question,
+ RefusalAnswer,
+ ScoreAnswer,
+ ScoreQuestion,
+)
+
+from products.ai_observability.backend.llm.errors import (
+ AuthenticationError,
+ ModelNotFoundError,
+ ModelPermissionError,
+ ProviderConnectionError,
+ ProviderRequestRejectedError,
+ QuotaExceededError,
+ RetryableRateLimitError,
+ StructuredOutputParseError,
+)
+from products.ai_observability.backend.llm.providers.openai_decisions import OpenAIDecisionAdapter
+
+
[email protected](autouse=True)
+def pin_endpoint() -> Iterator[None]:
+ with patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")}):
+ yield
+
+
+def _json_response(status: int, payload: object, headers: dict[str, str] | None = None) -> httpx.Response:
+ return httpx.Response(
+ status,
+ headers={"Content-Type": "application/json", **(headers or {})},
+ stream=httpx.ByteStream(json.dumps(payload).encode()),
+ )
+
+
+def test_native_questions_and_answers() -> None:
+ questions: dict[str, Question] = {
+ "verdict": NoulQuestion(
+ instructions="Is the reply helpful?", criteria_true="Helpful", criteria_false="Unhelpful"
+ ),
+ "category": ChoiceQuestion(
+ instructions="Classify the reply.", criteria={"resolved": "Solved", "other": "Other"}
+ ),
+ "score": ScoreQuestion(instructions="Rate the reply.", criteria=["Poor", "Good", "Excellent"]),
+ "applicable": NoulQuestion(instructions="Are the criteria relevant?"),
+ }
+ response = _json_response(
+ 200,
+ payload={
+ "model": "gpt-6-luna",
+ "answers": [
+ {
+ "name": "score",
+ "type": "score",
+ "score": 1.5,
+ "confidence": 0.5,
+ "probabilities": [
+ {"value": 0, "label": "0", "probability": 0},
+ {"value": 1, "label": "1", "probability": 0.5},
+ {"value": 2, "label": "2", "probability": 0.5},
+ ],
+ },
+ {
+ "name": "category",
+ "type": "choice",
+ "choice": "resolved",
+ "confidence": 0.8,
+ "probabilities": [
+ {"value": "resolved", "probability": 0.8},
+ {"value": "other", "probability": 0.2},
+ ],
+ },
+ {"name": "verdict", "type": "predicate", "probability": 0.7},
+ {"name": "applicable", "type": "refusal"},
+ ],
+ "usage": {"input_tokens": 120, "output_tokens": 0},
+ },
+ )
+ with patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response) as transport:
+ result = OpenAIDecisionAdapter().evaluate(
+ api_key="example-token", model="gpt-6-luna", state="Hello!", questions=questions
+ )
+
+ request = transport.call_args.args[0]
+ assert str(request.url) == "https://api.openai.com/v1/decisions"
+ assert request.headers["Authorization"] == "Bearer example-token"
+ sent = json.loads(request.content)
+ assert sent["input"] == "Hello!"
+ assert sent["model"] == "gpt-6-luna"
+ assert sent["questions"] == [
+ {
+ "name": "verdict",
+ "type": "predicate",
+ "instructions": "Is the reply helpful?\nTrue: Helpful\nFalse: Unhelpful",
+ },
+ {
+ "name": "category",
+ "type": "choice",
+ "instructions": "Classify the reply.",
+ "choices": [
+ {"value": "resolved", "description": "Solved"},
+ {"value": "other", "description": "Other"},
+ ],
+ },
+ {
+ "name": "score",
+ "type": "score",
+ "instructions": "Rate the reply.",
+ "levels": [
+ {"label": "0", "description": "Poor"},
+ {"label": "1", "description": "Good"},
+ {"label": "2", "description": "Excellent"},
+ ],
+ },
+ {"name": "applicable", "type": "predicate", "instructions": "Are the criteria relevant?"},
+ ]
+ assert result.answers["verdict"] == NoulAnswer(probability=0.7)
+ assert result.answers["category"] == ChoiceAnswer(
+ choice="resolved", confidence=0.8, probabilities={"resolved": 0.8, "other": 0.2}
+ )
+ assert result.answers["score"] == ScoreAnswer(score=1.5, confidence=0.5, probabilities={"0": 0, "1": 0.5, "2": 0.5})
+ assert isinstance(result.answers["applicable"], RefusalAnswer)
+ assert (result.input_tokens, result.output_tokens) == (120, 0)
+
+
+ "answers",
+ [
+ [],
+ [{"name": "other", "type": "predicate", "probability": 0.9}],
+ [{"name": "verdict", "type": "predicate", "probability": 0.9}] * 2,
+ [{"name": "verdict", "type": "predicate", "probability": True}],
+ [{"name": "verdict", "type": "predicate", "probability": "0.9"}],
+ [{"name": "verdict", "type": "predicate", "probability": 1.1}],
+ [{"name": "verdict", "type": "noul", "noul": 0.9}],
+ [{"name": "verdict", "type": "choice", "choice": "true", "confidence": 1, "probabilities": []}],
+ ],
+)
+def test_invalid_answers_are_rejected(answers: object) -> None:
+ response = _json_response(200, payload={"model": "gpt-6-luna", "answers": answers})
+ with (
+ patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response),
+ pytest.raises(StructuredOutputParseError),
+ ):
+ OpenAIDecisionAdapter().evaluate(
+ api_key="example-token",
+ model="gpt-6-luna",
+ state="Hello!",
+ questions={"verdict": NoulQuestion(instructions="Is this a greeting?")},
+ )
+
+
+def test_invalid_json_is_a_structured_output_error() -> None:
+ response = httpx.Response(200, headers={"Content-Type": "application/json"}, stream=httpx.ByteStream(b"{"))
+ with (
+ patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response),
+ pytest.raises(StructuredOutputParseError),
+ ):
+ OpenAIDecisionAdapter().evaluate(
+ api_key="example-token",
+ model="gpt-6-luna",
+ state="Example reply.",
+ questions={"verdict": NoulQuestion(instructions="Is this a greeting?")},
+ )
+
+
[email protected]("values", [[0, 0, 2], [0, 1, 3], [False, 1, 2], [0.0, 1, 2]])
+def test_native_score_probabilities_keep_integer_level_identity(values: list[object]) -> None:
+ response = _json_response(
+ 200,
+ payload={
+ "model": "gpt-6-luna",
+ "answers": [
+ {
+ "name": "score",
+ "type": "score",
+ "score": 1.5,
+ "confidence": 0.5,
+ "probabilities": [{"value": value, "label": str(value), "probability": 0.5} for value in values],
+ }
+ ],
+ },
+ )
+ with (
+ patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response),
+ pytest.raises(StructuredOutputParseError),
+ ):
+ OpenAIDecisionAdapter().evaluate(
+ api_key="example-token",
+ model="gpt-6-luna",
+ state="Example reply.",
+ questions={"score": ScoreQuestion(instructions="Rate the reply.", criteria=["Poor", "Good", "Excellent"])},
+ )
+
+
+ "status,code,expected",
+ [
+ (401, "invalid_api_key", AuthenticationError),
+ (403, "permission_denied", ModelPermissionError),
+ (404, "model_not_found", ModelNotFoundError),
+ (408, "request_timeout", ProviderConnectionError),
+ (409, "conflict", ProviderConnectionError),
+ (429, "insufficient_quota", QuotaExceededError),
+ (429, "rate_limit_exceeded", RetryableRateLimitError),
+ (500, "internal_error", ProviderConnectionError),
+ (503, "unavailable", RetryableRateLimitError),
+ (529, "overloaded", RetryableRateLimitError),
+ (307, "redirect", ProviderConnectionError),
+ (422, "invalid_request", ProviderRequestRejectedError),
+ ],
+)
+def test_http_errors_keep_retryable_and_terminal_failures_distinct(
+ status: int, code: str, expected: type[Exception]
+) -> None:
+ response = _json_response(
+ status,
+ payload={"error": {"code": code, "message": "Example provider error", "type": code}},
+ headers={"retry-after": "12", "Location": "https://redirect.example.com/decisions"},
+ )
+ with (
+ patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response) as transport,
+ pytest.raises(expected) as error,
+ ):
+ OpenAIDecisionAdapter().evaluate(
+ api_key="example-token",
+ model="gpt-6-luna",
+ state="Hello!",
+ questions={"verdict": NoulQuestion(instructions="Is this a greeting?")},
+ )
+ assert transport.call_count == 1
+ if isinstance(error.value, RetryableRateLimitError):
+ assert error.value.retry_after == 12
+
+
[email protected]("error", [httpx.ConnectError("DNS unavailable"), httpx.ReadTimeout("Timed out"), None])
+def test_transport_failure_is_retryable(error: httpx.RequestError | None) -> None:
+ with (
+ patch("httpx.AsyncHTTPTransport.handle_async_request", side_effect=error),
+ patch("posthog.security.url_validation.resolve_host_ips", return_value=set())
+ if error is None
+ else nullcontext(),
+ pytest.raises(ProviderConnectionError),
+ ):
+ OpenAIDecisionAdapter().evaluate(
+ api_key="example-token",
+ model="gpt-6-luna",
+ state="Hello!",
+ questions={"verdict": NoulQuestion(instructions="Is this a greeting?")},
+ )
+
+
[email protected]("phase", ["headers", "body"])
+def test_total_request_deadline_closes_slow_connections(phase: str) -> None:
+ clock = [0.0]
+ stream = httpcore.AsyncMockStream([])
+ reads = 0
+
+ async def read(max_bytes: int, timeout: float | None = None) -> bytes:
+ nonlocal reads
+ reads += 1
+ clock[0] += 1
+ await asyncio.sleep(0)
+ if phase == "headers":
+ return b"HTTP/1.1 200 OK\r\nX-Slow: " if reads == 1 else b"x"
+ return b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" if reads == 1 else b"1\r\nx\r\n"
+
+ response = httpx.Response(
+ 200,
+ json={"model": "gpt-6-luna", "answers": [{"name": "verdict", "type": "predicate", "probability": 0.9}]},
+ )
+ with (
+ patch("asyncio.BaseEventLoop.time", side_effect=lambda: clock[0]),
+ patch("httpx.HTTPTransport.handle_request", return_value=response),
+ patch("httpcore.AnyIOBackend.connect_tcp", return_value=stream),
+ patch.object(stream, "read", side_effect=read),
+ patch.object(stream, "aclose", wraps=stream.aclose) as close,
+ pytest.raises(ProviderConnectionError),
+ ):
+ OpenAIDecisionAdapter().evaluate(
+ api_key="example-token",
+ model="gpt-6-luna",
+ state="Hello!",
+ questions={"verdict": NoulQuestion(instructions="Is this a greeting?")},
+ )
+ close.assert_awaited()
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationModelPicker.stories.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationModelPicker.stories.tsx
index 0c0d508f9dd2..e5b6b372b3e6 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationModelPicker.stories.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationModelPicker.stories.tsx
@@ -9,52 +9,71 @@ import { llmEvaluationLogic } from '../llmEvaluationLogic'
import type { JudgeMethod } from '../types'
import { EvaluationModelPicker } from './EvaluationModelPicker'
-const meta: Meta<{ method?: JudgeMethod; narrow?: boolean; empty?: boolean }> = {
+const meta: Meta<{ method?: JudgeMethod; narrow?: boolean; empty?: boolean; nativeOpenAI?: boolean }> = {
title: 'Scenes-App/LLM observability/EvaluationModelPicker',
component: EvaluationModelPicker,
parameters: {
layout: 'padded',
featureFlags: [FEATURE_FLAGS.LLM_ANALYTICS_SYSTEM_ONE_EVALUATIONS],
},
- render: ({ method = 'llm', narrow = false, empty = false }) => {
+ render: ({ method = 'llm', narrow = false, empty = false, nativeOpenAI = false }) => {
useStorybookMocks({
get: {
'/api/environments/:team_id/llm_analytics/provider_keys/': {
results: [
- { id: 'example-openrouter-key', name: 'OpenRouter', provider: 'openrouter', state: 'ok' },
+ nativeOpenAI
+ ? { id: 'example-openai-key', name: 'OpenAI', provider: 'openai', state: 'ok' }
+ : { id: 'example-openrouter-key', name: 'OpenRouter', provider: '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.has('provider_key_id')
- ? [
- {
- id: 'example/chat-model',
- name: 'example/chat-model',
- provider: 'OpenRouter',
- supports_chat: true,
- supports_decisions: false,
- },
- ...(!empty
- ? [
- {
- id: 'example/decision-model',
- name: 'example/decision-model',
- provider: 'OpenRouter',
- supports_chat: false,
- supports_decisions: true,
- },
- {
- id: 'example/dual-model',
- name: 'example/dual-model',
- provider: 'OpenRouter',
- supports_chat: true,
- supports_decisions: true,
- },
- ]
- : []),
- ]
+ ? nativeOpenAI
+ ? [
+ {
+ id: 'gpt-5-mini',
+ name: 'gpt-5-mini',
+ provider: 'OpenAI',
+ supports_chat: true,
+ supports_decisions: false,
+ },
+ {
+ id: 'gpt-6-luna',
+ name: 'gpt-6-luna',
+ provider: 'OpenAI',
+ supports_chat: true,
+ supports_decisions: true,
+ },
+ ]
+ : [
+ {
+ id: 'example/chat-model',
+ name: 'example/chat-model',
+ provider: 'OpenRouter',
+ supports_chat: true,
+ supports_decisions: false,
+ },
+ ...(!empty
+ ? [
+ {
+ id: 'example/decision-model',
+ name: 'example/decision-model',
+ provider: 'OpenRouter',
+ supports_chat: false,
+ supports_decisions: true,
+ },
+ {
+ id: 'example/dual-model',
+ name: 'example/dual-model',
+ provider: 'OpenRouter',
+ supports_chat: true,
+ supports_decisions: true,
+ },
+ ]
+ : []),
+ ]
: [],
],
'/api/projects/:team_id/evaluations/example-evaluation/': {
@@ -89,3 +108,5 @@ export const Decision: Story = { args: { method: 'decision' } }
export const DecisionNarrow: Story = { args: { method: 'decision', narrow: true } }
export const NoDecisionModels: Story = { args: { method: 'decision', empty: true } }
export const FlagOff: Story = { parameters: { featureFlags: [] } }
+export const NativeOpenAI: Story = { args: { method: 'decision', nativeOpenAI: true } }
+export const NativeOpenAINarrow: Story = { args: { method: 'decision', nativeOpenAI: true, narrow: true } }
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
index a62c7b9dd7c4..bf9b9d0b4570 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
@@ -1751,9 +1751,14 @@ return result`,
}
)
- it.each(['llm', 'decision'] as const)(
- 'keeps compatible models and custom deployments when selecting %s',
- async (method) => {
+ it.each([
+ ['llm', 'openrouter', 'OpenRouter', 'key-3'],
+ ['decision', 'openrouter', 'OpenRouter', 'key-3'],
+ ['llm', 'openai', 'OpenAI', 'key-1'],
+ ['decision', 'openai', 'OpenAI', 'key-1'],
+ ] as const)(
+ 'keeps compatible models and custom deployments when selecting %s for %s',
+ async (method, provider, displayName, keyId) => {
useMocks({
get: {
'/api/environments/:teamId/llm_analytics/provider_keys/': {
@@ -1769,26 +1774,26 @@ return result`,
},
'/api/llm_proxy/models/': ({ request }) => [
200,
- new URL(request.url).searchParams.get('provider_key_id') === 'key-3'
+ new URL(request.url).searchParams.get('provider_key_id') === keyId
? [
{
id: 'example/dual-model',
name: 'example/dual-model',
- provider: 'OpenRouter',
+ provider: displayName,
supports_decisions: true,
supports_chat: true,
},
{
id: 'example/chat-model',
name: 'example/chat-model',
- provider: 'OpenRouter',
+ provider: displayName,
supports_decisions: false,
supports_chat: true,
},
{
id: 'example/decision-model',
name: 'example/decision-model',
- provider: 'OpenRouter',
+ provider: displayName,
supports_decisions: true,
supports_chat: false,
},
@@ -1800,7 +1805,7 @@ return result`,
await expectLogic(keysLogic, () => keysLogic.actions.loadProviderKeys()).toFinishAllListeners()
await expectLogic(modelPickerLogic).toFinishAllListeners()
await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
- logic.actions.selectModelFromPicker('example/dual-model', 'key-3')
+ logic.actions.selectModelFromPicker('example/dual-model', keyId)
logic.actions.setJudgeMethod(method === 'llm' ? 'decision' : 'llm')
logic.actions.saveEvaluationSuccess(logic.values.evaluation!)
expect(logic.values.hasUnsavedChanges).toBe(false)
@@ -1808,9 +1813,9 @@ return result`,
expect(logic.values.judgeMethod).toBe(method)
expect(logic.values.hasUnsavedChanges).toBe(true)
expect(logic.values.evaluation?.model_configuration).toEqual({
- provider: 'openrouter',
+ provider,
model: 'example/dual-model',
- provider_key_id: 'key-3',
+ provider_key_id: keyId,
})
expect(logic.values.evaluation?.evaluation_config).toEqual({ prompt: '', judge_method: method })
expect(logic.values.judgeModelGroups.flatMap((group) => group.models.map((model) => model.id))).toEqual(
@@ -2098,6 +2103,105 @@ return result`,
})
})
+ describe('saveEvaluation updates', () => {
+ it.each([
+ { change: 'name', expected: { name: 'Renamed decision evaluation' }, rejected: false },
+ { change: 'disable', expected: { enabled: false }, rejected: false },
+ { change: 'enable', expected: { enabled: true }, rejected: true },
+ {
+ change: 'output_config',
+ expected: { output_config: { allows_na: true } },
+ rejected: true,
+ },
+ {
+ change: 'model_configuration',
+ expected: {
+ model_configuration: { provider: 'openai', model: 'gpt-5-mini', provider_key_id: 'key-1' },
+ },
+ rejected: true,
+ },
+ {
+ change: 'sentiment',
+ expected: {
+ evaluation_type: 'sentiment',
+ evaluation_config: { source: 'user_messages' },
+ output_type: 'sentiment',
+ output_config: {},
+ model_configuration: null,
+ },
+ rejected: false,
+ },
+ ] as const)(
+ 'sends only $change changes when the decision flag is off',
+ async ({ change, expected, rejected }) => {
+ const evaluation: EvaluationConfig = {
+ ...mockEvaluation,
+ enabled: change !== 'enable',
+ evaluation_type: 'llm_judge',
+ evaluation_config: { prompt: 'Is this response helpful?', judge_method: 'decision' },
+ output_type: 'boolean',
+ output_config: { allows_na: false },
+ model_configuration: { provider: 'openai', model: 'gpt-6-luna', provider_key_id: 'key-1' },
+ }
+ let savedPayload: unknown
+ const pushSpy = jest.spyOn(router.actions, 'push').mockImplementation(() => {})
+ useMocks({
+ get: { '/api/projects/:teamId/evaluations/:id/': evaluation },
+ patch: {
+ '/api/projects/:teamId/evaluations/:id/': async ({ request }) => {
+ savedPayload = await request.json()
+ return rejected
+ ? [
+ 400,
+ {
+ model_configuration: [
+ 'Decision evaluations are not available for this project.',
+ ],
+ },
+ ]
+ : { ...evaluation, ...expected }
+ },
+ },
+ })
+ logic = llmEvaluationLogic({ evaluationId: 'eval-123' })
+ logic.mount()
+
+ try {
+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
+ logic.actions.setModelConfiguration({ ...evaluation.model_configuration! })
+ logic.actions.setAllowsNA(true)
+ logic.actions.setAllowsNA(false)
+ switch (change) {
+ case 'name':
+ logic.actions.setEvaluationName(expected.name)
+ break
+ case 'disable':
+ case 'enable':
+ logic.actions.setEvaluationEnabled(expected.enabled)
+ break
+ case 'output_config':
+ logic.actions.setAllowsNA(true)
+ break
+ case 'model_configuration':
+ logic.actions.setModelConfiguration(expected.model_configuration)
+ break
+ case 'sentiment':
+ logic.actions.setEvaluationType('sentiment')
+ break
+ }
+ logic.actions.saveEvaluation()
+
+ await expectLogic(logic)
+ .toDispatchActions([rejected ? 'saveEvaluationFailure' : 'saveEvaluationSuccess'])
+ .toMatchValues({ evaluationFormSubmitting: false })
+ expect(savedPayload).toEqual(expected)
+ } finally {
+ pushSpy.mockRestore()
+ }
+ }
+ )
+ })
+
describe('saveEvaluation report persistence', () => {
it('does not create an evaluation when the report threshold is invalid', async () => {
let evaluationCreateCount = 0
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
index 3a6081379855..327def5497e5 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
@@ -5,6 +5,7 @@ import posthog from 'posthog-js'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { objectsEqual } from 'lib/utils/objects'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -1383,15 +1384,24 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
return
}
+ // Unchanged configuration triggers capability checks that can block rename/disable after flag-off.
+ const evaluationData = isNew
+ ? values.evaluation
+ : Object.fromEntries(
+ Object.entries(values.evaluation).filter(
+ ([field, value]) =>
+ !objectsEqual(value, values.originalEvaluation?.[field as keyof EvaluationConfig])
+ )
+ )
const response = (isNew
? await evaluationsCreate(
teamId.toString(),
- values.evaluation as Parameters<typeof evaluationsCreate>[1]
+ evaluationData as Parameters<typeof evaluationsCreate>[1]
)
: await evaluationsPartialUpdate(
teamId.toString(),
props.evaluationId,
- values.evaluation as Parameters<typeof evaluationsPartialUpdate>[2]
+ evaluationData as Parameters<typeof evaluationsPartialUpdate>[2]
)) as unknown as EvaluationConfig
actions.saveEvaluationSuccess(response)
// The list and the self-driving table read from llmEvaluationsLogic, which only