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 categorical system one and bound endpoint requests (#108615)

Bernat Torres5c1859434085
diff --git a/docs/internal/ai-observability-judge-inputs.md b/docs/internal/ai-observability-judge-inputs.md
index d11b6696e5e5..33bd5eafce8e 100644
--- a/docs/internal/ai-observability-judge-inputs.md
+++ b/docs/internal/ai-observability-judge-inputs.md
@@ -58,14 +58,24 @@ 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.
-HTTP timeouts apply to individual network operations, as with OpenAI-compatible BYOK connections; this integration does not impose a total request deadline or a response-size limit.
+System One 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.
+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.
Select the connection and configured model on each evaluation; these connections cannot become the shared active provider key used by other AI features.
Provider keys keep the provider they were created with; switching providers requires a new key.
The evaluation integration uses Noul for boolean outputs, with the same formatted text for generation, trace, and session targets.
-The product client reuses the request builder and response parser in `posthog/llm/system_one.py` and the HTTP client used by OpenAI-compatible BYOK connections, including `posthog/security/pinned_httpx.py`.
+The product client reuses the request builder and response parser in `posthog/llm/system_one.py` and constructs a DNS-pinned client from `posthog/security/pinned_httpx.py` with the bounded transport.
Customer connections do not consume PostHog's TypeSafe account budgets or emit TypeSafe egress metrics.
The selected connection supplies its own endpoint and credential; it never falls back to instance gateway settings.
-Numeric and categorical support is separate from this integration.
+Categorical evaluations use a native Choice question for single selection, with option keys mapped to their labels.
+Multiple selection uses one Noul question per option and includes each category with probability at least 0.5.
+The endpoint must support the configured number of options and questions; model limits can be lower than the evaluation's configuration limit.
+Results use the existing categorical event property and passing rules.
+An empty selection is an applicable result; N/A remains a separate outcome.
+`$ai_evaluation_probability` remains the probability of true for boolean evaluations and is not emitted for categorical results.
Numeric evaluations retain their existing arbitrary ranges and completion-based judges.
API compatibility does not guarantee equivalent judgments or calibration across models.
Compare results on representative inputs when changing models.
diff --git a/posthog/security/bounded_httpx.py b/posthog/security/bounded_httpx.py
new file mode 100644
index 000000000000..804235bb4dd9
--- /dev/null
+++ b/posthog/security/bounded_httpx.py
@@ -0,0 +1,120 @@
+import asyncio
+from collections.abc import Awaitable, Callable, Iterator
+from typing import Any
+
+from django.utils.asyncio import async_unsafe
+
+import httpx
+
+
+class _BoundedResponseStream(httpx.SyncByteStream):
+ def __init__(self, transport: "BoundedHTTPTransport", request: httpx.Request) -> None:
+ self._owner = transport
+ self._request = request
+ self._transport = httpx.AsyncHTTPTransport(**transport.transport_kwargs)
+ self._runner = asyncio.Runner()
+ self._deadline = self._runner.get_loop().time() + transport.total_timeout
+ self._response: httpx.Response | None = None
+ self._closed = False
+
+ async def _wait[T](self, operation: Callable[[], Awaitable[T]]) -> T:
+ if asyncio.get_running_loop().time() >= self._deadline:
+ raise TimeoutError
+ async with asyncio.timeout_at(self._deadline):
+ return await operation()
+
+ def _run[T](self, operation: Callable[[], Awaitable[T]]) -> T:
+ try:
+ return self._runner.run(self._wait(operation))
+ except TimeoutError as error:
+ raise httpx.ReadTimeout(
+ "The endpoint exceeded the total request deadline.", request=self._request
+ ) from error
+
+ def open(self) -> httpx.Response:
+ # Refuse compression so a small wire response cannot expand beyond the byte limit.
+ self._request.headers["Accept-Encoding"] = "identity"
+ self._request.read()
+ self._response = self._run(lambda: self._transport.handle_async_request(self._request))
+ encoding = self._response.headers.get("Content-Encoding", "identity").lower().strip()
+ if encoding != "identity":
+ raise httpx.DecodingError("The endpoint must return an uncompressed response.", request=self._request)
+ content_length = self._response.headers.get("Content-Length")
+ if content_length is not None:
+ try:
+ length = int(content_length)
+ except ValueError:
+ raise httpx.RemoteProtocolError("Invalid Content-Length.", request=self._request) from None
+ if length < 0 or length > self._owner.max_response_bytes:
+ raise httpx.DecodingError("The endpoint response exceeds the size limit.", request=self._request)
+ return httpx.Response(
+ self._response.status_code,
+ headers=self._response.headers,
+ stream=self,
+ extensions=self._response.extensions,
+ )
+
+ def __iter__(self) -> Iterator[bytes]:
+ if self._response is None or self._closed:
+ raise httpx.StreamClosed()
+ iterator = self._response.aiter_raw()
+ size = 0
+ try:
+ while True:
+ try:
+ chunk = self._run(lambda: anext(iterator))
+ except StopAsyncIteration:
+ break
+ size += len(chunk)
+ if size > self._owner.max_response_bytes:
+ raise httpx.DecodingError("The endpoint response exceeds the size limit.", request=self._request)
+ yield chunk
+ finally:
+ self.close()
+
+ async def _close(self) -> None:
+ try:
+ if self._response is not None:
+ await self._response.aclose()
+ finally:
+ await self._transport.aclose()
+
+ def close(self) -> None:
+ if self._closed:
+ return
+ self._closed = True
+ try:
+ self._runner.run(self._close())
+ finally:
+ self._runner.close()
+ self._owner.streams.discard(self)
+
+
+class BoundedHTTPTransport(httpx.BaseTransport):
+ """Sync HTTPX interface with cancellable I/O and a bounded response body.
+
+ Each response owns its async transport and event loop until it is consumed or closed.
+ Connections are not pooled across requests. No background request survives a timeout.
+ """
+
+ def __init__(self, *, total_timeout: float, max_response_bytes: int, **transport_kwargs: Any) -> None:
+ if total_timeout <= 0 or max_response_bytes <= 0:
+ raise ValueError("Request limits must be positive.")
+ self.total_timeout = total_timeout
+ self.max_response_bytes = max_response_bytes
+ self.transport_kwargs = transport_kwargs
+ self.streams: set[_BoundedResponseStream] = set()
+
+ @async_unsafe("Bounded HTTP requests must run in a synchronous worker.")
+ def handle_request(self, request: httpx.Request) -> httpx.Response:
+ stream = _BoundedResponseStream(self, request)
+ self.streams.add(stream)
+ try:
+ return stream.open()
+ except BaseException:
+ stream.close()
+ raise
+
+ def close(self) -> None:
+ for stream in list(self.streams):
+ stream.close()
diff --git a/posthog/security/pinned_httpx.py b/posthog/security/pinned_httpx.py
index 8028b9048ffa..f08e74b41718 100644
--- a/posthog/security/pinned_httpx.py
+++ b/posthog/security/pinned_httpx.py
@@ -27,6 +27,7 @@ from django.conf import settings
import httpx
+from posthog.security.bounded_httpx import BoundedHTTPTransport
from posthog.security.pinned_requests import SSRFBlockedError, select_pinned_ip
from posthog.security.url_validation import ResolvedIPs
@@ -93,15 +94,38 @@ class PinnedClient(httpx.Client):
``httpx.Client`` would instead switch environment proxies off altogether.
"""
- def __init__(self, *, pins: Mapping[str, IPAddress], **kwargs: Any) -> None:
+ def __init__(
+ self,
+ *,
+ pins: Mapping[str, IPAddress],
+ total_timeout: float | None = None,
+ max_response_bytes: int = 1_048_576,
+ **kwargs: Any,
+ ) -> None:
self._pins = dict(pins)
+ self._total_timeout = total_timeout
+ self._max_response_bytes = max_response_bytes
super().__init__(**kwargs)
def _init_transport(self, *args: Any, **kwargs: Any) -> httpx.BaseTransport:
- return PinnedTransport(super()._init_transport(*args, **kwargs), self._pins)
+ if self._total_timeout is None:
+ inner = super()._init_transport(*args, **kwargs)
+ else:
+ if kwargs.pop("transport", None) is not None:
+ raise ValueError("Bounded clients manage their own HTTP transport.")
+ inner = BoundedHTTPTransport(
+ total_timeout=self._total_timeout, max_response_bytes=self._max_response_bytes, **kwargs
+ )
+ return PinnedTransport(inner, self._pins)
def _init_proxy_transport(self, proxy: httpx.Proxy, *args: Any, **kwargs: Any) -> httpx.BaseTransport:
- return PinnedTransport(super()._init_proxy_transport(proxy, *args, **kwargs), self._pins, proxy_url=proxy.url)
+ if self._total_timeout is None:
+ inner = super()._init_proxy_transport(proxy, *args, **kwargs)
+ else:
+ inner = BoundedHTTPTransport(
+ proxy=proxy, total_timeout=self._total_timeout, max_response_bytes=self._max_response_bytes, **kwargs
+ )
+ return PinnedTransport(inner, self._pins, proxy_url=proxy.url)
def pinned_client(url: str, pinned_ips: ResolvedIPs, **kwargs: Any) -> httpx.Client:
diff --git a/posthog/security/test/test_pinned_httpx.py b/posthog/security/test/test_pinned_httpx.py
index bd23bc9378f3..3afd084bdc3a 100644
--- a/posthog/security/test/test_pinned_httpx.py
+++ b/posthog/security/test/test_pinned_httpx.py
@@ -1,7 +1,9 @@
import os
import ssl
import socket
+import asyncio
import ipaddress
+from collections.abc import AsyncIterator
import pytest
from unittest.mock import MagicMock, patch
@@ -30,6 +32,119 @@ def _without_environment_proxies() -> dict[str, str]:
return {key: "" for key in os.environ if key.lower().endswith("_proxy")}
+class TestBoundedPinnedClient:
+ @pytest.mark.parametrize("status", [200, 302, 500])
+ @pytest.mark.parametrize("advertised_length", [None, "100"])
+ def test_rejects_oversized_bodies_and_closes_the_connection(
+ self, status: int, advertised_length: str | None
+ ) -> None:
+ received: list[bytes] = []
+
+ class Body(httpx.AsyncByteStream):
+ closed = False
+
+ async def __aiter__(self) -> AsyncIterator[bytes]:
+ while True:
+ received.append(b"data")
+ yield b"data"
+
+ async def aclose(self) -> None:
+ self.closed = True
+
+ body = Body()
+ headers = {"Content-Length": advertised_length} if advertised_length is not None else {}
+ response = httpx.Response(status, stream=body, headers=headers)
+ with (
+ patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response),
+ pinned_client(
+ "https://example.com", {PUBLIC_IP}, total_timeout=10, max_response_bytes=4, trust_env=False
+ ) as client,
+ pytest.raises(httpx.DecodingError, match="size limit"),
+ ):
+ client.get("https://example.com")
+ assert received == ([] if advertised_length is not None else [b"data", b"data"])
+ assert body.closed
+
+ def test_refuses_compression_before_decoding(self) -> None:
+ response = httpx.Response(200, headers={"Content-Encoding": "gzip"}, stream=httpx.ByteStream(b"compressed"))
+ with (
+ patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response) as send,
+ pinned_client("https://example.com", {PUBLIC_IP}, total_timeout=10, trust_env=False) as client,
+ pytest.raises(httpx.DecodingError, match="uncompressed"),
+ ):
+ client.get("https://example.com")
+ assert send.call_args.args[0].headers["Accept-Encoding"] == "identity"
+ assert response.is_closed
+
+ @pytest.mark.parametrize("phase", ["headers", "body", "buffered_body"])
+ def test_total_deadline_cancels_slow_headers_and_dripping_body(self, 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
+ if phase != "buffered_body":
+ 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"
+
+ with (
+ patch("asyncio.BaseEventLoop.time", side_effect=lambda: clock[0]),
+ patch("httpcore.AnyIOBackend.connect_tcp", return_value=stream),
+ patch.object(stream, "read", side_effect=read),
+ patch.object(stream, "aclose", wraps=stream.aclose) as close,
+ pinned_client("https://example.com", {PUBLIC_IP}, total_timeout=10, trust_env=False) as client,
+ pytest.raises(httpx.ReadTimeout, match="total request deadline"),
+ ):
+ client.get("https://example.com")
+ close.assert_awaited()
+
+ @pytest.mark.parametrize("proxy", [None, "http://proxy.example.com:8080"])
+ def test_streams_incrementally_with_pinning_and_trusted_proxy_routing(self, proxy: str | None) -> None:
+ sent: list[tuple[str, str, object]] = []
+ consumed: list[bytes] = []
+
+ class Body(httpx.AsyncByteStream):
+ closed = False
+
+ async def __aiter__(self) -> AsyncIterator[bytes]:
+ for chunk in (b"first", b"second"):
+ consumed.append(chunk)
+ yield chunk
+
+ async def aclose(self) -> None:
+ self.closed = True
+
+ body = Body()
+
+ async def respond(request: httpx.Request) -> httpx.Response:
+ sent.append((str(request.url), request.headers["Host"], request.extensions.get("sni_hostname")))
+ return httpx.Response(200, stream=body)
+
+ with (
+ override_settings(SSRF_TRUSTED_PROXY_URLS=[proxy] if proxy else []),
+ patch("httpx.AsyncHTTPTransport.handle_async_request", side_effect=respond),
+ pinned_client("https://example.com", {PUBLIC_IP}, total_timeout=10, trust_env=False, proxy=proxy) as client,
+ ):
+ with client.stream("GET", "https://example.com") as response:
+ assert consumed == []
+ assert next(response.iter_bytes()) == b"first"
+ assert consumed == [b"first"]
+ assert response.url == httpx.URL("https://example.com")
+ assert body.closed
+ assert sent == [
+ (
+ "https://example.com" if proxy else f"https://{PUBLIC_IP}",
+ "example.com",
+ None if proxy else "example.com",
+ )
+ ]
+
+
class TestPinnedTransport:
@pytest.mark.parametrize(
"url,ip,expected_url,expected_host_header,expected_sni",
@@ -134,17 +249,20 @@ class TestPinnedTransport:
class TestPinnedClientRouting:
@override_settings(SSRF_TRUSTED_PROXY_URLS=[])
@pytest.mark.parametrize("proxy_variable", ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"])
- def test_refuses_untrusted_proxy_before_sending_credentials(self, proxy_variable: str) -> None:
+ @pytest.mark.parametrize("bounded", [False, True])
+ def test_refuses_untrusted_proxy_before_sending_credentials(self, proxy_variable: str, bounded: bool) -> None:
scheme = "http" if proxy_variable == "HTTP_PROXY" else "https"
url = f"{scheme}://example.com/"
with (
patch.dict(os.environ, {**_without_environment_proxies(), proxy_variable: "http://egress.example:3128"}),
patch.object(httpx.HTTPTransport, "handle_request", return_value=httpx.Response(200)) as send,
- pinned_client(url, {PUBLIC_IP}) as client,
+ patch.object(httpx.AsyncHTTPTransport, "handle_async_request") as async_send,
+ pinned_client(url, {PUBLIC_IP}, total_timeout=10 if bounded else None) as client,
):
with pytest.raises(SSRFBlockedError, match="proxy"):
client.get(url, headers={"Authorization": "Bearer fake-test-token"})
send.assert_not_called()
+ async_send.assert_not_called()
@override_settings(SSRF_TRUSTED_PROXY_URLS=["http://egress.example:3128"])
@pytest.mark.parametrize(
@@ -220,15 +338,18 @@ class TestPinnedClientRouting:
@override_settings(SSRF_TRUSTED_PROXY_URLS=["http://egress.example:3128"])
@pytest.mark.parametrize("proxied", [False, True])
@pytest.mark.parametrize("certificate_rejected", [False, True])
+ @pytest.mark.parametrize("bounded", [False, True])
def test_tls_keeps_original_hostname_and_certificate_verification(
- self, proxied: bool, certificate_rejected: bool
+ self, proxied: bool, certificate_rejected: bool, bounded: bool
) -> None:
responses = [b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"]
if proxied:
responses.insert(0, b"HTTP/1.1 200 Connection Established\r\n\r\n")
- stream = httpcore.MockStream(responses)
+ stream = httpcore.AsyncMockStream(responses) if bounded else httpcore.MockStream(responses)
- def start_tls(ssl_context: ssl.SSLContext, server_hostname: str, timeout: float) -> httpcore.NetworkStream:
+ def start_tls(
+ ssl_context: ssl.SSLContext, server_hostname: str, timeout: float
+ ) -> httpcore.NetworkStream | httpcore.AsyncNetworkStream:
assert ssl_context.verify_mode == ssl.CERT_REQUIRED
assert ssl_context.check_hostname
assert server_hostname == "example.com"
@@ -239,16 +360,20 @@ class TestPinnedClientRouting:
environment = {"HTTPS_PROXY": "http://egress.example:3128"} if proxied else {}
with (
patch.dict(os.environ, {**_without_environment_proxies(), **environment}),
- patch("httpcore.SyncBackend.connect_tcp", return_value=stream) as connect,
+ patch(
+ "httpcore.AnyIOBackend.connect_tcp" if bounded else "httpcore.SyncBackend.connect_tcp",
+ return_value=stream,
+ ) as connect,
patch.object(stream, "start_tls", side_effect=start_tls) as tls,
- pinned_client("https://example.com/", {PUBLIC_IP}) as client,
+ pinned_client("https://example.com/", {PUBLIC_IP}, total_timeout=10 if bounded else None) as client,
):
if certificate_rejected:
with pytest.raises(httpx.ConnectError, match="CERTIFICATE_VERIFY_FAILED"):
client.get("https://example.com/")
else:
assert client.get("https://example.com/").status_code == 200
- assert connect.call_args.kwargs["host"] == ("egress.example" if proxied else str(PUBLIC_IP))
+ host = connect.call_args.args[0] if bounded else connect.call_args.kwargs["host"]
+ assert host == ("egress.example" if proxied else str(PUBLIC_IP))
tls.assert_called_once()
@override_settings(FORCE_URL_VALIDATION=True)
diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.py
index 781a2e235fcd..b3a41076bec3 100644
--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py
+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py
@@ -12,7 +12,7 @@ from temporalio.common import RetryPolicy
from temporalio.exceptions import ApplicationError
from posthog.dataclasses import frozen
-from posthog.llm.system_one import NoulAnswer, NoulQuestion, Question
+from posthog.llm.system_one import ChoiceAnswer, ChoiceQuestion, NoulAnswer, NoulQuestion, Question
from posthog.temporal.ai_observability.evaluation_errors import (
require_user_error_spec,
terminal_user_error_result,
@@ -474,11 +474,11 @@ def call_llm_judge(
key_id = str(provider_key.id) if provider_key else None
if provider == "system_one":
- if output_type != "boolean":
+ if output_type not in ("boolean", "categorical"):
return build_skipped_evaluation_result(
output_type=output_type,
allows_na=allows_na,
- reasoning="System One currently supports boolean evaluations only.",
+ reasoning="System One supports boolean and categorical evaluations.",
skip_reason="unsupported_output_type",
)
base_url = provider_key.encrypted_config.get("base_url", "") if provider_key else ""
@@ -506,7 +506,28 @@ def call_llm_judge(
try:
if provider == "system_one":
prompt = evaluation["evaluation_config"]["prompt"]
- questions: dict[str, Question] = {"verdict": NoulQuestion(instructions=prompt)}
+ categorical_config = (
+ CategoricalOutputConfig.model_validate(output_config) if output_type == "categorical" else None
+ )
+ questions: dict[str, Question]
+ if categorical_config is None:
+ questions = {"verdict": NoulQuestion(instructions=prompt)}
+ elif categorical_config.selection_mode == "single":
+ questions = {
+ "category": ChoiceQuestion(
+ instructions=prompt,
+ criteria={option.key: option.label for option in categorical_config.options},
+ )
+ }
+ else:
+ questions = {
+ f"category_{index}": NoulQuestion(
+ instructions=prompt,
+ criteria_true=f"Matches category: {option.label}",
+ criteria_false=f"Does not match category: {option.label}",
+ )
+ for index, option in enumerate(categorical_config.options)
+ }
if allows_na:
questions["applicable"] = NoulQuestion(
instructions=(
@@ -528,18 +549,39 @@ def call_llm_judge(
if not isinstance(applicability_answer, NoulAnswer):
raise StructuredOutputParseError("The endpoint returned an invalid applicability answer.")
applicable = applicability_answer.probability >= 0.5
- verdict_answer = system_one_result.answers["verdict"]
- if not isinstance(verdict_answer, NoulAnswer):
- raise StructuredOutputParseError("The endpoint returned an invalid verdict answer.")
- probability = verdict_answer.probability
- parsed = (
- BooleanWithNAEvalResult(
- reasoning="",
- outcome="not_applicable" if not applicable else "pass" if probability >= 0.5 else "fail",
+ parsed: BooleanEvalResult | BooleanWithNAEvalResult | CategoricalEvalResult | CategoricalWithNAEvalResult
+ if categorical_config is not None:
+ categories: list[str] = []
+ if categorical_config.selection_mode == "single":
+ category_answer = system_one_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}"]
+ if not isinstance(category_match, NoulAnswer):
+ raise StructuredOutputParseError("The endpoint returned an invalid category answer.")
+ if category_match.probability >= 0.5:
+ categories.append(option.key)
+ parsed = (
+ CategoricalWithNAEvalResult(reasoning="", categories=categories if applicable else None)
+ if allows_na
+ else CategoricalEvalResult(reasoning="", categories=categories)
+ )
+ else:
+ verdict_answer = system_one_result.answers["verdict"]
+ if not isinstance(verdict_answer, NoulAnswer):
+ raise StructuredOutputParseError("The endpoint returned an invalid verdict answer.")
+ probability = verdict_answer.probability
+ parsed = (
+ BooleanWithNAEvalResult(
+ reasoning="",
+ outcome="not_applicable" if not applicable else "pass" if probability >= 0.5 else "fail",
+ )
+ if allows_na
+ else BooleanEvalResult(reasoning="", verdict=probability >= 0.5)
)
- if allows_na
- else BooleanEvalResult(reasoning="", verdict=probability >= 0.5)
- )
response = CompletionResponse(
content="",
model=model,
@@ -794,6 +836,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 isinstance(parsed_result, CategoricalEvalResult | CategoricalWithNAEvalResult):
result_dict["result_type"] = "categorical"
@@ -852,8 +897,4 @@ def call_llm_judge(
if probability is not None and result_dict["verdict"] is not None:
result_dict["probability"] = probability
- 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
-
return result_dict
diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.py
index 9e38f134c90f..7b9f0ba8f923 100644
--- a/posthog/temporal/ai_observability/test_run_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_evaluation.py
@@ -146,7 +146,7 @@ def test_system_one_judge_emits_boolean_probability_without_reasoning(
},
"usage": usage,
}
- response = httpx.Response(200, json=response_body)
+ response = httpx.Response(200, stream=httpx.ByteStream(json.dumps(response_body).encode()))
evaluation = {
"id": "test-evaluation",
"name": "Politeness",
@@ -159,7 +159,7 @@ def test_system_one_judge_emits_boolean_probability_without_reasoning(
patch(
"posthog.temporal.ai_observability.evaluation_llm_judge.system_one_evaluations_enabled", return_value=True
),
- patch("httpx.HTTPTransport.handle_request", return_value=response) as request,
+ patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response) as request,
):
spec.return_value.resolve.return_value = resolved
result = call_llm_judge(
@@ -186,6 +186,79 @@ def test_system_one_judge_emits_boolean_probability_without_reasoning(
assert properties["$ai_evaluation_key_type"] == "byok"
+ "selection_mode,probabilities,allows_na,applicable,expected",
+ [
+ ("single", [0.8, 0.2], False, True, ["resolved"]),
+ ("single", [0.8, 0.2], True, False, None),
+ ("multiple", [0.5, 0.9], False, True, ["resolved", "applicable"]),
+ ("multiple", [0.49, 0.9], True, True, ["applicable"]),
+ ("multiple", [0.1, 0.2], True, True, []),
+ ("multiple", [0.9, 0.9], True, False, None),
+ ],
+)
+def test_system_one_categorical_results_use_category_keys_without_boolean_probability(
+ selection_mode: str,
+ probabilities: list[float],
+ allows_na: bool,
+ applicable: bool,
+ expected: list[str] | None,
+) -> None:
+ options = [{"key": "resolved", "label": "Resolved issue"}, {"key": "applicable", "label": "Relevant reply"}]
+ evaluation = {
+ "id": "test-evaluation",
+ "name": "Response categories",
+ "team_id": 1,
+ "evaluation_type": "llm_judge",
+ "evaluation_config": {"prompt": "Classify the response."},
+ "output_type": "categorical",
+ "output_config": {"options": options, "selection_mode": selection_mode, "allows_na": allows_na},
+ }
+ answers: dict[str, dict[str, str | float | dict[str, float]]] = (
+ {"category": {"choice": "resolved", "confidence": 0.8, "probabilities": {"resolved": 0.8, "applicable": 0.2}}}
+ if selection_mode == "single"
+ else {f"category_{index}": {"noul": probability} for index, probability in enumerate(probabilities)}
+ )
+ if allows_na:
+ answers["applicable"] = {"noul": 0.9 if applicable else 0.1}
+ key = MagicMock(
+ provider="system_one",
+ 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
+ ),
+ 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
+ )
+ request.return_value = httpx.Response(
+ 200, stream=httpx.ByteStream(json.dumps({"model": "custom-model", "answers": answers}).encode())
+ )
+ result = call_llm_judge(evaluation=evaluation, system_prompt="", user_prompt="Hello!", allows_na=allows_na)
+
+ sent = json.loads(request.call_args.args[0].content)
+ assert sent["state"] == "Hello!"
+ if selection_mode == "single":
+ assert sent["questions"]["category"]["criteria"] == {option["key"]: option["label"] for option in options}
+ else:
+ assert sent["questions"]["category_0"]["criteria"]["true"] == "Matches category: Resolved issue"
+ assert result["result_type"] == "categorical"
+ assert result.get("categories") == expected
+ assert "probability" not in result
+ assert "verdict" not in result
+ assert result["input_tokens"] is None
+ assert result["reasoning"] == ""
+ properties = build_evaluation_event_properties(evaluation, result, datetime(2026, 1, 1, tzinfo=UTC))
+ assert properties.get("$ai_evaluation_categorical_result") == expected
+ assert properties["$ai_evaluation_applicable"] is applicable
+ assert "$ai_evaluation_probability" not in properties
+
+
def test_system_one_numeric_mapping_is_not_enabled() -> None:
with (
patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")}),
@@ -193,7 +266,7 @@ def test_system_one_numeric_mapping_is_not_enabled() -> None:
patch(
"posthog.temporal.ai_observability.evaluation_llm_judge.system_one_evaluations_enabled", return_value=True
),
- patch("httpx.HTTPTransport.handle_request") as request,
+ patch("httpx.AsyncHTTPTransport.handle_async_request") as request,
):
spec.return_value.resolve.return_value = MagicMock(provider="system_one")
result = call_llm_judge(
@@ -216,7 +289,7 @@ def test_system_one_restricted_connection_does_not_send_evaluation_data(base_url
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("httpx.HTTPTransport.handle_request") as request,
+ 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(
@@ -248,14 +321,14 @@ def test_system_one_rejections_distinguish_blocked_endpoints_from_bad_inputs(
provider="system_one",
encrypted_config={"api_key": "example-token", "base_url": "https://decisions.example.com/v1"},
)
- response = httpx.Response(status, text="Invalid request")
+ response = httpx.Response(status, stream=httpx.ByteStream(b"Invalid request"))
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("httpx.HTTPTransport.handle_request", return_value=response),
+ patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response),
):
spec.return_value.resolve.return_value = MagicMock(
provider="system_one", model="example-judge-v1", provider_key=key, is_byok=True
@@ -290,8 +363,8 @@ def test_system_one_rate_limit_retries_without_disabling_the_evaluation() -> Non
"posthog.temporal.ai_observability.evaluation_llm_judge.system_one_evaluations_enabled", return_value=True
),
patch(
- "httpx.HTTPTransport.handle_request",
- return_value=httpx.Response(429, headers={"Retry-After": "15"}),
+ "httpx.AsyncHTTPTransport.handle_async_request",
+ return_value=httpx.Response(429, headers={"Retry-After": "15"}, stream=httpx.ByteStream(b"")),
),
pytest.raises(ApplicationError) as error,
):
diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.py
index 3e5241d9ee81..54c8490db6b2 100644
--- a/products/ai_observability/backend/api/evaluations.py
+++ b/products/ai_observability/backend/api/evaluations.py
@@ -571,7 +571,7 @@ class EvaluationSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
if isinstance(model_configuration, dict)
else getattr(model_configuration, "provider", None)
)
- if model_provider == LLMProvider.SYSTEM_ONE and output_type != "boolean":
+ if model_provider == LLMProvider.SYSTEM_ONE and output_type not in ("boolean", "categorical"):
raise serializers.ValidationError(
{"model_configuration": "Select a model that supports this evaluation output type."}
)
diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.py
index ffdfce6fe292..edca78fb7d1a 100644
--- a/products/ai_observability/backend/api/test/test_evaluations.py
+++ b/products/ai_observability/backend/api/test/test_evaluations.py
@@ -120,16 +120,22 @@ class TestNumericEvaluationSerializer(SimpleTestCase):
class TestModelConfigurationSerializer(SimpleTestCase):
- def test_numeric_evaluation_rejects_system_one_connection(self) -> None:
+ @parameterized.expand([("boolean", True), ("categorical", True), ("numeric", False)])
+ def test_system_one_supports_boolean_and_categorical_outputs(self, output_type: str, supported: bool) -> None:
evaluation = Evaluation(
evaluation_type="llm_judge",
evaluation_config={"prompt": "Score quality"},
- output_type="numeric",
+ output_type=output_type,
output_config={},
)
serializer = EvaluationSerializer(instance=evaluation, partial=True)
- with self.assertRaisesMessage(ValidationError, "Select a model that supports this evaluation output type"):
- serializer.validate({"model_configuration": {"provider": "system_one", "model": "custom-model"}})
+ data = {"model_configuration": {"provider": "system_one", "model": "custom-model"}}
+ if supported:
+ with patch.object(serializer, "_validate_chat_model"):
+ self.assertEqual(serializer.validate(data), data)
+ else:
+ with self.assertRaisesMessage(ValidationError, "Select a model that supports this evaluation output type"):
+ serializer.validate(data)
@parameterized.expand(
[
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 04d3a7b06008..0a26e24089d2 100644
--- a/products/ai_observability/backend/api/test/test_provider_keys.py
+++ b/products/ai_observability/backend/api/test/test_provider_keys.py
@@ -190,7 +190,7 @@ class TestLLMProviderKeyViewSet(APIBaseTest):
"products.ai_observability.backend.llm.system_one.get_feature_flag_or_none",
return_value=operation != "prevalidate",
),
- patch("httpx.HTTPTransport.handle_request") as request,
+ patch("httpx.AsyncHTTPTransport.handle_async_request") as request,
):
if operation == "create":
response = self.client.post(
@@ -260,7 +260,7 @@ class TestLLMProviderKeyViewSet(APIBaseTest):
mock_validate.assert_called_once_with(provider, "sk-test-key-12345", team_id=self.team.id, **expected_config)
@patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("8.8.8.8")})
- @patch("httpx.HTTPTransport.handle_request")
+ @patch("httpx.AsyncHTTPTransport.handle_async_request")
@patch("products.ai_observability.backend.llm.system_one.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(
@@ -273,7 +273,7 @@ class TestLLMProviderKeyViewSet(APIBaseTest):
response_status = 200
def respond(*_args: object, **_kwargs: object) -> httpx.Response:
- return httpx.Response(response_status, content=body)
+ return httpx.Response(response_status, stream=httpx.ByteStream(body))
request.side_effect = respond
url = f"/api/environments/{self.team.id}/llm_analytics/provider_keys/"
diff --git a/products/ai_observability/backend/llm/system_one.py b/products/ai_observability/backend/llm/system_one.py
index 2201633e9e81..1341dd711a38 100644
--- a/products/ai_observability/backend/llm/system_one.py
+++ b/products/ai_observability/backend/llm/system_one.py
@@ -19,6 +19,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_httpx import pinned_client
from posthog.security.pinned_requests import SSRFBlockedError
from posthog.security.url_validation import has_authority_bypass_chars, validate_url_and_pin_ips
@@ -33,7 +34,7 @@ from products.ai_observability.backend.llm.errors import (
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._diagnostics import _tag_response
def system_one_evaluations_enabled(team_id: int, *, base_url: str) -> bool:
@@ -125,8 +126,13 @@ class SystemOneClient:
verdict = validate_url_and_pin_ips(base_url)
if not verdict.allowed:
raise SSRFBlockedError(verdict.reason)
- with tagged_http_client(
- timeout=timeout, pin=(base_url, verdict.pinned_ips), follow_redirects=False
+ with pinned_client(
+ base_url,
+ verdict.pinned_ips,
+ timeout=timeout,
+ total_timeout=timeout,
+ follow_redirects=False,
+ event_hooks={"response": [_tag_response]},
) as client:
response = client.post(
f"{base_url}/systemone",
@@ -135,6 +141,11 @@ class SystemOneClient:
)
except SSRFBlockedError as error:
raise SystemOneEndpointBlockedError("This endpoint is not allowed. Use a public HTTPS endpoint.") from error
+ except httpx.DecodingError as error:
+ raise SystemOneRequestRejectedError(
+ "The endpoint returned a compressed or oversized response. "
+ "Configure it to return uncompressed responses no larger than 1 MiB."
+ ) from error
except httpx.RequestError as error:
raise ProviderConnectionError("Could not reach the System One endpoint. Try again.") from error
diff --git a/products/ai_observability/backend/llm/test/test_system_one.py b/products/ai_observability/backend/llm/test/test_system_one.py
index b666d2a14546..4d1221d9762e 100644
--- a/products/ai_observability/backend/llm/test/test_system_one.py
+++ b/products/ai_observability/backend/llm/test/test_system_one.py
@@ -31,7 +31,9 @@ from products.ai_observability.backend.llm.system_one import (
def _response(status: int, body: dict[str, object] | str = "") -> httpx.Response:
- return httpx.Response(status, content=json.dumps(body) if isinstance(body, dict) else body)
+ return httpx.Response(
+ status, stream=httpx.ByteStream((json.dumps(body) if isinstance(body, dict) else body).encode())
+ )
@pytest.fixture(autouse=True)
@@ -81,25 +83,37 @@ def test_system_one_key_validation(status: int, expected_state: str) -> None:
"usage": {"input_tokens": 12, "output_tokens": 0},
},
)
+ response.headers["x-request-id"] = "example-request-id"
with (
- patch("httpx.HTTPTransport.handle_request", return_value=response) as request,
+ patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response) as request,
+ patch("posthoganalytics.tag") as tag,
):
state, message = Client.validate_key(
"system_one", "example-token", base_url="https://decisions.example.com/v1", model="custom-model"
)
assert state == expected_state
+ tag.assert_any_call("provider.last_status", status)
+ tag.assert_any_call("provider.last_request_id", "example-request-id")
assert (message is None) == (expected_state == "ok")
assert str(request.call_args.args[0].url) == "https://decisions.example.com/v1/systemone"
assert request.call_args.args[0].headers["Authorization"] == "Bearer example-token"
assert request.call_args.args[0].extensions["timeout"] == {"connect": 10, "read": 10, "write": 10, "pool": 10}
[email protected]("error", [httpx.ConnectError("Connection refused"), httpx.ReadTimeout("Timed out")])
-def test_transport_failures_are_retryable_connection_errors(error: Exception) -> None:
+ "error,expected_error",
+ [
+ (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),
+ ],
+)
+def test_transport_failures_map_to_provider_errors(error: Exception, expected_error: type[Exception]) -> None:
with (
- patch("httpx.HTTPTransport.handle_request", side_effect=error),
- pytest.raises(ProviderConnectionError),
+ patch("httpx.AsyncHTTPTransport.handle_async_request", side_effect=error),
+ pytest.raises(expected_error),
):
SystemOneClient.evaluate(
api_key="example-token",
@@ -121,7 +135,7 @@ def test_system_one_rejects_invalid_probabilities(probability: object) -> None:
},
)
with (
- patch("httpx.HTTPTransport.handle_request", return_value=response),
+ patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response),
pytest.raises(StructuredOutputParseError),
):
SystemOneClient.evaluate(
@@ -138,7 +152,7 @@ def test_system_one_rate_limits_are_retryable(status: int) -> None:
response = _response(status)
response.headers["Retry-After"] = "15"
with (
- patch("httpx.HTTPTransport.handle_request", return_value=response),
+ patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response),
pytest.raises(SystemOneRateLimitError) as error,
):
SystemOneClient.evaluate(
@@ -170,7 +184,7 @@ def test_unavailable_usage_does_not_discard_a_valid_answer(
"usage": usage,
},
)
- with patch("httpx.HTTPTransport.handle_request", return_value=response):
+ with patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response):
result = SystemOneClient.evaluate(
api_key="example-token",
base_url="https://decisions.example.com/v1",
@@ -189,7 +203,7 @@ def test_unavailable_usage_does_not_discard_a_valid_answer(
)
def test_official_endpoint_is_blocked(base_url: str) -> None:
with (
- patch("httpx.HTTPTransport.handle_request") as request,
+ patch("httpx.AsyncHTTPTransport.handle_async_request") as request,
pytest.raises(SystemOneEndpointBlockedError, match="hosted endpoint is not available"),
):
SystemOneClient.evaluate(
@@ -213,7 +227,7 @@ def test_system_one_requires_every_requested_answer(answers: dict[str, object])
},
)
with (
- patch("httpx.HTTPTransport.handle_request", return_value=response),
+ patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response),
pytest.raises(StructuredOutputParseError),
):
SystemOneClient.evaluate(
@@ -245,7 +259,7 @@ def test_system_one_preserves_error_categories(status: int, message: str, error_
response = _response(status, message)
response.headers["Location"] = "https://other.example.com/systemone"
with (
- patch("httpx.HTTPTransport.handle_request", return_value=response),
+ patch("httpx.AsyncHTTPTransport.handle_async_request", return_value=response),
pytest.raises(error_type),
):
SystemOneClient.evaluate(
@@ -283,7 +297,7 @@ def test_custom_endpoint_and_model(api_key: str) -> None:
return response
with (
- patch("httpx.HTTPTransport.handle_request", side_effect=respond) as request,
+ patch("httpx.AsyncHTTPTransport.handle_async_request", side_effect=respond) as request,
patch("posthog.egress.typesafe.transport.consume_typesafe_sync") as budget,
patch("posthog.egress.typesafe.observability.typesafe_egress.record_response") as telemetry,
):
@@ -319,7 +333,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.HTTPTransport.handle_request") as request:
+ with patch("httpx.AsyncHTTPTransport.handle_async_request") as request:
state, _ = SystemOneClient.validate_key("example-token", base_url=base_url, model="custom-model")
assert state == "error"
request.assert_not_called()
@@ -330,7 +344,7 @@ def test_private_endpoint_is_blocked(base_url: str) -> None:
with (
override_settings(DEBUG=False, TEST=False),
patch("posthog.security.url_validation.resolve_host_ips", return_value={ip_address("127.0.0.1")}),
- patch("httpx.HTTPTransport.handle_request") as request,
+ patch("httpx.AsyncHTTPTransport.handle_async_request") as request,
):
state, _ = SystemOneClient.validate_key("example-token", base_url=base_url, model="custom-model")
assert state == "error"
diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
index aac841395f07..deef47c69973 100644
--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
@@ -957,7 +957,10 @@ function EvaluationModelPicker(): JSX.Element {
// Evals always run on the team's own provider key, so only BYOK models are offered.
const selectedModelName = byokModels.find((m) => m.id === selectedModel)?.name
const groups = evaluationProviderModelGroups.filter(
- (group) => evaluation?.output_type === 'boolean' || group.provider !== 'system_one'
+ (group) =>
+ evaluation?.output_type === 'boolean' ||
+ evaluation?.output_type === 'categorical' ||
+ group.provider !== 'system_one'
)
const loading = byokModelsLoading || providerKeysLoading
@@ -986,8 +989,9 @@ function EvaluationModelPicker(): JSX.Element {
<ByokModelPickerNotice forEvaluation />
{evaluation?.model_configuration?.provider === 'system_one' && (
<p className="text-sm text-muted mt-2">
- This judge returns a probability without written reasoning. A probability of 50% or
- higher produces a true result.
+ {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 judge returns a probability without written reasoning. A probability of 50% or higher produces a true result.'}
</p>
)}
{modelSelectionRequired && !selectedModel && (