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): accept a response format on the playground completion endpoint (#118534)

Juraj Majerika94880bd4ad9
diff --git a/products/ai_observability/backend/api/proxy.py b/products/ai_observability/backend/api/proxy.py
index 0305aaeca11b..738dc319d578 100644
--- a/products/ai_observability/backend/api/proxy.py
+++ b/products/ai_observability/backend/api/proxy.py
@@ -14,6 +14,7 @@ from time import perf_counter
from typing import Any
from django.core.cache import cache
+from django.db import models
from django.http.response import HttpResponseBase
from django.utils import timezone
@@ -41,6 +42,7 @@ from posthog.renderers import SafeJSONRenderer, ServerSentEventRenderer
from posthog.settings import SERVER_GATEWAY_INTERFACE
from products.access_control.backend.facade.user_access_control import AccessControlLevel, UserAccessControl
+from products.ai_observability.backend.api.datasets import JSONObjectField
from products.ai_observability.backend.api.metrics import (
LLMA_PROXY_BYOK_EMPTY_MODEL_LISTS,
LLMA_PROXY_BYOK_REQUESTS,
@@ -52,6 +54,7 @@ from products.ai_observability.backend.llm import (
Client,
CompletionRequest,
ModelInfo,
+ OutputSchema,
get_playground_models,
)
from products.ai_observability.backend.llm.decisions import decision_evaluations_enabled
@@ -96,6 +99,27 @@ PROVIDER_DISPLAY_NAMES: dict[str, str] = {
}
+class LLMProxyResponseFormatType(models.TextChoices):
+ JSON_SCHEMA = "json_schema", "JSON schema"
+
+
+class LLMProxyJSONSchemaSerializer(serializers.Serializer):
+ name = serializers.CharField(
+ default="response", help_text="Schema name, sent to providers that require one (OpenAI)."
+ )
+ schema = JSONObjectField(help_text="JSON schema the reply must match. Sent to the provider unchanged.")
+ strict = serializers.BooleanField(
+ default=True, help_text="Enforce the schema exactly, where the provider has a strictness switch."
+ )
+
+
+class LLMProxyResponseFormatSerializer(serializers.Serializer):
+ type = serializers.ChoiceField(
+ choices=LLMProxyResponseFormatType.choices, help_text="Only `json_schema` is supported."
+ )
+ json_schema = LLMProxyJSONSchemaSerializer(help_text="The schema and its options, in the OpenAI shape.")
+
+
class LLMProxyCompletionSerializer(serializers.Serializer):
system = serializers.CharField(allow_blank=True)
messages = serializers.ListField(child=serializers.DictField())
@@ -110,6 +134,9 @@ class LLMProxyCompletionSerializer(serializers.Serializer):
reasoning_level = serializers.ChoiceField(
choices=["minimal", "low", "medium", "high"], required=False, allow_null=True
)
+ response_format = LLMProxyResponseFormatSerializer(
+ required=False, allow_null=True, help_text="Ask the model for JSON that matches a schema."
+ )
provider_key_id = serializers.UUIDField(required=False, allow_null=True)
@@ -357,6 +384,7 @@ class LLMProxyViewSet(viewsets.ViewSet):
seed=data.get("seed"),
max_tokens=data.get("max_tokens"),
tools=data.get("tools"),
+ output_schema=self._build_output_schema(data.get("response_format")),
thinking=thinking,
reasoning_level=data.get("reasoning_level"),
)
@@ -440,6 +468,13 @@ class LLMProxyViewSet(viewsets.ViewSet):
return Response({"error": "An internal error occurred"}, status=500)
+ @staticmethod
+ def _build_output_schema(response_format: dict[str, Any] | None) -> OutputSchema | None:
+ if not response_format:
+ return None
+ json_schema = response_format["json_schema"]
+ return OutputSchema(schema=json_schema["schema"], name=json_schema["name"], strict=json_schema["strict"])
+
def _extract_request_properties(self, validated_data: dict, model: str | None = None) -> dict:
"""Extract common properties from request for event tracking"""
model_name = model or validated_data.get("model")
@@ -452,6 +487,7 @@ class LLMProxyViewSet(viewsets.ViewSet):
"has_seed": validated_data.get("seed") is not None,
"has_max_tokens": validated_data.get("max_tokens") is not None,
"has_reasoning_level": validated_data.get("reasoning_level") is not None,
+ "has_response_format": validated_data.get("response_format") is not None,
"has_system_prompt": bool(validated_data.get("system")),
}
diff --git a/products/ai_observability/backend/api/test/test_proxy.py b/products/ai_observability/backend/api/test/test_proxy.py
index 02cdb7cf72eb..5d4fbd9aa9b2 100644
--- a/products/ai_observability/backend/api/test/test_proxy.py
+++ b/products/ai_observability/backend/api/test/test_proxy.py
@@ -10,6 +10,7 @@ from unittest import TestCase
from unittest.mock import patch
from django.http import StreamingHttpResponse
+from django.test import SimpleTestCase
import httpx
from parameterized import parameterized
@@ -33,6 +34,7 @@ from products.ai_observability.backend.llm import (
get_default_models,
get_playground_models,
)
+from products.ai_observability.backend.llm.types import OutputSchema
from products.ai_observability.backend.models.provider_keys import LLMProviderKey
PLAYGROUND_THROTTLES = (LLMProxyBurstRateThrottle, LLMProxySustainedRateThrottle, LLMProxyDailyRateThrottle)
@@ -233,6 +235,45 @@ class TestLLMProxyThrottles(APIBaseTest):
assert serializer.validated_data["seed"] == 42
+RESPONSE_SCHEMA = {"type": "object", "properties": {"ok": {"type": "boolean"}}, "required": ["ok"]}
+
+
+class TestLLMProxyCompletionSerializerResponseFormat(SimpleTestCase):
+ def _validate(self, response_format: object) -> LLMProxyCompletionSerializer:
+ serializer = LLMProxyCompletionSerializer(
+ data={
+ "system": "",
+ "messages": [{"role": "user", "content": "Hello"}],
+ "model": "gpt-4.1-mini",
+ "provider": "openai",
+ "response_format": response_format,
+ }
+ )
+ serializer.is_valid()
+ return serializer
+
+ def test_fills_name_and_strict_defaults(self) -> None:
+ serializer = self._validate({"type": "json_schema", "json_schema": {"schema": RESPONSE_SCHEMA}})
+
+ assert serializer.errors == {}
+ assert serializer.validated_data["response_format"] == {
+ "type": "json_schema",
+ "json_schema": {"name": "response", "schema": RESPONSE_SCHEMA, "strict": True},
+ }
+
+ @parameterized.expand(
+ [
+ ("unknown_type", {"type": "json_object", "json_schema": {"schema": RESPONSE_SCHEMA}}, "type"),
+ ("missing_schema", {"type": "json_schema", "json_schema": {"name": "x"}}, "json_schema"),
+ ("schema_not_an_object", {"type": "json_schema", "json_schema": {"schema": ["a"]}}, "json_schema"),
+ ]
+ )
+ def test_rejects_malformed_response_format(self, _name: str, response_format: dict, error_key: str) -> None:
+ serializer = self._validate(response_format)
+
+ assert error_key in serializer.errors["response_format"]
+
+
class TestPlaygroundModelAllowlist(TestCase):
def test_playground_models_are_subset_of_supported_models(self) -> None:
for _, config in PROVIDERS:
@@ -286,15 +327,15 @@ class TestPlaygroundModelEnforcement(APIBaseTest):
@patch("products.ai_observability.backend.api.proxy.Client")
def test_completion_allows_playground_model(self, mock_client_cls) -> None:
mock_client_cls.return_value.stream.return_value = iter([])
- response = self.client.post(
- "/api/llm_proxy/completion/",
- data=self._completion_payload("gpt-4.1-mini", "openai"),
- format="json",
- )
+ payload = self._completion_payload("gpt-4.1-mini", "openai")
+ payload["response_format"] = {"type": "json_schema", "json_schema": {"schema": RESPONSE_SCHEMA}}
+ response = self.client.post("/api/llm_proxy/completion/", data=payload, format="json")
assert response.status_code == 200
# Consume the streaming response to trigger the generator
b"".join(response.streaming_content) # type: ignore[attr-defined]
mock_client_cls.return_value.stream.assert_called_once()
+ completion_request = mock_client_cls.return_value.stream.call_args.args[0]
+ assert completion_request.output_schema == OutputSchema(schema=RESPONSE_SCHEMA)
@patch("products.ai_observability.backend.api.proxy.Client")
def test_byok_key_bypasses_playground_allowlist(self, mock_client_cls) -> None:
diff --git a/products/ai_observability/backend/llm/__init__.py b/products/ai_observability/backend/llm/__init__.py
index 71b5e063149e..a78e78948c70 100644
--- a/products/ai_observability/backend/llm/__init__.py
+++ b/products/ai_observability/backend/llm/__init__.py
@@ -5,7 +5,13 @@ from products.ai_observability.backend.llm.errors import LLMError, ProviderMisma
from products.ai_observability.backend.llm.providers.anthropic import AnthropicConfig
from products.ai_observability.backend.llm.providers.gemini import GeminiConfig
from products.ai_observability.backend.llm.providers.openai import OpenAIConfig
-from products.ai_observability.backend.llm.types import CompletionRequest, CompletionResponse, StreamChunk, Usage
+from products.ai_observability.backend.llm.types import (
+ CompletionRequest,
+ CompletionResponse,
+ OutputSchema,
+ StreamChunk,
+ Usage,
+)
SUPPORTED_MODELS_WITH_THINKING = (
AnthropicConfig.SUPPORTED_MODELS_WITH_THINKING + OpenAIConfig.SUPPORTED_MODELS_WITH_THINKING
@@ -72,6 +78,7 @@ DEFAULT_MODEL_BY_PROVIDER: dict[str, str] = {
__all__ = [
"Client",
"CompletionRequest",
+ "OutputSchema",
"CompletionResponse",
"StreamChunk",
"Usage",